From fec647a5d815a364fa53ece59731770b293a0b08 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 3 Nov 2026 22:16:39 +1300 Subject: [PATCH 01/23] Converge Account billing history and tenant entitlement sources --- .../account-service/api-contracts.md | 6 +- .../account-service/runtime-and-data.md | 2 +- .../player-access-and-session.md | 12 +- .../tenant_operation_entitlement_read.proto | 31 + .../StripeHostingSubscriptionProvisioner.java | 186 + .../accountservice/data/TestDataSeeder.java | 24 - .../entity/RetainedSubscriptionEvidence.java | 20 + ...ostingSubscriptionLifecycleRepository.java | 259 + ...HostingSubscriptionTerminalResolution.java | 159 + ...etainedSubscriptionEvidenceRepository.java | 41 + .../repository/SubscriptionRepository.java | 158 - ...nantOperationEntitlementWorkloadGuard.java | 75 + ...ostingSubscriptionProvisioningService.java | 125 + ...ccountTenantOperationEntitlementOwner.java | 334 + .../service/impl/AccountServiceImpl.java | 1510 +---- ...TenantOperationEntitlementGrpcService.java | 122 + .../service/impl/PaymentServiceImpl.java | 4 - ...SubscriptionTerminalResolutionService.java | 188 + ..._non_authorizing_subscription_evidence.sql | 44 + ...bscription_intent_and_provider_history.sql | 494 ++ ...sting_subscription_provisioning_claims.sql | 561 ++ ...g_subscription_first_provider_dispatch.sql | 82 + ...sting_subscription_terminal_resolution.sql | 202 + .../AccountApplicationIntegrationTest.java | 921 +-- ...horityProducerPostgresIntegrationTest.java | 7 +- ...ntAuthorityCurrentnessIntegrationTest.java | 196 +- ...rceEvidencePersistenceIntegrationTest.java | 3 - ...iptionDispatchPostgresIntegrationTest.java | 653 ++ ...ptionLifecyclePostgresIntegrationTest.java | 1705 +++++ .../AccountRepositoryIntegrationTest.java | 106 +- ...urceOwnerGuardPostgresIntegrationTest.java | 7 +- ...criptionIntentPostgresIntegrationTest.java | 1751 +++++ ...ourceSelectionPostgresIntegrationTest.java | 351 + ...nonicalHostingSubscriptionTestFixture.java | 470 ++ ...iptionEvidencePostgresIntegrationTest.java | 233 + ...titlementOwnerPostgresIntegrationTest.java | 271 + ...AuthenticationPostgresIntegrationTest.java | 7 +- ...ameplayDelegationRedisIntegrationTest.java | 12 +- ...entialVerifierPostgresIntegrationTest.java | 6 +- ...authenticationPostgresIntegrationTest.java | 7 +- ...ationAdmissionPostgresIntegrationTest.java | 7 +- ...tionCompletionPostgresIntegrationTest.java | 7 +- ...ionSourceOrderPostgresIntegrationTest.java | 7 +- ...ipeHostingSubscriptionProvisionerTest.java | 280 + .../data/TestDataSeederTest.java | 85 +- ...ngSubscriptionLifecycleRepositoryTest.java | 46 + ...OperationEntitlementWorkloadGuardTest.java | 119 + ...ngSubscriptionProvisioningServiceTest.java | 127 + .../service/impl/AccountServiceImplTest.java | 5782 ++--------------- .../LegacySubscriptionContainmentTest.java | 175 + .../service/impl/PaymentServiceImplTest.java | 8 +- ...GameplayPrimaryCredentialVerifierTest.java | 7 +- ...criptionTerminalResolutionServiceTest.java | 484 ++ .../AccountControlUiOwnerSourcesFixture.java | 9 +- ...imeTenantOperationEntitlementEvidence.java | 341 + ...meTenantOperationEntitlementGrpcCodec.java | 128 + ...enantOperationEntitlementEvidenceTest.java | 233 + ...nantOperationEntitlementGrpcCodecTest.java | 114 + ...tOperationEntitlementTransportFixture.java | 95 + ...countTenantOperationEntitlementClient.java | 119 + ...antOperationEntitlementClientMtlsTest.java | 303 + 61 files changed, 11907 insertions(+), 7914 deletions(-) create mode 100644 protos/account/v1/tenant_operation_entitlement_read.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisioner.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/RetainedSubscriptionEvidence.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionTerminalResolution.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/RetainedSubscriptionEvidenceRepository.java delete mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/SubscriptionRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantOperationEntitlementWorkloadGuard.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwner.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantOperationEntitlementGrpcService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionService.java create mode 100644 services/account-service/src/main/resources/db/migration/V1028__retain_non_authorizing_subscription_evidence.sql create mode 100644 services/account-service/src/main/resources/db/migration/V1029__canonical_subscription_intent_and_provider_history.sql create mode 100644 services/account-service/src/main/resources/db/migration/V1030__hosting_subscription_provisioning_claims.sql create mode 100644 services/account-service/src/main/resources/db/migration/V1032__hosting_subscription_first_provider_dispatch.sql create mode 100644 services/account-service/src/main/resources/db/migration/V1036__hosting_subscription_terminal_resolution.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecyclePostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/RetainedSubscriptionEvidencePostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisionerTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantOperationEntitlementWorkloadGuardTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/LegacySubscriptionContainmentTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementEvidenceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementGrpcCodecTest.java create mode 100644 services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/authority/TenantOperationEntitlementTransportFixture.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClient.java create mode 100644 services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClientMtlsTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index d6db52c687..3627a6d2eb 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -123,9 +123,9 @@ Fresh-enrollment certification is internal Account owner work, not a public regi ## Implementation Status -The public bootstrap WORLDS source is prepared as an unregistered Account owner and is not yet wired into the existing `ListBootstrapWorlds` facade. Its current schema-backed source is the canonical Account DEMO entitlement; paid-hosting discovery remains unavailable until the subscription schema and retained facade consumers migrate together. Current source and proof status are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#public-bootstrap-worlds-source-preparation). +The UUID billing foundation archives numeric subscription rows as immutable, non-authorizing retained evidence and supplies canonical intent, provisioning, lifecycle and cancellation-recovery storage. It also prepares the distinct `TENANT_OPERATION` source and protected transport; these owners remain manually composed and unregistered. Detailed receiving proof and unfinished authority boundaries belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). -The opaque `bootstrap-connect-scope` artifact uses canonical non-nil Account UUID subject/claim equality. Both browser discovery and the existing direct-text Account producer obtain that identity from Account persistence; the dedicated reader resolves it back to Account-local storage before existing binding checks. Numeric scopes have no compatibility parser: clients obtain fresh scope evidence through bounded rediscovery, while retained rows/receipts are not rewritten and existing retained-replay guards remain. Caller authentication, public-join policy and the held connect-token issuer are unchanged. Detailed receiving proof belongs to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#bootstrap-connect-scope-uuid-artifact). +The existing public WORLDS, REALMS, CHARS, browser/direct JOIN, direct scope and connect-token facades currently return `AUTH_UNAVAILABLE` before legacy discovery or subscription reads. The complete canonical UUID public facade and positive compositions remain in the preserved receiving successor. Ordinary authentication/player-bootstrap identity remains available. Retained numeric rows never authorize current billing or admission. The prepared selected gameplay-rule intake authorization, source-reservation/recovery, read and terminal-settlement owners are standalone and unregistered. Their typed transports add no available API or caller authority. Before enabling any standalone intake receiver (authorization, source read, HELD read, or settlement), its inbound message limit must accommodate the applicable 24 MiB codec bound: authorization and HELD read use `GameLogicIntakeAuthorizationGrpcCodec.MAX_WIRE_BYTES`; source read uses `GameLogicIntakeSourceReadProtoCodec.MAX_WIRE_BYTES`; settlement uses `AccountGameLogicIntakeSettlementEvidence.MAX_WIRE_BYTES`. The authorization receiver also carries the unchanged protected creator credential in binary metadata, so its inbound metadata limit must accommodate `AccountGameLogicIntakeAuthorizationCredentials.MAX_METADATA_BYTES`, which includes base64 wire encoding of the existing 16 KiB credential maximum plus metadata overhead. Binding a service configures neither limit. These are required receiver configurations, not claims about current deployment. The [Account prerequisite tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-gameplay-rule-intake-authorization-prerequisite) records qualification and receiving pipeline gaps. @@ -193,7 +193,7 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - `CreateAccount` – registers a global Account identity and returns its canonical UUID as REST `AccountDto.id` and gRPC `CreateAccountResponse.account_id`; its platform audit outbox payload carries the same UUID. It does not select a tenant or create membership/profile state. - `SendNotification` – deliver account notifications asynchronously. - `Authenticate` – verifies one account-selected ordinary credential mode, either `PASSWORD` or verified-email `EMAIL_OTP`, using a required, typed `CredentialSourceContext` and, only for the approved Game Session-to-Account control path, issues the receiver-specific private `game-session-account-delegation` JWT with exact audience `account-service`. Gameplay credential and email-code authentication are global Account-identity operations: their current wire requests reserve the former `tenant_id` fields, and Account neither selects nor requires membership before returning identity. The pre-v1 wire convergence also reserves the former `username` field number and places `email` on a new field number, so mixed old/new Account and Game Session versions fail closed instead of reinterpreting identifiers; the two services must be deployed as one compatibility cohort for uninterrupted gameplay login. The target registry-backed flow stores one `session:auth:token:` record; current gameplay issuance uses the legacy account-scoped session key and defers tenant membership/grant/entitlement to `JOIN`/`PLAY`. Generic `Service JWT` and `aud=internal` profiles are forbidden; workload-only authorization uses mTLS. The context contains a server-derived canonical client address and transport class; Account rejects absent or untrusted context in player-facing environments, and public callers cannot assert it. -- `JoinPublicProductionMembership` – implemented local internal Account RPC for explicit public-production membership creation/restoration. It accepts the Account-issued `connectScopeId`, operation `requestId`, and authenticated caller context; it revalidates the exact stored target and fresh `allowPublicJoin` entitlement evidence, binds a v1 digest to that caller/scope/policy snapshot, and commits membership/version, durable operation outcome, and tenant audit outbox evidence together. The digest's canonical grammar remains owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). A `PENDING` operation after an unknown database commit outcome still requires recovery/reconciliation implementation and exact-final-head PostgreSQL proof; no implicit membership writer or production end-to-end completion is claimed. +- `JoinPublicProductionMembership` – prepared internal Account interface for explicit public-production membership creation/restoration; the current receiving facade returns `AUTH_UNAVAILABLE` pending its complete canonical consumer. It accepts the Account-issued `connectScopeId`, operation `requestId`, and authenticated caller context; it revalidates the exact stored target and fresh `allowPublicJoin` entitlement evidence, binds the versioned digest to that caller/scope/policy snapshot, and commits membership/version, durable operation outcome, and tenant audit outbox evidence together. The digest's canonical grammar remains owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). A `PENDING` operation after an unknown database commit outcome still requires recovery/reconciliation implementation and exact-final-head PostgreSQL proof; no implicit membership writer or production end-to-end completion is claimed. - `ResolveEffectiveSecurityPolicy` – **Target-state internal Account contract.** Resolve the effective policy for the exact account, optional tenant-scoped action, and action class from the versioned platform baseline, deployment policy, and applicable tenant policy using the tightening precedence in ADR 0045. Return the contributing policy versions, resolved values, and opaque `effectivePolicyVersion`/digest from one Account-owned resolution. Callers must not merge inputs or use cached/default policy; missing, invalid, contradictory, stale, or unavailable resolution fails the sensitive action closed. No other service is a policy authority. - `ApplyAccountSafetyRestriction` / `GetAccountSafetyRestrictions` – target Account-owned owner-command and safe projection contracts for `account_security_lock` and `platform_access_ban`. The command carries one exact category, global account scope, source case/security-event identity, a distinct `ownerEnforcementRequestId`, owner-enforcement digest, and owner authorization evidence; `controlPlaneRequestId` remains correlation-only and never carries or aliases the owner identity. Account validates and atomically commits its monotonic revision, account authority-generation effects, and idempotent result. The current proto/transport mapping does not yet expose the distinct owner request field; that is implementation drift, not proof that the target command is implemented. These contracts do not create a moderation appeal case, and current proto/implementation/proof do not yet provide the complete lifecycle. - `RefreshGameplayServiceToken` – Account-local RPC for the token refresh/replacement operation defined in [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md). Account validates the declared receiver binding and current authority, while Game Session supplies the binding-refresh installation/reconciliation consequence; the current proto and implementation do not yet prove the target registry-backed operation. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 5a56bdc50a..99d5891076 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -316,7 +316,7 @@ Entitlement producer contract: - `provisioningStatus` is `pending`, `provisioning`, or null; while non-null, `subscriptionStatus` is null and all new gameplay/admission/instance-start flags are false. `tenantAuthorityGeneration` is opaque and may be compared only for exact equality, never ordered or used as an event identity. - The focused producer proof must show that every entitlement response is one Account-authenticated bundle from the same authoritative committed evaluation, that `tenantAuthorityGeneration` is the Account-committed fence rather than a value reconstructed from a later projection read, and that no caller reconstructs or separately sources bundle identities, tuple members, cutoff evidence, or checkpoints. -Current implementation remains a narrower local subscription read: unusable row sets and versions fail closed, and classified storage failures are kept distinct from programming faults. JOIN diagnostic persistence uses its existing post-rollback path, while terminal retry refusal preserves the original receipt. This supplies neither the complete bundle above nor positive connect-token issuance. Current proof and remaining boundaries belong to the [entitlement read tracker](../../../project-management/implementation-tracking/player-access-and-session.md#entitlement-read-and-join-failure-classification). +The current numeric runtime entitlement endpoint refuses with `ENTITLEMENT_UNAVAILABLE` before historical subscription reads. Canonical UUID billing and the distinct unregistered `TENANT_OPERATION` source are prepared separately; the complete public `PLAYER_ADMISSION` consumer remains in its receiving successor. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving) owns receiving proof and gaps. ### Playtest Grant Persistence and Authority Consequences 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 9846ce038c..c1ab76d5cc 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,6 +8,16 @@ This is a non-normative implementation tracker for player access and session. Ca Account initial/current/final creation owners, explicit initial billing-owner consent, private Game Design create/close receivers, and original-bound dispatch/recovery are locally composed and unregistered. Focused receiving proof passes, while physical cross-owner qualification, protected Redis/source custody and public/default registration remain incomplete; proof limits are recorded below. +### Canonical billing and retention receiving + +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 provisioning and cancellation components keep actual Account actor/authentication and owner-local atomic receipt/fence/event checks; cancellation does not establish provider absence, transfer, a registered recovery route or closure of the accepted terminal-recovery Major. + +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 compilation328 passes. Focused331 executes203Account units, nine shared evidence/transport cases, four actual World→Account mTLS cases and80PostgreSQL cases; its aggregate fails two intent fixtures. Corrected336 passes all20intent cases (including the additional unaudited-update refusal), enabled affected static checks, formatting and documentation. Together these executions establish81unique focused PostgreSQL cases without failures/errors/skips; unchanged passing suites retain331attribution. Fresh-image/runtime and current-head CI/review remain required; controlled sources/PKI do not establish production custody or authenticated transfer. + +The existing public WORLDS/REALMS/CHARS, browser/direct JOIN, direct scope and connect-token facade paths temporarily return AUTH_UNAVAILABLE before legacy authority reads; the numeric runtime entitlement endpoint returns ENTITLEMENT_UNAVAILABLE. Complete canonical V2/JOIN/CHARS implementation and all positive compositions remain preserved in the separate public receiving source. This temporary boundary does not complete that work or permit dropping its positive obligations. Ordinary Account authentication, UUID player-bootstrap issuance, profile and retention/deletion protections remain in scope for receiving qualification. Private/ISOLATED/PLAYER_CREATED/AUTO positives, protected target currentness through commit, genuine installation delivery and private FRESH/CLOSED aggregation remain unfinished; registration/issuer/custody/activation holds remain. + ### Lifecycle-bound private realm-grant source preparation Local source includes [`RealmGrantMutation`](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/RealmGrantMutation.java), the [shared grant scope codec](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/GrantAuthorityScopeCodec.java), the [grant event codec](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RealmGrantAuthorityEventV1Codec.java), and Account's [lifecycle-bound grant repository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLifecycleBoundRealmGrantRepository.java) with [migration V1027.2](../../../services/account-service/src/main/resources/db/migration/V1027.2__lifecycle_bound_realm_grant_authority.sql). The composed read uses [`AccountCurrentLifecycleRealmGrantReadOwner`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/realm/AccountCurrentLifecycleRealmGrantReadOwner.java), [`GameSessionCurrentPrivatePlaytestLifecycleReadClient`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameSessionCurrentPrivatePlaytestLifecycleReadClient.java), and the shared [`CurrentPrivatePlaytestLifecycleReadGrpcCodec`](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CurrentPrivatePlaytestLifecycleReadGrpcCodec.java). Canonical grant/lifecycle behavior remains in [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#account-owned-playtest-grant-contract) and [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md), with the Game Session handoff recorded in [Realm Routing](./realm-routing-and-playable-state.md#initial-fresh-lifecycle-preparation). @@ -22,7 +32,7 @@ The source owner refuses ambient Account SQL and requires a workload-only `Sessi [`AccountPublicBootstrapWorldsOwnerTest`](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java), [`AccountPublicBootstrapEntitlementOwnerTest`](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwnerTest.java), the [Account target client test](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClientTest.java), and the focused [Game Session collection-read](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java) and [workload-guard tests](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayAdmissionDecisionReadWorkloadGuardTest.java) cover the manually composed discovery source. Proof163/166 executes 165 selected units (17 shared codec, 44 Game Session and 104 Account); proof164/166 executes seven real Account PostgreSQL discovery cases, including successful deterministic filtering, genuine source-head mutation, missing source, expiry, ambiguity, target change and caller-currentness loss. Proof167 qualifies the nullable transaction-definition fixture and Account test static analysis; proof168 adds three real loopback mTLS client cases for exact peer identity, authenticated empty collection and malformed/correlation refusal. These source tests use actual Account DEMO SQL and a controlled complete Game Session response; the loopback mTLS tests use a controlled Game Session server. Neither establishes the whole authenticated source chain or deployment custody. Proof178 passes 189 selected unit/loopback cases and 13 physical cases, with affected static, formatting and documentation checks; the physical cases include the seven discovery cases, three pre-V1028 scope cases and three final-admission composition cases. The latter use a controlled World capture, not a qualified end-to-end World source chain. -The existing [`AccountServiceImpl.listBootstrapWorlds`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java) and its positive tests remain on the legacy path in this source slice. The local [`AccountCanonicalPublicRealmScopeOwner`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java) separately issues and retains signed canonical UUID V2 public selector scopes; its focused and pre-V1028 PostgreSQL proof is included in the counts above. This scope owner is not consumed by the existing facade, and this source slice adds no browser scope reader. Paid types in the compile closure do not establish paid discovery: V1028 must archive the old subscription table, V1029 creates the canonical UUID table, and dependent V1030/V1032 plus the facade and its positive consumers remain for the later coherent core. No numeric fallback or second subscription table is introduced. Private `REALMS`, browser/direct scope reading, `PLAYER_ADMISSION`, JOIN consumer migration, default registration and gameplay admission remain separate gaps. +The existing public facade is temporarily unavailable during the [canonical billing receiving](#canonical-billing-and-retention-receiving) split. Its complete canonical consumer and positive proof remain preserved for the successor; neither retained numeric billing history nor the separately prepared scope owner supplies a fallback. The local [`AccountCanonicalPublicRealmScopeOwner`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java) adds an actual public selector-scope producer over the same complete target and current Account source owners. It preserves genuine membership absence without enrolling a pair, returns current ACTIVE/INACTIVE facts without treating closed enrollment as loss of public visibility, and persists signed canonical UUID V2 scope preimages through the existing Account scope repository. Root's proof176 passes 21 focused signing/orchestration/refusal cases and affected enabled checks. These use real local signing and bootstrap verification with controlled source/transaction inputs; proof177 also passes the three actual pre-V1028 PostgreSQL scope cases alongside the seven existing WORLDS cases (1m20), with enabled affected checks. These retain exact signed UUID/V2 hash/digest/provenance bytes without membership/pair/JOIN/event writes, refuse a real DEMO source-head change, and roll back a real PostgreSQL insert refusal. No facade/default registration, private lifecycle completion, JOIN or admission is established. diff --git a/protos/account/v1/tenant_operation_entitlement_read.proto b/protos/account/v1/tenant_operation_entitlement_read.proto new file mode 100644 index 0000000000..81abb10bee --- /dev/null +++ b/protos/account/v1/tenant_operation_entitlement_read.proto @@ -0,0 +1,31 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Private Account owner read for exact same-namespace World Management over workload mTLS. +// Explicit eligibility source selection creates neither capacity nor player admission authority. +service AccountTenantOperationEntitlementReadService { + rpc ReadTenantOperationEntitlement(ReadTenantOperationEntitlementRequest) + returns (ReadTenantOperationEntitlementResponse); +} + +// Repeated transport members must each have exactly one value. This preserves duplicate scalar +// occurrences for closed-schema validation instead of protobuf's singular last-value-wins parsing. +message ReadTenantOperationEntitlementRequest { + repeated int32 schema_version = 1; + repeated string target_namespace = 2; + repeated string tenant_id = 3; + repeated string request_id = 4; + // Exactly PAID_HOSTING or NON_PAID_DEMO. No default, inference, or fallback. + repeated string source_kind = 5; +} + +message ReadTenantOperationEntitlementResponse { + repeated ReadTenantOperationEntitlementRequest request = 1; + // Exactly one existing strict canonical TENANT_OPERATION value, bounded to 64 KiB. + // Its callerWorkload is derived from the authenticated peer, never request data. + repeated bytes canonical_evidence = 2; +} 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..3802718ae2 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisioner.java @@ -0,0 +1,186 @@ +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.SubscriptionSearchParams; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Clock; +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 final com.stripe.StripeClient stripe; + private final Clock clock; + 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) { + this.stripe = Objects.requireNonNull(stripe); + this.clock = Objects.requireNonNull(clock); + observer = new StripeHostingSubscriptionObserver(stripe, clock); + 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())); + 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()); + 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()) { + return new Pending("PROVIDER_LOOKUP_UNRESOLVED", null); + } + 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.builder() + .setIdempotencyKey(creation.subscriptionProvisioningRequestId().toString()) + .setMaxNetworkRetries(0) + .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/data/TestDataSeeder.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java index ac571813e3..de5bde5a35 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java @@ -2,19 +2,15 @@ import de.mkammerer.argon2.Argon2; import de.mkammerer.argon2.Argon2Factory; -import java.time.LocalDateTime; -import java.util.List; import java.util.Objects; import java.util.Optional; import lombok.RequiredArgsConstructor; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; -import net.firedevops.firemud.accountservice.entity.Subscription; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.ProfileRepository; -import net.firedevops.firemud.accountservice.repository.SubscriptionRepository; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -34,12 +30,10 @@ public class TestDataSeeder implements ApplicationRunner { private static final String DEMO_USERNAME = "demo"; private static final String DEMO_EMAIL = "demo@example.com"; private static final String DEMO_PASSWORD = "swordfish"; - private static final String DEMO_SUBSCRIPTION_PLAN_ID = "local-smoke"; private final AccountRepository accountRepository; private final AccountTenantMembershipRepository accountTenantMembershipRepository; private final ProfileRepository profileRepository; - private final SubscriptionRepository subscriptionRepository; @Override @Transactional @@ -98,24 +92,6 @@ public void run(ApplicationArguments args) { profile.setPresenceVisibilityPolicy(ProfilePresenceVisibilityPolicy.FRIENDS_ONLY); profileRepository.save(profile); } - - List subscriptions = subscriptionRepository.findByTenantId(DEMO_TENANT_ID); - if (subscriptions.isEmpty()) { - Subscription subscription = new Subscription(); - subscription.setAccount(account); - subscription.setPlanId(DEMO_SUBSCRIPTION_PLAN_ID); - subscription.setStatus("active"); - subscription.setStartedAt(LocalDateTime.now()); - subscription.setTenantId(DEMO_TENANT_ID); - subscriptionRepository.save(subscription); - } else if (subscriptions.size() > 1) { - throw new IllegalStateException( - "Cannot seed demo tenant entitlement: tenant " - + DEMO_TENANT_ID - + " has ambiguous subscription authority (" - + subscriptions.size() - + " rows)"); - } } private static boolean isQuarantinedDemoMembership( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/RetainedSubscriptionEvidence.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/RetainedSubscriptionEvidence.java new file mode 100644 index 0000000000..595c15b6bc --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/RetainedSubscriptionEvidence.java @@ -0,0 +1,20 @@ +package net.firedevops.firemud.accountservice.entity; + +import java.time.LocalDateTime; +import java.util.UUID; + +/** + * Immutable historical numeric subscription evidence, never current billing or entitlement + * authority. All identifiers and counters here are retained values, not canonical identity or + * billing sequence. + */ +public record RetainedSubscriptionEvidence( + Long id, + Long accountId, + String planId, + String status, + LocalDateTime startedAt, + LocalDateTime endedAt, + Long tenantId, + long entitlementVersion, + UUID tenantAuthorityGeneration) {} 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 de3fa3ca34..39b55f3f39 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 @@ -1,6 +1,7 @@ package net.firedevops.firemud.accountservice.repository; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; import java.time.Clock; import java.time.Duration; import java.time.Instant; @@ -17,6 +18,9 @@ import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver.ObservedSubscription; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy.RecoveryTiming; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy.Status; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionTerminalResolution.Authorization; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionTerminalResolution.LockedTarget; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionTerminalResolution.Request; import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.FenceRejectedException; import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; import org.jooq.DSLContext; @@ -73,6 +77,261 @@ public AccountHostingSubscriptionLifecycleRepository( dsl, new AccountAuthorityOutboxRepository(dsl), billing, tenantIdentity, generations); } + /** Locked read capture only. No journal, intent, audit or fence changes precede final auth. */ + public ResolutionPreparation prepareTerminalResolution(Request request) { + requireTransaction(); + Objects.requireNonNull(request); + var original = intents.findCreation(request.creationRequestId()).orElseThrow(); + var observedCurrent = intents.findCurrentByTenant(original.tenantId()).orElseThrow(); + var current = intents.lockForLifecycle(original.requestId(), observedCurrent.rowVersion()); + Record failed = operationForUpdate(request.failedRequestId()); + Record journal = + dsl.fetchOne( + "SELECT * FROM subscription_lifecycle_terminal_resolutions WHERE resolution_request_id = ? FOR UPDATE", + request.resolutionRequestId()); + if (!request.tenantId().equals(original.tenantId()) + || !request.subscriptionId().equals(current.subscriptionId()) + || !request.actorAccountId().equals(original.owner().accountUuid()) + || !request.creationRequestId().equals(failed.get("creation_request_id", UUID.class)) + || !request.subscriptionId().equals(failed.get("subscription_id", UUID.class)) + || !"BILLING_RECONCILIATION_TERMINAL_FAILURE".equals(failed.get("state", String.class)) + || request.expectedFailedOperationVersion() != failed.get("row_version", Long.class)) { + throw new FenceRejectedException("Exact same-owner terminal lifecycle target rejected"); + } + ExpectedBinding binding = + expected(original, failed.get("provider_subscription_id", String.class)); + if (journal != null) { + if (!request.digest().equals(journal.get("request_digest", String.class)) + || !Arrays.equals(request.payload(), journal.get("request_payload", byte[].class))) { + throw new FenceRejectedException("IDEMPOTENCY_CONFLICT: terminal resolution tuple changed"); + } + Record receipt = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM subscription_lifecycle_receipts WHERE request_id = ?", + request.resolutionRequestId())); + if (!"COMMITTED".equals(journal.get("state", String.class)) + || !"canceled".equals(receipt.get("status", String.class)) + || !journal + .get("receipt_digest", String.class) + .equals(receipt.get("receipt_digest", String.class))) { + throw new FenceRejectedException("Terminal resolution receipt readback differs"); + } + new AccountAuditOutboxRepository(dsl) + .findCanonicalTenantEnvelopeForUpdate(request.auditEventId()) + .filter( + audit -> + request.digest().equals(audit.payloadDigest()) + && "HOSTING_SUBSCRIPTION_TERMINAL_RESOLVED".equals(audit.eventType()) + && request.tenantId().equals(audit.tenantUuid())) + .orElseThrow( + () -> new FenceRejectedException("Terminal resolution audit readback differs")); + return new ResolutionPreparation( + request, + binding, + current.rowVersion(), + now(), + now(), + new TransitionResult( + request.resolutionRequestId(), + Outcome.COMMITTED, + journal.get("result_row_version", Long.class), + null)); + } + if (request.expectedSubscriptionVersion() != current.rowVersion() + || !request + .failedRequestId() + .equals( + links(current.subscriptionId()).get("lifecycle_inflight_request_id", UUID.class))) { + throw new FenceRejectedException("Terminal resolution lost its exact failed current fence"); + } + Instant captured = now(); + Instant deadline = + earlier( + captured.plus(limits.lease()), + captured.plusMillis(failed.get("observation_age_millis", Long.class))); + return new ResolutionPreparation( + request, binding, current.rowVersion(), captured, deadline, null); + } + + /** + * Final cancellation-only owner mutation. The mandatory callback runs under exact target locks + * immediately before writes; callback inputs/outputs alone do not establish Account authority. + * The caller must roll back the transaction on every failure, including callback/commit failure. + */ + public TransitionResult applyTerminalResolution( + ResolutionPreparation prepared, + StripeHostingSubscriptionObserver.Result result, + Authorization authorization) { + requireTransaction(); + Objects.requireNonNull(prepared); + Objects.requireNonNull(authorization, "Explicit final Account authorization callback required"); + Request request = prepared.request; + ResolutionPreparation locked = prepareTerminalResolution(request); + Instant evaluated = now(); + if (locked.replay == null) { + if (prepared.replay != null + || !prepared.binding.equals(locked.binding) + || evaluated.isBefore(prepared.capturedAt) + || !evaluated.isBefore(prepared.deadline) + || !(result instanceof ObservedSubscription observed) + || !observed.providerStatusIsCanceled() + || observed.readStartedAt().isBefore(prepared.capturedAt) + || observed.observedAt().isAfter(evaluated)) { + throw new FenceRejectedException( + "Fresh exact canceled SDK evidence required for resolution"); + } + requireObservedBinding(prepared.binding, observed); + Record failed = operationForUpdate(request.failedRequestId()); + var decision = retainedPolicy(failed).evaluate(observed, evaluated, null); + if (!decision.resolved() || decision.status() != Status.CANCELED) { + throw new FenceRejectedException("Terminal cancellation evidence expired or is unresolved"); + } + } + Instant authenticationStarted = now(); + var actor = + Objects.requireNonNull( + authorization.requireAuthorized( + new LockedTarget(request, request.actorAccountId(), locked.currentVersion))); + Instant authenticated = now(); + if (!request.actorAccountId().equals(actor.actorAccountId()) + || !request.controlUiIssuanceOperationId().equals(actor.controlUiIssuanceOperationId()) + || !request.controlUiTokenHash().equals(actor.controlUiTokenHash()) + || actor.authenticatedAt().isBefore(authenticationStarted) + || actor.authenticatedAt().isAfter(authenticated)) { + throw new FenceRejectedException( + "Final primary-authentication source differs from exact actor"); + } + if (locked.replay != null) return locked.replay; + if (!authenticated.isBefore(prepared.deadline)) { + throw new FenceRejectedException("Terminal resolution capture expired during authorization"); + } + new AccountAuditOutboxRepository(dsl) + .appendCanonicalTenant( + request.auditEventId(), + request.tenantId().toString(), + "HOSTING_SUBSCRIPTION_TERMINAL_RESOLVED", + new String(request.payload(), StandardCharsets.UTF_8)); + UUID attemptId = UUID.randomUUID(); + dsl.execute( + "INSERT INTO subscription_lifecycle_terminal_resolutions (resolution_request_id, failed_request_id, creation_request_id, " + + "subscription_id, tenant_id, expected_failed_version, expected_subscription_version, actor_account_id, " + + "control_ui_issuance_operation_id, control_ui_token_hash, audit_event_id, audit_reason, request_payload, request_digest, " + + "attempt_id, captured_at, expires_at, authenticated_at, state) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?::timestamptz, ?::timestamptz, ?::timestamptz, 'PREPARED')", + request.resolutionRequestId(), + request.failedRequestId(), + request.creationRequestId(), + request.subscriptionId(), + request.tenantId(), + request.expectedFailedOperationVersion(), + request.expectedSubscriptionVersion(), + request.actorAccountId(), + request.controlUiIssuanceOperationId(), + request.controlUiTokenHash(), + request.auditEventId(), + request.auditReason(), + request.payload(), + request.digest(), + attemptId, + utc(prepared.capturedAt), + utc(prepared.deadline), + utc(actor.authenticatedAt())); + dsl.execute( + "INSERT INTO subscription_lifecycle_operations (request_id, creation_request_id, subscription_id, tenant_id, expected_row_version, " + + "reserved_row_version, provider_subscription_id, provisioning_attempt_id, request_payload, request_digest, state, row_version, " + + "max_attempts, max_stalled_attempts, lease_millis, backoff_millis, observation_age_millis, warning_millis, grace_millis, deadline_at, retry_at, created_at) " + + "SELECT ?, creation_request_id, subscription_id, tenant_id, ?, ?, provider_subscription_id, provisioning_attempt_id, ?, ?, 'PENDING', 1, " + + "1, 1, lease_millis, backoff_millis, observation_age_millis, warning_millis, grace_millis, ?::timestamptz, ?::timestamptz, ?::timestamptz " + + "FROM subscription_lifecycle_operations WHERE request_id = ? AND state = 'BILLING_RECONCILIATION_TERMINAL_FAILURE' AND row_version = ?", + request.resolutionRequestId(), + request.expectedSubscriptionVersion(), + request.expectedSubscriptionVersion() + 1, + request.payload(), + request.digest(), + utc(prepared.deadline), + utc(prepared.capturedAt), + utc(prepared.capturedAt), + request.failedRequestId(), + request.expectedFailedOperationVersion()); + if (dsl.execute( + "UPDATE subscription SET lifecycle_inflight_request_id = ?, row_version = row_version + 1 " + + "WHERE subscription_id = ? AND row_version = ? AND lifecycle_inflight_request_id = ? AND superseded_at IS NULL", + request.resolutionRequestId(), + request.subscriptionId(), + request.expectedSubscriptionVersion(), + request.failedRequestId()) + != 1) { + throw new FenceRejectedException("Terminal resolution expected-current CAS rejected"); + } + dsl.execute( + "INSERT INTO subscription_lifecycle_attempts (attempt_id, request_id, attempt_number, started_at, expires_at) VALUES (?, ?, 1, ?::timestamptz, ?::timestamptz)", + attemptId, + request.resolutionRequestId(), + utc(prepared.capturedAt), + utc(prepared.deadline)); + dsl.execute( + "UPDATE subscription_lifecycle_operations SET attempt_count = 1, last_attempt_id = ?, row_version = row_version + 1 WHERE request_id = ?", + attemptId, + request.resolutionRequestId()); + TransitionResult committed = + apply( + new Preparation( + request.resolutionRequestId(), + attemptId, + prepared.binding, + Outcome.READY, + null, + request.expectedSubscriptionVersion() + 1), + result); + if (committed.outcome() != Outcome.COMMITTED) + throw new FenceRejectedException("Cancellation resolution did not commit"); + dsl.execute( + "UPDATE subscription_lifecycle_terminal_resolutions SET state = 'COMMITTED', result_row_version = ?, " + + "receipt_digest = (SELECT receipt_digest FROM subscription_lifecycle_receipts WHERE request_id = ?), committed_at = ?::timestamptz " + + "WHERE resolution_request_id = ? AND state = 'PREPARED'", + committed.committedRowVersion(), + request.resolutionRequestId(), + utc(now()), + request.resolutionRequestId()); + return committed; + } + + public static final class ResolutionPreparation { + private final Request request; + private final ExpectedBinding binding; + private final long currentVersion; + private final Instant capturedAt; + private final Instant deadline; + private final TransitionResult replay; + + private ResolutionPreparation( + Request request, + ExpectedBinding binding, + long currentVersion, + Instant capturedAt, + Instant deadline, + TransitionResult replay) { + this.request = request; + this.binding = binding; + this.currentVersion = currentVersion; + this.capturedAt = capturedAt; + this.deadline = deadline; + this.replay = replay; + } + + public Request request() { + return request; + } + + public ExpectedBinding binding() { + return binding; + } + + public TransitionResult replayResult() { + return replay; + } + } + /** * Reserves currentness before an SDK read; stable request replay never issues a second * transition. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionTerminalResolution.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionTerminalResolution.java new file mode 100644 index 0000000000..e57d831350 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionTerminalResolution.java @@ -0,0 +1,159 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.text.Normalizer; +import java.time.Instant; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; + +/** + * Credential-free cancellation-resolution comparison data. Construction grants no authorization. + * The unregistered owner must invoke an explicit final authorization source under its SQL locks; + * actual Account actor/primary-authentication integration belongs to its outer composition. + */ +public final class AccountHostingSubscriptionTerminalResolution { + private AccountHostingSubscriptionTerminalResolution() {} + + public record Request( + UUID resolutionRequestId, + UUID failedRequestId, + UUID creationRequestId, + UUID subscriptionId, + UUID tenantId, + long expectedFailedOperationVersion, + long expectedSubscriptionVersion, + UUID actorAccountId, + UUID controlUiIssuanceOperationId, + String controlUiTokenHash, + UUID auditEventId, + String auditReason) { + public Request { + for (UUID id : + new UUID[] { + resolutionRequestId, + failedRequestId, + creationRequestId, + subscriptionId, + tenantId, + actorAccountId, + controlUiIssuanceOperationId, + auditEventId + }) { + AccountBillingCustomerRecord.requireUuid(id); + } + if (resolutionRequestId.equals(failedRequestId) + || expectedFailedOperationVersion < 1 + || expectedSubscriptionVersion < 1 + || expectedSubscriptionVersion >= Long.MAX_VALUE - 2) { + throw new IllegalArgumentException( + "Distinct resolution identity and advanceable versions required"); + } + requireTokenHash(controlUiTokenHash); + auditReason = requireReason(auditReason); + } + + public byte[] payload() { + return AccountHostingSubscriptionLifecycleEvidence.encode( + Map.ofEntries( + Map.entry("schemaVersion", "account-hosting-terminal-resolution/v1"), + Map.entry("outcome", "CANCELED"), + Map.entry("resolutionRequestId", resolutionRequestId.toString()), + Map.entry("failedRequestId", failedRequestId.toString()), + Map.entry("creationRequestId", creationRequestId.toString()), + Map.entry("subscriptionId", subscriptionId.toString()), + Map.entry("tenantId", tenantId.toString()), + Map.entry( + "expectedFailedOperationVersion", Long.toString(expectedFailedOperationVersion)), + Map.entry("expectedSubscriptionVersion", Long.toString(expectedSubscriptionVersion)), + Map.entry("actorAccountId", actorAccountId.toString()), + Map.entry("controlUiIssuanceOperationId", controlUiIssuanceOperationId.toString()), + Map.entry("controlUiTokenHash", controlUiTokenHash), + Map.entry("auditEventId", auditEventId.toString()), + Map.entry("auditReason", auditReason))); + } + + public String digest() { + return AccountHostingSubscriptionLifecycleEvidence.digest(payload()); + } + } + + public record LockedTarget( + Request request, UUID billingOwnerAccountId, long currentSubscriptionVersion) { + public LockedTarget { + Objects.requireNonNull(request); + AccountBillingCustomerRecord.requireUuid(billingOwnerAccountId); + } + } + + /** + * Same-transaction primary-authentication source identifiers, not authority from construction. + */ + public record AuthorizedActor( + UUID actorAccountId, + UUID controlUiIssuanceOperationId, + String controlUiTokenHash, + Instant authenticatedAt) { + public AuthorizedActor { + AccountBillingCustomerRecord.requireUuid(actorAccountId); + AccountBillingCustomerRecord.requireUuid(controlUiIssuanceOperationId); + requireTokenHash(controlUiTokenHash); + Objects.requireNonNull(authenticatedAt); + } + } + + /** + * Must revalidate the exact actual Account actor and fresh primary authentication in this SQL. + */ + @FunctionalInterface + public interface Authorization { + AuthorizedActor requireAuthorized(LockedTarget target); + } + + private static String requireReason(String reason) { + String normalized = Normalizer.normalize(Objects.requireNonNull(reason), Normalizer.Form.NFC); + try { + int bytes = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(normalized)) + .remaining(); + if (bytes > 1000 + || normalized.indexOf(0) >= 0 + || normalized + .codePoints() + .allMatch(AccountHostingSubscriptionTerminalResolution::sharedWhitespace)) { + throw new IllegalArgumentException( + "Nonblank credential-free audit reason of at most 1000 UTF-8 bytes required"); + } + } catch (CharacterCodingException failure) { + throw new IllegalArgumentException("Audit reason must contain Unicode scalars", failure); + } + return normalized; + } + + private static boolean sharedWhitespace(int value) { + return (value >= 0x0009 && value <= 0x000D) + || value == 0x0020 + || value == 0x0085 + || value == 0x00A0 + || value == 0x1680 + || (value >= 0x2000 && value <= 0x200A) + || value == 0x2028 + || value == 0x2029 + || value == 0x202F + || value == 0x205F + || value == 0x3000; + } + + private static void requireTokenHash(String hash) { + if (hash == null || !hash.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("Exact native control-ui token hash required"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/RetainedSubscriptionEvidenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/RetainedSubscriptionEvidenceRepository.java new file mode 100644 index 0000000000..5aa35ca5b9 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/RetainedSubscriptionEvidenceRepository.java @@ -0,0 +1,41 @@ +package net.firedevops.firemud.accountservice.repository; + +import static net.firedevops.firemud.accountservice.jooq.Tables.ACCOUNT_RETAINED_SUBSCRIPTION_EVIDENCE; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.List; +import net.firedevops.firemud.accountservice.entity.RetainedSubscriptionEvidence; +import org.jooq.DSLContext; +import org.springframework.stereotype.Repository; + +/** Historical evidence for Account retention/deletion checks only; no current-tenant selector. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class RetainedSubscriptionEvidenceRepository { + private final DSLContext dsl; + + public RetainedSubscriptionEvidenceRepository(DSLContext dsl) { + this.dsl = dsl; + } + + public List findHistoryByAccountId(Long accountId) { + var evidence = ACCOUNT_RETAINED_SUBSCRIPTION_EVIDENCE; + return dsl.selectFrom(evidence) + .where(evidence.ACCOUNT_ID.eq(accountId)) + .orderBy(evidence.ID.asc()) + .fetch( + row -> + new RetainedSubscriptionEvidence( + row.get(evidence.ID), + row.get(evidence.ACCOUNT_ID), + row.get(evidence.PLAN_ID), + row.get(evidence.STATUS), + row.get(evidence.STARTED_AT), + row.get(evidence.ENDED_AT), + row.get(evidence.TENANT_ID), + row.get(evidence.ENTITLEMENT_VERSION), + row.get(evidence.TENANT_AUTHORITY_GENERATION))); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/SubscriptionRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/SubscriptionRepository.java deleted file mode 100644 index 483e041c33..0000000000 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/SubscriptionRepository.java +++ /dev/null @@ -1,158 +0,0 @@ -package net.firedevops.firemud.accountservice.repository; - -import static net.firedevops.firemud.accountservice.jooq.Tables.ACCOUNTS; -import static net.firedevops.firemud.accountservice.jooq.Tables.SUBSCRIPTION; - -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import java.util.List; -import java.util.UUID; -import net.firedevops.firemud.accountservice.entity.Subscription; -import org.jooq.DSLContext; -import org.jooq.Record; -import org.springframework.stereotype.Repository; - -@Repository -@SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "Injected DSLContext is an internal Spring collaborator.") -public class SubscriptionRepository { - private final DSLContext dsl; - - public SubscriptionRepository(DSLContext dsl) { - this.dsl = dsl; - } - - public List findByTenantId(Long tenantId) { - return baseSelect() - .where(SUBSCRIPTION.TENANT_ID.eq(tenantId)) - .orderBy(SUBSCRIPTION.ID.asc()) - .fetch(this::toEntity); - } - - /** Shares the row lock with subscription writers through the JOIN commit boundary. */ - public List findByTenantIdForUpdate(Long tenantId) { - return baseSelect() - .where(SUBSCRIPTION.TENANT_ID.eq(tenantId)) - .orderBy(SUBSCRIPTION.ID.asc()) - .forUpdate() - .of(SUBSCRIPTION) - .fetch(this::toEntity); - } - - public List findByAccountId(Long accountId) { - return baseSelect() - .where(SUBSCRIPTION.ACCOUNT_ID.eq(accountId)) - .orderBy(SUBSCRIPTION.ID.asc()) - .fetch(this::toEntity); - } - - public Subscription save(Subscription entity) { - Long accountId = entity.getAccount() == null ? null : entity.getAccount().getId(); - if (entity.getId() == null) { - var inserted = - dsl.insertInto(SUBSCRIPTION) - .set(SUBSCRIPTION.ACCOUNT_ID, accountId) - .set(SUBSCRIPTION.PLAN_ID, entity.getPlanId()) - .set(SUBSCRIPTION.STATUS, entity.getStatus()) - .set(SUBSCRIPTION.STARTED_AT, entity.getStartedAt()) - .set(SUBSCRIPTION.ENDED_AT, entity.getEndedAt()) - .set(SUBSCRIPTION.TENANT_ID, entity.getTenantId()) - .set(SUBSCRIPTION.ENTITLEMENT_VERSION, 1L) - .set(SUBSCRIPTION.TENANT_AUTHORITY_GENERATION, UUID.randomUUID()) - .returningResult( - SUBSCRIPTION.ID, - SUBSCRIPTION.ENTITLEMENT_VERSION, - SUBSCRIPTION.TENANT_AUTHORITY_GENERATION) - .fetchOne(); - if (inserted == null) { - throw new IllegalStateException("Subscription insert did not return its authority state"); - } - entity.setId(inserted.get(SUBSCRIPTION.ID)); - entity.setEntitlementVersion(1L); - entity.setTenantAuthorityGeneration(inserted.get(SUBSCRIPTION.TENANT_AUTHORITY_GENERATION)); - return entity; - } - var updated = - dsl.update(SUBSCRIPTION) - .set(SUBSCRIPTION.ACCOUNT_ID, accountId) - .set(SUBSCRIPTION.PLAN_ID, entity.getPlanId()) - .set(SUBSCRIPTION.STATUS, entity.getStatus()) - .set(SUBSCRIPTION.STARTED_AT, entity.getStartedAt()) - .set(SUBSCRIPTION.ENDED_AT, entity.getEndedAt()) - .set(SUBSCRIPTION.TENANT_ID, entity.getTenantId()) - .where( - SUBSCRIPTION - .ID - .eq(entity.getId()) - .and(SUBSCRIPTION.ENTITLEMENT_VERSION.eq(entity.getEntitlementVersion())) - .and( - entity.getTenantAuthorityGeneration() == null - ? SUBSCRIPTION.TENANT_AUTHORITY_GENERATION.isNull() - : SUBSCRIPTION.TENANT_AUTHORITY_GENERATION.eq( - entity.getTenantAuthorityGeneration()))) - .returningResult( - SUBSCRIPTION.ENTITLEMENT_VERSION, SUBSCRIPTION.TENANT_AUTHORITY_GENERATION) - .fetchOne(); - if (updated == null) { - throw JooqAccountRepositorySupport.staleWrite("subscription", entity.getId()); - } - entity.setEntitlementVersion(updated.get(SUBSCRIPTION.ENTITLEMENT_VERSION)); - entity.setTenantAuthorityGeneration(updated.get(SUBSCRIPTION.TENANT_AUTHORITY_GENERATION)); - return entity; - } - - public void deleteByAccountId(Long accountId, Long tenantId) { - dsl.deleteFrom(SUBSCRIPTION) - .where(SUBSCRIPTION.ACCOUNT_ID.eq(accountId).and(SUBSCRIPTION.TENANT_ID.eq(tenantId))) - .execute(); - } - - public void deleteByAccountId(Long accountId) { - dsl.deleteFrom(SUBSCRIPTION).where(SUBSCRIPTION.ACCOUNT_ID.eq(accountId)).execute(); - } - - private org.jooq.SelectOnConditionStep baseSelect() { - return dsl.select( - SUBSCRIPTION.ID, - SUBSCRIPTION.ACCOUNT_ID, - SUBSCRIPTION.PLAN_ID, - SUBSCRIPTION.STATUS, - SUBSCRIPTION.STARTED_AT, - SUBSCRIPTION.ENDED_AT, - SUBSCRIPTION.TENANT_ID, - SUBSCRIPTION.ENTITLEMENT_VERSION, - SUBSCRIPTION.TENANT_AUTHORITY_GENERATION, - ACCOUNTS.ID, - ACCOUNTS.USERNAME, - ACCOUNTS.EMAIL, - ACCOUNTS.PASSWORD_HASH, - ACCOUNTS.ROLE, - ACCOUNTS.EMAIL_VERIFIED, - ACCOUNTS.LOGIN_AUTH_MODES) - .from(SUBSCRIPTION) - .join(ACCOUNTS) - .on(SUBSCRIPTION.ACCOUNT_ID.eq(ACCOUNTS.ID)); - } - - private Subscription toEntity(Record record) { - Subscription entity = new Subscription(); - entity.setId(record.get(SUBSCRIPTION.ID)); - entity.setAccount( - JooqAccountRepositorySupport.partialAccount( - record.get(ACCOUNTS.ID), - record.get(ACCOUNTS.USERNAME), - record.get(ACCOUNTS.EMAIL), - record.get(ACCOUNTS.PASSWORD_HASH), - record.get(ACCOUNTS.ROLE), - record.get(ACCOUNTS.EMAIL_VERIFIED), - record.get(ACCOUNTS.LOGIN_AUTH_MODES))); - entity.setPlanId(record.get(SUBSCRIPTION.PLAN_ID)); - entity.setStatus(record.get(SUBSCRIPTION.STATUS)); - entity.setStartedAt(record.get(SUBSCRIPTION.STARTED_AT)); - entity.setEndedAt(record.get(SUBSCRIPTION.ENDED_AT)); - entity.setTenantId(record.get(SUBSCRIPTION.TENANT_ID)); - entity.setEntitlementVersion(record.get(SUBSCRIPTION.ENTITLEMENT_VERSION)); - entity.setTenantAuthorityGeneration(record.get(SUBSCRIPTION.TENANT_AUTHORITY_GENERATION)); - return entity; - } -} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantOperationEntitlementWorkloadGuard.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantOperationEntitlementWorkloadGuard.java new file mode 100644 index 0000000000..2ac1413e2b --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantOperationEntitlementWorkloadGuard.java @@ -0,0 +1,75 @@ +package net.firedevops.firemud.accountservice.security; + +import io.grpc.Context; +import io.grpc.Contexts; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.Status; +import net.firedevops.firemud.account.v1.AccountTenantOperationEntitlementReadServiceGrpc; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; + +/** + * Exact method/World gate deriving its private assertion from transport TLS, never caller context. + */ +public final class AccountTenantOperationEntitlementWorkloadGuard implements ServerInterceptor { + private final Context.Key authenticatedCaller = + Context.key("tenant-operation-world-peer"); + private final String expectedWorkload; + + public AccountTenantOperationEntitlementWorkloadGuard(String namespace) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + expectedWorkload = "spiffe://firemud/ns/" + namespace + "/sa/world-management-service"; + } + + /** Only this guard's TLS interception can supply the private method-authorized assertion. */ + public String requireAuthenticatedWorldCaller() { + if (!expectedWorkload.equals(authenticatedCaller.get()) || hasSessionContext()) { + throw Status.UNAUTHENTICATED + .withDescription("Protected World workload call required") + .asRuntimeException(); + } + return expectedWorkload; + } + + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + var peer = + GrpcPeerIdentity.fromSslSession(call.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION)); + if (peer.isEmpty()) return deny(call, Status.UNAUTHENTICATED); + if (!expectedWorkload.equals(peer.orElseThrow().uri()) + || hasSessionContext() + || !AccountTenantOperationEntitlementReadServiceGrpc + .getReadTenantOperationEntitlementMethod() + .getFullMethodName() + .equals(call.getMethodDescriptor().getFullMethodName())) { + return deny(call, Status.PERMISSION_DENIED); + } + return Contexts.interceptCall( + Context.current().withValue(authenticatedCaller, peer.orElseThrow().uri()), + call, + headers, + next); + } + + private static boolean hasSessionContext() { + return SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService() + || SessionContext.getServiceName() != null + || SessionContext.getServiceInstanceId() != null; + } + + private static ServerCall.Listener deny( + ServerCall call, Status status) { + call.close( + status.withDescription("Exact protected World entitlement method required"), + new Metadata()); + return new ServerCall.Listener<>() {}; + } +} 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..1cc49b0b19 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java @@ -0,0 +1,125 @@ +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.ProvisioningClaim; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.TransitionResult; +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(); + var prepared = + Objects.requireNonNull( + transaction.execute(status -> repository.prepareProviderDispatch(claim, dispatchId))); + var dispatch = + Objects.requireNonNull( + transaction.execute(status -> repository.readProviderDispatch(prepared))); + 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 = + lifecycle.readCurrent(claim.creation().tenantId()); + 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, Committed {} + + public record Pending( + Disposition disposition, StripeHostingSubscriptionProvisioner.Result providerResult) + implements Result {} + + public record Reconciling(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/main/java/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwner.java new file mode 100644 index 0000000000..c2d2b44b6d --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwner.java @@ -0,0 +1,334 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Clock; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +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.dto.DemoTenantEntitlementSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionCurrentReceipt; +import net.firedevops.firemud.common.account.authority.RuntimeTenantOperationEntitlementEvidence; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Manually composed Account source owner for TENANT_OPERATION evaluations only. + * + *

Held source boundary: this owner and its peer-qualified receiver are manually composed and + * unregistered. The receiver must authenticate and method-authorize the exact World Management peer + * before constructing Request; parsing a workload URI and supplying UUIDs never grants authority. + * Capacity commitment, durable evaluation replay and player admission remain outside this boundary. + * Paid and demo selection is explicit and never falls back on absence. Pending/provisioning without + * a genuine current receipt remains unavailable. Every returned canonical value is captured before + * its source transaction commits; a failed commit returns no value. + */ +public final class AccountTenantOperationEntitlementOwner { + private final AccountHostingSubscriptionLifecycleService hosting; + private final AccountDemoTenantEntitlementRepository demos; + private final TransactionTemplate transaction; + private final Clock clock; + private final String expectedWorkload; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected SDK/repository collaborators remain private; copying would break owner composition.") + public AccountTenantOperationEntitlementOwner( + AccountHostingSubscriptionLifecycleService hosting, + AccountDemoTenantEntitlementRepository demos, + PlatformTransactionManager transactions, + Clock clock, + String workloadNamespace) { + this.hosting = Objects.requireNonNull(hosting); + this.demos = Objects.requireNonNull(demos); + this.clock = Objects.requireNonNull(clock); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical World Management namespace is required"); + } + expectedWorkload = + GrpcPeerIdentity.parseUri( + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service") + .orElseThrow() + .uri(); + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + } + + public RuntimeTenantOperationEntitlementEvidence evaluatePaid(Request request) { + requireRequest(request); + return hosting.readCurrentAndCapture(request.tenantId(), receipt -> paid(request, receipt)); + } + + public RuntimeTenantOperationEntitlementEvidence evaluateDemo(Request request) { + requireRequest(request); + requireNoAmbientTransaction(); + return Objects.requireNonNull( + transaction.execute( + status -> { + requireSourceTransaction(); + DemoTenantEntitlementSnapshot snapshot = demos.readCurrent(request.tenantId()); + if (!request.tenantId().equals(snapshot.canonicalTenantId())) { + throw unavailable("Demo source targets another tenant"); + } + Map facts = + facts( + request.tenantId(), + "NON_PAID_DEMO", + snapshot.subscriptionStatus(), + snapshot.gameplayAvailable(), + snapshot.allowPublicJoin(), + snapshot.allowNewGameplayBindings(), + snapshot.allowNewInstanceStarts(), + quotas( + snapshot.quotas().maxActiveSessions(), + snapshot.quotas().maxConcurrentGameInstances(), + snapshot.quotas().maxStorageBytes()), + snapshot.entitlementVersion(), + snapshot.tenantBillingSequence(), + snapshot.tenantAuthorityGeneration(), + snapshot.tenantAuthorityOutboxStreamKey(), + snapshot.tenantAuthorityOutboxSequence(), + snapshot.tenantAuthorityEventId(), + snapshot.tenantAuthorityEventDigest()); + Map source = new LinkedHashMap<>(); + source.put("sourceEvidenceDigest", snapshot.sourceEvidence().evidenceDigest()); + source.put( + "tenantAuthoritySourceVersion", + Long.toString(snapshot.tenantAuthoritySourceVersion())); + source.put("billingStream", snapshot.outboxStreamKey()); + source.put("billingSequence", Long.toString(snapshot.tenantBillingSequence())); + source.put("billingEventId", snapshot.eventId().toString()); + source.put("billingEventDigest", snapshot.eventDigest()); + return capture(request, facts, source, now()); + })); + } + + private RuntimeTenantOperationEntitlementEvidence paid( + Request request, AccountHostingSubscriptionCurrentReceipt receipt) { + requireSourceTransaction(); + Objects.requireNonNull(receipt, "Current hosting receipt is required"); + Instant evaluatedAt = now(); + if (!request.tenantId().equals(receipt.current().tenantId()) + || receipt.evaluatedAt() == null + || receipt.validUntil() == null + || evaluatedAt.isBefore(receipt.evaluatedAt()) + || !evaluatedAt.isBefore(receipt.validUntil())) { + throw unavailable("Current hosting receipt is not fresh for this tenant"); + } + var event = receipt.tenantAuthorityEvent(); + if (!request.tenantId().equals(event.tenantId()) + || receipt.tenantBillingSequence() != event.tenantBillingSequence() + || !receipt.billingEventId().equals(event.tenantBillingEventId()) + || !receipt.billingEventDigest().equals(event.tenantBillingEventDigest())) { + throw unavailable("Hosting receipt and current tenant authority disagree"); + } + var quote = receipt.current().planQuote(); + Map facts = + facts( + request.tenantId(), + "PAID_HOSTING", + receipt.subscriptionStatus().storageValue(), + receipt.gameplayAvailable(), + receipt.allowPublicJoin(), + receipt.allowNewGameplayBindings(), + receipt.allowNewInstanceStarts(), + quotas( + quote.maxActiveSessions(), + quote.maxConcurrentGameInstances(), + quote.maxStorageBytes()), + receipt.entitlementVersion(), + receipt.tenantBillingSequence(), + event.tenantAuthorityGeneration(), + event.outboxStreamKey(), + event.outboxSequence(), + event.eventId(), + event.eventDigest()); + Map source = new LinkedHashMap<>(); + source.put("receiptRequestId", receipt.receiptRequestId().toString()); + source.put("subscriptionId", receipt.current().subscriptionId().toString()); + source.put("subscriptionRowVersion", Long.toString(receipt.current().rowVersion())); + source.put("creationRequestId", receipt.current().creationRequestId().toString()); + source.put("retainedPlanQuoteDigest", quote.digest()); + source.put("sourceEvidenceDigest", event.sourceEvidence().evidenceDigest()); + source.put("tenantAuthoritySourceVersion", Long.toString(event.tenantAuthoritySourceVersion())); + source.put("billingStream", event.tenantBillingStreamKey()); + source.put("billingSequence", Long.toString(receipt.tenantBillingSequence())); + source.put("billingEventId", receipt.billingEventId().toString()); + source.put("billingEventDigest", receipt.billingEventDigest()); + return capture(request, facts, source, evaluatedAt); + } + + private static Map facts( + UUID tenantId, + String sourceKind, + String subscriptionStatus, + boolean gameplayAvailable, + boolean allowPublicJoin, + boolean allowNewGameplayBindings, + boolean allowNewInstanceStarts, + Map quotas, + long entitlementVersion, + long billingSequence, + long generation, + String authorityStream, + long authoritySequence, + UUID eventId, + String eventDigest) { + if (!TenantAuthorityEventV1Codec.streamKey(tenantId).equals(authorityStream)) { + throw unavailable("Tenant authority stream differs from requested tenant"); + } + Map facts = new LinkedHashMap<>(); + facts.put("schema", RuntimeTenantOperationEntitlementEvidence.SCHEMA); + facts.put("variant", RuntimeTenantOperationEntitlementEvidence.VARIANT); + facts.put("authorityAvailability", "AVAILABLE"); + facts.put("bundleVersion", "1"); + facts.put("tenantId", tenantId.toString()); + facts.put("sourceKind", sourceKind); + facts.put("subscriptionStatus", subscriptionStatus); + facts.put("provisioningStatus", null); + facts.put("gameplayAvailable", gameplayAvailable); + facts.put("allowPublicJoin", allowPublicJoin); + facts.put("allowNewGameplayBindings", allowNewGameplayBindings); + facts.put("allowNewInstanceStarts", allowNewInstanceStarts); + facts.put("quotas", quotas); + facts.put("entitlementVersion", Long.toString(entitlementVersion)); + facts.put("tenantBillingSequence", Long.toString(billingSequence)); + facts.put("tenantAuthorityGeneration", Long.toString(generation)); + Map cutoff = + Map.of( + "tenantAuthorityGeneration", + Long.toString(generation), + "tenantBillingSequence", + Long.toString(billingSequence), + "outboxStreamKey", + authorityStream, + "outboxSequence", + Long.toString(authoritySequence)); + facts.put( + "authorityTuple", + Map.of( + "tenantAuthorityGeneration", Map.of(tenantId.toString(), Long.toString(generation)), + "tenantBillingCutoff", Map.of(tenantId.toString(), cutoff))); + facts.put( + "outboxCheckpoints", + List.of( + Map.of( + "outboxStreamKey", + authorityStream, + "outboxSequence", + Long.toString(authoritySequence), + "sourceEventId", + eventId.toString(), + "sourceEventDigest", + eventDigest))); + return facts; + } + + private static RuntimeTenantOperationEntitlementEvidence capture( + Request request, Map facts, Map source, Instant evaluatedAt) { + requireSourceTransaction(); + String snapshot = + RuntimeTenantOperationEntitlementEvidence.canonicalDigest( + Map.of( + "schema", + "tenant-operation-entitlement-snapshot/v1", + "committedFacts", + new LinkedHashMap<>(facts), + "committedSource", + source)); + facts.put("requestId", request.requestId().toString()); + facts.put("callerWorkload", request.authenticatedCallerWorkload()); + facts.put("evaluatedAt", evaluatedAt.toString()); + facts.put("snapshotIdentity", snapshot); + facts.put( + "evaluationIdentity", + RuntimeTenantOperationEntitlementEvidence.canonicalDigest( + Map.of( + "schema", + "tenant-operation-entitlement-evaluation/v1", + "snapshotIdentity", + snapshot, + "tenantId", + request.tenantId().toString(), + "requestId", + request.requestId().toString(), + "callerWorkload", + request.authenticatedCallerWorkload(), + "evaluatedAt", + evaluatedAt.toString(), + "evaluationNonce", + UUID.randomUUID().toString()))); + return RuntimeTenantOperationEntitlementEvidence.fromOwnerEvaluation(facts); + } + + private static Map quotas(long sessions, long instances, long storage) { + return Map.of( + "maxActiveSessions", + Long.toString(sessions), + "maxConcurrentGameInstances", + Long.toString(instances), + "maxStorageBytes", + Long.toString(storage)); + } + + private Instant now() { + return clock.instant().truncatedTo(ChronoUnit.MICROS); + } + + private void requireRequest(Request request) { + Objects.requireNonNull(request, "Tenant operation request is required"); + if (!expectedWorkload.equals(request.authenticatedCallerWorkload())) { + throw new IllegalArgumentException("Expected exact same-namespace World Management peer"); + } + } + + private static void requireSourceTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw unavailable( + "Complete runtime evidence requires its writable Account source transaction"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw unavailable("Demo evaluation refuses an ambient transaction or synchronization"); + } + } + + private static IllegalStateException unavailable(String message) { + return new IllegalStateException("ENTITLEMENT_UNAVAILABLE: " + message); + } + + /** Trusted transport assertion only; construction itself does not authenticate the caller. */ + public record Request(UUID tenantId, UUID requestId, String authenticatedCallerWorkload) { + public Request { + if (tenantId == null + || tenantId.equals(new UUID(0L, 0L)) + || requestId == null + || requestId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException( + "Canonical non-nil tenant and request UUIDs are required"); + } + GrpcPeerIdentity peer = + GrpcPeerIdentity.parseUri(authenticatedCallerWorkload) + .filter(identity -> identity.uri().equals(authenticatedCallerWorkload)) + .orElseThrow( + () -> + new IllegalArgumentException("Canonical authenticated workload is required")); + if (!"world-management-service".equals(peer.service())) { + throw new IllegalArgumentException("Tenant operation requires World Management"); + } + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 4564e1e49f..756f83b446 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -13,7 +13,6 @@ import java.security.SecureRandom; import java.time.Instant; import java.time.LocalDateTime; -import java.util.Comparator; import java.util.HashMap; import java.util.HexFormat; import java.util.LinkedHashMap; @@ -24,13 +23,10 @@ import java.util.UUID; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.accountservice.AccountUuidText; -import net.firedevops.firemud.accountservice.client.EntityManagementClient; -import net.firedevops.firemud.accountservice.client.GameSessionClient; import net.firedevops.firemud.accountservice.config.AccountTokenProperties; import net.firedevops.firemud.accountservice.config.MailProperties; import net.firedevops.firemud.accountservice.dto.AccountDataExportDto; import net.firedevops.firemud.accountservice.dto.AccountDto; -import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.AccountLoginAuthModesDto; import net.firedevops.firemud.accountservice.dto.BootstrapCharacterDto; import net.firedevops.firemud.accountservice.dto.BootstrapRealmDto; @@ -55,7 +51,6 @@ import net.firedevops.firemud.accountservice.dto.UpdateAccountLoginAuthModesRequest; import net.firedevops.firemud.accountservice.dto.UpdateProfileRequest; import net.firedevops.firemud.accountservice.dto.UsernameRecoveryRequest; -import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; import net.firedevops.firemud.accountservice.dto.VerifyEmailRequest; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge; @@ -68,6 +63,7 @@ import net.firedevops.firemud.accountservice.entity.EmailVerificationToken; import net.firedevops.firemud.accountservice.entity.Profile; import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; +import net.firedevops.firemud.accountservice.entity.RetainedSubscriptionEvidence; import net.firedevops.firemud.accountservice.mapper.AccountMapper; import net.firedevops.firemud.accountservice.mapper.ProfileMapper; import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; @@ -79,10 +75,8 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.EventEvidence; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; -import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; -import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.JoinOperation; import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.PasswordResetReceipt; @@ -95,7 +89,7 @@ import net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository; import net.firedevops.firemud.accountservice.repository.PaymentTransactionRepository; import net.firedevops.firemud.accountservice.repository.ProfileRepository; -import net.firedevops.firemud.accountservice.repository.SubscriptionRepository; +import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository.Intent; @@ -113,7 +107,6 @@ import net.firedevops.firemud.common.security.JwtAuthProperties; import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.common.security.JwtUtil; -import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import org.jooq.exception.IntegrityConstraintViolationException; import org.slf4j.Logger; import org.springframework.dao.DataAccessException; @@ -122,14 +115,11 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; -import org.springframework.util.StringUtils; import org.springframework.web.server.ResponseStatusException; -import tools.jackson.databind.json.JsonMapper; @Service public class AccountServiceImpl implements AccountService { @@ -149,7 +139,6 @@ public class AccountServiceImpl implements AccountService { private static final int EMAIL_LOGIN_OTP_MAX_ATTEMPTS = 5; private static final UUID NIL_ACCOUNT_UUID = new UUID(0L, 0L); private static final SecureRandom EMAIL_LOGIN_OTP_RANDOM = new SecureRandom(); - private static final JsonMapper AUDIT_JSON = JsonMapper.builder().build(); private String gameplayDecoyPasswordVerifier; @@ -161,7 +150,6 @@ public class AccountServiceImpl implements AccountService { private final AccountAuthoritySourceEventReadback accountAuthoritySourceEventReadback; private final AccountPasswordResetDraftSourceChangeRepository passwordResetDraftSourceChanges; private final AccountAuditOutboxRepository accountAuditOutboxRepository; - private final AccountConnectScopeRepository accountConnectScopeRepository; private final AccountJoinOperationRepository accountJoinOperationRepository; private final AccountEmailLoginChallengeRepository accountEmailLoginChallengeRepository; private final AccountRealmAccessGrantRepository accountRealmAccessGrantRepository; @@ -170,7 +158,7 @@ public class AccountServiceImpl implements AccountService { private final ProfileRepository profileRepository; private final ProfileMapper profileMapper; private final PaymentTransactionRepository paymentTransactionRepository; - private final SubscriptionRepository subscriptionRepository; + private final RetainedSubscriptionEvidenceRepository retainedSubscriptionEvidenceRepository; private final ExternalAccountRepository externalAccountRepository; private final PasswordResetTokenRepository passwordResetTokenRepository; private final EmailVerificationTokenRepository emailVerificationTokenRepository; @@ -179,8 +167,6 @@ public class AccountServiceImpl implements AccountService { private final MailProperties mailProperties; private final AccountTokenProperties tokenProperties; private final JwtAuthProperties jwtAuthProperties; - private final GameSessionClient gameSessionClient; - private final EntityManagementClient entityManagementClient; private final JwtUtil jwtUtil; private final net.firedevops.firemud.accountservice.service.session.SessionService sessionService; private final TransactionTemplate joinTransactionTemplate; @@ -199,7 +185,6 @@ public AccountServiceImpl( AccountSecurityStateOperationRepository securityStateOperationRepository, AccountPasswordResetDraftSourceChangeRepository passwordResetDraftSourceChanges, AccountAuditOutboxRepository accountAuditOutboxRepository, - AccountConnectScopeRepository accountConnectScopeRepository, AccountJoinOperationRepository accountJoinOperationRepository, AccountEmailLoginChallengeRepository accountEmailLoginChallengeRepository, AccountRealmAccessGrantRepository accountRealmAccessGrantRepository, @@ -208,7 +193,7 @@ public AccountServiceImpl( ProfileRepository profileRepository, ProfileMapper profileMapper, PaymentTransactionRepository paymentTransactionRepository, - SubscriptionRepository subscriptionRepository, + RetainedSubscriptionEvidenceRepository retainedSubscriptionEvidenceRepository, ExternalAccountRepository externalAccountRepository, PasswordResetTokenRepository passwordResetTokenRepository, EmailVerificationTokenRepository emailVerificationTokenRepository, @@ -217,8 +202,6 @@ public AccountServiceImpl( MailProperties mailProperties, AccountTokenProperties tokenProperties, JwtAuthProperties jwtAuthProperties, - GameSessionClient gameSessionClient, - EntityManagementClient entityManagementClient, JwtUtil jwtUtil, net.firedevops.firemud.accountservice.service.session.SessionService sessionService, PlatformTransactionManager transactionManager) { @@ -235,7 +218,6 @@ public AccountServiceImpl( securityStateOperationRepository); this.passwordResetDraftSourceChanges = passwordResetDraftSourceChanges; this.accountAuditOutboxRepository = accountAuditOutboxRepository; - this.accountConnectScopeRepository = accountConnectScopeRepository; this.accountJoinOperationRepository = accountJoinOperationRepository; this.accountEmailLoginChallengeRepository = accountEmailLoginChallengeRepository; this.accountRealmAccessGrantRepository = accountRealmAccessGrantRepository; @@ -244,7 +226,7 @@ public AccountServiceImpl( this.profileRepository = profileRepository; this.profileMapper = profileMapper; this.paymentTransactionRepository = paymentTransactionRepository; - this.subscriptionRepository = subscriptionRepository; + this.retainedSubscriptionEvidenceRepository = retainedSubscriptionEvidenceRepository; this.externalAccountRepository = externalAccountRepository; this.passwordResetTokenRepository = passwordResetTokenRepository; this.emailVerificationTokenRepository = emailVerificationTokenRepository; @@ -253,13 +235,13 @@ public AccountServiceImpl( this.mailProperties = mailProperties; this.tokenProperties = tokenProperties; this.jwtAuthProperties = jwtAuthProperties; - this.gameSessionClient = gameSessionClient; - this.entityManagementClient = entityManagementClient; this.jwtUtil = jwtUtil; this.sessionService = sessionService; this.joinTransactionTemplate = new TransactionTemplate(transactionManager); this.joinTransactionTemplate.setPropagationBehavior( TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.joinTransactionTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + this.joinTransactionTemplate.setReadOnly(false); this.passwordResetOwnerTransaction = new TransactionTemplate(transactionManager); this.passwordResetOwnerTransaction.setPropagationBehavior( TransactionDefinition.PROPAGATION_REQUIRES_NEW); @@ -437,543 +419,53 @@ public PlayerBootstrapResult issuePlayerBootstrap(String accountIdentifier, Stri Instant.ofEpochMilli(expiresAt).toString()); } + // Numeric retained billing history cannot authorize public discovery or admission. + // The complete canonical public facade is integrated in the receiving successor. @Override - @Transactional(readOnly = true) @Timed(value = "account.bootstrap_worlds") public List listBootstrapWorlds(String bootstrapToken) { - BootstrapContext bootstrapContext = requireBootstrapContext(bootstrapToken); - Map discoveryEntitlementMemo = new HashMap<>(); - return gameSessionClient.listGameplayWorlds().stream() - .filter( - world -> - hasAdmissibleRealm( - bootstrapContext, world.getWorldSlug(), discoveryEntitlementMemo)) - .map(world -> new BootstrapWorldDto(world.getWorldSlug(), world.getDisplayName())) - .toList(); + throw publicBootstrapUnavailable(); } @Override - @Transactional(propagation = Propagation.NOT_SUPPORTED) @Timed(value = "account.bootstrap_realms") public List listBootstrapRealms(String bootstrapToken, String worldSlug) { - BootstrapContext bootstrapContext = requireBootstrapContext(bootstrapToken); - Map discoveryEntitlementMemo = new HashMap<>(); - Instant evaluatedAt = Instant.now(); - Instant expiresAt = evaluatedAt.plusMillis(tokenProperties.getConnectScopeExpirationMs()); - final List admissibleRealms; - try { - admissibleRealms = - listAdmissibleRuntimeRealmTargets(bootstrapContext, worldSlug, discoveryEntitlementMemo); - } catch (AuthenticationException ex) { - throw ex; - } catch (RuntimeException ex) { - throw admissionPointerUnavailable(ex); - } - return admissibleRealms.stream() - .map( - discovered -> { - RuntimeRealmTarget current = - requireRealmTarget( - discovered.tenantId(), discovered.worldSlug(), discovered.realmSlug()); - if (!sameRuntimeRealmAuthority(discovered, current)) { - throw admissionPointerUnavailable( - new IllegalStateException( - "Public realm authority changed during bootstrap discovery")); - } - return current; - }) - .map( - realm -> - new BootstrapRealmDto( - realm.worldSlug(), - realm.realmSlug(), - realm.realmId().toString(), - realm.displayName(), - realm.tenantId(), - realm.gameInstanceId(), - realm.pointerVersion(), - realm.catalogRevision(), - realm.playableStateNamespaceId(), - toPlayableStateScope(realm).name(), - realm.requiresCharacterSelection(), - realm.stateScope(), - realm.characterCreationPolicy(), - evaluatedAt.toString(), - expiresAt.toString(), - mintAndRetainConnectScope(bootstrapContext, realm, evaluatedAt, expiresAt))) - .toList(); + throw publicBootstrapUnavailable(); } @Override - @Transactional(readOnly = true) @Timed(value = "account.bootstrap_characters") public List listBootstrapCharacters( String bootstrapToken, String worldSlug, String realmSlug, String connectScopeId) { - BootstrapContext bootstrapContext = requireBootstrapContext(bootstrapToken); - ConnectScopeContext scopeContext = requireConnectScopeContext(connectScopeId); - validateConnectScopeAgainstBootstrap(bootstrapContext, scopeContext); - validateConnectScopeRoute(scopeContext, worldSlug, realmSlug); - RuntimeRealmTarget realm = - requireCurrentAdmissibleConnectScopeTarget(bootstrapContext, scopeContext); - UUID accountUuid = bootstrapContext.accountUuid(); - if (accountUuid == null || NIL_ACCOUNT_UUID.equals(accountUuid)) { - throw new IllegalStateException("Bootstrap Account UUID is unavailable"); - } - return entityManagementClient - .listCharactersByAccount( - realm.tenantId(), accountUuid, realm.gameInstanceId(), toPlayableStateScope(realm)) - .stream() - .sorted(Comparator.comparing(net.firedevops.firemud.entitymanagement.v1.Character::getName)) - .map( - character -> - new BootstrapCharacterDto( - character.getId(), - character.getName(), - character.getLevel(), - realm.stateScope(), - realm.characterCreationPolicy())) - .toList(); + throw publicBootstrapUnavailable(); } @Override @Timed(value = "account.public_production_join") public JoinPublicProductionResult joinPublicProduction( String bootstrapToken, JoinPublicProductionRequest request) { - BootstrapContext caller = requireBootstrapContext(bootstrapToken); - Claims callerClaims = - requireSignedTokenClaims( - bootstrapToken, - "player-bootstrap", - "CONNECT_CONTEXT_INVALID", - "Missing bootstrap token", - "Invalid bootstrap token"); - String callerBinding; - try { - callerBinding = JwtClaims.requireText(callerClaims.get("jti"), "jti"); - } catch (IllegalArgumentException ex) { - throw new AuthenticationException( - "CONNECT_CONTEXT_INVALID", "Bootstrap caller binding is missing", ex); - } - requireAuthenticationEligible(requireAccount(caller.accountId())); - return projectJoinOutcome( - joinPublicProductionForTrustedCaller(caller.accountId(), callerBinding, null, request)); + throw publicBootstrapUnavailable(); } @Override - @Transactional(propagation = Propagation.NOT_SUPPORTED) @Timed(value = "account.direct_text_connect_scope") public DirectTextJoinScope issueDirectTextConnectScope( DirectTextCallerContext caller, DirectTextJoinTarget target) { - if (caller == null - || target == null - || caller.accountId() <= 0L - || !StringUtils.hasText(caller.requestId()) - || caller.tenantId() != target.tenantId() - || !caller.realmId().equals(target.realmId()) - || caller.gameInstanceId() != target.gameInstanceId() - || !caller.playableStateNamespaceId().equals(target.playableStateNamespaceId()) - || !caller.playableStateScope().equals(target.playableStateScope())) { - throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); - } - Account account = requireAccount(caller.accountId()); - requireAuthenticationEligible(account); - RuntimeRealmTarget current = - requireRealmTarget(target.tenantId(), target.worldSlug(), target.realmSlug()); - if (!isPublicProductionRealm(current)) { - throw new AuthenticationException( - "REALM_UNAVAILABLE", "Selected public realm is unavailable"); - } - if (!current.realmId().equals(target.realmId()) - || !current.playableStateNamespaceId().equals(target.playableStateNamespaceId()) - || !current.stateScope().equals(target.playableStateScope()) - || current.gameInstanceId() != target.gameInstanceId() - || current.catalogRevision() != target.catalogRevision() - || current.pointerVersion() != target.pointerVersion()) { - throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); - } - RuntimeEntitlementsDto entitlements = - getTenantEntitlementsForRuntime(current.tenantId(), caller.requestId()); - if (!entitlements.gameplayAvailable()) { - throw new AuthenticationException( - "TENANT_BILLING_BLOCKED", "Gameplay is not available for this tenant"); - } - Instant evaluatedAt = Instant.now(); - Instant expiresAt = evaluatedAt.plusMillis(tokenProperties.getConnectScopeExpirationMs()); - requireAuthenticationAccountUuid(account); - String scopeId = - mintAndRetainConnectScope( - new BootstrapContext(caller.accountId(), account.getAccountUuid()), - current, - evaluatedAt, - expiresAt); - return new DirectTextJoinScope(scopeId, expiresAt.toString(), evaluatedAt.toString()); + throw publicBootstrapUnavailable(); } @Override @Timed(value = "account.public_production_join_internal") public JoinPublicProductionResult joinPublicProductionFromGameSession( DirectTextCallerContext caller, JoinPublicProductionRequest request) { - if (caller == null - || caller.accountId() <= 0L - || !StringUtils.hasText(caller.sessionId()) - || request == null - || !caller.requestId().equals(request.requestId())) { - throw new AuthenticationException( - "CONNECT_CONTEXT_INVALID", "JOIN caller context is missing"); - } - requireAuthenticationEligible(requireAccount(caller.accountId())); - return projectJoinOutcome( - joinPublicProductionForTrustedCaller( - caller.accountId(), caller.sessionId(), caller, request)); - } - - private JoinOutcome joinPublicProductionForTrustedCaller( - long accountId, - String callerBinding, - DirectTextCallerContext directTextCaller, - JoinPublicProductionRequest request) { - if (request == null - || !StringUtils.hasText(request.connectScopeId()) - || !StringUtils.hasText(request.requestId())) { - throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); - } - if (request.requestId().length() > JoinPublicProductionRequest.MAX_REQUEST_ID_LENGTH) { - throw new AuthenticationException( - "INVALID_ARGUMENT", "JOIN requestId exceeds the maximum length"); - } - String requestId = request.requestId(); - String scopeTokenHash = AccountJoinDigest.tokenHash(request.connectScopeId()); - Optional existing = accountJoinOperationRepository.find(requestId); - VerifiedJoinScope retained; - if (existing.isPresent()) { - JoinOperation operation = existing.orElseThrow(); - if (operation.accountId() != accountId - || !operation.callerBinding().equals(callerBinding) - || !operation.scopeTokenHash().equals(scopeTokenHash)) { - throw new AuthenticationException( - "IDEMPOTENCY_CONFLICT", "JOIN request ID was reused with different input"); - } - retained = retainedJoinScope(request.connectScopeId()); - validateDirectTextJoinScope(directTextCaller, retained); - requireMatchingJoinIntent(operation, requestId, callerBinding, retained); - } else { - ConnectScopeContext signedScope = requireConnectScopeContext(request.connectScopeId()); - retained = retainedJoinScope(request.connectScopeId()); - validateDirectTextJoinScope(directTextCaller, retained); - validateSignedJoinScope(signedScope, retained, accountId); - String intentDigest = AccountJoinDigest.intent(requestId, retained, callerBinding); - try { - joinTransactionTemplate.execute( - transactionStatus -> - accountJoinOperationRepository.insertIntent( - requestId, retained, callerBinding, intentDigest)); - } catch (RuntimeException ex) { - Optional claimReadback = safeFindJoinOperation(requestId); - if (claimReadback.isEmpty()) { - if (connectScopeEvidenceIsMissing(request.connectScopeId())) { - throw new AuthenticationException( - "CONNECT_SCOPE_INVALID", "JOIN scope evidence is unavailable", ex); - } - throw new AuthenticationException( - "AUTH_UNAVAILABLE", "JOIN request claim is uncertain; retry the same request", ex); - } - requireMatchingJoinIntent(claimReadback.orElseThrow(), requestId, callerBinding, retained); - } - JoinOperation claimed = - accountJoinOperationRepository - .find(requestId) - .orElseThrow( - () -> - new AuthenticationException( - "AUTH_UNAVAILABLE", "JOIN request claim is not yet readable")); - requireMatchingJoinIntent(claimed, requestId, callerBinding, retained); - } - - try { - JoinAttemptOutcome outcome = - joinTransactionTemplate.execute( - transactionStatus -> - executeJoinAttempt(accountId, callerBinding, requestId, retained)); - if (outcome.terminalOperation() != null) { - return replayTerminalJoinSafely(outcome.terminalOperation(), callerBinding, retained); - } - return outcome.result(); - } catch (AuthenticationException ex) { - if ("IDEMPOTENCY_CONFLICT".equals(ex.getCode())) { - throw ex; - } - recordJoinAttemptFailureAfterRollback(requestId, ex.getCode()); - return pendingJoinFailure(retained, ex.getCode()); - } catch (RuntimeException ex) { - Optional outcomeReadback = safeFindJoinOperation(requestId); - if (outcomeReadback.isPresent()) { - JoinOperation operation = outcomeReadback.orElseThrow(); - requireMatchingJoinIntent(operation, requestId, callerBinding, retained); - if (!"PENDING".equals(operation.status())) { - return replayTerminalJoinSafely(operation, callerBinding, retained); - } - recordJoinAttemptFailureAfterRollback(requestId, "AUTH_UNAVAILABLE"); - } - throw new AuthenticationException( - "AUTH_UNAVAILABLE", "JOIN outcome is uncertain; retry the same request", ex); - } - } - - private JoinAttemptOutcome executeJoinAttempt( - long accountId, String callerBinding, String requestId, VerifiedJoinScope scope) { - accountJoinOperationRepository.lockAccount(accountId); - JoinOperation operation = - accountJoinOperationRepository - .findForUpdate(requestId) - .orElseThrow(() -> new IllegalStateException("JOIN request claim disappeared")); - requireMatchingJoinIntent(operation, requestId, callerBinding, scope); - - if (!"PENDING".equals(operation.status())) { - return JoinAttemptOutcome.terminal(operation); - } - return JoinAttemptOutcome.result( - executePendingJoinAttempt(accountId, callerBinding, requestId, scope, operation)); - } - - private JoinOutcome executePendingJoinAttempt( - long accountId, - String callerBinding, - String requestId, - VerifiedJoinScope scope, - JoinOperation operation) { - if (isConnectScopeExpired(scope)) { - return failedJoin(requestId, scope, "CONNECT_SCOPE_INVALID"); - } - - JoinEvaluation evaluation = evaluateJoin(scope, false); - if (evaluation.failureCode() != null) { - if (isRetryableJoinAuthorityFailure(evaluation)) { - accountJoinOperationRepository.recordAttemptFailure( - requestId, evaluation.authorityAvailability(), evaluation.failureCode()); - return pendingJoinFailure(scope, evaluation.failureCode()); - } - return failedJoin(requestId, scope, evaluation.failureCode()); - } - if (!"AVAILABLE".equals(evaluation.authorityAvailability()) - || evaluation.allowPublicJoin() == null - || evaluation.entitlementVersion() == null) { - accountJoinOperationRepository.recordAttemptFailure( - requestId, evaluation.authorityAvailability(), "ENTITLEMENT_UNAVAILABLE"); - return pendingJoinFailure(scope, "ENTITLEMENT_UNAVAILABLE"); - } - String requestDigest = - AccountJoinDigest.request( - scope, callerBinding, evaluation.allowPublicJoin(), evaluation.entitlementVersion()); - if (operation.requestDigest() != null - && (!Integer.valueOf(1).equals(operation.requestDigestVersion()) - || !operation.requestDigest().equals(requestDigest))) { - return failedJoin(requestId, scope, "IDEMPOTENCY_CONFLICT"); - } - if (operation.requestDigest() == null) { - accountJoinOperationRepository.bindPolicyEvidence( - requestId, requestDigest, evaluation.entitlementVersion(), evaluation.allowPublicJoin()); - } - if (!evaluation.gameplayAvailable()) { - return failedJoin(requestId, scope, "TENANT_BILLING_BLOCKED"); - } - if (!evaluation.allowPublicJoin()) { - return failedJoin(requestId, scope, "PUBLIC_PRODUCTION_ADMISSION_DENIED"); - } - - JoinEvaluation commitEvaluation = evaluateJoin(scope, true); - if (commitEvaluation.failureCode() != null) { - if (isRetryableJoinAuthorityFailure(commitEvaluation)) { - accountJoinOperationRepository.recordAttemptFailure( - requestId, commitEvaluation.authorityAvailability(), commitEvaluation.failureCode()); - return pendingJoinFailure(scope, commitEvaluation.failureCode()); - } - return failedJoin(requestId, scope, commitEvaluation.failureCode()); - } - if (!"AVAILABLE".equals(commitEvaluation.authorityAvailability())) { - accountJoinOperationRepository.recordAttemptFailure( - requestId, commitEvaluation.authorityAvailability(), "ENTITLEMENT_UNAVAILABLE"); - return pendingJoinFailure(scope, "ENTITLEMENT_UNAVAILABLE"); - } - String commitDigest = - AccountJoinDigest.request( - scope, - callerBinding, - commitEvaluation.allowPublicJoin(), - commitEvaluation.entitlementVersion()); - if (!requestDigest.equals(commitDigest)) { - return failedJoin(requestId, scope, "IDEMPOTENCY_CONFLICT"); - } - if (!commitEvaluation.gameplayAvailable()) { - return failedJoin(requestId, scope, "TENANT_BILLING_BLOCKED"); - } - if (!commitEvaluation.allowPublicJoin()) { - return failedJoin(requestId, scope, "PUBLIC_PRODUCTION_ADMISSION_DENIED"); - } - AccountTenantMembership membership = - accountTenantMembershipRepository - .findByAccountIdAndTenantId(accountId, scope.tenantId()) - .orElse(null); - boolean transitioned = false; - if (membership == null) { - membership = new AccountTenantMembership(); - membership.setAccount(requireAccount(accountId)); - membership.setTenantId(scope.tenantId()); - membership.setMembershipVersion(1L); - membership.setMembershipAuthorityGeneration(1L); - membership.setLifecycleState("ACTIVE"); - membership.setGameplayAdmissionAllowed(true); - membership.setAuthorityProvenance("EXPLICIT_JOIN"); - accountTenantMembershipRepository.save(membership); - transitioned = true; - } else if ("INACTIVE".equals(membership.getLifecycleState())) { - accountJoinOperationRepository.recordCallerBoundAuthorityInvalidation(requestId); - membership.setLifecycleState("ACTIVE"); - membership.setGameplayAdmissionAllowed(true); - membership.setMembershipVersion(membership.getMembershipVersion() + 1L); - membership.setMembershipAuthorityGeneration( - membership.getMembershipAuthorityGeneration() + 1L); - membership.setAuthorityProvenance("EXPLICIT_JOIN"); - accountTenantMembershipRepository.save(membership); - transitioned = true; - } else if (!"ACTIVE".equals(membership.getLifecycleState()) - || !membership.isGameplayAdmissionAllowed()) { - return failedJoin(requestId, scope, "MEMBERSHIP_RECONCILIATION_REQUIRED"); - } - if (transitioned) { - String payload = - AUDIT_JSON.writeValueAsString( - new JoinAuditPayload( - accountId, - scope.tenantId(), - scope.worldSlug(), - scope.realmSlug(), - membership.getMembershipVersion(), - requestId)); - UUID auditEventId = - UUID.nameUUIDFromBytes( - ("account-join-audit/v1:" + requestId).getBytes(StandardCharsets.UTF_8)); - accountAuditOutboxRepository.append( - auditEventId, "tenant", scope.tenantId(), "ACCOUNT_JOINED_PUBLIC_PRODUCTION", payload); - } - accountJoinOperationRepository.finish( - requestId, - "COMMITTED", - transitioned ? "JOINED" : "ALREADY_ACTIVE", - membership.getId(), - membership.getMembershipVersion(), - membership.getMembershipAuthorityGeneration()); - return new JoinOutcome( - true, - transitioned ? "JOINED" : "ALREADY_ACTIVE", - accountId, - scope.tenantId(), - membership.getId(), - membership.getMembershipVersion(), - membership.getMembershipAuthorityGeneration(), - false); - } - - private JoinOutcome failedJoin(String requestId, VerifiedJoinScope scope, String outcomeCode) { - accountJoinOperationRepository.finish(requestId, "FAILED", outcomeCode, null, null, null); - return new JoinOutcome( - false, outcomeCode, scope.accountId(), scope.tenantId(), 0L, 0L, 0L, false); - } - - private JoinOutcome pendingJoinFailure(VerifiedJoinScope scope, String outcomeCode) { - return joinRetryFailure(scope, outcomeCode); - } - - private JoinOutcome replayTerminalJoin( - JoinOperation operation, String callerBinding, VerifiedJoinScope scope) { - if (isConnectScopeExpired(scope)) { - return joinRetryFailure(scope, "CONNECT_SCOPE_INVALID"); - } - - boolean replayUnboundFailure = - "FAILED".equals(operation.status()) && operation.requestDigest() == null; - - JoinEvaluation evaluation; - try { - evaluation = evaluateJoin(scope); - } catch (AuthenticationException ex) { - return joinRetryFailure( - scope, isStorageBackedEntitlementFailure(ex) ? ex.getCode() : "AUTH_UNAVAILABLE"); - } catch (RuntimeException ex) { - return joinRetryFailure(scope, "AUTH_UNAVAILABLE"); - } - if (evaluation.failureCode() != null) { - if ("ENTITLEMENT_UNAVAILABLE".equals(evaluation.failureCode())) { - return joinRetryFailure(scope, evaluation.failureCode()); - } - if (isRetryableJoinAuthorityFailure(evaluation)) { - return joinRetryFailure(scope, "AUTH_UNAVAILABLE"); - } - return joinRetryFailure(scope, evaluation.failureCode()); - } - if (!"AVAILABLE".equals(evaluation.authorityAvailability()) - || evaluation.allowPublicJoin() == null - || evaluation.entitlementVersion() == null) { - return joinRetryFailure(scope, "AUTH_UNAVAILABLE"); - } - if (replayUnboundFailure) { - return resultFromJoinOperation(operation, true); - } - - String currentRequestDigest = - AccountJoinDigest.request( - scope, callerBinding, evaluation.allowPublicJoin(), evaluation.entitlementVersion()); - if (!Integer.valueOf(1).equals(operation.requestDigestVersion()) - || operation.requestDigest() == null - || operation.allowPublicJoin() == null - || !operation.allowPublicJoin().equals(evaluation.allowPublicJoin()) - || operation.entitlementVersion() == null - || !operation.entitlementVersion().equals(evaluation.entitlementVersion()) - || !operation.requestDigest().equals(currentRequestDigest) - || ("COMMITTED".equals(operation.status()) - && (!evaluation.gameplayAvailable() || !evaluation.allowPublicJoin()))) { - return joinRetryFailure(scope, "IDEMPOTENCY_CONFLICT"); - } - return resultFromJoinOperation(operation, true); + throw publicBootstrapUnavailable(); } - private JoinOutcome replayTerminalJoinSafely( - JoinOperation operation, String callerBinding, VerifiedJoinScope scope) { - try { - return replayTerminalJoin(operation, callerBinding, scope); - } catch (RuntimeException policyCheckFailure) { - return joinRetryFailure(scope, "AUTH_UNAVAILABLE"); - } - } - - private JoinOutcome joinRetryFailure(VerifiedJoinScope scope, String outcomeCode) { - return new JoinOutcome( - false, outcomeCode, scope.accountId(), scope.tenantId(), 0L, 0L, 0L, false); - } - - /** Project only after the JOIN transaction has returned, preserving any committed receipt. */ - private JoinPublicProductionResult projectJoinOutcome(JoinOutcome outcome) { - return new JoinPublicProductionResult( - outcome.success(), - outcome.outcomeCode(), - responseAccountUuid(outcome.accountId()), - outcome.tenantId(), - outcome.membershipId(), - outcome.membershipVersion(), - outcome.membershipAuthorityGeneration(), - outcome.replayed()); + private AuthenticationException publicBootstrapUnavailable() { + return new AuthenticationException( + "AUTH_UNAVAILABLE", "Canonical public gameplay authority is unavailable"); } - /** Private Account row identities never escape through response projection. */ - private record JoinOutcome( - boolean success, - String outcomeCode, - long accountId, - long tenantId, - long membershipId, - long membershipVersion, - long membershipAuthorityGeneration, - boolean replayed) {} - private String responseAccountUuid(Long accountId) { try { return responseAccountUuid(requireAccount(accountId), accountId); @@ -995,258 +487,18 @@ private String responseAccountUuid(Account account, Long accountId) { } } - private boolean isConnectScopeExpired(VerifiedJoinScope scope) { - try { - return !Instant.parse(scope.connectScopeExpiresAt()).isAfter(Instant.now()); - } catch (RuntimeException ex) { - return true; - } - } - - private boolean isRetryableJoinAuthorityFailure(JoinEvaluation evaluation) { - return "UNAVAILABLE".equals(evaluation.authorityAvailability()) - || "ADMISSION_POINTER_UNAVAILABLE".equals(evaluation.failureCode()) - || "AUTH_UNAVAILABLE".equals(evaluation.failureCode()) - || "ENTITLEMENT_UNAVAILABLE".equals(evaluation.failureCode()); - } - - private VerifiedJoinScope retainedJoinScope(String connectScopeId) { - return accountConnectScopeRepository - .find(connectScopeId) - .orElseThrow( - () -> - new AuthenticationException( - "CONNECT_SCOPE_INVALID", "JOIN scope evidence is unavailable")); - } - - private boolean connectScopeEvidenceIsMissing(String connectScopeId) { - try { - return accountConnectScopeRepository.find(connectScopeId).isEmpty(); - } catch (RuntimeException ex) { - return false; - } - } - - private void validateSignedJoinScope( - ConnectScopeContext signedScope, VerifiedJoinScope retained, long accountId) { - if (retained.accountId() != accountId - || signedScope.accountId() != accountId - || signedScope.tenantId() != retained.tenantId() - || !signedScope.realmId().equals(retained.realmId()) - || !signedScope.playableStateNamespaceId().equals(retained.playableStateNamespaceId()) - || !signedScope.playableStateScope().equals(retained.playableStateScope()) - || signedScope.gameInstanceId() != retained.gameInstanceId() - || signedScope.catalogRevision() != retained.catalogRevision() - || signedScope.pointerVersion() != retained.pointerVersion() - || !signedScope.worldSlug().equals(retained.worldSlug()) - || !signedScope.realmSlug().equals(retained.realmSlug()) - || !signedScope.evaluatedAt().toString().equals(retained.evaluatedAt()) - || !signedScope - .connectScopeExpiresAt() - .toString() - .equals(retained.connectScopeExpiresAt())) { - throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); - } - } - - private void requireMatchingJoinIntent( - JoinOperation operation, String requestId, String callerBinding, VerifiedJoinScope scope) { - String expectedIntentDigest = AccountJoinDigest.intent(requestId, scope, callerBinding); - if (operation.accountId() != scope.accountId() - || !operation.realmId().equals(scope.realmId()) - || !operation.callerBinding().equals(callerBinding) - || !operation.scopeTokenHash().equals(AccountJoinDigest.tokenHash(scope.connectScopeId())) - || !operation.connectScopeDigest().equals(scope.snapshotDigest()) - || operation.intentDigestVersion() != 1 - || !operation.intentDigest().equals(expectedIntentDigest)) { - throw new AuthenticationException( - "IDEMPOTENCY_CONFLICT", "JOIN request ID was reused with different input"); - } - } - - private JoinOutcome resultFromJoinOperation(JoinOperation operation, boolean replayed) { - return new JoinOutcome( - "COMMITTED".equals(operation.status()), - operation.outcome(), - operation.accountId(), - operation.tenantId(), - operation.membershipId() == null ? 0L : operation.membershipId(), - operation.membershipVersion() == null ? 0L : operation.membershipVersion(), - operation.membershipAuthorityGeneration() == null - ? 0L - : operation.membershipAuthorityGeneration(), - replayed); - } - - private Optional safeFindJoinOperation(String requestId) { - try { - return accountJoinOperationRepository.find(requestId); - } catch (RuntimeException ignored) { - return Optional.empty(); - } - } - - private void recordJoinAttemptFailureAfterRollback(String requestId, String failureCode) { - String availability = - "ENTITLEMENT_UNAVAILABLE".equals(failureCode) ? "UNAVAILABLE" : "NOT_EVALUATED"; - try { - joinTransactionTemplate.execute( - transactionStatus -> { - accountJoinOperationRepository - .findForUpdate(requestId) - .ifPresent( - operation -> { - if ("PENDING".equals(operation.status())) { - accountJoinOperationRepository.recordAttemptFailure( - requestId, availability, failureCode); - } - }); - return null; - }); - } catch (RuntimeException ignored) { - // The durable intent stays pending, and the caller retries the same request ID. - } - } - - private void validateDirectTextJoinScope( - DirectTextCallerContext caller, VerifiedJoinScope scope) { - if (caller != null - && (caller.accountId() != scope.accountId() - || caller.tenantId() != scope.tenantId() - || !caller.realmId().equals(scope.realmId()) - || caller.gameInstanceId() != scope.gameInstanceId() - || !caller.playableStateNamespaceId().equals(scope.playableStateNamespaceId()) - || !caller.playableStateScope().equals(scope.playableStateScope()))) { - throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); - } - } - - private JoinEvaluation evaluateJoin(VerifiedJoinScope scope) { - return evaluateJoin(scope, true); - } - - private JoinEvaluation evaluateJoin(VerifiedJoinScope scope, boolean lockEntitlement) { - return evaluateJoin( - new ConnectScopeContext( - scope.accountId(), - scope.tenantId(), - scope.realmId(), - scope.worldSlug(), - scope.realmSlug(), - scope.playableStateNamespaceId(), - scope.playableStateScope(), - scope.gameInstanceId(), - scope.catalogRevision(), - scope.pointerVersion(), - Instant.parse(scope.evaluatedAt()), - Instant.parse(scope.connectScopeExpiresAt())), - lockEntitlement); - } - - private JoinEvaluation evaluateJoin(ConnectScopeContext scope, boolean lockEntitlement) { - RuntimeRealmTarget target; - try { - target = requireCurrentConnectScopeTarget(scope); - } catch (AuthenticationException ex) { - if ("CONNECT_SCOPE_MISMATCH".equals(ex.getCode()) - || "ADMISSION_POINTER_UNAVAILABLE".equals(ex.getCode())) { - return new JoinEvaluation("NOT_EVALUATED", null, null, false, ex.getCode()); - } - throw ex; - } - if (!isPublicProductionRealm(target)) { - return new JoinEvaluation( - "NOT_EVALUATED", null, null, false, "PUBLIC_PRODUCTION_ADMISSION_DENIED"); - } - try { - RuntimeEntitlementsDto entitlement = joinEntitlement(scope.tenantId(), lockEntitlement); - return new JoinEvaluation( - "AVAILABLE", - entitlement.allowPublicJoin(), - entitlement.entitlementVersion(), - entitlement.gameplayAvailable(), - null); - } catch (AuthenticationException ex) { - if ("ENTITLEMENT_UNAVAILABLE".equals(ex.getCode())) { - if (isStorageBackedEntitlementFailure(ex)) { - // Leave a potentially aborted SQL transaction before recording the failed attempt. - throw ex; - } - return new JoinEvaluation("UNAVAILABLE", null, null, false, ex.getCode()); - } - throw ex; - } - } - - private boolean isStorageBackedEntitlementFailure(AuthenticationException failure) { - return "ENTITLEMENT_UNAVAILABLE".equals(failure.getCode()) - && (failure.getCause() instanceof org.jooq.exception.DataAccessException - || failure.getCause() instanceof DataAccessException); - } - - private record JoinEvaluation( - String authorityAvailability, - Boolean allowPublicJoin, - Long entitlementVersion, - boolean gameplayAvailable, - String failureCode) {} - - private record JoinAttemptOutcome(JoinOutcome result, JoinOperation terminalOperation) { - private static JoinAttemptOutcome result(JoinOutcome result) { - return new JoinAttemptOutcome(result, null); - } - - private static JoinAttemptOutcome terminal(JoinOperation operation) { - return new JoinAttemptOutcome(null, operation); - } - } - - private RuntimeEntitlementsDto joinEntitlement(long tenantId, boolean lockSubscription) { - return readTenantEntitlements(tenantId, lockSubscription); - } - private RuntimeEntitlementsDto readTenantEntitlements(long tenantId, boolean lockSubscription) { - List rows; - try { - rows = - lockSubscription - ? subscriptionRepository.findByTenantIdForUpdate(tenantId) - : subscriptionRepository.findByTenantId(tenantId); - } catch (org.jooq.exception.MappingException | org.jooq.exception.ConfigurationException ex) { - throw ex; - } catch (org.jooq.exception.DataAccessException | DataAccessException ex) { - throw new AuthenticationException( - "ENTITLEMENT_UNAVAILABLE", - "Tenant entitlement authority is unavailable; retry later", - ex); - } - if (rows == null || rows.size() != 1 || rows.getFirst() == null) { - throw new AuthenticationException( - "ENTITLEMENT_UNAVAILABLE", "Tenant entitlement authority is missing or ambiguous"); - } - var subscription = rows.getFirst(); - if (subscription.getEntitlementVersion() <= 0L) { - throw new AuthenticationException( - "ENTITLEMENT_UNAVAILABLE", "Entitlement version is missing"); - } - return new RuntimeEntitlementsDto( - tenantId, - isGameplayAvailableStatus(subscription.getStatus()), - isPublicJoinAllowedStatus(subscription.getStatus()), - subscription.getEntitlementVersion(), - subscription.getEntitlementVersion(), - Instant.now().toString()); + // Retained numeric rows cannot supply canonical identity, provider provenance, current-row + // selection, or a committed billing checkpoint. Deny before any historical evidence read. + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", + "Canonical tenant entitlement authority is unavailable; retry later"); } @Override - @Transactional(readOnly = true) @Timed(value = "account.connect_token") public ConnectTokenResult issueConnectToken(String bootstrapToken, ConnectTokenRequest request) { - BootstrapContext bootstrapContext = requireBootstrapContext(bootstrapToken); - ConnectScopeContext scopeContext = requireConnectScopeContext(request.connectScopeId()); - validateConnectScopeAgainstBootstrap(bootstrapContext, scopeContext); - throw new AuthenticationException( - "AUTH_UNAVAILABLE", "Canonical gameplay connect-token authority is unavailable"); + throw publicBootstrapUnavailable(); } @Override @@ -1348,385 +600,11 @@ public RuntimeEntitlementsDto getTenantEntitlementsForRuntime(Long tenantId, Str } private BootstrapContext requireBootstrapContext(String bootstrapToken) { - Claims claims = - requireSignedTokenClaims( - bootstrapToken, - "player-bootstrap", - "CONNECT_CONTEXT_INVALID", - "Missing bootstrap token", - "Invalid bootstrap token"); - UUID subject = - claims.get("sub") instanceof String text ? AccountUuidText.parseOrNull(text) : null; - UUID accountUuid = - claims.get("accountId") instanceof String text ? AccountUuidText.parseOrNull(text) : null; - if (subject == null || accountUuid == null || !subject.equals(accountUuid)) { - throw new AuthenticationException("CONNECT_CONTEXT_INVALID", "Invalid bootstrap token"); - } - final Long accountId; - try { - accountId = resolveAccountStorageId(accountUuid); - } catch (IllegalArgumentException | IllegalStateException | DataAccessException ex) { - throw new AuthenticationException("AUTH_UNAVAILABLE", "Account authority is unavailable", ex); - } - if (!sessionService.isAccountSessionActive(accountId, bootstrapToken)) { - throw new AuthenticationException("CONNECT_CONTEXT_INVALID", "Bootstrap token expired"); - } - return new BootstrapContext(accountId, accountUuid); - } - - private RuntimeRealmTarget requireRealmTarget( - Long expectedTenantId, String worldSlug, String realmSlug) { - try { - List candidates = - listRuntimeRealmTargets(worldSlug, realmSlug).stream() - .filter(realm -> java.util.Objects.equals(worldSlug, realm.worldSlug())) - .filter(realm -> java.util.Objects.equals(realmSlug, realm.realmSlug())) - .filter(realm -> expectedTenantId == null || realm.tenantId() == expectedTenantId) - .toList(); - if (candidates.size() != 1) { - throw new IllegalStateException("Selected gameplay realm is absent or ambiguous"); - } - RuntimeRealmTarget candidate = candidates.getFirst(); - RuntimeRealmTarget realm = - readRuntimeRealmTarget( - gameSessionClient.getAdmissionPointer(candidate.tenantId(), worldSlug, realmSlug)); - if (realm.tenantId() != candidate.tenantId() - || !realm.realmId().equals(candidate.realmId()) - || !realm.playableStateNamespaceId().equals(candidate.playableStateNamespaceId()) - || !realm.stateScope().equals(candidate.stateScope()) - || realm.gameInstanceId() != candidate.gameInstanceId() - || realm.visible() != candidate.visible() - || realm.publicProductionRealm() != candidate.publicProductionRealm() - || realm.catalogRevision() != candidate.catalogRevision() - || realm.pointerVersion() != candidate.pointerVersion() - || !java.util.Objects.equals(worldSlug, realm.worldSlug()) - || !java.util.Objects.equals(realmSlug, realm.realmSlug())) { - throw new AuthenticationException( - "ADMISSION_POINTER_UNAVAILABLE", - "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry"); - } - return realm; - } catch (AuthenticationException ex) { - throw ex; - } catch (RuntimeException ex) { - throw admissionPointerUnavailable(ex); - } - } - - private boolean hasAdmissibleRealm( - BootstrapContext bootstrapContext, - String worldSlug, - Map discoveryEntitlementMemo) { - try { - return !listAdmissibleRuntimeRealmTargets( - bootstrapContext, worldSlug, discoveryEntitlementMemo) - .isEmpty(); - } catch (IllegalStateException ex) { - return false; - } - } - - private List listAdmissibleRuntimeRealmTargets( - BootstrapContext bootstrapContext, - String worldSlug, - Map discoveryEntitlementMemo) { - List realms = - gameSessionClient.listGameplayRealms(worldSlug); - if (realms == null) { - throw new IllegalStateException("Gameplay realm discovery returned no authority"); - } - List targets = - realms.stream() - .map(realm -> readReachableDiscoveryRealm(bootstrapContext, realm)) - .flatMap(Optional::stream) - .toList(); - validatePublicRealmCardinality(targets); - return targets.stream() - .filter( - realm -> isDiscoveryRealmAdmissible(bootstrapContext, realm, discoveryEntitlementMemo)) - .toList(); - } - - private List listRuntimeRealmTargets( - String worldSlug, String selectedRealmSlug) { - try { - List realms = - gameSessionClient.listGameplayRealms(worldSlug); - if (realms == null) { - throw new IllegalStateException("Gameplay realm discovery returned no authority"); - } - var realmStream = realms.stream(); - if (selectedRealmSlug != null) { - realmStream = - realmStream.filter( - realm -> - realm != null - && java.util.Objects.equals(selectedRealmSlug, realm.getRealmSlug())); - } - List targets = realmStream.map(this::readRuntimeRealmTarget).toList(); - validatePublicRealmCardinality(targets); - return targets; - } catch (AuthenticationException ex) { - throw ex; - } catch (RuntimeException ex) { - throw admissionPointerUnavailable(ex); - } - } - - private void validatePublicRealmCardinality(List realms) { - // The RPC is world-local: zero local public realms may be a valid private-only world when the - // tenant's public realm is in another world. Game Session owns the tenant-global zero check; - // Account can defensively reject only duplicate visible public targets returned here. - Map visiblePublicRealmCounts = - realms.stream() - .filter(this::isPublicProductionRealm) - .collect( - java.util.stream.Collectors.groupingBy( - RuntimeRealmTarget::tenantId, java.util.stream.Collectors.counting())); - if (realms.stream() - .map(RuntimeRealmTarget::tenantId) - .distinct() - .anyMatch(tenantId -> visiblePublicRealmCounts.getOrDefault(tenantId, 0L) > 1L)) { - throw admissionPointerUnavailable( - new IllegalStateException("Public production realm authority is ambiguous")); - } - } - - private Optional readReachableDiscoveryRealm( - BootstrapContext bootstrapContext, - net.firedevops.firemud.gamesession.v1.GameplayRealm realm) { - if (realm == null) { - throw admissionPointerUnavailable( - new IllegalArgumentException("Gameplay realm discovery returned a null realm")); - } - final RuntimeRealmTarget target; - try { - target = readRuntimeRealmTarget(realm); - } catch (IllegalArgumentException ex) { - if (isMalformedRealmReachable(bootstrapContext, realm)) { - throw admissionPointerUnavailable(ex); - } - return Optional.empty(); - } - return Optional.of(target); - } - - private boolean isMalformedRealmReachable( - BootstrapContext bootstrapContext, - net.firedevops.firemud.gamesession.v1.GameplayRealm realm) { - if (realm.getVisible() && realm.getPublicProductionRealm()) { - return true; - } - - final long tenantId; - try { - tenantId = requirePositiveLong(realm.getTenantId(), "tenantId"); - } catch (IllegalArgumentException ex) { - return false; - } - if (accountTenantMembershipRepository - .findByAccountIdAndTenantId(bootstrapContext.accountId(), tenantId) - .filter(AccountTenantMembership::isGameplayAdmissionAllowed) - .isEmpty()) { - return false; - } - if (!hasRealmAccessGrant( - bootstrapContext.accountId(), tenantId, realm.getWorldSlug(), realm.getRealmSlug())) { - return false; - } - return true; - } - - private AuthenticationException admissionPointerUnavailable(Throwable cause) { - return new AuthenticationException( - "ADMISSION_POINTER_UNAVAILABLE", - "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry", - cause); - } - - private boolean isDiscoveryRealmAdmissible( - BootstrapContext bootstrapContext, - RuntimeRealmTarget realm, - Map discoveryEntitlementMemo) { - if (!hasRealmAdmissionAccess(bootstrapContext, realm)) { - return false; - } - RuntimeEntitlementsDto entitlements = - discoveryEntitlementMemo.computeIfAbsent( - realm.tenantId(), - tenantId -> getTenantEntitlementsForRuntime(tenantId, "bootstrap-discovery")); - return entitlements.gameplayAvailable(); - } - - private boolean hasRealmAdmissionAccess( - BootstrapContext bootstrapContext, RuntimeRealmTarget realm) { - long tenantId = realm.tenantId(); - if (!isPublicProductionRealm(realm)) { - if (accountTenantMembershipRepository - .findByAccountIdAndTenantId(bootstrapContext.accountId(), tenantId) - .filter(AccountTenantMembership::isGameplayAdmissionAllowed) - .isEmpty()) { - return false; - } - if (!hasRealmAccessGrant( - bootstrapContext.accountId(), tenantId, realm.worldSlug(), realm.realmSlug())) { - return false; - } - } - return true; - } - - private boolean isPublicProductionRealm(RuntimeRealmTarget realm) { - return realm.visible() && realm.publicProductionRealm(); - } - - private boolean sameRuntimeRealmAuthority( - RuntimeRealmTarget expected, RuntimeRealmTarget actual) { - return expected.tenantId() == actual.tenantId() - && expected.realmId().equals(actual.realmId()) - && expected.playableStateNamespaceId().equals(actual.playableStateNamespaceId()) - && expected.gameInstanceId() == actual.gameInstanceId() - && expected.worldSlug().equals(actual.worldSlug()) - && expected.realmSlug().equals(actual.realmSlug()) - && expected.pointerVersion() == actual.pointerVersion() - && expected.catalogRevision() == actual.catalogRevision() - && expected.visible() == actual.visible() - && expected.publicProductionRealm() == actual.publicProductionRealm() - && expected.stateScope().equals(actual.stateScope()) - && expected.characterCreationPolicy().equals(actual.characterCreationPolicy()) - && expected.requiresCharacterSelection() == actual.requiresCharacterSelection(); - } - - private String mintConnectScopeId( - BootstrapContext bootstrapContext, - RuntimeRealmTarget realm, - Instant evaluatedAt, - Instant expiresAt) { - long expirationMs = Math.max(1L, expiresAt.toEpochMilli() - evaluatedAt.toEpochMilli()); - return mintToken( - bootstrapContext.accountUuid().toString(), - expirationMs, - Map.ofEntries( - Map.entry("aud", "bootstrap-connect-scope"), - Map.entry("accountId", bootstrapContext.accountUuid().toString()), - Map.entry("tenantId", realm.tenantId()), - Map.entry("realmId", realm.realmId().toString()), - Map.entry("worldSlug", realm.worldSlug()), - Map.entry("realmSlug", realm.realmSlug()), - Map.entry("playableStateNamespaceId", realm.playableStateNamespaceId()), - Map.entry("playableStateScope", realm.stateScope()), - Map.entry("gameInstanceId", realm.gameInstanceId()), - Map.entry("catalogRevision", realm.catalogRevision()), - Map.entry("pointerVersion", realm.pointerVersion()), - Map.entry("evaluatedAt", evaluatedAt.toString()), - Map.entry("connectScopeExpiresAt", expiresAt.toString()), - Map.entry( - "jti", - stableId( - "connect-scope", - bootstrapContext.accountId(), - Long.toString(realm.tenantId()), - realm.worldSlug(), - realm.realmSlug(), - realm.pointerVersion(), - evaluatedAt.toString())))); - } - - private String mintAndRetainConnectScope( - BootstrapContext caller, RuntimeRealmTarget realm, Instant evaluatedAt, Instant expiresAt) { - try { - if (!Long.valueOf(caller.accountId()).equals(resolveAccountStorageId(caller.accountUuid()))) { - throw new IllegalStateException("Scope Account UUID resolved to a different owner"); - } - } catch (IllegalArgumentException | IllegalStateException | DataAccessException ex) { - throw new AuthenticationException("AUTH_UNAVAILABLE", "Account authority is unavailable", ex); - } - String connectScopeId = mintConnectScopeId(caller, realm, evaluatedAt, expiresAt); - if (isPublicProductionRealm(realm)) { - VerifiedJoinScope pending = - new VerifiedJoinScope( - connectScopeId, - caller.accountId(), - realm.tenantId(), - realm.realmId(), - realm.worldSlug(), - realm.realmSlug(), - realm.playableStateNamespaceId(), - realm.stateScope(), - realm.gameInstanceId(), - realm.catalogRevision(), - realm.pointerVersion(), - evaluatedAt.toString(), - expiresAt.toString(), - ""); - accountConnectScopeRepository.insert( - new VerifiedJoinScope( - pending.connectScopeId(), - pending.accountId(), - pending.tenantId(), - pending.realmId(), - pending.worldSlug(), - pending.realmSlug(), - pending.playableStateNamespaceId(), - pending.playableStateScope(), - pending.gameInstanceId(), - pending.catalogRevision(), - pending.pointerVersion(), - pending.evaluatedAt(), - pending.connectScopeExpiresAt(), - AccountJoinDigest.scope(pending))); - } - return connectScopeId; - } - - private ConnectScopeContext requireConnectScopeContext(String connectScopeId) { - Claims claims = - requireSignedTokenClaims( - connectScopeId, - "bootstrap-connect-scope", - "CONNECT_SCOPE_INVALID", - INVALID_CONNECT_SCOPE_MESSAGE, - INVALID_CONNECT_SCOPE_MESSAGE); - try { - JwtClaims.SignedGameplayRoutingClaims routingClaims = - JwtClaims.requireSignedGameplayRoutingClaims( - claims, "signed token account subject mismatch"); - Instant connectScopeExpiresAt = parseInstant(claims.get("connectScopeExpiresAt")); - Instant evaluatedAt = parseInstant(claims.get("evaluatedAt")); - if (connectScopeExpiresAt == null) { - throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); - } - if (evaluatedAt == null) { - throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); - } - UUID realmId = requireCanonicalRealmId(claims.get("realmId")); - String namespace = - JwtClaims.requireText(claims.get("playableStateNamespaceId"), "playableStateNamespaceId"); - String scope = JwtClaims.requireText(claims.get("playableStateScope"), "playableStateScope"); - long catalogRevision = requirePositiveLong(claims.get("catalogRevision"), "catalogRevision"); - final Long accountId; - try { - accountId = resolveAccountStorageId(UUID.fromString(routingClaims.accountId())); - } catch (IllegalArgumentException | IllegalStateException | DataAccessException ex) { - throw new AuthenticationException( - "AUTH_UNAVAILABLE", "Account authority is unavailable", ex); - } - return new ConnectScopeContext( - accountId, - routingClaims.tenantId(), - realmId, - routingClaims.worldSlug(), - routingClaims.realmSlug(), - namespace, - scope, - routingClaims.gameInstanceId(), - catalogRevision, - routingClaims.pointerVersion(), - evaluatedAt, - connectScopeExpiresAt); - } catch (IllegalArgumentException ex) { - throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE, ex); - } + var caller = + new net.firedevops.firemud.accountservice.service.session + .AccountPlayerBootstrapCallerVerifier(jwtUtil, accountRepository, sessionService) + .requireCaller(bootstrapToken); + return new BootstrapContext(caller.accountId(), caller.accountUuid()); } private Claims requireSignedTokenClaims( @@ -1754,93 +632,6 @@ private Claims requireSignedTokenClaims( } } - private void validateConnectScopeAgainstBootstrap( - BootstrapContext bootstrapContext, ConnectScopeContext scopeContext) { - if (scopeContext.accountId() != bootstrapContext.accountId()) { - throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); - } - } - - private void validateConnectScopeRoute( - ConnectScopeContext scopeContext, String worldSlug, String realmSlug) { - if (!java.util.Objects.equals(scopeContext.worldSlug(), worldSlug) - || !java.util.Objects.equals(scopeContext.realmSlug(), realmSlug)) { - throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); - } - } - - private RuntimeRealmTarget requireCurrentConnectScopeTarget(ConnectScopeContext scopeContext) { - RuntimeRealmTarget currentRealm = - requireRealmTarget( - scopeContext.tenantId(), scopeContext.worldSlug(), scopeContext.realmSlug()); - if (currentRealm.tenantId() != scopeContext.tenantId() - || !currentRealm.realmId().equals(scopeContext.realmId()) - || !currentRealm.playableStateNamespaceId().equals(scopeContext.playableStateNamespaceId()) - || !currentRealm.stateScope().equals(scopeContext.playableStateScope()) - || currentRealm.gameInstanceId() != scopeContext.gameInstanceId() - || currentRealm.catalogRevision() != scopeContext.catalogRevision() - || currentRealm.pointerVersion() != scopeContext.pointerVersion()) { - throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); - } - return currentRealm; - } - - private RuntimeRealmTarget requireCurrentAdmissibleConnectScopeTarget( - BootstrapContext bootstrapContext, ConnectScopeContext scopeContext) { - RuntimeRealmTarget currentRealm = requireCurrentConnectScopeTarget(scopeContext); - RuntimeEntitlementsDto entitlements = - getTenantEntitlementsForRuntime(currentRealm.tenantId(), "bootstrap-characters"); - if (!entitlements.gameplayAvailable()) { - throw new AuthenticationException( - "TENANT_BILLING_BLOCKED", "Gameplay is not available for this tenant"); - } - - boolean publicProductionRealm = isPublicProductionRealm(currentRealm); - Optional maybeMembership = - accountTenantMembershipRepository.findByAccountIdAndTenantId( - bootstrapContext.accountId(), currentRealm.tenantId()); - if (maybeMembership.isPresent() - && "INACTIVE".equals(maybeMembership.orElseThrow().getLifecycleState()) - && publicProductionRealm) { - if (!entitlements.allowPublicJoin()) { - throw new AuthenticationException( - "PUBLIC_PRODUCTION_ADMISSION_DENIED", - "Public joining is not allowed for the selected game"); - } - throw new AuthenticationException("JOIN_REQUIRED", JOIN_REQUIRED_CHARACTERS_MESSAGE); - } - if (maybeMembership.isPresent() - && !maybeMembership.orElseThrow().isGameplayAdmissionAllowed()) { - throw new AuthenticationException( - "CONNECT_TOKEN_REJECTED", "Gameplay admission is not allowed for this account"); - } - if (maybeMembership.isEmpty()) { - if (!publicProductionRealm) { - throw new AuthenticationException( - "NON_PUBLIC_ENROLLMENT_REQUIRED", - "Existing game membership is required for this non-public realm"); - } - if (!entitlements.allowPublicJoin()) { - throw new AuthenticationException( - "PUBLIC_PRODUCTION_ADMISSION_DENIED", - "Public joining is not allowed for the selected game"); - } - throw new AuthenticationException("JOIN_REQUIRED", JOIN_REQUIRED_CHARACTERS_MESSAGE); - } - - if (!publicProductionRealm - && !hasRealmAccessGrant( - bootstrapContext.accountId(), - currentRealm.tenantId(), - currentRealm.worldSlug(), - currentRealm.realmSlug())) { - throw new AuthenticationException( - "ADMISSION_POINTER_UNAVAILABLE", - "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry"); - } - return currentRealm; - } - private Optional findAccountForAuthentication(String usernameOrEmail) { Optional emailMatch = accountRepository.findByEmail(EmailCanonicalization.normalize(usernameOrEmail)); @@ -2248,12 +1039,6 @@ private long requireAccountStorageId(Account account, UUID accountUuid) { return account.getId(); } - private boolean hasRealmAccessGrant( - Long accountId, Long tenantId, String worldSlug, String realmSlug) { - return accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( - accountId, tenantId, worldSlug, realmSlug); - } - private String mintToken(String subject, long expirationMs, Map claims) { return jwtUtil.generateToken(subject, expirationMs, claims); } @@ -2274,56 +1059,6 @@ private Map authenticationTokenClaims(String audience, Account a UUID.randomUUID().toString()); } - private Instant parseInstant(Object value) { - if (value == null) { - return null; - } - try { - return Instant.parse(value.toString()); - } catch (RuntimeException ex) { - return null; - } - } - - private String stableId(Object... components) { - try { - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - for (Object component : components) { - digest.update(String.valueOf(component).getBytes(StandardCharsets.UTF_8)); - digest.update((byte) 0); - } - byte[] encoded = digest.digest(); - StringBuilder builder = new StringBuilder(encoded.length * 2); - for (byte value : encoded) { - builder.append(Character.forDigit((value >> 4) & 0xF, 16)); - builder.append(Character.forDigit(value & 0xF, 16)); - } - return builder.toString(); - } catch (NoSuchAlgorithmException ex) { - throw new IllegalStateException("Missing SHA-256 implementation", ex); - } - } - - private boolean isGameplayAvailableStatus(String status) { - if (status == null) { - return false; - } - return switch (status.trim().toLowerCase(java.util.Locale.ROOT)) { - case "active", "trialing", "past_due", "grace" -> true; - default -> false; - }; - } - - private boolean isPublicJoinAllowedStatus(String status) { - if (status == null) { - return false; - } - return switch (status.trim().toLowerCase(java.util.Locale.ROOT)) { - case "active", "trialing", "past_due" -> true; - default -> false; - }; - } - @Override @Transactional(readOnly = true) @Timed(value = "account.get_profile") @@ -2474,9 +1209,9 @@ public void deleteAccount(Long accountId) { "ACCOUNT_DELETE_JOIN_RECEIPT_RETAINED", "Account JOIN receipts require retention and deletion reconciliation"); } - List subscriptions = - subscriptionRepository.findByAccountId(accountId); - Optional blockingSubscription = + List subscriptions = + retainedSubscriptionEvidenceRepository.findHistoryByAccountId(accountId); + Optional blockingSubscription = subscriptions.stream().filter(this::isNonterminalSubscription).findFirst(); if (blockingSubscription.isPresent()) { throw new AccountLifecycleException( @@ -2489,18 +1224,17 @@ public void deleteAccount(Long accountId) { + "deletion reconciliation are implemented"); } - private boolean isNonterminalSubscription( - net.firedevops.firemud.accountservice.entity.Subscription subscription) { + private boolean isNonterminalSubscription(RetainedSubscriptionEvidence subscription) { String status = - subscription.getStatus() == null + subscription.status() == null ? "" - : subscription.getStatus().trim().toLowerCase(java.util.Locale.ROOT); + : subscription.status().trim().toLowerCase(java.util.Locale.ROOT); boolean terminalStatus = switch (status) { case "canceled", "cancelled", "ended", "expired" -> true; default -> false; }; - return !terminalStatus || subscription.getEndedAt() == null; + return !terminalStatus || subscription.endedAt() == null; } @Override @@ -3396,176 +2130,4 @@ public void afterCommit() { } private record BootstrapContext(long accountId, UUID accountUuid) {} - - private record JoinAuditPayload( - long accountId, - long tenantId, - String worldSlug, - String realmSlug, - long membershipVersion, - String requestId) {} - - private RuntimeRealmTarget readRuntimeRealmTarget( - net.firedevops.firemud.gamesession.v1.GameplayRealm realm) { - return buildRuntimeRealmTarget( - realm.getTenantId(), - realm.getRealmId(), - realm.getPlayableStateNamespaceId(), - realm.getGameInstanceId(), - realm.getCatalogRevision(), - realm.getPointerVersion(), - realm.getWorldSlug(), - realm.getRealmSlug(), - realm.getVisible(), - realm.getPublicProductionRealm(), - realm.getStateScope(), - realm.getCharacterCreationPolicy(), - realm.getRequiresCharacterSelection(), - realm.getDisplayName()); - } - - private RuntimeRealmTarget readRuntimeRealmTarget( - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer realm) { - return buildRuntimeRealmTarget( - realm.getTenantId(), - realm.getRealmId(), - realm.getPlayableStateNamespaceId(), - realm.getGameInstanceId(), - realm.getCatalogRevision(), - realm.getPointerVersion(), - realm.getWorldSlug(), - realm.getRealmSlug(), - realm.getVisible(), - realm.getPublicProductionRealm(), - realm.getStateScope(), - realm.getCharacterCreationPolicy(), - realm.getRequiresCharacterSelection(), - realm.getRealmDisplayName()); - } - - private RuntimeRealmTarget buildRuntimeRealmTarget( - String tenantIdText, - String realmIdText, - String playableStateNamespaceId, - String gameInstanceIdText, - long catalogRevision, - long pointerVersion, - String worldSlug, - String realmSlug, - boolean visible, - boolean publicProductionRealm, - String stateScope, - String characterCreationPolicy, - boolean requiresCharacterSelection, - String displayName) { - long tenantId = requirePositiveLong(tenantIdText, "tenantId"); - UUID realmId = requireCanonicalRealmId(realmIdText); - long gameInstanceId = requirePositiveLong(gameInstanceIdText, "gameInstanceId"); - String canonicalPlayableStateNamespaceId = - requireCanonicalPlayableStateNamespaceId(playableStateNamespaceId); - if (catalogRevision <= 0) { - throw new IllegalArgumentException("catalogRevision must be positive"); - } - if (pointerVersion <= 0) { - throw new IllegalArgumentException("pointerVersion must be positive"); - } - if (!StringUtils.hasText(worldSlug)) { - throw new IllegalArgumentException("worldSlug is required"); - } - if (!StringUtils.hasText(realmSlug)) { - throw new IllegalArgumentException("realmSlug is required"); - } - if (!"SHARED".equals(stateScope) && !"ISOLATED".equals(stateScope)) { - throw new IllegalArgumentException("stateScope must be SHARED or ISOLATED"); - } - return new RuntimeRealmTarget( - tenantId, - realmId, - canonicalPlayableStateNamespaceId, - gameInstanceId, - worldSlug, - realmSlug, - pointerVersion, - catalogRevision, - visible, - publicProductionRealm, - stateScope, - characterCreationPolicy, - requiresCharacterSelection, - displayName); - } - - private PlayableStateScope toPlayableStateScope(RuntimeRealmTarget realm) { - if ("SHARED".equals(realm.stateScope())) { - return PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED; - } - if ("ISOLATED".equals(realm.stateScope())) { - return PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED; - } - throw new IllegalArgumentException("stateScope must be SHARED or ISOLATED"); - } - - private long requirePositiveLong(Object value, String field) { - return JwtClaims.requireLong(value, field, false); - } - - private UUID requireCanonicalRealmId(Object value) { - if (!(value instanceof String text) || text.isBlank()) { - throw new IllegalArgumentException("realmId must be a canonical UUID"); - } - try { - UUID realmId = UUID.fromString(text); - if (!realmId.toString().equals(text)) { - throw new IllegalArgumentException("realmId must be a canonical UUID"); - } - return realmId; - } catch (IllegalArgumentException ex) { - throw new IllegalArgumentException("realmId must be a canonical UUID", ex); - } - } - - private String requireCanonicalPlayableStateNamespaceId(String value) { - if (!StringUtils.hasText(value)) { - throw new IllegalArgumentException("playableStateNamespaceId is required"); - } - try { - UUID namespaceId = UUID.fromString(value); - if (!namespaceId.toString().equals(value)) { - throw new IllegalArgumentException("playableStateNamespaceId must be a canonical UUID"); - } - return value; - } catch (IllegalArgumentException ex) { - throw new IllegalArgumentException("playableStateNamespaceId must be a canonical UUID", ex); - } - } - - private record ConnectScopeContext( - long accountId, - long tenantId, - UUID realmId, - String worldSlug, - String realmSlug, - String playableStateNamespaceId, - String playableStateScope, - long gameInstanceId, - long catalogRevision, - long pointerVersion, - Instant evaluatedAt, - Instant connectScopeExpiresAt) {} - - private record RuntimeRealmTarget( - long tenantId, - UUID realmId, - String playableStateNamespaceId, - long gameInstanceId, - String worldSlug, - String realmSlug, - long pointerVersion, - long catalogRevision, - boolean visible, - boolean publicProductionRealm, - String stateScope, - String characterCreationPolicy, - boolean requiresCharacterSelection, - String displayName) {} } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantOperationEntitlementGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantOperationEntitlementGrpcService.java new file mode 100644 index 0000000000..705cba6dae --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantOperationEntitlementGrpcService.java @@ -0,0 +1,122 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.TlsServerCredentials; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.Objects; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.TrustManagerFactory; +import net.firedevops.firemud.account.v1.AccountTenantOperationEntitlementReadServiceGrpc; +import net.firedevops.firemud.account.v1.ReadTenantOperationEntitlementRequest; +import net.firedevops.firemud.account.v1.ReadTenantOperationEntitlementResponse; +import net.firedevops.firemud.accountservice.security.AccountTenantOperationEntitlementWorkloadGuard; +import net.firedevops.firemud.accountservice.service.AccountTenantOperationEntitlementOwner; +import net.firedevops.firemud.common.account.authority.RuntimeTenantOperationEntitlementGrpcCodec; +import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; +import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered Account owner receiver. No component annotation, capacity commit, or player gate. + */ +public final class AccountTenantOperationEntitlementGrpcService + extends AccountTenantOperationEntitlementReadServiceGrpc + .AccountTenantOperationEntitlementReadServiceImplBase { + private final AccountTenantOperationEntitlementOwner owner; + private final String namespace; + private final AccountTenantOperationEntitlementWorkloadGuard guard; + + public AccountTenantOperationEntitlementGrpcService( + AccountTenantOperationEntitlementOwner owner, String namespace) { + this.owner = Objects.requireNonNull(owner); + this.guard = new AccountTenantOperationEntitlementWorkloadGuard(namespace); + this.namespace = namespace; + } + + /** + * Explicit private composition, requiring real client certificates. Returns an unstarted server. + */ + public Server createUnregisteredServer( + String address, KeyManagerFactory keys, TrustManagerFactory trust) { + var factory = + new BoundedGrpcServerFactory( + Objects.requireNonNull(address), + List.of(), + Objects.requireNonNull(keys), + Objects.requireNonNull(trust), + TlsServerCredentials.ClientAuth.REQUIRE, + GrpcRequestBytePolicy.ordinary(), + RuntimeTenantOperationEntitlementGrpcCodec.MAX_REQUEST_WIRE_BYTES); + factory.addService(ServerInterceptors.interceptForward(this, guard)); + return factory.createServer(); + } + + @Override + public void readTenantOperationEntitlement( + ReadTenantOperationEntitlementRequest wire, + StreamObserver observer) { + Objects.requireNonNull(observer); + final String authenticatedCaller; + try { + authenticatedCaller = guard.requireAuthenticatedWorldCaller(); + } catch (StatusRuntimeException denied) { + fail(observer, denied.getStatus()); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + fail(observer, Status.FAILED_PRECONDITION); + return; + } + final RuntimeTenantOperationEntitlementGrpcCodec.Request request; + if (wire == null) { + fail(observer, Status.INVALID_ARGUMENT); + return; + } + try { + request = RuntimeTenantOperationEntitlementGrpcCodec.parseRequest(wire); + } catch (IllegalArgumentException invalid) { + fail(observer, Status.INVALID_ARGUMENT); + return; + } + if (!namespace.equals(request.targetNamespace())) { + fail(observer, Status.PERMISSION_DENIED); + return; + } + final ReadTenantOperationEntitlementResponse response; + try { + var sourceRequest = + new AccountTenantOperationEntitlementOwner.Request( + request.tenantId(), request.requestId(), authenticatedCaller); + var evidence = + switch (request.sourceKind()) { + case PAID_HOSTING -> owner.evaluatePaid(sourceRequest); + case NON_PAID_DEMO -> owner.evaluateDemo(sourceRequest); + }; + response = RuntimeTenantOperationEntitlementGrpcCodec.toResponse(request, evidence); + } catch (RuntimeException unavailableSource) { + // No positive evidence, alternate source, or exception details escape an unavailable + // evaluation. + fail(observer, Status.UNAVAILABLE); + return; + } + try { + observer.onNext(response); + } catch (RuntimeException callbackFailure) { + fail(observer, Status.INTERNAL); + return; + } + observer.onCompleted(); + } + + private static void fail(StreamObserver observer, Status status) { + observer.onError( + Status.fromCode(status.getCode()) + .withDescription("Tenant-operation entitlement evidence is unavailable") + .asRuntimeException()); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java index 3e6c459e01..23ccaf27d4 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java @@ -10,7 +10,6 @@ import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.PaymentTransactionRepository; -import net.firedevops.firemud.accountservice.repository.SubscriptionRepository; import net.firedevops.firemud.accountservice.service.PaymentService; import net.firedevops.firemud.common.LoggingUtil; import org.slf4j.Logger; @@ -23,7 +22,6 @@ public class PaymentServiceImpl implements PaymentService { private final AccountRepository accountRepository; private final AccountTenantMembershipRepository accountTenantMembershipRepository; private final PaymentTransactionRepository paymentTransactionRepository; - private final SubscriptionRepository subscriptionRepository; private final StripeClient stripeClient; @SuppressFBWarnings( @@ -33,12 +31,10 @@ public PaymentServiceImpl( AccountRepository accountRepository, AccountTenantMembershipRepository accountTenantMembershipRepository, PaymentTransactionRepository paymentTransactionRepository, - SubscriptionRepository subscriptionRepository, StripeClient stripeClient) { this.accountRepository = accountRepository; this.accountTenantMembershipRepository = accountTenantMembershipRepository; this.paymentTransactionRepository = paymentTransactionRepository; - this.subscriptionRepository = subscriptionRepository; this.stripeClient = stripeClient; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionService.java new file mode 100644 index 0000000000..3e677bfa09 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionService.java @@ -0,0 +1,188 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.time.Clock; +import java.time.temporal.ChronoUnit; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.TransitionResult; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionTerminalResolution.AuthorizedActor; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionTerminalResolution.Request; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.FenceRejectedException; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiActorService.AccountAuthenticatedActor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Manually composed same-billing-owner cancellation recovery. Current Account identity and fresh + * primary authentication precede the final guarded mutation in its owner transaction. A role, + * caller-supplied actor, expired observation or provider lookup failure cannot clear the hold. No + * HTTP route, global intervention, provider cancellation, registration or activation is added. + */ +public final class AccountHostingSubscriptionTerminalResolutionService { + private final AccountControlUiActorService actors; + private final AccountServiceImpl primaryAuthentication; + private final AccountHostingSubscriptionLifecycleRepository repository; + private final StripeHostingSubscriptionObserver observer; + private final Clock clock; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected Account owner collaborators are retained privately and never exposed.") + public AccountHostingSubscriptionTerminalResolutionService( + AccountControlUiActorService actors, + AccountServiceImpl primaryAuthentication, + AccountHostingSubscriptionLifecycleRepository repository, + StripeHostingSubscriptionObserver observer, + Clock clock) { + this.actors = Objects.requireNonNull(actors); + this.primaryAuthentication = Objects.requireNonNull(primaryAuthentication); + this.repository = Objects.requireNonNull(repository); + this.observer = Objects.requireNonNull(observer); + this.clock = Objects.requireNonNull(clock); + } + + /** + * The input identifies the exact failed owner operation; it supplies no actor or authorization. + * The final primary-authentication call is purpose-local and immediate, rather than reusing a + * game-creation reauthentication grant or treating a control-ui token's issue time as step-up. + */ + public TransitionResult resolve(String controlUiJwt, String email, String secret, Input input) { + outsideSql(); + Objects.requireNonNull(input, "Exact resolution input is required"); + var prepared = + actors.withCurrentAccount( + controlUiJwt, actor -> repository.prepareTerminalResolution(input.request(actor))); + if (prepared.replayResult() != null) { + // This is an authenticated exact-result read, not another mutation or reauthentication. + return prepared.replayResult(); + } + requireCredentials(email, secret); + outsideSql(); + var observed = observer.observe(prepared.binding()); + outsideSql(); + Attempt attempt = + actors.withCurrentAccount( + controlUiJwt, + actor -> { + requireExactActor(prepared.request(), actor); + try { + return new Attempt( + repository.applyTerminalResolution( + prepared, + observed, + target -> { + requireExactActor(target.request(), actor); + if (!actor.accountId().equals(target.billingOwnerAccountId())) { + throw new FenceRejectedException( + "Only the exact current billing-owner subject may resolve"); + } + requireWritableOwnerTransaction(); + AccountServiceImpl.ControlUiPrimaryIdentity actual; + try { + actual = + primaryAuthentication.authenticateControlUiPrimaryIdentity( + email, secret); + } catch (AuthenticationException denied) { + // The repository invokes this callback before its first mutation. + // Returning the failure from the enclosing transaction preserves real + // failed-login accounting without writing a resolution or consuming + // OTP. + throw new PrimaryAuthenticationDenied(denied.getCode()); + } + if (!actor.accountId().equals(actual.accountId())) { + throw new FenceRejectedException( + "Primary authentication belongs to another Account"); + } + return new AuthorizedActor( + actor.accountId(), + actor.issuanceOperationId(), + actor.tokenHash(), + clock.instant().truncatedTo(ChronoUnit.MICROS)); + }), + null); + } catch (PrimaryAuthenticationDenied denied) { + return new Attempt(null, denied.code); + } + }); + if (attempt.failureCode != null) { + throw new AuthenticationException(attempt.failureCode, "Account reauthentication failed"); + } + return Objects.requireNonNull(attempt.result); + } + + private static void requireExactActor(Request request, AccountAuthenticatedActor actor) { + if (!request.actorAccountId().equals(actor.accountId()) + || !request.controlUiIssuanceOperationId().equals(actor.issuanceOperationId()) + || !request.controlUiTokenHash().equals(actor.tokenHash())) { + throw new FenceRejectedException("Current Account actor differs from the captured operation"); + } + } + + private static void requireCredentials(String email, String secret) { + if (email == null + || email.isBlank() + || email.length() > 254 + || secret == null + || secret.isEmpty() + || secret.length() > 1024) { + throw new IllegalArgumentException("Bounded fresh Account credentials are required"); + } + } + + private static void requireWritableOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable Account owner transaction is required"); + } + } + + private static void outsideSql() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("Recovery refuses an ambient transaction or synchronization"); + } + } + + /** Exact identifiers and reason only; credentials never enter this value or its digest. */ + public record Input( + UUID resolutionRequestId, + UUID failedRequestId, + UUID creationRequestId, + UUID subscriptionId, + UUID tenantId, + long expectedFailedOperationVersion, + long expectedSubscriptionVersion, + UUID auditEventId, + String auditReason) { + Request request(AccountAuthenticatedActor actor) { + return new Request( + resolutionRequestId, + failedRequestId, + creationRequestId, + subscriptionId, + tenantId, + expectedFailedOperationVersion, + expectedSubscriptionVersion, + actor.accountId(), + actor.issuanceOperationId(), + actor.tokenHash(), + auditEventId, + auditReason); + } + } + + private record Attempt(TransitionResult result, String failureCode) {} + + private static final class PrimaryAuthenticationDenied extends RuntimeException { + private final String code; + + private PrimaryAuthenticationDenied(String code) { + super("Account primary authentication denied"); + this.code = code; + } + } +} diff --git a/services/account-service/src/main/resources/db/migration/V1028__retain_non_authorizing_subscription_evidence.sql b/services/account-service/src/main/resources/db/migration/V1028__retain_non_authorizing_subscription_evidence.sql new file mode 100644 index 0000000000..c5d5ff151d --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1028__retain_non_authorizing_subscription_evidence.sql @@ -0,0 +1,44 @@ +-- Preview-only containment: retain the original heap, not a copy/backfill. No UUID +-- subscription, owner, provider mapping, winner or billing sequence is inferred. +/* [jooq ignore start] */ +LOCK TABLE subscription IN ACCESS EXCLUSIVE MODE; +/* [jooq ignore stop] */ + +ALTER TABLE subscription RENAME TO account_retained_subscription_evidence; +-- PostgreSQL-generated object names are absent from the jOOQ/H2 schema simulator. +/* [jooq ignore start] */ +ALTER TABLE account_retained_subscription_evidence + RENAME CONSTRAINT subscription_pkey TO account_retained_subscription_evidence_pkey; +ALTER TABLE account_retained_subscription_evidence + RENAME CONSTRAINT subscription_account_id_fkey TO account_retained_subscription_evidence_account_fk; +ALTER TABLE account_retained_subscription_evidence + RENAME CONSTRAINT subscription_entitlement_version_positive TO account_retained_subscription_evidence_version_positive; +ALTER TABLE account_retained_subscription_evidence + RENAME CONSTRAINT subscription_tenant_authority_generation_non_nil TO account_retained_subscription_evidence_generation_non_nil; +ALTER INDEX idx_subscription_account_id RENAME TO idx_account_retained_subscription_evidence_account; +ALTER INDEX idx_subscription_tenant_id RENAME TO idx_account_retained_subscription_evidence_tenant; +ALTER SEQUENCE subscription_id_seq RENAME TO account_retained_subscription_evidence_id_seq; +/* [jooq ignore stop] */ + +/* [jooq ignore start] */ +DROP TRIGGER subscription_authority_generation_advance ON account_retained_subscription_evidence; +-- RESTRICT is deliberate: an unexpected user of the obsolete function aborts +-- this whole transactional migration, including the rename, without row changes. +DROP FUNCTION advance_subscription_authority_generation() RESTRICT; + +CREATE FUNCTION account_retained_subscription_evidence_refuse_mutation() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Retained subscription evidence is immutable and non-authorizing' + USING ERRCODE = '23514'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER account_retained_subscription_evidence_immutable + BEFORE INSERT OR UPDATE OR DELETE OR TRUNCATE ON account_retained_subscription_evidence + FOR EACH STATEMENT EXECUTE FUNCTION account_retained_subscription_evidence_refuse_mutation(); +ALTER TABLE account_retained_subscription_evidence + ENABLE ALWAYS TRIGGER account_retained_subscription_evidence_immutable; +/* [jooq ignore stop] */ + +COMMENT ON TABLE account_retained_subscription_evidence IS + 'Immutable numeric historical evidence only. Not subscription, billing-owner, provider or production entitlement authority.'; diff --git a/services/account-service/src/main/resources/db/migration/V1029__canonical_subscription_intent_and_provider_history.sql b/services/account-service/src/main/resources/db/migration/V1029__canonical_subscription_intent_and_provider_history.sql new file mode 100644 index 0000000000..c2418e52a7 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1029__canonical_subscription_intent_and_provider_history.sql @@ -0,0 +1,494 @@ +-- One new, initially empty UUID owner. Numeric evidence remains untouched in the V1028 archive. +-- No provider dispatch, verified lifecycle producer, transfer, entitlement or runtime grant. +CREATE TABLE subscription_create_operations ( + request_id UUID PRIMARY KEY CHECK (request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + subscription_id UUID NOT NULL UNIQUE CHECK (subscription_id <> '00000000-0000-0000-0000-000000000000'::UUID), + tenant_id UUID NOT NULL REFERENCES account_tenant_billing_owners(tenant_uuid) ON DELETE RESTRICT, + account_uuid UUID NOT NULL REFERENCES accounts(account_uuid) ON DELETE RESTRICT, + owner_version BIGINT NOT NULL CHECK (owner_version > 0), + owner_generation UUID NOT NULL CHECK (owner_generation <> '00000000-0000-0000-0000-000000000000'::UUID), + actor_account_uuid UUID NOT NULL REFERENCES accounts(account_uuid) ON DELETE RESTRICT, + authorization_operation_id UUID NOT NULL CHECK (authorization_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID), + authorization_digest VARCHAR(71) NOT NULL CHECK (authorization_digest ~ '^sha256:[0-9a-f]{64}$'), + plan_code VARCHAR(255) NOT NULL CHECK (length(btrim(plan_code)) > 0 AND plan_code = btrim(plan_code)), + plan_quote_payload BYTEA NOT NULL CHECK (octet_length(plan_quote_payload) BETWEEN 1 AND 4096), + plan_quote_digest VARCHAR(71) NOT NULL CHECK (plan_quote_digest ~ '^sha256:[0-9a-f]{64}$') + CHECK (plan_quote_digest = 'sha256:' || encode(sha256(plan_quote_payload), 'hex')), + provider_price_id VARCHAR(255) NOT NULL CHECK (provider_price_id ~ '^price_[A-Za-z0-9]+$'), + provider_quantity BIGINT NOT NULL CHECK (provider_quantity > 0), + max_active_sessions BIGINT NOT NULL CHECK (max_active_sessions >= 0), + max_concurrent_game_instances BIGINT NOT NULL CHECK (max_concurrent_game_instances >= 0), + max_storage_bytes BIGINT NOT NULL CHECK (max_storage_bytes >= 0), + payment_instrument_id UUID NOT NULL REFERENCES payment_instrument(instrument_uuid) ON DELETE RESTRICT, + reserved_instrument_version BIGINT NOT NULL CHECK (reserved_instrument_version > 0), + customer_provisioning_request_id UUID NOT NULL REFERENCES billing_customer(customer_provisioning_request_id) ON DELETE RESTRICT, + provider_customer_id VARCHAR(255) NOT NULL, + subscription_provisioning_request_id UUID NOT NULL UNIQUE + CHECK (subscription_provisioning_request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + cleanup_provider_identity UUID NOT NULL UNIQUE + CHECK (cleanup_provider_identity <> '00000000-0000-0000-0000-000000000000'::UUID), + request_payload BYTEA NOT NULL CHECK (octet_length(request_payload) BETWEEN 1 AND 1048576), + request_digest VARCHAR(71) NOT NULL CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$') + CHECK (request_digest = 'sha256:' || encode(sha256(request_payload), 'hex')), + replaced_subscription_id UUID, + replaced_row_version BIGINT CHECK (replaced_row_version > 0), + -- The immutable creation result is these columns, not a later mutable lifecycle snapshot. + result_status VARCHAR(16) NOT NULL DEFAULT 'pending' CHECK (result_status = 'pending'), + result_row_version BIGINT NOT NULL DEFAULT 1 CHECK (result_row_version = 1), + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + CHECK ((replaced_subscription_id IS NULL) = (replaced_row_version IS NULL)), + CHECK (request_id <> subscription_provisioning_request_id AND request_id <> cleanup_provider_identity + AND subscription_provisioning_request_id <> cleanup_provider_identity + AND customer_provisioning_request_id NOT IN (request_id, subscription_provisioning_request_id, cleanup_provider_identity)), + UNIQUE (request_id, subscription_id), + UNIQUE (request_id, plan_quote_digest), + UNIQUE (request_id, subscription_provisioning_request_id), + UNIQUE (request_id, cleanup_provider_identity), + UNIQUE (request_id, subscription_id, payment_instrument_id, reserved_instrument_version), + FOREIGN KEY (account_uuid, customer_provisioning_request_id, provider_customer_id) + REFERENCES billing_customer(account_uuid, customer_provisioning_request_id, provider_customer_id) ON DELETE RESTRICT +); + +CREATE TABLE subscription ( + subscription_id UUID PRIMARY KEY, + tenant_id UUID NOT NULL REFERENCES account_tenant_billing_owners(tenant_uuid) ON DELETE RESTRICT, + account_uuid UUID NOT NULL REFERENCES accounts(account_uuid) ON DELETE RESTRICT, + owner_version BIGINT NOT NULL CHECK (owner_version > 0), + owner_generation UUID NOT NULL, + plan_code VARCHAR(255) NOT NULL, + -- The exact current quote is retained by the immutable operation, not reconstructed from a + -- mutable plan catalog. This digest couples the current read to that original snapshot. + plan_quote_digest VARCHAR(71) NOT NULL, + payment_instrument_id UUID NOT NULL REFERENCES payment_instrument(instrument_uuid) ON DELETE RESTRICT, + reserved_instrument_version BIGINT NOT NULL CHECK (reserved_instrument_version > 0), + customer_provisioning_request_id UUID NOT NULL REFERENCES billing_customer(customer_provisioning_request_id) ON DELETE RESTRICT, + provider_customer_id VARCHAR(255) NOT NULL, + creation_request_id UUID NOT NULL UNIQUE, + row_version BIGINT NOT NULL CHECK (row_version > 0), + status VARCHAR(16) NOT NULL CHECK (status IN ('pending','provisioning','trialing','active','past_due','grace','suspended','canceled')), + provider_subscription_id VARCHAR(255) CHECK (provider_subscription_id ~ '^sub_[A-Za-z0-9]+$'), + terminal_resolution_id UUID, + superseded_at TIMESTAMPTZ, + superseded_by_request_id UUID UNIQUE, + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + CHECK (status NOT IN ('trialing','active','past_due','grace','suspended') OR provider_subscription_id IS NOT NULL), + -- Effective hosting cutoff and provider retirement are separate: a scheduled end may close + -- hosting before a provider-terminal read permits retiring the instrument reservation. + CHECK (terminal_resolution_id IS NULL OR status = 'canceled'), + CHECK ((superseded_at IS NULL) = (superseded_by_request_id IS NULL)), + CHECK (superseded_at IS NULL OR status = 'canceled'), + UNIQUE (creation_request_id, subscription_id), + FOREIGN KEY (creation_request_id, subscription_id) + REFERENCES subscription_create_operations(request_id, subscription_id) DEFERRABLE INITIALLY DEFERRED, + FOREIGN KEY (creation_request_id, plan_quote_digest) + REFERENCES subscription_create_operations(request_id, plan_quote_digest) ON DELETE RESTRICT, + FOREIGN KEY (superseded_by_request_id) REFERENCES subscription_create_operations(request_id) DEFERRABLE INITIALLY DEFERRED +); +ALTER TABLE subscription_create_operations ADD CONSTRAINT subscription_create_current_pair_fk + FOREIGN KEY (request_id, subscription_id) REFERENCES subscription(creation_request_id, subscription_id) + DEFERRABLE INITIALLY DEFERRED; +ALTER TABLE subscription_create_operations ADD CONSTRAINT subscription_create_replaced_fk + FOREIGN KEY (replaced_subscription_id) REFERENCES subscription(subscription_id) ON DELETE RESTRICT; + +-- A shared key registry prevents even cross-role reuse between different subscription creates. +CREATE TABLE subscription_create_provider_identities ( + provider_identity UUID PRIMARY KEY, + request_id UUID NOT NULL REFERENCES subscription_create_operations(request_id) ON DELETE RESTRICT, + purpose VARCHAR(16) NOT NULL CHECK (purpose IN ('CREATE','CLEANUP')), + UNIQUE (request_id, purpose) +); + +CREATE TABLE subscription_instrument_reservations ( + request_id UUID PRIMARY KEY, + subscription_id UUID NOT NULL UNIQUE, + payment_instrument_id UUID NOT NULL, + instrument_version BIGINT NOT NULL CHECK (instrument_version > 0), + terminal_resolution_id UUID UNIQUE, + released_at TIMESTAMPTZ, + CHECK ((terminal_resolution_id IS NULL) = (released_at IS NULL)), + FOREIGN KEY (request_id, subscription_id, payment_instrument_id, instrument_version) + REFERENCES subscription_create_operations(request_id, subscription_id, payment_instrument_id, reserved_instrument_version) + ON DELETE RESTRICT, + UNIQUE (request_id, subscription_id) +); +CREATE INDEX idx_subscription_instrument_hold ON subscription_instrument_reservations(payment_instrument_id) + WHERE released_at IS NULL; + +-- An immutable local work intent, NOT a dispatched item or lifecycle-event authority bridge. +CREATE TABLE subscription_create_outbox ( + request_id UUID PRIMARY KEY, + subscription_id UUID NOT NULL UNIQUE, + work_kind VARCHAR(40) NOT NULL CHECK (work_kind = 'SUBSCRIPTION_PROVISIONING_INTENT'), + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + FOREIGN KEY (request_id, subscription_id) REFERENCES subscription_create_operations(request_id, subscription_id) ON DELETE RESTRICT, + UNIQUE (request_id, subscription_id) +); +ALTER TABLE subscription_create_operations ADD CONSTRAINT subscription_create_reservation_pair_fk + FOREIGN KEY (request_id, subscription_id) REFERENCES subscription_instrument_reservations(request_id, subscription_id) + DEFERRABLE INITIALLY DEFERRED; +ALTER TABLE subscription_create_operations ADD CONSTRAINT subscription_create_outbox_pair_fk + FOREIGN KEY (request_id, subscription_id) REFERENCES subscription_create_outbox(request_id, subscription_id) + DEFERRABLE INITIALLY DEFERRED; + +CREATE TABLE subscription_provider_history ( + provider_subscription_id VARCHAR(255) PRIMARY KEY CHECK (provider_subscription_id ~ '^sub_[A-Za-z0-9]+$'), + subscription_id UUID NOT NULL REFERENCES subscription(subscription_id) ON DELETE RESTRICT, + operation_kind VARCHAR(32) NOT NULL CHECK (operation_kind = 'SUBSCRIPTION_PROVISIONING'), + request_id UUID NOT NULL, + provider_operation_id UUID NOT NULL, + -- Transfer roles/references require the genuine transfer owner, not an invented operation. + role VARCHAR(16) NOT NULL CHECK (role = 'canonical'), + effective_at TIMESTAMPTZ NOT NULL, + evidence_digest VARCHAR(71) NOT NULL CHECK (evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + recorded_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + UNIQUE (provider_subscription_id, subscription_id), + UNIQUE (request_id), + FOREIGN KEY (request_id, subscription_id) REFERENCES subscription_create_operations(request_id, subscription_id) ON DELETE RESTRICT, + FOREIGN KEY (request_id, provider_operation_id) + REFERENCES subscription_create_operations(request_id, subscription_provisioning_request_id) ON DELETE RESTRICT +); +ALTER TABLE subscription ADD CONSTRAINT subscription_confirmed_provider_history_fk + FOREIGN KEY (provider_subscription_id, subscription_id) + REFERENCES subscription_provider_history(provider_subscription_id, subscription_id) DEFERRABLE INITIALLY DEFERRED; + +-- Separate immutable terminal evidence; inserting a history mapping cannot imply cancellation. +-- No public writer exists until provider reconciliation and local cleanup are genuinely composed. +CREATE TABLE subscription_provider_terminal_resolutions ( + resolution_id UUID PRIMARY KEY CHECK (resolution_id <> '00000000-0000-0000-0000-000000000000'::UUID), + request_id UUID NOT NULL UNIQUE, + subscription_id UUID NOT NULL UNIQUE, + cleanup_provider_identity UUID NOT NULL, + provider_subscription_id VARCHAR(255), + outcome VARCHAR(24) NOT NULL CHECK (outcome IN ('PROVIDER_ABSENT','CANCELED')), + effective_at TIMESTAMPTZ NOT NULL, + evidence_digest VARCHAR(71) NOT NULL CHECK (evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + recorded_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + CHECK ((outcome = 'PROVIDER_ABSENT') = (provider_subscription_id IS NULL)), + UNIQUE (resolution_id, subscription_id), + FOREIGN KEY (request_id, subscription_id) REFERENCES subscription_create_operations(request_id, subscription_id) ON DELETE RESTRICT, + FOREIGN KEY (request_id, cleanup_provider_identity) + REFERENCES subscription_create_operations(request_id, cleanup_provider_identity) ON DELETE RESTRICT, + FOREIGN KEY (provider_subscription_id, subscription_id) + REFERENCES subscription_provider_history(provider_subscription_id, subscription_id) ON DELETE RESTRICT +); +ALTER TABLE subscription ADD CONSTRAINT subscription_terminal_resolution_fk + FOREIGN KEY (terminal_resolution_id, subscription_id) + REFERENCES subscription_provider_terminal_resolutions(resolution_id, subscription_id) DEFERRABLE INITIALLY DEFERRED; +ALTER TABLE subscription_instrument_reservations ADD CONSTRAINT subscription_reservation_resolution_fk + FOREIGN KEY (terminal_resolution_id, subscription_id) + REFERENCES subscription_provider_terminal_resolutions(resolution_id, subscription_id) DEFERRABLE INITIALLY DEFERRED; + +CREATE TABLE subscription_current_observations ( + subscription_id UUID NOT NULL REFERENCES subscription(subscription_id) ON DELETE RESTRICT, + row_version BIGINT NOT NULL CHECK (row_version > 0), + status VARCHAR(16) NOT NULL, + provider_subscription_id VARCHAR(255), + terminal_resolution_id UUID, + superseded_at TIMESTAMPTZ, + superseded_by_request_id UUID, + recorded_at TIMESTAMPTZ NOT NULL, + PRIMARY KEY (subscription_id, row_version) +); + +-- [jooq ignore start] +-- The canonical relation is new and empty. No old numeric row is a duplicate candidate/winner. +-- Fence this new owner while checking the exact index candidates, not another schema catalog. +LOCK TABLE subscription IN ACCESS EXCLUSIVE MODE; +DO $$ +BEGIN + IF EXISTS (SELECT tenant_id FROM subscription WHERE superseded_at IS NULL GROUP BY tenant_id HAVING count(*) > 1) + OR EXISTS (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) THEN + RAISE EXCEPTION 'Canonical subscription candidates require explicit reconciliation'; + END IF; +END; +$$; +-- [jooq ignore stop] +CREATE UNIQUE INDEX uq_subscription_active_tenant ON subscription(tenant_id) WHERE superseded_at IS NULL; +CREATE UNIQUE INDEX uq_subscription_active_provider ON subscription(provider_subscription_id) + WHERE superseded_at IS NULL AND provider_subscription_id IS NOT NULL; + +-- [jooq ignore start] +CREATE FUNCTION account_subscription_no_mutation() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Canonical subscription evidence is retained and immutable' USING ERRCODE = '23514'; +END; +$$; + +CREATE FUNCTION account_subscription_create_source_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + wallet payment_instrument%ROWTYPE; + customer billing_customer%ROWTYPE; + owner account_tenant_billing_owners%ROWTYPE; + previous subscription%ROWTYPE; +BEGIN + -- Same lock order as V1027 repositories: Account -> customer -> instrument -> tenant owner. + PERFORM 1 FROM accounts WHERE account_uuid = NEW.account_uuid FOR UPDATE; + SELECT * INTO STRICT customer FROM billing_customer WHERE account_uuid = NEW.account_uuid FOR UPDATE; + SELECT * INTO STRICT wallet FROM payment_instrument WHERE instrument_uuid = NEW.payment_instrument_id FOR UPDATE; + SELECT * INTO STRICT owner FROM account_tenant_billing_owners WHERE tenant_uuid = NEW.tenant_id FOR UPDATE; + IF convert_from(NEW.plan_quote_payload, 'UTF8')::jsonb IS DISTINCT FROM jsonb_build_object( + 'schemaVersion', 'account-hosting-plan-quote/v1', 'planCode', NEW.plan_code, + 'providerPriceId', NEW.provider_price_id, 'providerQuantity', NEW.provider_quantity::text, + 'maxActiveSessions', NEW.max_active_sessions::text, + 'maxConcurrentGameInstances', NEW.max_concurrent_game_instances::text, + 'maxStorageBytes', NEW.max_storage_bytes::text) THEN + RAISE EXCEPTION 'Subscription hosting quote differs from its exact retained fields' USING ERRCODE = '23514'; + END IF; + IF (owner.owner_account_uuid, owner.owner_version, owner.owner_generation) + IS DISTINCT FROM (NEW.account_uuid, NEW.owner_version, NEW.owner_generation) + OR (wallet.account_uuid, wallet.row_version, wallet.customer_provisioning_request_id, wallet.provider_customer_id) + IS DISTINCT FROM (NEW.account_uuid, NEW.reserved_instrument_version, NEW.customer_provisioning_request_id, NEW.provider_customer_id) + OR wallet.state <> 'ATTACHABLE' OR customer.state <> 'CONFIRMED' + OR customer.provider_customer_id IS DISTINCT FROM NEW.provider_customer_id + OR customer.provider_idempotency_id IN (NEW.request_id, NEW.subscription_provisioning_request_id, NEW.cleanup_provider_identity) + OR convert_from(NEW.request_payload, 'UTF8')::jsonb IS DISTINCT FROM jsonb_build_object( + 'schemaVersion', 'account-subscription-create-request/v1', 'tenantId', NEW.tenant_id::text, + 'ownerAccountId', NEW.account_uuid::text, 'planCode', NEW.plan_code, + 'instrumentSelection', jsonb_build_object('kind', 'EXACT_SAVED_INSTRUMENT', 'paymentInstrumentId', NEW.payment_instrument_id::text)) THEN + RAISE EXCEPTION 'Subscription create owner, wallet or normalized request fence rejected' USING ERRCODE = '23514'; + END IF; + IF NEW.replaced_subscription_id IS NOT NULL THEN + SELECT * INTO STRICT previous FROM subscription WHERE subscription_id = NEW.replaced_subscription_id FOR UPDATE; + IF previous.tenant_id <> NEW.tenant_id OR previous.status <> 'canceled' + OR previous.terminal_resolution_id IS NULL + OR previous.row_version <> NEW.replaced_row_version + 1 + OR previous.superseded_by_request_id IS DISTINCT FROM NEW.request_id THEN + RAISE EXCEPTION 'Canceled subscription replacement fence rejected' USING ERRCODE = '23514'; + END IF; + ELSIF EXISTS (SELECT 1 FROM subscription WHERE tenant_id = NEW.tenant_id AND superseded_at IS NULL) THEN + RAISE EXCEPTION 'Tenant already has a current subscription' USING ERRCODE = '23514'; + END IF; + NEW.created_at := clock_timestamp(); + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_subscription_record_provider_identities() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + INSERT INTO subscription_create_provider_identities VALUES (NEW.subscription_provisioning_request_id, NEW.request_id, 'CREATE'); + INSERT INTO subscription_create_provider_identities VALUES (NEW.cleanup_provider_identity, NEW.request_id, 'CLEANUP'); + RETURN NEW; +END; +$$; +CREATE FUNCTION account_subscription_provider_identity_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM subscription_create_operations WHERE request_id = NEW.request_id + AND ((NEW.purpose = 'CREATE' AND subscription_provisioning_request_id = NEW.provider_identity) + OR (NEW.purpose = 'CLEANUP' AND cleanup_provider_identity = NEW.provider_identity))) THEN + RAISE EXCEPTION 'Subscription provider identity differs from its typed operation' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_subscription_current_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + intent subscription_create_operations%ROWTYPE; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Canonical subscription cannot be deleted' USING ERRCODE = '23514'; + ELSIF TG_OP = 'INSERT' THEN + SELECT * INTO STRICT intent FROM subscription_create_operations WHERE request_id = NEW.creation_request_id; + IF (NEW.subscription_id, NEW.tenant_id, NEW.account_uuid, NEW.owner_version, NEW.owner_generation, + NEW.plan_code, NEW.plan_quote_digest, NEW.payment_instrument_id, NEW.reserved_instrument_version, + NEW.customer_provisioning_request_id, NEW.provider_customer_id) + IS DISTINCT FROM (intent.subscription_id, intent.tenant_id, intent.account_uuid, intent.owner_version, + intent.owner_generation, intent.plan_code, intent.plan_quote_digest, intent.payment_instrument_id, intent.reserved_instrument_version, + intent.customer_provisioning_request_id, intent.provider_customer_id) + OR NEW.row_version <> 1 OR NEW.status <> 'pending' OR NEW.provider_subscription_id IS NOT NULL + OR NEW.terminal_resolution_id IS NOT NULL OR NEW.superseded_at IS NOT NULL THEN + RAISE EXCEPTION 'Subscription must begin as its exact pending intent' USING ERRCODE = '23514'; + END IF; + NEW.created_at := intent.created_at; + NEW.updated_at := NEW.created_at; + ELSE + -- No generic plan/instrument/owner rebind. Future typed update/transfer owners must extend + -- this guard with their real operation and authority evidence, never a compatibility path. + IF (NEW.subscription_id, NEW.tenant_id, NEW.account_uuid, NEW.owner_version, NEW.owner_generation, + NEW.plan_code, NEW.plan_quote_digest, NEW.payment_instrument_id, NEW.reserved_instrument_version, + NEW.customer_provisioning_request_id, NEW.provider_customer_id, NEW.creation_request_id, NEW.created_at) + IS DISTINCT FROM (OLD.subscription_id, OLD.tenant_id, OLD.account_uuid, OLD.owner_version, OLD.owner_generation, + OLD.plan_code, OLD.plan_quote_digest, OLD.payment_instrument_id, OLD.reserved_instrument_version, + OLD.customer_provisioning_request_id, OLD.provider_customer_id, OLD.creation_request_id, OLD.created_at) + OR OLD.superseded_at IS NOT NULL OR NEW.row_version <> OLD.row_version + 1 + OR (OLD.provider_subscription_id IS NOT NULL AND NEW.provider_subscription_id IS DISTINCT FROM OLD.provider_subscription_id) + OR (OLD.terminal_resolution_id IS NOT NULL AND NEW.terminal_resolution_id IS DISTINCT FROM OLD.terminal_resolution_id) + OR (OLD.status = 'canceled' AND NEW.status <> 'canceled') THEN + RAISE EXCEPTION 'Subscription identity, terminal state or row-version fence rejected' USING ERRCODE = '23514'; + END IF; + IF NEW.superseded_at IS NOT NULL THEN + IF OLD.status <> 'canceled' OR OLD.terminal_resolution_id IS NULL OR NEW.status <> OLD.status + OR NEW.provider_subscription_id IS DISTINCT FROM OLD.provider_subscription_id + OR NEW.terminal_resolution_id IS DISTINCT FROM OLD.terminal_resolution_id THEN + RAISE EXCEPTION 'Only terminal canceled current subscriptions may be superseded' USING ERRCODE = '23514'; + END IF; + NEW.superseded_at := clock_timestamp(); + END IF; + NEW.updated_at := clock_timestamp(); + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_subscription_record_observation() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + INSERT INTO subscription_current_observations VALUES (NEW.subscription_id, NEW.row_version, NEW.status, + NEW.provider_subscription_id, NEW.terminal_resolution_id, NEW.superseded_at, NEW.superseded_by_request_id, NEW.updated_at); + RETURN NEW; +END; +$$; +CREATE FUNCTION account_subscription_observation_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE current_row subscription%ROWTYPE; +BEGIN + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = NEW.subscription_id FOR UPDATE; + IF (NEW.row_version, NEW.status, NEW.provider_subscription_id, NEW.terminal_resolution_id, + NEW.superseded_at, NEW.superseded_by_request_id, NEW.recorded_at) IS DISTINCT FROM + (current_row.row_version, current_row.status, current_row.provider_subscription_id, current_row.terminal_resolution_id, + current_row.superseded_at, current_row.superseded_by_request_id, current_row.updated_at) THEN + RAISE EXCEPTION 'Subscription observation differs from its current owner' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_subscription_reservation_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.terminal_resolution_id IS NOT NULL OR NEW.released_at IS NOT NULL THEN + RAISE EXCEPTION 'Subscription reservation must begin held' USING ERRCODE = '23514'; + END IF; + ELSIF TG_OP = 'DELETE' OR OLD.released_at IS NOT NULL + OR (NEW.request_id, NEW.subscription_id, NEW.payment_instrument_id, NEW.instrument_version) + IS DISTINCT FROM (OLD.request_id, OLD.subscription_id, OLD.payment_instrument_id, OLD.instrument_version) + OR NEW.terminal_resolution_id IS NULL OR NEW.released_at IS NULL THEN + RAISE EXCEPTION 'Subscription reservation identity or terminal release fence rejected' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_subscription_final_pair_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + current_row subscription%ROWTYPE; + hold subscription_instrument_reservations%ROWTYPE; + resolution subscription_provider_terminal_resolutions%ROWTYPE; + successor subscription_create_operations%ROWTYPE; + wallet payment_instrument%ROWTYPE; + owner account_tenant_billing_owners%ROWTYPE; +BEGIN + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = NEW.subscription_id; + SELECT * INTO STRICT hold FROM subscription_instrument_reservations WHERE subscription_id = NEW.subscription_id; + IF current_row.row_version = 1 AND current_row.status = 'pending' THEN + SELECT * INTO STRICT wallet FROM payment_instrument WHERE instrument_uuid = current_row.payment_instrument_id; + SELECT * INTO STRICT owner FROM account_tenant_billing_owners WHERE tenant_uuid = current_row.tenant_id; + IF (owner.owner_account_uuid, owner.owner_version, owner.owner_generation) + IS DISTINCT FROM (current_row.account_uuid, current_row.owner_version, current_row.owner_generation) + OR (wallet.account_uuid, wallet.row_version, wallet.customer_provisioning_request_id, wallet.provider_customer_id, wallet.state) + IS DISTINCT FROM (current_row.account_uuid, current_row.reserved_instrument_version, + current_row.customer_provisioning_request_id, current_row.provider_customer_id, 'ATTACHABLE'::varchar) THEN + RAISE EXCEPTION 'Subscription commit owner/instrument fence rejected' USING ERRCODE = '23514'; + END IF; + END IF; + IF current_row.status = 'canceled' AND current_row.terminal_resolution_id IS NOT NULL THEN + SELECT * INTO STRICT resolution FROM subscription_provider_terminal_resolutions + WHERE resolution_id = current_row.terminal_resolution_id; + IF hold.terminal_resolution_id IS DISTINCT FROM current_row.terminal_resolution_id OR hold.released_at IS NULL + OR resolution.provider_subscription_id IS DISTINCT FROM current_row.provider_subscription_id THEN + RAISE EXCEPTION 'Subscription terminal result requires exact provider resolution and reservation release' USING ERRCODE = '23514'; + END IF; + ELSIF hold.released_at IS NOT NULL THEN + RAISE EXCEPTION 'Nonterminal subscription must retain its instrument reservation' USING ERRCODE = '23514'; + END IF; + IF current_row.superseded_at IS NOT NULL THEN + SELECT * INTO STRICT successor FROM subscription_create_operations WHERE request_id = current_row.superseded_by_request_id; + IF successor.replaced_subscription_id IS DISTINCT FROM current_row.subscription_id + OR successor.replaced_row_version <> current_row.row_version - 1 OR successor.tenant_id <> current_row.tenant_id THEN + RAISE EXCEPTION 'Subscription supersession requires the exact atomic replacement operation' USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NULL; +END; +$$; +CREATE FUNCTION account_subscription_terminal_source_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE current_row subscription%ROWTYPE; +BEGIN + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = NEW.subscription_id FOR UPDATE; + IF NEW.request_id IS DISTINCT FROM current_row.creation_request_id + OR (NEW.provider_subscription_id IS DISTINCT FROM current_row.provider_subscription_id + AND NOT (current_row.provider_subscription_id IS NULL AND NEW.provider_subscription_id IS NOT NULL + AND EXISTS (SELECT 1 FROM subscription_provider_history h + WHERE h.subscription_id = NEW.subscription_id AND h.provider_subscription_id = NEW.provider_subscription_id))) + OR (NEW.provider_subscription_id IS NULL AND EXISTS ( + SELECT 1 FROM subscription_provider_history WHERE subscription_id = NEW.subscription_id)) THEN + RAISE EXCEPTION 'Subscription terminal evidence differs from its exact provider mapping' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE FUNCTION account_subscription_provider_history_source_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE current_row subscription%ROWTYPE; +BEGIN + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = NEW.subscription_id FOR UPDATE; + IF current_row.status = 'canceled' OR current_row.superseded_at IS NOT NULL + OR EXISTS (SELECT 1 FROM subscription_provider_terminal_resolutions WHERE subscription_id = NEW.subscription_id) THEN + RAISE EXCEPTION 'Terminal subscription cannot acquire a new provider mapping' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER subscription_create_source_guard BEFORE INSERT ON subscription_create_operations + FOR EACH ROW EXECUTE FUNCTION account_subscription_create_source_guard(); +CREATE TRIGGER subscription_create_provider_keys AFTER INSERT ON subscription_create_operations + FOR EACH ROW EXECUTE FUNCTION account_subscription_record_provider_identities(); +CREATE TRIGGER subscription_provider_key_guard BEFORE INSERT ON subscription_create_provider_identities + FOR EACH ROW EXECUTE FUNCTION account_subscription_provider_identity_guard(); +CREATE TRIGGER subscription_current_guard BEFORE INSERT OR UPDATE OR DELETE ON subscription + FOR EACH ROW EXECUTE FUNCTION account_subscription_current_guard(); +CREATE TRIGGER subscription_current_history AFTER INSERT OR UPDATE ON subscription + FOR EACH ROW EXECUTE FUNCTION account_subscription_record_observation(); +CREATE TRIGGER subscription_observation_guard BEFORE INSERT ON subscription_current_observations + FOR EACH ROW EXECUTE FUNCTION account_subscription_observation_guard(); +CREATE TRIGGER subscription_terminal_source_guard BEFORE INSERT ON subscription_provider_terminal_resolutions + FOR EACH ROW EXECUTE FUNCTION account_subscription_terminal_source_guard(); +CREATE TRIGGER subscription_provider_history_source_guard BEFORE INSERT ON subscription_provider_history + FOR EACH ROW EXECUTE FUNCTION account_subscription_provider_history_source_guard(); +CREATE TRIGGER subscription_reservation_guard BEFORE INSERT OR UPDATE OR DELETE ON subscription_instrument_reservations + FOR EACH ROW EXECUTE FUNCTION account_subscription_reservation_guard(); +CREATE CONSTRAINT TRIGGER subscription_final_pair_guard AFTER INSERT OR UPDATE ON subscription + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_final_pair_guard(); +CREATE CONSTRAINT TRIGGER subscription_reservation_final_pair_guard AFTER INSERT OR UPDATE ON subscription_instrument_reservations + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_final_pair_guard(); + +CREATE TRIGGER subscription_create_immutable BEFORE UPDATE OR DELETE ON subscription_create_operations + FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_create_no_truncate BEFORE TRUNCATE ON subscription_create_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_provider_keys_immutable BEFORE UPDATE OR DELETE ON subscription_create_provider_identities + FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_provider_keys_no_truncate BEFORE TRUNCATE ON subscription_create_provider_identities + FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_no_truncate BEFORE TRUNCATE ON subscription + FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_reservation_no_truncate BEFORE TRUNCATE ON subscription_instrument_reservations + FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_outbox_immutable BEFORE UPDATE OR DELETE ON subscription_create_outbox + FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_outbox_no_truncate BEFORE TRUNCATE ON subscription_create_outbox + FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_provider_history_immutable BEFORE UPDATE OR DELETE ON subscription_provider_history + FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_provider_history_no_truncate BEFORE TRUNCATE ON subscription_provider_history + FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_terminal_immutable BEFORE UPDATE OR DELETE ON subscription_provider_terminal_resolutions + FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_terminal_no_truncate BEFORE TRUNCATE ON subscription_provider_terminal_resolutions + FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_observation_immutable BEFORE UPDATE OR DELETE ON subscription_current_observations + FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_observation_no_truncate BEFORE TRUNCATE ON subscription_current_observations + FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1030__hosting_subscription_provisioning_claims.sql b/services/account-service/src/main/resources/db/migration/V1030__hosting_subscription_provisioning_claims.sql new file mode 100644 index 0000000000..20fd82966c --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1030__hosting_subscription_provisioning_claims.sql @@ -0,0 +1,561 @@ +-- Local durable provisioning ownership only. No runtime reader, provider dispatch or entitlement +-- receipt is enabled by these rows. Failure never proves provider absence or releases a hold. +CREATE TABLE subscription_provisioning_work ( + request_id UUID PRIMARY KEY, + subscription_id UUID NOT NULL UNIQUE, + phase VARCHAR(48) NOT NULL CHECK (phase IN ('RECONCILING','CLAIMED','CONFIRMED','BILLING_RECONCILIATION_TERMINAL_FAILURE')), + row_version BIGINT NOT NULL CHECK (row_version > 0), + attempt_count INTEGER NOT NULL CHECK (attempt_count >= 0), + max_attempts INTEGER NOT NULL CHECK (max_attempts > 0), + max_stalled_attempts INTEGER NOT NULL CHECK (max_stalled_attempts > 0), + lease_millis BIGINT NOT NULL CHECK (lease_millis > 0), + backoff_millis BIGINT NOT NULL CHECK (backoff_millis > 0), + deadline_at TIMESTAMPTZ NOT NULL, + retry_at TIMESTAMPTZ NOT NULL, + last_attempt_id UUID, + subscription_row_version BIGINT CHECK (subscription_row_version > 1), + lease_expires_at TIMESTAMPTZ, + failure_reason VARCHAR(64), + terminal_at TIMESTAMPTZ, + CHECK ((attempt_count = 0) = (last_attempt_id IS NULL)), + CHECK ((last_attempt_id IS NULL) = (subscription_row_version IS NULL)), + CHECK ((last_attempt_id IS NULL) = (lease_expires_at IS NULL)), + CHECK (phase <> 'CLAIMED' OR last_attempt_id IS NOT NULL), + CHECK ((phase = 'BILLING_RECONCILIATION_TERMINAL_FAILURE') = (terminal_at IS NOT NULL)), + CHECK (phase <> 'BILLING_RECONCILIATION_TERMINAL_FAILURE' OR failure_reason IS NOT NULL), + FOREIGN KEY (request_id, subscription_id) REFERENCES subscription_create_outbox(request_id, subscription_id) ON DELETE RESTRICT, + UNIQUE (request_id, subscription_id) +); + +CREATE TABLE subscription_provisioning_attempts ( + attempt_id UUID PRIMARY KEY CHECK (attempt_id <> '00000000-0000-0000-0000-000000000000'::UUID), + request_id UUID NOT NULL, + subscription_id UUID NOT NULL, + attempt_number INTEGER NOT NULL CHECK (attempt_number > 0), + expected_row_version BIGINT NOT NULL CHECK (expected_row_version > 0), + claimed_row_version BIGINT NOT NULL CHECK (claimed_row_version = expected_row_version + 1), + claimed_at TIMESTAMPTZ NOT NULL, + expires_at TIMESTAMPTZ NOT NULL CHECK (expires_at > claimed_at), + FOREIGN KEY (request_id, subscription_id) REFERENCES subscription_provisioning_work(request_id, subscription_id) ON DELETE RESTRICT, + UNIQUE (request_id, attempt_number), + UNIQUE (attempt_id, request_id, subscription_id, claimed_row_version) +); +ALTER TABLE subscription_provisioning_work ADD CONSTRAINT subscription_provisioning_last_attempt_fk + FOREIGN KEY (last_attempt_id, request_id, subscription_id, subscription_row_version) + REFERENCES subscription_provisioning_attempts(attempt_id, request_id, subscription_id, claimed_row_version) + DEFERRABLE INITIALLY DEFERRED; + +CREATE TABLE subscription_provisioning_operator_outbox ( + request_id UUID PRIMARY KEY, + subscription_id UUID NOT NULL UNIQUE, + reason VARCHAR(64) NOT NULL CHECK (reason IN ('ABSOLUTE_DEADLINE','ATTEMPT_BUDGET','STALLED_WITHOUT_COMMITTED_PROGRESS')), + recorded_at TIMESTAMPTZ NOT NULL, + FOREIGN KEY (request_id, subscription_id) REFERENCES subscription_provisioning_work(request_id, subscription_id) ON DELETE RESTRICT +); + +-- [jooq ignore start] +CREATE FUNCTION account_subscription_provisioning_work_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Provisioning work is retained' USING ERRCODE = '23514'; + ELSIF TG_OP = 'INSERT' THEN + IF NEW.phase <> 'RECONCILING' OR NEW.attempt_count <> 0 OR NEW.row_version <> 1 + OR NEW.failure_reason IS NOT NULL OR NEW.terminal_at IS NOT NULL THEN + RAISE EXCEPTION 'Provisioning work must start unclaimed' USING ERRCODE = '23514'; + END IF; + ELSE + IF OLD.phase IN ('CONFIRMED','BILLING_RECONCILIATION_TERMINAL_FAILURE') + OR (NEW.request_id, NEW.subscription_id, NEW.max_attempts, NEW.max_stalled_attempts, + NEW.lease_millis, NEW.backoff_millis, NEW.deadline_at) + IS DISTINCT FROM (OLD.request_id, OLD.subscription_id, OLD.max_attempts, OLD.max_stalled_attempts, + OLD.lease_millis, OLD.backoff_millis, OLD.deadline_at) + OR NEW.row_version <> OLD.row_version + 1 THEN + RAISE EXCEPTION 'Provisioning identity, limits or terminal fence rejected' USING ERRCODE = '23514'; + END IF; + IF NEW.phase = 'CLAIMED' THEN + IF NEW.attempt_count <> OLD.attempt_count + 1 OR NEW.last_attempt_id IS NOT DISTINCT FROM OLD.last_attempt_id + OR NEW.attempt_count > NEW.max_attempts OR NEW.attempt_count > NEW.max_stalled_attempts THEN + RAISE EXCEPTION 'Provisioning claim count or attempt fence rejected' USING ERRCODE = '23514'; + END IF; + ELSIF (NEW.attempt_count, NEW.last_attempt_id, NEW.subscription_row_version, NEW.lease_expires_at) + IS DISTINCT FROM (OLD.attempt_count, OLD.last_attempt_id, OLD.subscription_row_version, OLD.lease_expires_at) THEN + RAISE EXCEPTION 'Provisioning settlement cannot replace its attempt' USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_subscription_provisioning_consistency() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + work subscription_provisioning_work%ROWTYPE; + attempt subscription_provisioning_attempts%ROWTYPE; + current_row subscription%ROWTYPE; + notice subscription_provisioning_operator_outbox%ROWTYPE; +BEGIN + SELECT * INTO STRICT work FROM subscription_provisioning_work WHERE request_id = NEW.request_id; + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = work.subscription_id; + IF work.last_attempt_id IS NOT NULL THEN + SELECT * INTO STRICT attempt FROM subscription_provisioning_attempts WHERE attempt_id = work.last_attempt_id; + IF (attempt.request_id, attempt.subscription_id, attempt.attempt_number, attempt.claimed_row_version, attempt.expires_at) + IS DISTINCT FROM (work.request_id, work.subscription_id, work.attempt_count, work.subscription_row_version, work.lease_expires_at) + OR attempt.expires_at > work.deadline_at + OR (work.phase <> 'CONFIRMED' AND (current_row.status <> 'provisioning' OR current_row.row_version < attempt.claimed_row_version + OR current_row.superseded_at IS NOT NULL)) THEN + RAISE EXCEPTION 'Provisioning attempt lacks its exact current CAS' USING ERRCODE = '23514'; + END IF; + END IF; + IF work.phase = 'BILLING_RECONCILIATION_TERMINAL_FAILURE' THEN + SELECT * INTO STRICT notice FROM subscription_provisioning_operator_outbox WHERE request_id = work.request_id; + IF (notice.subscription_id, notice.reason, notice.recorded_at) + IS DISTINCT FROM (work.subscription_id, work.failure_reason, work.terminal_at) THEN + RAISE EXCEPTION 'Provisioning failure lacks its exact operator work item' USING ERRCODE = '23514'; + END IF; + ELSIF EXISTS (SELECT 1 FROM subscription_provisioning_operator_outbox WHERE request_id = work.request_id) THEN + RAISE EXCEPTION 'Operator resolution work requires terminal reconciliation failure' USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_subscription_provisioning_attempt_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + work subscription_provisioning_work%ROWTYPE; + current_row subscription%ROWTYPE; +BEGIN + SELECT * INTO STRICT work FROM subscription_provisioning_work WHERE request_id = NEW.request_id FOR UPDATE; + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = NEW.subscription_id; + IF work.phase = 'BILLING_RECONCILIATION_TERMINAL_FAILURE' + OR work.subscription_id <> NEW.subscription_id OR current_row.status <> 'provisioning' + OR current_row.provider_subscription_id IS NOT NULL OR current_row.superseded_at IS NOT NULL + OR current_row.row_version <> NEW.claimed_row_version + OR NEW.attempt_number <> work.attempt_count + 1 + OR NEW.attempt_number > work.max_attempts OR NEW.attempt_number > work.max_stalled_attempts + OR NEW.expected_row_version <> coalesce(work.subscription_row_version, 1) + OR NEW.claimed_at < current_row.created_at OR NEW.claimed_at < work.retry_at + OR NEW.claimed_at >= work.deadline_at OR NEW.expires_at > work.deadline_at + OR (work.phase = 'CLAIMED' AND NEW.claimed_at < work.lease_expires_at) + OR extract(epoch FROM (NEW.expires_at - NEW.claimed_at)) * 1000 > work.lease_millis THEN + RAISE EXCEPTION 'Provisioning attempt lacks its exact work and current-row fence' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER subscription_provisioning_work_guard BEFORE INSERT OR UPDATE OR DELETE ON subscription_provisioning_work + FOR EACH ROW EXECUTE FUNCTION account_subscription_provisioning_work_guard(); +CREATE TRIGGER subscription_provisioning_attempt_guard BEFORE INSERT ON subscription_provisioning_attempts + FOR EACH ROW EXECUTE FUNCTION account_subscription_provisioning_attempt_guard(); +CREATE CONSTRAINT TRIGGER subscription_provisioning_work_consistency AFTER INSERT OR UPDATE ON subscription_provisioning_work + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_provisioning_consistency(); +CREATE CONSTRAINT TRIGGER subscription_provisioning_attempt_consistency AFTER INSERT ON subscription_provisioning_attempts + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_provisioning_consistency(); +CREATE CONSTRAINT TRIGGER subscription_provisioning_notice_consistency AFTER INSERT ON subscription_provisioning_operator_outbox + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_provisioning_consistency(); +CREATE TRIGGER subscription_provisioning_work_no_truncate BEFORE TRUNCATE ON subscription_provisioning_work + FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_provisioning_attempt_immutable BEFORE UPDATE OR DELETE ON subscription_provisioning_attempts + FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_provisioning_attempt_no_truncate BEFORE TRUNCATE ON subscription_provisioning_attempts + FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_provisioning_notice_immutable BEFORE UPDATE OR DELETE ON subscription_provisioning_operator_outbox + FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_provisioning_notice_no_truncate BEFORE TRUNCATE ON subscription_provisioning_operator_outbox + FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +-- [jooq ignore stop] + +-- Provider reads are outside SQL. One durable, row-version-bound reconciliation operation fences +-- currentness before the SDK read starts. It is not a provider mutation or a reused create command. +CREATE TABLE subscription_lifecycle_operations ( + request_id UUID PRIMARY KEY CHECK (request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + creation_request_id UUID NOT NULL, + subscription_id UUID NOT NULL, + tenant_id UUID NOT NULL, + expected_row_version BIGINT NOT NULL CHECK (expected_row_version > 0), + reserved_row_version BIGINT NOT NULL CHECK (reserved_row_version = expected_row_version + 1), + provider_subscription_id VARCHAR(255) NOT NULL CHECK (provider_subscription_id ~ '^sub_[A-Za-z0-9]+$'), + provisioning_attempt_id UUID REFERENCES subscription_provisioning_attempts(attempt_id) ON DELETE RESTRICT, + request_payload BYTEA NOT NULL, + request_digest VARCHAR(71) NOT NULL CHECK (request_digest = 'sha256:' || encode(sha256(request_payload), 'hex')), + state VARCHAR(48) NOT NULL CHECK (state IN ('PENDING','COMMITTED','BILLING_RECONCILIATION_TERMINAL_FAILURE')), + row_version BIGINT NOT NULL CHECK (row_version > 0), + attempt_count INTEGER NOT NULL DEFAULT 0 CHECK (attempt_count >= 0), + stalled_count INTEGER NOT NULL DEFAULT 0 CHECK (stalled_count >= 0), + max_attempts INTEGER NOT NULL CHECK (max_attempts > 0), + max_stalled_attempts INTEGER NOT NULL CHECK (max_stalled_attempts > 0), + lease_millis BIGINT NOT NULL CHECK (lease_millis > 0), + backoff_millis BIGINT NOT NULL CHECK (backoff_millis > 0), + observation_age_millis BIGINT NOT NULL CHECK (observation_age_millis > 0), + warning_millis BIGINT NOT NULL CHECK (warning_millis > 0), + grace_millis BIGINT NOT NULL CHECK (grace_millis > 0), + deadline_at TIMESTAMPTZ NOT NULL, + retry_at TIMESTAMPTZ NOT NULL, + last_attempt_id UUID, + last_facts_digest VARCHAR(71), + failure_reason VARCHAR(96), + created_at TIMESTAMPTZ NOT NULL, + created_transaction_id BIGINT NOT NULL DEFAULT txid_current(), + FOREIGN KEY (creation_request_id, subscription_id) REFERENCES subscription_create_operations(request_id, subscription_id) ON DELETE RESTRICT, + UNIQUE (request_id, subscription_id), + UNIQUE (request_id, tenant_id), + CHECK (octet_length(request_payload) BETWEEN 1 AND 32768) +); +CREATE UNIQUE INDEX subscription_lifecycle_one_inflight ON subscription_lifecycle_operations(subscription_id) + WHERE state IN ('PENDING','BILLING_RECONCILIATION_TERMINAL_FAILURE'); + +CREATE TABLE subscription_lifecycle_attempts ( + attempt_id UUID PRIMARY KEY, + request_id UUID NOT NULL REFERENCES subscription_lifecycle_operations(request_id) ON DELETE RESTRICT, + attempt_number INTEGER NOT NULL CHECK (attempt_number > 0), + started_at TIMESTAMPTZ NOT NULL, + expires_at TIMESTAMPTZ NOT NULL CHECK (expires_at > started_at), + UNIQUE (request_id, attempt_number), + UNIQUE (request_id, attempt_id) +); +ALTER TABLE subscription_lifecycle_operations ADD CONSTRAINT subscription_lifecycle_last_attempt_fk + FOREIGN KEY (request_id, last_attempt_id) REFERENCES subscription_lifecycle_attempts(request_id, attempt_id) + DEFERRABLE INITIALLY DEFERRED; + +CREATE TABLE subscription_lifecycle_observations ( + attempt_id UUID PRIMARY KEY, + request_id UUID NOT NULL, + payload BYTEA NOT NULL CHECK (octet_length(payload) BETWEEN 1 AND 32768), + evidence_digest VARCHAR(71) NOT NULL CHECK (evidence_digest = 'sha256:' || encode(sha256(payload), 'hex')), + facts_digest VARCHAR(71) NOT NULL CHECK (facts_digest ~ '^sha256:[0-9a-f]{64}$'), + raw_status VARCHAR(32), + period_start TIMESTAMPTZ, + period_end TIMESTAMPTZ, + read_started_at TIMESTAMPTZ NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + mapping_reason VARCHAR(64) NOT NULL, + recorded_transaction_id BIGINT NOT NULL DEFAULT txid_current(), + FOREIGN KEY (request_id, attempt_id) REFERENCES subscription_lifecycle_attempts(request_id, attempt_id) ON DELETE RESTRICT, + UNIQUE (request_id, attempt_id, evidence_digest) +); + +CREATE TABLE subscription_lifecycle_receipts ( + request_id UUID PRIMARY KEY, + subscription_id UUID NOT NULL, + tenant_id UUID NOT NULL, + request_digest VARCHAR(71) NOT NULL, + subscription_row_version BIGINT NOT NULL CHECK (subscription_row_version > 0), + status VARCHAR(16) NOT NULL CHECK (status IN ('trialing','active','past_due','grace','suspended','canceled')), + plan_quote_digest VARCHAR(71) NOT NULL, + provider_subscription_id VARCHAR(255) NOT NULL, + attempt_id UUID NOT NULL, + observation_digest VARCHAR(71) NOT NULL, + receipt_payload BYTEA NOT NULL CHECK (octet_length(receipt_payload) BETWEEN 1 AND 32768), + receipt_digest VARCHAR(71) NOT NULL CHECK (receipt_digest = 'sha256:' || encode(sha256(receipt_payload), 'hex')), + valid_until TIMESTAMPTZ NOT NULL, + cutoff_at TIMESTAMPTZ, + past_due_since TIMESTAMPTZ, + warning_millis BIGINT NOT NULL CHECK (warning_millis > 0), + grace_millis BIGINT NOT NULL CHECK (grace_millis > 0), + entitlement_version BIGINT NOT NULL CHECK (entitlement_version > 0), + billing_sequence BIGINT NOT NULL CHECK (billing_sequence > 0), + billing_event_id UUID NOT NULL, + billing_event_digest VARCHAR(71) NOT NULL, + authority_generation BIGINT NOT NULL CHECK (authority_generation > 1), + authority_source_version BIGINT NOT NULL CHECK (authority_source_version > 1), + authority_sequence BIGINT NOT NULL CHECK (authority_sequence > 0), + authority_event_id VARCHAR(512) NOT NULL, + authority_event_digest VARCHAR(71) NOT NULL, + committed_at TIMESTAMPTZ NOT NULL, + committed_transaction_id BIGINT NOT NULL DEFAULT txid_current(), + FOREIGN KEY (request_id, subscription_id) REFERENCES subscription_lifecycle_operations(request_id, subscription_id) ON DELETE RESTRICT, + FOREIGN KEY (request_id, attempt_id, observation_digest) REFERENCES subscription_lifecycle_observations(request_id, attempt_id, evidence_digest) ON DELETE RESTRICT, + FOREIGN KEY (tenant_id, billing_sequence, billing_event_id, billing_event_digest) + REFERENCES account_tenant_entitlement_outbox_events(tenant_uuid, tenant_billing_sequence, event_id, event_digest) ON DELETE RESTRICT, + UNIQUE (request_id, subscription_id), + UNIQUE (subscription_id, subscription_row_version) +); +CREATE TABLE subscription_lifecycle_operator_outbox ( + request_id UUID PRIMARY KEY REFERENCES subscription_lifecycle_operations(request_id) ON DELETE RESTRICT, + reason VARCHAR(96) NOT NULL, + recorded_at TIMESTAMPTZ NOT NULL +); +ALTER TABLE subscription ADD COLUMN lifecycle_inflight_request_id UUID, + ADD COLUMN current_receipt_request_id UUID; +ALTER TABLE subscription ADD CONSTRAINT subscription_lifecycle_inflight_fk + FOREIGN KEY (lifecycle_inflight_request_id, subscription_id) REFERENCES subscription_lifecycle_operations(request_id, subscription_id) + DEFERRABLE INITIALLY DEFERRED; +ALTER TABLE subscription ADD CONSTRAINT subscription_current_receipt_fk + FOREIGN KEY (current_receipt_request_id, subscription_id) REFERENCES subscription_lifecycle_receipts(request_id, subscription_id) + DEFERRABLE INITIALLY DEFERRED; + +-- [jooq ignore start] +CREATE FUNCTION account_subscription_lifecycle_current_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.lifecycle_inflight_request_id IS NOT NULL OR NEW.current_receipt_request_id IS NOT NULL THEN + RAISE EXCEPTION 'Subscription cannot begin with lifecycle authority' USING ERRCODE = '23514'; + END IF; + ELSIF OLD.lifecycle_inflight_request_id IS NOT NULL THEN + IF NEW.lifecycle_inflight_request_id IS NULL THEN + IF NEW.current_receipt_request_id IS DISTINCT FROM OLD.lifecycle_inflight_request_id THEN + RAISE EXCEPTION 'Lifecycle fence may clear only into its exact receipt' USING ERRCODE = '23514'; + END IF; + ELSIF NEW.lifecycle_inflight_request_id IS DISTINCT FROM OLD.lifecycle_inflight_request_id + OR NEW.current_receipt_request_id IS DISTINCT FROM OLD.current_receipt_request_id THEN + RAISE EXCEPTION 'In-flight lifecycle ownership cannot be replaced' USING ERRCODE = '23514'; + END IF; + ELSE + IF NEW.current_receipt_request_id IS DISTINCT FROM OLD.current_receipt_request_id THEN + RAISE EXCEPTION 'Committed current receipt cannot be detached or replaced without a lifecycle fence' USING ERRCODE = '23514'; + END IF; + IF NEW.lifecycle_inflight_request_id IS NOT NULL + AND (NEW.status, NEW.provider_subscription_id, NEW.terminal_resolution_id) + IS DISTINCT FROM (OLD.status, OLD.provider_subscription_id, OLD.terminal_resolution_id) THEN + RAISE EXCEPTION 'Lifecycle preparation cannot pre-commit provider state' USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER subscription_lifecycle_current_guard BEFORE INSERT OR UPDATE ON subscription + FOR EACH ROW EXECUTE FUNCTION account_subscription_lifecycle_current_guard(); + +CREATE FUNCTION account_subscription_lifecycle_operation_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Lifecycle operation is retained' USING ERRCODE = '23514'; + ELSIF TG_OP = 'INSERT' THEN + IF NEW.state <> 'PENDING' OR NEW.row_version <> 1 OR NEW.attempt_count <> 0 OR NEW.last_attempt_id IS NOT NULL THEN + RAISE EXCEPTION 'Lifecycle operation must start pending' USING ERRCODE = '23514'; + END IF; + NEW.created_transaction_id := txid_current(); + ELSE + IF OLD.state <> 'PENDING' OR NEW.row_version <> OLD.row_version + 1 + OR (NEW.request_id, NEW.creation_request_id, NEW.subscription_id, NEW.tenant_id, NEW.expected_row_version, + NEW.reserved_row_version, NEW.provider_subscription_id, NEW.provisioning_attempt_id, NEW.request_payload, + NEW.request_digest, NEW.max_attempts, NEW.max_stalled_attempts, NEW.lease_millis, NEW.backoff_millis, + NEW.observation_age_millis, NEW.warning_millis, NEW.grace_millis, NEW.deadline_at, NEW.created_at, NEW.created_transaction_id) + IS DISTINCT FROM (OLD.request_id, OLD.creation_request_id, OLD.subscription_id, OLD.tenant_id, OLD.expected_row_version, + OLD.reserved_row_version, OLD.provider_subscription_id, OLD.provisioning_attempt_id, OLD.request_payload, + OLD.request_digest, OLD.max_attempts, OLD.max_stalled_attempts, OLD.lease_millis, OLD.backoff_millis, + OLD.observation_age_millis, OLD.warning_millis, OLD.grace_millis, OLD.deadline_at, OLD.created_at, OLD.created_transaction_id) + OR NEW.attempt_count NOT BETWEEN OLD.attempt_count AND OLD.attempt_count + 1 THEN + RAISE EXCEPTION 'Lifecycle immutable identity or transition CAS rejected' USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_subscription_lifecycle_observation_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE attempt subscription_lifecycle_attempts%ROWTYPE; operation subscription_lifecycle_operations%ROWTYPE; +BEGIN + SELECT * INTO STRICT attempt FROM subscription_lifecycle_attempts WHERE attempt_id = NEW.attempt_id; + SELECT * INTO STRICT operation FROM subscription_lifecycle_operations WHERE request_id = NEW.request_id; + IF operation.state <> 'PENDING' OR operation.last_attempt_id IS DISTINCT FROM NEW.attempt_id + OR NEW.read_started_at < attempt.started_at OR NEW.observed_at < NEW.read_started_at + OR NEW.observed_at >= attempt.expires_at THEN + RAISE EXCEPTION 'SDK observation is not from the exact live read attempt' USING ERRCODE = '23514'; + END IF; + NEW.recorded_transaction_id := txid_current(); + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_subscription_lifecycle_receipt_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE operation subscription_lifecycle_operations%ROWTYPE; observation subscription_lifecycle_observations%ROWTYPE; + current_row subscription%ROWTYPE; creation subscription_create_operations%ROWTYPE; payload JSONB; +BEGIN + SELECT * INTO STRICT operation FROM subscription_lifecycle_operations WHERE request_id = NEW.request_id; + SELECT * INTO STRICT observation FROM subscription_lifecycle_observations WHERE attempt_id = NEW.attempt_id; + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = NEW.subscription_id; + SELECT * INTO STRICT creation FROM subscription_create_operations WHERE request_id = operation.creation_request_id; + payload := convert_from(NEW.receipt_payload, 'UTF8')::jsonb; + IF operation.state <> 'PENDING' OR current_row.lifecycle_inflight_request_id IS DISTINCT FROM NEW.request_id + OR current_row.row_version <> operation.reserved_row_version + OR NEW.subscription_row_version <> current_row.row_version + 1 + OR NEW.request_digest IS DISTINCT FROM operation.request_digest OR NEW.tenant_id <> operation.tenant_id + OR NEW.provider_subscription_id <> operation.provider_subscription_id + OR NEW.plan_quote_digest <> creation.plan_quote_digest + OR observation.recorded_transaction_id <> txid_current() + OR payload->>'requestId' IS DISTINCT FROM NEW.request_id::text + OR payload->>'subscriptionId' IS DISTINCT FROM NEW.subscription_id::text + OR payload->>'tenantId' IS DISTINCT FROM NEW.tenant_id::text + OR payload->>'subscriptionRowVersion' IS DISTINCT FROM NEW.subscription_row_version::text + OR payload->>'subscriptionStatus' IS DISTINCT FROM NEW.status + OR payload->>'planQuoteDigest' IS DISTINCT FROM NEW.plan_quote_digest + OR payload->>'planQuote' IS DISTINCT FROM convert_from(creation.plan_quote_payload, 'UTF8') + OR payload->>'billingOwnerAccountId' IS DISTINCT FROM creation.account_uuid::text + OR payload->>'billingOwnerVersion' IS DISTINCT FROM creation.owner_version::text + OR payload->>'billingOwnerGeneration' IS DISTINCT FROM creation.owner_generation::text + OR payload->>'paymentInstrumentId' IS DISTINCT FROM creation.payment_instrument_id::text + OR payload->>'reservedInstrumentVersion' IS DISTINCT FROM creation.reserved_instrument_version::text + OR payload->>'customerProvisioningRequestId' IS DISTINCT FROM creation.customer_provisioning_request_id::text + OR payload->>'providerCustomerId' IS DISTINCT FROM creation.provider_customer_id + OR payload->>'entitlementVersion' IS DISTINCT FROM NEW.entitlement_version::text + OR payload->>'observationDigest' IS DISTINCT FROM NEW.observation_digest + OR payload->>'providerSubscriptionId' IS DISTINCT FROM NEW.provider_subscription_id THEN + RAISE EXCEPTION 'Hosting receipt lacks its exact same-transaction provider/current CAS' USING ERRCODE = '23514'; + END IF; + NEW.committed_transaction_id := txid_current(); + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_subscription_lifecycle_consistency() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE current_row subscription%ROWTYPE; operation subscription_lifecycle_operations%ROWTYPE; + receipt subscription_lifecycle_receipts%ROWTYPE; notice subscription_lifecycle_operator_outbox%ROWTYPE; + source_head account_tenant_authority_source_records%ROWTYPE; generation_row RECORD; +BEGIN + IF TG_TABLE_NAME = 'subscription' THEN + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = NEW.subscription_id; + ELSE + SELECT * INTO STRICT operation FROM subscription_lifecycle_operations WHERE request_id = NEW.request_id; + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = operation.subscription_id; + IF operation.state = 'COMMITTED' THEN + SELECT * INTO STRICT receipt FROM subscription_lifecycle_receipts WHERE request_id = operation.request_id; + IF EXISTS (SELECT 1 FROM subscription_lifecycle_operator_outbox WHERE request_id = operation.request_id) THEN + RAISE EXCEPTION 'Committed lifecycle cannot carry terminal-failure work' USING ERRCODE = '23514'; + END IF; + ELSIF operation.state = 'BILLING_RECONCILIATION_TERMINAL_FAILURE' THEN + SELECT * INTO STRICT notice FROM subscription_lifecycle_operator_outbox WHERE request_id = operation.request_id; + IF notice.reason IS DISTINCT FROM operation.failure_reason THEN + RAISE EXCEPTION 'Lifecycle failure lacks its exact operator work item' USING ERRCODE = '23514'; + END IF; + END IF; + END IF; + IF current_row.lifecycle_inflight_request_id IS NOT NULL THEN + SELECT * INTO STRICT operation FROM subscription_lifecycle_operations WHERE request_id = current_row.lifecycle_inflight_request_id; + IF operation.state = 'COMMITTED' OR current_row.row_version <> operation.reserved_row_version + OR current_row.tenant_id <> operation.tenant_id THEN + RAISE EXCEPTION 'In-flight lifecycle operation lacks its exact current fence' USING ERRCODE = '23514'; + END IF; + ELSIF current_row.current_receipt_request_id IS NOT NULL THEN + SELECT * INTO STRICT receipt FROM subscription_lifecycle_receipts WHERE request_id = current_row.current_receipt_request_id; + SELECT * INTO STRICT operation FROM subscription_lifecycle_operations WHERE request_id = receipt.request_id; + IF operation.state <> 'COMMITTED' OR current_row.status <> receipt.status + OR current_row.provider_subscription_id IS DISTINCT FROM receipt.provider_subscription_id + OR current_row.plan_quote_digest <> receipt.plan_quote_digest + OR (current_row.superseded_at IS NULL AND current_row.row_version <> receipt.subscription_row_version) THEN + RAISE EXCEPTION 'Hosting current row lacks its exact committed lifecycle receipt' USING ERRCODE = '23514'; + END IF; + IF current_row.superseded_at IS NULL THEN + SELECT * INTO STRICT source_head FROM account_tenant_authority_source_records WHERE tenant_uuid = current_row.tenant_id; + SELECT generation, source_version INTO STRICT generation_row FROM account_authority_generations + WHERE scope_kind = 'TENANT' AND tenant_uuid = current_row.tenant_id; + IF source_head.last_request_id IS DISTINCT FROM receipt.request_id + OR source_head.last_request_digest IS DISTINCT FROM receipt.request_digest + OR source_head.current_generation <> receipt.authority_generation + OR source_head.current_source_version <> receipt.authority_source_version + OR source_head.last_outbox_sequence <> receipt.authority_sequence + OR source_head.last_event_id IS DISTINCT FROM receipt.authority_event_id + OR source_head.last_event_digest IS DISTINCT FROM receipt.authority_event_digest + OR source_head.tenant_billing_sequence <> receipt.billing_sequence + OR source_head.tenant_billing_event_id IS DISTINCT FROM receipt.billing_event_id + OR source_head.tenant_billing_event_digest IS DISTINCT FROM receipt.billing_event_digest + OR generation_row.generation <> receipt.authority_generation OR generation_row.source_version <> receipt.authority_source_version THEN + RAISE EXCEPTION 'Hosting current receipt requires its atomic canonical source checkpoint' USING ERRCODE = '23514'; + END IF; + END IF; + END IF; + RETURN NULL; +END; +$$; + +-- Extend only the canonical source's receipt branch. Original demo receipt semantics remain intact. +CREATE OR REPLACE FUNCTION account_tenant_authority_source_consistency() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE head RECORD; generation_row RECORD; stream_sequence BIGINT; operation_row RECORD; entitlement_row RECORD; + hosting subscription_lifecycle_receipts%ROWTYPE; current_row subscription%ROWTYPE; billing RECORD; +BEGIN + SELECT * INTO head FROM account_tenant_authority_source_records WHERE outbox_stream_key = NEW.outbox_stream_key; + SELECT generation, source_version INTO generation_row FROM account_authority_generations WHERE scope_kind = 'TENANT' AND tenant_uuid = NEW.tenant_uuid; + SELECT last_sequence INTO stream_sequence FROM account_authority_outbox_streams WHERE outbox_stream_key = NEW.outbox_stream_key; + IF head.outbox_stream_key IS NULL OR head.last_outbox_sequence <= 0 + OR head.current_generation IS DISTINCT FROM generation_row.generation + OR head.current_source_version IS DISTINCT FROM generation_row.source_version OR stream_sequence IS DISTINCT FROM head.last_outbox_sequence THEN + RAISE EXCEPTION 'Tenant authority source checkpoint is not the current Account generation' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_consistent'; + END IF; + SELECT * INTO hosting FROM subscription_lifecycle_receipts WHERE request_id = head.last_request_id; + IF FOUND THEN + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = hosting.subscription_id; + SELECT * INTO STRICT operation_row FROM subscription_lifecycle_operations WHERE request_id = hosting.request_id; + SELECT * INTO STRICT billing FROM account_tenant_entitlement_outbox_events + WHERE tenant_uuid = hosting.tenant_id AND tenant_billing_sequence = hosting.billing_sequence; + IF operation_row.state <> 'COMMITTED' OR hosting.tenant_id <> NEW.tenant_uuid + OR current_row.superseded_at IS NOT NULL OR current_row.current_receipt_request_id IS DISTINCT FROM hosting.request_id + OR current_row.lifecycle_inflight_request_id IS NOT NULL OR current_row.row_version <> hosting.subscription_row_version + OR current_row.status <> hosting.status OR current_row.provider_subscription_id IS DISTINCT FROM hosting.provider_subscription_id + OR hosting.request_digest IS DISTINCT FROM head.last_request_digest + OR hosting.authority_generation <> head.current_generation OR hosting.authority_source_version <> head.current_source_version + OR hosting.authority_sequence <> head.last_outbox_sequence OR hosting.authority_event_id IS DISTINCT FROM head.last_event_id + OR hosting.authority_event_digest IS DISTINCT FROM head.last_event_digest + OR hosting.billing_sequence <> head.tenant_billing_sequence OR hosting.billing_event_id IS DISTINCT FROM head.tenant_billing_event_id + OR hosting.billing_event_digest IS DISTINCT FROM head.tenant_billing_event_digest + OR convert_from(billing.payload, 'UTF8')::jsonb->'receipt' IS DISTINCT FROM convert_from(hosting.receipt_payload, 'UTF8')::jsonb THEN + RAISE EXCEPTION 'Hosting tenant source lacks its exact current receipt and billing event' USING ERRCODE = '23514'; + END IF; + RETURN NULL; + END IF; + SELECT request_id, tenant_uuid, request_digest, status, tenant_billing_sequence, event_id, event_digest, + tenant_authority_outbox_stream_key, tenant_authority_outbox_sequence, tenant_authority_event_id, tenant_authority_event_digest + INTO operation_row FROM account_demo_tenant_entitlement_operations WHERE request_id = head.last_request_id; + SELECT * INTO entitlement_row FROM account_demo_tenant_entitlements WHERE tenant_uuid = NEW.tenant_uuid; + IF operation_row.status IS DISTINCT FROM 'COMMITTED' OR operation_row.tenant_uuid IS DISTINCT FROM NEW.tenant_uuid + OR operation_row.request_digest IS DISTINCT FROM head.last_request_digest + OR operation_row.tenant_billing_sequence IS DISTINCT FROM head.tenant_billing_sequence + OR operation_row.event_id IS DISTINCT FROM head.tenant_billing_event_id OR operation_row.event_digest IS DISTINCT FROM head.tenant_billing_event_digest + OR operation_row.tenant_authority_outbox_stream_key IS DISTINCT FROM head.outbox_stream_key + OR operation_row.tenant_authority_outbox_sequence IS DISTINCT FROM head.last_outbox_sequence + OR operation_row.tenant_authority_event_id IS DISTINCT FROM head.last_event_id OR operation_row.tenant_authority_event_digest IS DISTINCT FROM head.last_event_digest + OR entitlement_row.tenant_uuid IS DISTINCT FROM NEW.tenant_uuid + OR entitlement_row.tenant_authority_generation IS DISTINCT FROM head.current_generation OR entitlement_row.tenant_authority_source_version IS DISTINCT FROM head.current_source_version + OR entitlement_row.tenant_billing_sequence IS DISTINCT FROM head.tenant_billing_sequence + OR entitlement_row.event_id IS DISTINCT FROM head.tenant_billing_event_id OR entitlement_row.event_digest IS DISTINCT FROM head.tenant_billing_event_digest + OR entitlement_row.tenant_authority_outbox_stream_key IS DISTINCT FROM head.outbox_stream_key + OR entitlement_row.tenant_authority_outbox_sequence IS DISTINCT FROM head.last_outbox_sequence + OR entitlement_row.tenant_authority_event_id IS DISTINCT FROM head.last_event_id OR entitlement_row.tenant_authority_event_digest IS DISTINCT FROM head.last_event_digest THEN + RAISE EXCEPTION 'Tenant authority source lacks its exact current Account receipt and entitlement' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_receipt'; + END IF; + RETURN NULL; +END; +$$; + +CREATE TRIGGER subscription_lifecycle_operation_guard BEFORE INSERT OR UPDATE OR DELETE ON subscription_lifecycle_operations + FOR EACH ROW EXECUTE FUNCTION account_subscription_lifecycle_operation_guard(); +CREATE TRIGGER subscription_lifecycle_observation_guard BEFORE INSERT ON subscription_lifecycle_observations + FOR EACH ROW EXECUTE FUNCTION account_subscription_lifecycle_observation_guard(); +CREATE TRIGGER subscription_lifecycle_receipt_guard BEFORE INSERT ON subscription_lifecycle_receipts + FOR EACH ROW EXECUTE FUNCTION account_subscription_lifecycle_receipt_guard(); +CREATE CONSTRAINT TRIGGER subscription_lifecycle_current_consistency AFTER INSERT OR UPDATE ON subscription + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_lifecycle_consistency(); +CREATE CONSTRAINT TRIGGER subscription_lifecycle_operation_consistency AFTER INSERT OR UPDATE ON subscription_lifecycle_operations + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_lifecycle_consistency(); +CREATE CONSTRAINT TRIGGER subscription_lifecycle_receipt_consistency AFTER INSERT ON subscription_lifecycle_receipts + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_lifecycle_consistency(); +CREATE CONSTRAINT TRIGGER subscription_lifecycle_notice_consistency AFTER INSERT ON subscription_lifecycle_operator_outbox + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_lifecycle_consistency(); + +CREATE TRIGGER subscription_lifecycle_operation_no_truncate BEFORE TRUNCATE ON subscription_lifecycle_operations FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_lifecycle_attempt_immutable BEFORE UPDATE OR DELETE ON subscription_lifecycle_attempts FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_lifecycle_attempt_no_truncate BEFORE TRUNCATE ON subscription_lifecycle_attempts FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_lifecycle_observation_immutable BEFORE UPDATE OR DELETE ON subscription_lifecycle_observations FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_lifecycle_observation_no_truncate BEFORE TRUNCATE ON subscription_lifecycle_observations FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_lifecycle_receipt_immutable BEFORE UPDATE OR DELETE ON subscription_lifecycle_receipts FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_lifecycle_receipt_no_truncate BEFORE TRUNCATE ON subscription_lifecycle_receipts FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_lifecycle_notice_immutable BEFORE UPDATE OR DELETE ON subscription_lifecycle_operator_outbox FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_lifecycle_notice_no_truncate BEFORE TRUNCATE ON subscription_lifecycle_operator_outbox FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); + +CREATE FUNCTION account_subscription_provisioning_confirmed_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE work subscription_provisioning_work%ROWTYPE; +BEGIN + SELECT * INTO STRICT work FROM subscription_provisioning_work WHERE request_id = NEW.request_id; + IF work.phase = 'CONFIRMED' AND NOT EXISTS ( + SELECT 1 FROM subscription_lifecycle_operations operation + JOIN subscription_lifecycle_receipts receipt USING (request_id, subscription_id) + WHERE operation.creation_request_id = work.request_id AND operation.subscription_id = work.subscription_id + AND operation.provisioning_attempt_id = work.last_attempt_id AND operation.state = 'COMMITTED') THEN + RAISE EXCEPTION 'Provisioning confirmation lacks its exact lifecycle receipt' USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; +CREATE CONSTRAINT TRIGGER subscription_provisioning_confirmed_guard AFTER INSERT OR UPDATE ON subscription_provisioning_work + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_provisioning_confirmed_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1032__hosting_subscription_first_provider_dispatch.sql b/services/account-service/src/main/resources/db/migration/V1032__hosting_subscription_first_provider_dispatch.sql new file mode 100644 index 0000000000..e3ec7519dd --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1032__hosting_subscription_first_provider_dispatch.sql @@ -0,0 +1,82 @@ +-- Separate remote dispatch from renewable worker attempts. Presence/replay is never permission. +CREATE TABLE subscription_provider_dispatch_claim ( + creation_request_id UUID PRIMARY KEY, + subscription_id UUID NOT NULL UNIQUE, + provider_operation_id UUID NOT NULL UNIQUE, + dispatch_id UUID NOT NULL UNIQUE CHECK (dispatch_id <> '00000000-0000-0000-0000-000000000000'::UUID), + classification VARCHAR(24) NOT NULL CHECK (classification IN ('FIRST_DISPATCH', 'PREEXISTING_UNKNOWN')), + first_attempt_id UUID, + first_claimed_row_version BIGINT, + recorded_at TIMESTAMPTZ NOT NULL, + CHECK ((first_attempt_id IS NULL) = (first_claimed_row_version IS NULL)), + CHECK (classification <> 'FIRST_DISPATCH' OR first_attempt_id IS NOT NULL), + FOREIGN KEY (creation_request_id, subscription_id) + REFERENCES subscription_create_operations(request_id, subscription_id) ON DELETE RESTRICT, + FOREIGN KEY (creation_request_id, provider_operation_id) + REFERENCES subscription_create_operations(request_id, subscription_provisioning_request_id) ON DELETE RESTRICT, + FOREIGN KEY (first_attempt_id, creation_request_id, subscription_id, first_claimed_row_version) + REFERENCES subscription_provisioning_attempts(attempt_id, request_id, subscription_id, claimed_row_version) ON DELETE RESTRICT +); + +-- Existing attempt-1/work rows may already have unknown remote effects. Preserve their bytes and +-- add only a non-authorizing guard. No dispatched/absent/canceled result is inferred. +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) +SELECT w.request_id, w.subscription_id, c.subscription_provisioning_request_id, + gen_random_uuid(), 'PREEXISTING_UNKNOWN', a.attempt_id, a.claimed_row_version, clock_timestamp() +FROM subscription_provisioning_work w +JOIN subscription_create_operations c ON c.request_id = w.request_id +LEFT JOIN subscription_provisioning_attempts a ON a.request_id = w.request_id AND a.attempt_number = 1; + +-- [jooq ignore start] +CREATE FUNCTION account_subscription_provider_dispatch_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + creation subscription_create_operations%ROWTYPE; + current_row subscription%ROWTYPE; + work subscription_provisioning_work%ROWTYPE; + attempt subscription_provisioning_attempts%ROWTYPE; + instrument payment_instrument%ROWTYPE; + customer billing_customer%ROWTYPE; +BEGIN + SELECT * INTO STRICT creation FROM subscription_create_operations WHERE request_id = NEW.creation_request_id; + PERFORM 1 FROM accounts WHERE account_uuid = creation.account_uuid FOR UPDATE; + SELECT * INTO STRICT instrument FROM payment_instrument WHERE instrument_uuid = creation.payment_instrument_id FOR UPDATE; + SELECT * INTO STRICT customer FROM billing_customer WHERE account_uuid = creation.account_uuid FOR UPDATE; + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = creation.subscription_id FOR UPDATE; + SELECT * INTO STRICT work FROM subscription_provisioning_work WHERE request_id = creation.request_id FOR UPDATE; + SELECT * INTO STRICT attempt FROM subscription_provisioning_attempts WHERE attempt_id = NEW.first_attempt_id; + IF NEW.classification <> 'FIRST_DISPATCH' + OR NEW.subscription_id <> creation.subscription_id + OR NEW.provider_operation_id <> creation.subscription_provisioning_request_id + OR NEW.dispatch_id IN (creation.request_id, creation.subscription_provisioning_request_id, creation.cleanup_provider_identity) + OR NEW.first_claimed_row_version <> attempt.claimed_row_version + OR attempt.request_id <> creation.request_id OR attempt.subscription_id <> creation.subscription_id + OR work.phase <> 'CLAIMED' OR work.last_attempt_id <> attempt.attempt_id + OR work.attempt_count > work.max_attempts OR work.attempt_count > work.max_stalled_attempts + OR current_row.row_version <> attempt.claimed_row_version + OR current_row.status <> 'provisioning' OR current_row.provider_subscription_id IS NOT NULL + OR current_row.superseded_at IS NOT NULL OR current_row.lifecycle_inflight_request_id IS NOT NULL + OR instrument.account_uuid <> creation.account_uuid OR instrument.state <> 'ATTACHABLE' + OR instrument.row_version <> creation.reserved_instrument_version + OR instrument.customer_provisioning_request_id <> creation.customer_provisioning_request_id + OR instrument.provider_customer_id <> creation.provider_customer_id + OR customer.state <> 'CONFIRMED' OR customer.provider_customer_id <> creation.provider_customer_id + OR customer.customer_provisioning_request_id <> creation.customer_provisioning_request_id + OR NEW.recorded_at < attempt.claimed_at OR NEW.recorded_at >= attempt.expires_at + OR NEW.recorded_at >= work.deadline_at THEN + RAISE EXCEPTION 'Provider dispatch lacks exact live original provisioning fence' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER subscription_provider_dispatch_insert_guard + BEFORE INSERT ON subscription_provider_dispatch_claim + FOR EACH ROW EXECUTE FUNCTION account_subscription_provider_dispatch_guard(); +CREATE TRIGGER subscription_provider_dispatch_immutable + BEFORE UPDATE OR DELETE ON subscription_provider_dispatch_claim + FOR EACH ROW EXECUTE FUNCTION account_billing_prerequisite_no_erasure(); +CREATE TRIGGER subscription_provider_dispatch_no_truncate + BEFORE TRUNCATE ON subscription_provider_dispatch_claim + FOR EACH STATEMENT EXECUTE FUNCTION account_billing_prerequisite_no_erasure(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1036__hosting_subscription_terminal_resolution.sql b/services/account-service/src/main/resources/db/migration/V1036__hosting_subscription_terminal_resolution.sql new file mode 100644 index 0000000000..11bb675ceb --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1036__hosting_subscription_terminal_resolution.sql @@ -0,0 +1,202 @@ +-- Internal cancellation-only recovery. No actor authentication, provider absence, transfer, +-- caller registration or operational permission is established by these stored comparison facts. +CREATE TABLE subscription_lifecycle_terminal_resolutions ( + resolution_request_id UUID PRIMARY KEY CHECK (resolution_request_id <> '00000000-0000-0000-0000-000000000000'::uuid), + failed_request_id UUID NOT NULL REFERENCES subscription_lifecycle_operations(request_id) ON DELETE RESTRICT, + creation_request_id UUID NOT NULL REFERENCES subscription_create_operations(request_id) ON DELETE RESTRICT, + subscription_id UUID NOT NULL REFERENCES subscription(subscription_id) ON DELETE RESTRICT, + tenant_id UUID NOT NULL, + expected_failed_version BIGINT NOT NULL CHECK (expected_failed_version > 0), + expected_subscription_version BIGINT NOT NULL CHECK (expected_subscription_version > 0 AND expected_subscription_version < 9223372036854775805), + actor_account_id UUID NOT NULL REFERENCES accounts(account_uuid) ON DELETE RESTRICT, + control_ui_issuance_operation_id UUID NOT NULL CHECK (control_ui_issuance_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid), + control_ui_token_hash VARCHAR(64) NOT NULL CHECK (control_ui_token_hash ~ '^[0-9a-f]{64}$'), + audit_event_id UUID NOT NULL UNIQUE REFERENCES account_audit_outbox(audit_event_id) ON DELETE RESTRICT, + audit_reason TEXT NOT NULL CHECK (octet_length(audit_reason) BETWEEN 1 AND 1000), + request_payload BYTEA NOT NULL CHECK (octet_length(request_payload) BETWEEN 1 AND 32768), + request_digest VARCHAR(71) NOT NULL CHECK (request_digest = 'sha256:' || encode(sha256(request_payload), 'hex')), + attempt_id UUID NOT NULL UNIQUE, + captured_at TIMESTAMPTZ NOT NULL, + expires_at TIMESTAMPTZ NOT NULL CHECK (expires_at > captured_at), + authenticated_at TIMESTAMPTZ NOT NULL, + authorization_outcome VARCHAR(32) NOT NULL DEFAULT 'PRIMARY_AUTHENTICATED' CHECK (authorization_outcome = 'PRIMARY_AUTHENTICATED'), + state VARCHAR(16) NOT NULL CHECK (state IN ('PREPARED', 'COMMITTED')), + result_row_version BIGINT, + receipt_digest VARCHAR(71), + committed_at TIMESTAMPTZ, + created_transaction_id BIGINT NOT NULL DEFAULT txid_current(), + CHECK (resolution_request_id <> failed_request_id), + CHECK (authenticated_at >= captured_at AND authenticated_at < expires_at), + CHECK ((state = 'PREPARED' AND result_row_version IS NULL AND receipt_digest IS NULL AND committed_at IS NULL) + OR (state = 'COMMITTED' AND result_row_version IS NOT NULL AND receipt_digest IS NOT NULL + AND result_row_version = expected_subscription_version + 2 + AND receipt_digest ~ '^sha256:[0-9a-f]{64}$' AND committed_at IS NOT NULL)), + UNIQUE (failed_request_id) +); + +-- Failure history stays immutable. Its retained subscription fence still blocks normal prepare; +-- only the journal-backed atomic cancellation transition may replace that fence. +DROP INDEX subscription_lifecycle_one_inflight; +CREATE UNIQUE INDEX subscription_lifecycle_one_inflight ON subscription_lifecycle_operations(subscription_id) + WHERE state = 'PENDING'; + +-- [jooq ignore start] +ALTER TABLE subscription_lifecycle_terminal_resolutions + ADD CONSTRAINT subscription_terminal_resolution_reason_nfc CHECK (audit_reason IS NFC NORMALIZED); + +CREATE FUNCTION account_subscription_terminal_resolution_guard() RETURNS trigger LANGUAGE plpgsql AS $$ +DECLARE failed subscription_lifecycle_operations%ROWTYPE; current_row subscription%ROWTYPE; + audit account_audit_outbox%ROWTYPE; payload JSONB; field_count INTEGER; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Terminal lifecycle resolution is retained' USING ERRCODE = '23514'; + ELSIF TG_OP = 'UPDATE' THEN + IF OLD.state <> 'PREPARED' OR NEW.state <> 'COMMITTED' + OR (to_jsonb(NEW) - ARRAY['state','result_row_version','receipt_digest','committed_at']) + IS DISTINCT FROM (to_jsonb(OLD) - ARRAY['state','result_row_version','receipt_digest','committed_at']) + OR OLD.created_transaction_id <> txid_current() THEN + RAISE EXCEPTION 'Terminal lifecycle resolution is immutable outside its owner commit' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + SELECT * INTO STRICT failed FROM subscription_lifecycle_operations WHERE request_id = NEW.failed_request_id FOR UPDATE; + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = NEW.subscription_id FOR UPDATE; + SELECT * INTO STRICT audit FROM account_audit_outbox WHERE audit_event_id = NEW.audit_event_id; + payload := convert_from(NEW.request_payload, 'UTF8')::jsonb; + SELECT count(*) INTO field_count FROM jsonb_object_keys(payload); + IF NEW.state <> 'PREPARED' OR failed.state <> 'BILLING_RECONCILIATION_TERMINAL_FAILURE' + OR failed.row_version <> NEW.expected_failed_version + OR failed.creation_request_id <> NEW.creation_request_id OR failed.subscription_id <> NEW.subscription_id + OR failed.tenant_id <> NEW.tenant_id OR current_row.tenant_id <> NEW.tenant_id + OR current_row.account_uuid <> NEW.actor_account_id OR current_row.creation_request_id <> NEW.creation_request_id + OR current_row.row_version <> NEW.expected_subscription_version OR current_row.superseded_at IS NOT NULL + OR current_row.lifecycle_inflight_request_id IS DISTINCT FROM NEW.failed_request_id + OR audit.scope <> 'tenant' OR audit.tenant_identity_version <> 2 OR audit.tenant_uuid IS DISTINCT FROM NEW.tenant_id + OR audit.producer_service <> 'account-service' OR audit.event_type <> 'HOSTING_SUBSCRIPTION_TERMINAL_RESOLVED' + OR audit.payload_digest <> NEW.request_digest OR audit.payload IS DISTINCT FROM convert_from(NEW.request_payload, 'UTF8') + OR field_count <> 14 OR payload->>'schemaVersion' IS DISTINCT FROM 'account-hosting-terminal-resolution/v1' + OR payload->>'outcome' IS DISTINCT FROM 'CANCELED' + OR payload->>'resolutionRequestId' IS DISTINCT FROM NEW.resolution_request_id::text + OR payload->>'failedRequestId' IS DISTINCT FROM NEW.failed_request_id::text + OR payload->>'creationRequestId' IS DISTINCT FROM NEW.creation_request_id::text + OR payload->>'subscriptionId' IS DISTINCT FROM NEW.subscription_id::text + OR payload->>'tenantId' IS DISTINCT FROM NEW.tenant_id::text + OR payload->>'expectedFailedOperationVersion' IS DISTINCT FROM NEW.expected_failed_version::text + OR payload->>'expectedSubscriptionVersion' IS DISTINCT FROM NEW.expected_subscription_version::text + OR payload->>'actorAccountId' IS DISTINCT FROM NEW.actor_account_id::text + OR payload->>'controlUiIssuanceOperationId' IS DISTINCT FROM NEW.control_ui_issuance_operation_id::text + OR payload->>'controlUiTokenHash' IS DISTINCT FROM NEW.control_ui_token_hash + OR payload->>'auditEventId' IS DISTINCT FROM NEW.audit_event_id::text + OR payload->>'auditReason' IS DISTINCT FROM NEW.audit_reason + OR btrim(NEW.audit_reason, E'\t\n\f\r ' || chr(11) || chr(133) || chr(160) || chr(5760) + || chr(8192) || chr(8193) || chr(8194) || chr(8195) || chr(8196) || chr(8197) + || chr(8198) || chr(8199) || chr(8200) || chr(8201) || chr(8202) || chr(8232) + || chr(8233) || chr(8239) || chr(8287) || chr(12288)) = '' THEN + RAISE EXCEPTION 'Terminal lifecycle resolution lacks its exact failed target and audit' USING ERRCODE = '23514'; + END IF; + NEW.created_transaction_id := txid_current(); + RETURN NEW; +END; +$$; +CREATE TRIGGER subscription_terminal_resolution_guard BEFORE INSERT OR UPDATE OR DELETE ON subscription_lifecycle_terminal_resolutions + FOR EACH ROW EXECUTE FUNCTION account_subscription_terminal_resolution_guard(); + +CREATE OR REPLACE FUNCTION account_subscription_lifecycle_current_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.lifecycle_inflight_request_id IS NOT NULL OR NEW.current_receipt_request_id IS NOT NULL THEN + RAISE EXCEPTION 'Subscription cannot begin with lifecycle authority' USING ERRCODE = '23514'; + END IF; + ELSIF OLD.lifecycle_inflight_request_id IS NOT NULL THEN + IF NEW.lifecycle_inflight_request_id IS NULL THEN + IF NEW.current_receipt_request_id IS DISTINCT FROM OLD.lifecycle_inflight_request_id THEN + RAISE EXCEPTION 'Lifecycle fence may clear only into its exact receipt' USING ERRCODE = '23514'; + END IF; + ELSIF NEW.lifecycle_inflight_request_id IS DISTINCT FROM OLD.lifecycle_inflight_request_id + OR NEW.current_receipt_request_id IS DISTINCT FROM OLD.current_receipt_request_id THEN + IF NEW.current_receipt_request_id IS DISTINCT FROM OLD.current_receipt_request_id + OR NOT EXISTS (SELECT 1 FROM subscription_lifecycle_terminal_resolutions resolution + JOIN subscription_lifecycle_operations operation ON operation.request_id = resolution.resolution_request_id + WHERE resolution.failed_request_id = OLD.lifecycle_inflight_request_id + AND resolution.resolution_request_id = NEW.lifecycle_inflight_request_id + AND resolution.subscription_id = OLD.subscription_id AND resolution.state = 'PREPARED' + AND resolution.expected_subscription_version = OLD.row_version + AND resolution.created_transaction_id = txid_current() + AND operation.state = 'PENDING' AND operation.request_digest = resolution.request_digest + AND operation.reserved_row_version = NEW.row_version + AND operation.creation_request_id = OLD.creation_request_id + AND operation.tenant_id = OLD.tenant_id) THEN + RAISE EXCEPTION 'In-flight lifecycle ownership cannot be replaced without exact resolution' USING ERRCODE = '23514'; + END IF; + END IF; + ELSE + IF NEW.current_receipt_request_id IS DISTINCT FROM OLD.current_receipt_request_id THEN + RAISE EXCEPTION 'Committed current receipt cannot be detached or replaced without a lifecycle fence' USING ERRCODE = '23514'; + END IF; + IF NEW.lifecycle_inflight_request_id IS NOT NULL + AND (NEW.status, NEW.provider_subscription_id, NEW.terminal_resolution_id) + IS DISTINCT FROM (OLD.status, OLD.provider_subscription_id, OLD.terminal_resolution_id) THEN + RAISE EXCEPTION 'Lifecycle preparation cannot pre-commit provider state' USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_subscription_terminal_resolution_consistency() RETURNS trigger LANGUAGE plpgsql AS $$ +DECLARE resolution subscription_lifecycle_terminal_resolutions%ROWTYPE; operation subscription_lifecycle_operations%ROWTYPE; + receipt subscription_lifecycle_receipts%ROWTYPE; observation subscription_lifecycle_observations%ROWTYPE; + current_row subscription%ROWTYPE; failed subscription_lifecycle_operations%ROWTYPE; +BEGIN + SELECT * INTO STRICT resolution FROM subscription_lifecycle_terminal_resolutions WHERE resolution_request_id = NEW.resolution_request_id; + SELECT * INTO STRICT failed FROM subscription_lifecycle_operations WHERE request_id = resolution.failed_request_id; + SELECT * INTO STRICT operation FROM subscription_lifecycle_operations WHERE request_id = resolution.resolution_request_id; + SELECT * INTO STRICT receipt FROM subscription_lifecycle_receipts WHERE request_id = resolution.resolution_request_id; + SELECT * INTO STRICT observation FROM subscription_lifecycle_observations WHERE attempt_id = resolution.attempt_id; + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = resolution.subscription_id; + IF resolution.state <> 'COMMITTED' OR resolution.created_transaction_id <> txid_current() + OR failed.state <> 'BILLING_RECONCILIATION_TERMINAL_FAILURE' OR failed.row_version <> resolution.expected_failed_version + OR operation.state <> 'COMMITTED' OR operation.request_digest <> resolution.request_digest + OR operation.request_payload <> resolution.request_payload OR operation.creation_request_id <> resolution.creation_request_id + OR receipt.status <> 'canceled' OR receipt.request_digest <> resolution.request_digest + OR receipt.subscription_id <> resolution.subscription_id OR receipt.tenant_id <> resolution.tenant_id + OR receipt.subscription_row_version <> resolution.result_row_version OR receipt.receipt_digest <> resolution.receipt_digest + OR receipt.attempt_id <> resolution.attempt_id OR receipt.committed_transaction_id <> txid_current() + OR observation.raw_status <> 'canceled' OR observation.recorded_transaction_id <> txid_current() + OR convert_from(observation.payload, 'UTF8')::jsonb->>'kind' IS DISTINCT FROM 'SDK_OBSERVED' + OR convert_from(observation.payload, 'UTF8')::jsonb->>'providerStatus' IS DISTINCT FROM 'canceled' + OR observation.read_started_at < resolution.captured_at OR observation.observed_at > resolution.authenticated_at + OR resolution.authenticated_at >= resolution.expires_at OR resolution.committed_at >= resolution.expires_at + OR current_row.current_receipt_request_id IS DISTINCT FROM resolution.resolution_request_id + OR current_row.lifecycle_inflight_request_id IS NOT NULL OR current_row.row_version <> resolution.result_row_version + OR current_row.status <> 'canceled' OR current_row.terminal_resolution_id IS NULL + OR NOT EXISTS (SELECT 1 FROM subscription_instrument_reservations reservation + WHERE reservation.request_id = resolution.creation_request_id AND reservation.subscription_id = resolution.subscription_id + AND reservation.terminal_resolution_id = current_row.terminal_resolution_id AND reservation.released_at IS NOT NULL) THEN + RAISE EXCEPTION 'Cancellation resolution lacks its atomic receipt, retained failure and terminal reservation' USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; +CREATE CONSTRAINT TRIGGER subscription_terminal_resolution_consistency AFTER INSERT OR UPDATE ON subscription_lifecycle_terminal_resolutions + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_terminal_resolution_consistency(); +CREATE TRIGGER subscription_terminal_resolution_no_truncate BEFORE TRUNCATE ON subscription_lifecycle_terminal_resolutions + FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); + +-- Replacing the partial index must not make unowned dangling PENDING rows committable. +CREATE FUNCTION account_subscription_pending_owner_consistency() RETURNS trigger LANGUAGE plpgsql AS $$ +DECLARE operation subscription_lifecycle_operations%ROWTYPE; current_row subscription%ROWTYPE; +BEGIN + SELECT * INTO STRICT operation FROM subscription_lifecycle_operations WHERE request_id = NEW.request_id; + IF operation.state = 'PENDING' THEN + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = operation.subscription_id; + IF current_row.lifecycle_inflight_request_id IS DISTINCT FROM operation.request_id THEN + RAISE EXCEPTION 'Pending lifecycle requires its exact retained current fence' USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NULL; +END; +$$; +CREATE CONSTRAINT TRIGGER subscription_pending_owner_consistency AFTER INSERT OR UPDATE ON subscription_lifecycle_operations + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_pending_owner_consistency(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java index cb6e7bc04c..8a1838fbec 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java @@ -7,10 +7,9 @@ import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; -import java.nio.charset.StandardCharsets; -import java.time.Instant; import java.time.LocalDateTime; import java.util.List; +import java.util.Objects; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; @@ -20,16 +19,15 @@ import net.firedevops.firemud.accountservice.client.EntityManagementClient; import net.firedevops.firemud.accountservice.client.GameSessionClient; import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.accountservice.dto.ConnectTokenRequest; import net.firedevops.firemud.accountservice.dto.CreateAccountRequest; -import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; -import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; -import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; import net.firedevops.firemud.accountservice.dto.VerifyEmailRequest; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException; import net.firedevops.firemud.accountservice.service.AccountService; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.session.SessionService; import net.firedevops.firemud.common.security.HttpAuthProperties; import net.firedevops.firemud.common.security.HttpAuthRoleRequirement; import net.firedevops.firemud.common.security.HttpJwtAuthInterceptor; @@ -93,6 +91,7 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private JwtUtil jwtUtil; @Autowired private DSLContext dsl; @Autowired private AccountService accountService; + @Autowired private SessionService realAccountSessions; @Autowired private HttpAuthProperties httpAuthProperties; @Autowired private ObjectProvider httpJwtAuthInterceptorProvider; @@ -103,18 +102,6 @@ static void configure(DynamicPropertyRegistry registry) { private net.firedevops.firemud.accountservice.repository.EmailVerificationTokenRepository emailVerificationTokenRepository; - @org.springframework.test.context.bean.override.mockito.MockitoSpyBean - private net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository - joinOperationRepository; - - @org.springframework.test.context.bean.override.mockito.MockitoSpyBean - private net.firedevops.firemud.accountservice.repository.SubscriptionRepository - subscriptionRepository; - - @Autowired - private net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository - connectScopeRepository; - @Autowired private org.springframework.transaction.PlatformTransactionManager transactionManager; @Autowired @@ -409,655 +396,6 @@ private List emailVerificationState(EmailVerificationFixture fixture) { private record EmailVerificationFixture(long accountId, String token) {} - @Test - void publicJoinLostCommitAcknowledgementAndReadbackReplayTheSameOriginalOnce() { - var fixture = publicJoinFixture(); - var readbackDropped = losePublicJoinTerminalResponse(fixture); - - assertPublicJoinUnavailable(fixture); - - assertThat(readbackDropped).isTrue(); - assertPublicJoinCommittedOnce(fixture); - var committed = publicJoinState(fixture); - var replay = publicJoin(fixture); - - assertThat(replay.success()).isTrue(); - assertThat(replay.replayed()).isTrue(); - assertThat(replay.outcomeCode()).isEqualTo("JOINED"); - assertThat(replay.accountId()).isEqualTo(fixture.accountUuid()); - assertPublicJoinCommittedOnce(fixture); - assertThat(publicJoinState(fixture)).isEqualTo(committed); - } - - @Test - void publicJoinFailureBeforeCommitRollsBackEffectsAndContinuesTheOriginalIntent() { - var fixture = publicJoinFixture(); - var failOnce = new AtomicBoolean(true); - org.mockito.Mockito.doAnswer( - invocation -> { - invocation.callRealMethod(); - if (failOnce.compareAndSet(true, false)) { - // The real terminal UPDATE ran, but its owner transaction has not committed. - throw new IllegalStateException("Injected failure before public JOIN commit"); - } - return null; - }) - .when(joinOperationRepository) - .finish( - org.mockito.ArgumentMatchers.eq(fixture.caller().requestId()), - org.mockito.ArgumentMatchers.eq("COMMITTED"), - org.mockito.ArgumentMatchers.eq("JOINED"), - org.mockito.ArgumentMatchers.any(), - org.mockito.ArgumentMatchers.any(), - org.mockito.ArgumentMatchers.any()); - - assertPublicJoinUnavailable(fixture); - - assertThat(failOnce).isFalse(); - var pending = - dsl.fetchOne( - "SELECT status, outcome, intent_digest, request_digest, membership_id " - + "FROM account_join_operations WHERE request_id = ?", - fixture.caller().requestId()); - assertThat(pending).isNotNull(); - assertThat(pending.get("status", String.class)).isEqualTo("PENDING"); - assertThat(pending.get("intent_digest", String.class)).startsWith("sha256:"); - assertThat(pending.get("outcome")).isNull(); - assertThat(pending.get("request_digest")).isNull(); - assertThat(pending.get("membership_id")).isNull(); - assertThat(publicJoinMembershipCount(fixture)).isZero(); - assertThat(publicJoinAuditCount(fixture)).isZero(); - - var continued = publicJoin(fixture); - - assertThat(continued.success()).isTrue(); - assertThat(continued.replayed()).isFalse(); - assertThat(continued.outcomeCode()).isEqualTo("JOINED"); - assertPublicJoinCommittedOnce(fixture); - assertThat(publicJoin(fixture).replayed()).isTrue(); - assertPublicJoinCommittedOnce(fixture); - } - - @Test - void publicJoinLostResponseThenExpiredScopePreservesTheCompleteCommittedOriginal() { - var fixture = publicJoinFixture(); - var readbackDropped = losePublicJoinTerminalResponse(fixture); - assertPublicJoinUnavailable(fixture); - assertThat(readbackDropped).isTrue(); - assertPublicJoinCommittedOnce(fixture); - var committed = publicJoinState(fixture); - String retainedExpiry = - dsl.resultQuery( - "SELECT s.connect_scope_expires_at FROM account_connect_scope_records s " - + "JOIN account_join_operations j ON j.scope_token_hash = s.scope_token_hash " - + "WHERE j.request_id = ?", - fixture.caller().requestId()) - .fetchOne(0, String.class); - assertThat(retainedExpiry).isNotBlank(); - Instant expiredNow = Instant.parse(retainedExpiry).plusSeconds(1); - - // Advance only the owner clock; never rewrite the original scope, intent or terminal row. - try (org.mockito.MockedStatic clock = - org.mockito.Mockito.mockStatic(Instant.class, org.mockito.Mockito.CALLS_REAL_METHODS)) { - clock.when(Instant::now).thenReturn(expiredNow); - var refused = publicJoin(fixture); - assertThat(refused.success()).isFalse(); - assertThat(refused.replayed()).isFalse(); - assertThat(refused.outcomeCode()).isEqualTo("CONNECT_SCOPE_INVALID"); - } - - assertThat(publicJoinState(fixture)).isEqualTo(committed); - assertPublicJoinCommittedOnce(fixture); - } - - @org.junit.jupiter.params.ParameterizedTest - @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) - void publicJoinUnavailableSubscriptionRetainsOriginalAndRecoversOnce(boolean ambiguous) { - var fixture = publicJoinFixture(); - var originalEvidence = publicJoinOriginalEvidence(fixture); - if (ambiguous) { - var duplicate = new net.firedevops.firemud.accountservice.entity.Subscription(); - duplicate.setAccount(accountRepository.findById(fixture.accountId()).orElseThrow()); - duplicate.setTenantId(fixture.tenantId()); - duplicate.setPlanId("join-proof-duplicate"); - duplicate.setStatus("active"); - subscriptionRepository.save(duplicate); - } else { - subscriptionRepository.deleteByAccountId(fixture.accountId(), fixture.tenantId()); - } - assertThat(subscriptionRepository.findByTenantId(fixture.tenantId())) - .hasSize(ambiguous ? 2 : 0); - - var unavailable = publicJoin(fixture); - - assertThat(unavailable.success()).isFalse(); - assertThat(unavailable.replayed()).isFalse(); - assertThat(unavailable.accountId()).isEqualTo(fixture.accountUuid()); - assertThat(unavailable.outcomeCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); - assertPublicJoinUnboundPending(fixture, "ENTITLEMENT_UNAVAILABLE", "UNAVAILABLE"); - String originalIntent = - joinOperationRepository.find(fixture.caller().requestId()).orElseThrow().intentDigest(); - assertThat(publicJoinOriginalEvidence(fixture)).isEqualTo(originalEvidence); - - var stillUnavailable = publicJoin(fixture); - assertThat(stillUnavailable.outcomeCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); - assertPublicJoinUnboundPending(fixture, "ENTITLEMENT_UNAVAILABLE", "UNAVAILABLE"); - assertThat( - joinOperationRepository.find(fixture.caller().requestId()).orElseThrow().intentDigest()) - .isEqualTo(originalIntent); - - // Restore explicit unique authority through the real repository, not a synthetic read result. - subscriptionRepository.deleteByAccountId(fixture.accountId(), fixture.tenantId()); - var restored = new net.firedevops.firemud.accountservice.entity.Subscription(); - restored.setAccount(accountRepository.findById(fixture.accountId()).orElseThrow()); - restored.setTenantId(fixture.tenantId()); - restored.setPlanId("join-proof-recovered"); - restored.setStatus("active"); - subscriptionRepository.save(restored); - assertThat(subscriptionRepository.findByTenantId(fixture.tenantId())).hasSize(1); - - var recovered = publicJoin(fixture); - assertThat(recovered.success()).isTrue(); - assertThat(recovered.replayed()).isFalse(); - assertThat(recovered.accountId()).isEqualTo(fixture.accountUuid()); - assertPublicJoinCommittedOnce(fixture); - assertThat( - joinOperationRepository.find(fixture.caller().requestId()).orElseThrow().intentDigest()) - .isEqualTo(originalIntent); - assertThat(publicJoinOriginalEvidence(fixture)).isEqualTo(originalEvidence); - var committed = publicJoinState(fixture); - assertThat(publicJoin(fixture).replayed()).isTrue(); - assertPublicJoinCommittedOnce(fixture); - assertThat(publicJoinState(fixture)).isEqualTo(committed); - } - - @Test - void publicJoinActualSqlAbortAtLockedReadRollsBackPolicyAndContinuesOriginalOnce() { - var fixture = publicJoinFixture(); - var originalEvidence = publicJoinOriginalEvidence(fixture); - var failOnce = new AtomicBoolean(true); - var rolledBack = new AtomicBoolean(); - var diagnosticWritten = new AtomicBoolean(); - var originalSqlFailure = new java.util.concurrent.atomic.AtomicReference(); - org.mockito.Mockito.doAnswer( - invocation -> { - assertThat(rolledBack).isTrue(); - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive()) - .isTrue(); - invocation.callRealMethod(); - diagnosticWritten.set(true); - return null; - }) - .when(joinOperationRepository) - .recordAttemptFailure( - fixture.caller().requestId(), "UNAVAILABLE", "ENTITLEMENT_UNAVAILABLE"); - org.mockito.Mockito.doAnswer( - invocation -> { - var lockedRows = invocation.callRealMethod(); - if (failOnce.compareAndSet(true, false)) { - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive()) - .isTrue(); - // The initial available read and real policy UPDATE have already run in this tx. - var transientPolicy = - joinOperationRepository.find(fixture.caller().requestId()).orElseThrow(); - assertThat(transientPolicy.entitlementAuthorityAvailability()) - .isEqualTo("AVAILABLE"); - assertThat(transientPolicy.allowPublicJoin()).isTrue(); - assertThat(transientPolicy.entitlementVersion()).isEqualTo(1L); - assertThat(transientPolicy.requestDigest()).startsWith("sha256:"); - var independentRead = new TransactionTemplate(transactionManager); - independentRead.setPropagationBehavior( - org.springframework.transaction.TransactionDefinition.PROPAGATION_REQUIRES_NEW); - independentRead.executeWithoutResult( - status -> { - var committedIntent = - joinOperationRepository.find(fixture.caller().requestId()).orElseThrow(); - assertThat(committedIntent.status()).isEqualTo("PENDING"); - assertThat(committedIntent.requestDigest()).isNull(); - assertThat(committedIntent.intentDigest()) - .isEqualTo(transientPolicy.intentDigest()); - }); - org.springframework.transaction.support.TransactionSynchronizationManager - .registerSynchronization( - new org.springframework.transaction.support.TransactionSynchronization() { - @Override - public void afterCompletion(int status) { - rolledBack.set(status == STATUS_ROLLED_BACK); - } - }); - try { - // A real PostgreSQL error poisons this physical owner transaction; no savepoint. - dsl.fetch("SELECT 1 / 0"); - throw new AssertionError("PostgreSQL division by zero must fail"); - } catch (org.jooq.exception.DataAccessException - | org.springframework.dao.DataAccessException ex) { - originalSqlFailure.set(ex); - throw ex; - } - } - return lockedRows; - }) - .when(subscriptionRepository) - .findByTenantIdForUpdate(fixture.tenantId()); - - var unavailable = publicJoin(fixture); - - assertThat(unavailable.success()).isFalse(); - assertThat(unavailable.replayed()).isFalse(); - assertThat(unavailable.outcomeCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); - assertThat(originalSqlFailure.get()).isNotNull(); - assertThat(sqlState(originalSqlFailure.get())).isEqualTo("22012"); - assertThat(rolledBack).isTrue(); - assertThat(diagnosticWritten).isTrue(); - org.mockito.Mockito.verify(joinOperationRepository) - .recordAttemptFailure( - fixture.caller().requestId(), "UNAVAILABLE", "ENTITLEMENT_UNAVAILABLE"); - assertPublicJoinUnboundPending(fixture, "ENTITLEMENT_UNAVAILABLE", "UNAVAILABLE"); - String originalIntent = - joinOperationRepository.find(fixture.caller().requestId()).orElseThrow().intentDigest(); - assertThat(publicJoinOriginalEvidence(fixture)).isEqualTo(originalEvidence); - - var recovered = publicJoin(fixture); - assertThat(recovered.success()).isTrue(); - assertThat(recovered.replayed()).isFalse(); - assertThat(recovered.accountId()).isEqualTo(fixture.accountUuid()); - assertPublicJoinCommittedOnce(fixture); - assertThat( - joinOperationRepository.find(fixture.caller().requestId()).orElseThrow().intentDigest()) - .isEqualTo(originalIntent); - assertThat(publicJoinOriginalEvidence(fixture)).isEqualTo(originalEvidence); - var committed = publicJoinState(fixture); - assertThat(publicJoin(fixture).replayed()).isTrue(); - assertPublicJoinCommittedOnce(fixture); - assertThat(publicJoinState(fixture)).isEqualTo(committed); - } - - @org.junit.jupiter.params.ParameterizedTest - @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) - void publicJoinTerminalEntitlementOutagePreservesOriginalBytes(boolean storageFailure) { - var fixture = publicJoinFixture(); - var originalResult = publicJoin(fixture); - assertThat(originalResult.success()).isTrue(); - assertPublicJoinCommittedOnce(fixture); - var committed = publicJoinState(fixture); - var originalEvidence = publicJoinOriginalEvidence(fixture); - var subscription = subscriptionRepository.findByTenantId(fixture.tenantId()).getFirst(); - var outage = new AtomicBoolean(true); - var sqlFailure = new java.util.concurrent.atomic.AtomicReference(); - if (storageFailure) { - org.mockito.Mockito.doAnswer( - invocation -> { - var rows = invocation.callRealMethod(); - if (outage.get()) { - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive()) - .isFalse(); - try { - dsl.fetch("SELECT 1 / 0"); - throw new AssertionError("PostgreSQL division by zero must fail"); - } catch (org.jooq.exception.DataAccessException - | org.springframework.dao.DataAccessException ex) { - sqlFailure.set(ex); - throw ex; - } - } - return rows; - }) - .when(subscriptionRepository) - .findByTenantIdForUpdate(fixture.tenantId()); - } else { - subscriptionRepository.deleteByAccountId(fixture.accountId(), fixture.tenantId()); - } - - var unavailable = publicJoin(fixture); - - assertThat(unavailable.success()).isFalse(); - assertThat(unavailable.replayed()).isFalse(); - assertThat(unavailable.accountId()).isEqualTo(fixture.accountUuid()); - assertThat(unavailable.outcomeCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); - if (storageFailure) { - assertThat(sqlFailure.get()).isNotNull(); - assertThat(sqlState(sqlFailure.get())).isEqualTo("22012"); - } - assertThat(publicJoinState(fixture)).isEqualTo(committed); - assertThat(publicJoinOriginalEvidence(fixture)).isEqualTo(originalEvidence); - assertPublicJoinCommittedOnce(fixture); - - outage.set(false); - if (!storageFailure) { - subscription.setId(null); - subscriptionRepository.save(subscription); - } - var replay = publicJoin(fixture); - assertThat(replay.success()).isTrue(); - assertThat(replay.replayed()).isTrue(); - assertThat(replay.accountId()).isEqualTo(originalResult.accountId()); - assertThat(replay.membershipId()).isEqualTo(originalResult.membershipId()); - assertThat(replay.membershipVersion()).isEqualTo(originalResult.membershipVersion()); - assertThat(replay.membershipAuthorityGeneration()) - .isEqualTo(originalResult.membershipAuthorityGeneration()); - assertThat(replay.outcomeCode()).isEqualTo(originalResult.outcomeCode()); - assertThat(publicJoinState(fixture)).isEqualTo(committed); - assertThat(publicJoinOriginalEvidence(fixture)).isEqualTo(originalEvidence); - assertPublicJoinCommittedOnce(fixture); - } - - @Test - void publicJoinChangedAvailablePolicyPreservesTheOriginalTerminalBytes() { - var fixture = publicJoinFixture(); - assertThat(publicJoin(fixture).success()).isTrue(); - assertPublicJoinCommittedOnce(fixture); - var committed = publicJoinState(fixture); - var originalEvidence = publicJoinOriginalEvidence(fixture); - var original = joinOperationRepository.find(fixture.caller().requestId()).orElseThrow(); - var subscription = subscriptionRepository.findByTenantId(fixture.tenantId()).getFirst(); - UUID originalGeneration = subscription.getTenantAuthorityGeneration(); - subscription.setStatus("trialing"); - subscriptionRepository.save(subscription); - assertThat(subscription.getEntitlementVersion()).isEqualTo(original.entitlementVersion() + 1L); - assertThat(subscription.getTenantAuthorityGeneration()).isNotEqualTo(originalGeneration); - var available = - accountService.getTenantEntitlementsForRuntime( - fixture.tenantId(), "changed-policy-" + fixture.caller().requestId()); - assertThat(available.gameplayAvailable()).isTrue(); - assertThat(available.allowPublicJoin()).isTrue(); - - var conflict = publicJoin(fixture); - - assertThat(conflict.success()).isFalse(); - assertThat(conflict.replayed()).isFalse(); - assertThat(conflict.accountId()).isEqualTo(fixture.accountUuid()); - assertThat(conflict.outcomeCode()).isEqualTo("IDEMPOTENCY_CONFLICT"); - assertThat(publicJoinState(fixture)).isEqualTo(committed); - assertThat(publicJoinOriginalEvidence(fixture)).isEqualTo(originalEvidence); - assertPublicJoinCommittedOnce(fixture); - } - - private static String sqlState(Throwable failure) { - for (Throwable cause = failure; cause != null; cause = cause.getCause()) { - if (cause instanceof java.sql.SQLException sql) { - return sql.getSQLState(); - } - } - return null; - } - - private void assertPublicJoinUnboundPending( - PublicJoinFixture fixture, String failureCode, String availability) { - var operation = joinOperationRepository.find(fixture.caller().requestId()).orElseThrow(); - var scope = connectScopeRepository.find(fixture.connectScopeId()).orElseThrow(); - assertThat(operation.accountId()).isEqualTo(fixture.accountId()); - assertThat(operation.tenantId()).isEqualTo(fixture.tenantId()); - assertThat(operation.callerBinding()).isEqualTo(fixture.caller().sessionId()); - assertThat(operation.scopeTokenHash()) - .isEqualTo( - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash( - fixture.connectScopeId())); - assertThat(operation.connectScopeDigest()).isEqualTo(scope.snapshotDigest()); - assertThat(operation.intentDigestVersion()).isEqualTo(1); - assertThat(operation.intentDigest()) - .isEqualTo( - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.intent( - fixture.caller().requestId(), scope, fixture.caller().sessionId())); - assertThat(operation.status()).isEqualTo("PENDING"); - assertThat(operation.outcome()).isNull(); - assertThat(operation.requestDigest()).isNull(); - assertThat(operation.requestDigestVersion()).isNull(); - assertThat(operation.allowPublicJoin()).isNull(); - assertThat(operation.entitlementVersion()).isNull(); - assertThat(operation.membershipId()).isNull(); - assertThat(operation.membershipVersion()).isNull(); - assertThat(operation.membershipAuthorityGeneration()).isNull(); - assertThat(operation.entitlementAuthorityAvailability()).isEqualTo(availability); - assertThat(operation.lastAttemptAuthorityAvailability()).isEqualTo(availability); - assertThat(operation.lastAttemptFailureCode()).isEqualTo(failureCode); - assertThat(publicJoinMembershipCount(fixture)).isZero(); - assertThat(publicJoinAuditCount(fixture)).isZero(); - } - - private List publicJoinOriginalEvidence(PublicJoinFixture fixture) { - assertThat(jwtUtil.parseToken(fixture.connectScopeId()).getPayload().getSubject()) - .isEqualTo(fixture.accountUuid()); - var account = accountRepository.findById(fixture.accountId()).orElseThrow(); - assertThat(account.getAccountUuid().toString()).isEqualTo(fixture.accountUuid()); - assertThat(account.getAccountUuidSourceNumericId()).isEqualTo(fixture.accountId()); - assertThat(account.getAccountUuidProvenance()) - .isEqualTo(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); - return List.of( - dsl.resultQuery( - "SELECT row_to_json(a)::text FROM accounts a WHERE id = ?", fixture.accountId()) - .fetchOne(0, String.class), - dsl.resultQuery( - "SELECT COALESCE(json_agg(s ORDER BY outbox_stream_key)::text, '[]') " - + "FROM account_authority_source_records s WHERE account_uuid = ?", - UUID.fromString(fixture.accountUuid())) - .fetchOne(0, String.class), - dsl.resultQuery( - "SELECT COALESCE(json_agg(e ORDER BY outbox_sequence)::text, '[]') " - + "FROM account_authority_outbox_events e WHERE outbox_stream_key = ?", - "account:auth-authority:v1:account/" + fixture.accountUuid()) - .fetchOne(0, String.class), - dsl.resultQuery( - "SELECT row_to_json(s)::text FROM account_connect_scope_records s WHERE scope_token_hash = ?", - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash( - fixture.connectScopeId())) - .fetchOne(0, String.class)); - } - - private AtomicBoolean losePublicJoinTerminalResponse(PublicJoinFixture fixture) { - var committed = new AtomicBoolean(); - var readbackDropped = new AtomicBoolean(); - org.mockito.Mockito.doAnswer( - invocation -> { - invocation.callRealMethod(); - org.springframework.transaction.support.TransactionSynchronizationManager - .registerSynchronization( - new org.springframework.transaction.support.TransactionSynchronization() { - @Override - public void afterCommit() { - committed.set(true); - throw new IllegalStateException("Injected lost public JOIN commit ACK"); - } - }); - return null; - }) - .when(joinOperationRepository) - .finish( - org.mockito.ArgumentMatchers.eq(fixture.caller().requestId()), - org.mockito.ArgumentMatchers.eq("COMMITTED"), - org.mockito.ArgumentMatchers.eq("JOINED"), - org.mockito.ArgumentMatchers.any(), - org.mockito.ArgumentMatchers.any(), - org.mockito.ArgumentMatchers.any()); - org.mockito.Mockito.doAnswer( - invocation -> { - if (committed.get() && readbackDropped.compareAndSet(false, true)) { - throw new org.springframework.dao.DataAccessResourceFailureException( - "Injected unavailable first post-commit JOIN readback"); - } - return invocation.callRealMethod(); - }) - .when(joinOperationRepository) - .find(fixture.caller().requestId()); - return readbackDropped; - } - - private void assertPublicJoinUnavailable(PublicJoinFixture fixture) { - var unavailable = - org.junit.jupiter.api.Assertions.assertThrows( - AuthenticationException.class, () -> publicJoin(fixture)); - assertThat(unavailable.getCode()).isEqualTo("AUTH_UNAVAILABLE"); - } - - private JoinPublicProductionResult publicJoin(PublicJoinFixture fixture) { - return accountService.joinPublicProductionFromGameSession( - fixture.caller(), - new JoinPublicProductionRequest(fixture.connectScopeId(), fixture.caller().requestId())); - } - - private PublicJoinFixture publicJoinFixture() { - String suffix = UUID.randomUUID().toString().substring(0, 8); - String world = "join-" + suffix; - var account = - accountService.createAccount( - new CreateAccountRequest(world, world + "@example.com", "password123")); - long accountId = - java.util.Objects.requireNonNull( - dsl.resultQuery( - "SELECT id FROM accounts WHERE account_uuid = ?", UUID.fromString(account.id())) - .fetchOne(0, Long.class)); - long tenantId = 6000000000L + accountId; - dsl.execute( - "INSERT INTO subscription(account_id,plan_id,status,tenant_id,entitlement_version) " - + "VALUES(?,'join-proof','active',?,1)", - accountId, - tenantId); - UUID realmId = UUID.randomUUID(); - String namespace = UUID.randomUUID().toString(); - var realm = - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setTenantId(Long.toString(tenantId)) - .setRealmId(realmId.toString()) - .setWorldSlug(world) - .setRealmSlug("production") - .setPlayableStateNamespaceId(namespace) - .setStateScope("SHARED") - .setGameInstanceId("44") - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .build(); - var pointer = - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setTenantId(Long.toString(tenantId)) - .setRealmId(realmId.toString()) - .setWorldSlug(world) - .setRealmSlug("production") - .setPlayableStateNamespaceId(namespace) - .setStateScope("SHARED") - .setGameInstanceId("44") - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .build(); - org.mockito.Mockito.when(gameSessionClient.listGameplayRealms(world)) - .thenReturn(List.of(realm)); - org.mockito.Mockito.when(gameSessionClient.getAdmissionPointer(tenantId, world, "production")) - .thenReturn(pointer); - var caller = - new DirectTextCallerContext( - accountId, - tenantId, - realmId, - namespace, - "SHARED", - 44L, - "controlled-join-session-" + suffix, - "original-join-" + suffix); - var scope = - accountService.issueDirectTextConnectScope( - caller, - new DirectTextJoinTarget( - tenantId, realmId, world, "production", namespace, "SHARED", 44L, 23L, 17L)); - return new PublicJoinFixture(accountId, account.id(), tenantId, caller, scope.connectScopeId()); - } - - private long publicJoinMembershipCount(PublicJoinFixture fixture) { - return java.util.Objects.requireNonNull( - dsl.resultQuery( - "SELECT COUNT(*) FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", - fixture.accountId(), - fixture.tenantId()) - .fetchOne(0, Long.class)); - } - - private UUID publicJoinAuditId(PublicJoinFixture fixture) { - return UUID.nameUUIDFromBytes( - ("account-join-audit/v1:" + fixture.caller().requestId()).getBytes(StandardCharsets.UTF_8)); - } - - private long publicJoinAuditCount(PublicJoinFixture fixture) { - return java.util.Objects.requireNonNull( - dsl.resultQuery( - "SELECT COUNT(*) FROM account_audit_outbox WHERE audit_event_id = ?", - publicJoinAuditId(fixture)) - .fetchOne(0, Long.class)); - } - - private void assertPublicJoinCommittedOnce(PublicJoinFixture fixture) { - assertThat(publicJoinMembershipCount(fixture)).isEqualTo(1L); - assertThat(publicJoinAuditCount(fixture)).isEqualTo(1L); - assertThat( - dsl.fetchValue( - "SELECT COUNT(*) FROM account_join_operations j " - + "JOIN account_tenant_membership m ON m.id = j.membership_id " - + "WHERE j.request_id = ? AND j.status = 'COMMITTED' AND j.outcome = 'JOINED' " - + "AND j.account_id = ? AND j.tenant_id = ? " - + "AND m.account_id = j.account_id AND m.tenant_id = j.tenant_id " - + "AND m.lifecycle_state = 'ACTIVE' AND m.authority_provenance = 'EXPLICIT_JOIN' " - + "AND m.membership_version = 1 AND m.membership_authority_generation = 1 " - + "AND j.outcome_membership_version = m.membership_version " - + "AND j.outcome_membership_authority_generation = m.membership_authority_generation", - fixture.caller().requestId(), - fixture.accountId(), - fixture.tenantId())) - .isEqualTo(1L); - assertThat( - dsl.fetchValue( - "SELECT COUNT(*) FROM account_audit_outbox " - + "WHERE audit_event_id = ? AND scope = 'tenant' AND tenant_id = ? " - + "AND producer_service = 'account-service' " - + "AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION' " - + "AND payload::jsonb ->> 'requestId' = ? " - + "AND payload::jsonb ->> 'accountId' = ? " - + "AND payload::jsonb ->> 'membershipVersion' = '1'", - publicJoinAuditId(fixture), - fixture.tenantId(), - fixture.caller().requestId(), - Long.toString(fixture.accountId()))) - .isEqualTo(1L); - } - - private List publicJoinState(PublicJoinFixture fixture) { - return List.of( - dsl.resultQuery( - "SELECT row_to_json(j)::text FROM account_join_operations j WHERE request_id = ?", - fixture.caller().requestId()) - .fetchOne(0, String.class), - dsl.resultQuery( - "SELECT row_to_json(m)::text FROM account_tenant_membership m " - + "WHERE account_id = ? AND tenant_id = ?", - fixture.accountId(), - fixture.tenantId()) - .fetchOne(0, String.class), - dsl.resultQuery( - // Delivery retry diagnostics may advance independently of original JOIN evidence. - "SELECT (to_jsonb(a) - ARRAY['attempt_count','last_attempt_at','next_attempt_at'])::text " - + "FROM account_audit_outbox a WHERE audit_event_id = ?", - publicJoinAuditId(fixture)) - .fetchOne(0, String.class), - dsl.resultQuery( - "SELECT row_to_json(s)::text FROM account_connect_scope_records s " - + "JOIN account_join_operations j ON j.scope_token_hash = s.scope_token_hash " - + "WHERE j.request_id = ?", - fixture.caller().requestId()) - .fetchOne(0, String.class)); - } - - private record PublicJoinFixture( - long accountId, - String accountUuid, - long tenantId, - DirectTextCallerContext caller, - String connectScopeId) {} - @Test void publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly() throws Exception { String suffix = UUID.randomUUID().toString().substring(0, 8); @@ -1140,7 +478,7 @@ void publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly() throws } @Test - void ordinaryUuidPasswordOtpBootstrapAndScopeJourneysPreservePersistedIdentity() + void ordinaryUuidPasswordOtpBootstrapJourneysPreserveIdentityWithPublicConsumersHeld() throws Exception { String suffix = UUID.randomUUID().toString().substring(0, 8); String username = "auth-uuid-" + suffix; @@ -1231,14 +569,58 @@ void ordinaryUuidPasswordOtpBootstrapAndScopeJourneysPreservePersistedIdentity() assertThat(bootstrapClaims.getSubject()).isEqualTo(persistedAccountUuid.toString()); assertThat(bootstrapClaims.get("accountId", String.class)) .isEqualTo(persistedAccountUuid.toString()); - org.mockito.Mockito.when(gameSessionClient.listGameplayWorlds()) - .thenReturn(java.util.List.of()); String passwordBootstrap = bootstrapData.path("bootstrapToken").asText(); - assertThat(bootstrapWorlds(passwordBootstrap).statusCode()).isEqualTo(200); + assertThat(bootstrapClaims.getAudience()).containsExactly("player-bootstrap"); + assertThat(realAccountSessions.isAccountSessionActive(numericAccountId, passwordBootstrap)) + .isTrue(); + HttpResponse heldPasswordWorlds = bootstrapWorlds(passwordBootstrap); + assertThat(heldPasswordWorlds.statusCode()).isEqualTo(503); + assertThat(heldPasswordWorlds.body()).contains("AUTH_UNAVAILABLE"); + // This foundation has genuine Account identity/session issuance but no public selector or + // admission composition. The complete positive public journeys are retained in the successor. + for (Runnable held : + List.of( + () -> accountService.listBootstrapWorlds(passwordBootstrap), + () -> accountService.listBootstrapRealms(passwordBootstrap, "world"), + () -> + accountService.listBootstrapCharacters( + passwordBootstrap, "world", "production", "uncomposed-scope"), + () -> + accountService.joinPublicProduction( + passwordBootstrap, + new JoinPublicProductionRequest("uncomposed-scope", "foundation-join")), + () -> accountService.issueDirectTextConnectScope(null, null), + () -> + accountService.joinPublicProductionFromGameSession( + null, + new JoinPublicProductionRequest("uncomposed-scope", "foundation-direct-join")), + () -> + accountService.issueConnectToken( + passwordBootstrap, + new ConnectTokenRequest("uncomposed-scope", "foundation-connect")))) { + assertThatThrownBy(held::run) + .isInstanceOf(AuthenticationException.class) + .extracting(value -> ((AuthenticationException) value).getCode()) + .isEqualTo("AUTH_UNAVAILABLE"); + } + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM account_tenant_membership WHERE account_id = ?", + numericAccountId)) + .isEqualTo(0L); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM account_connect_scope_records WHERE account_id = ?", + numericAccountId)) + .isEqualTo(0L); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM account_join_operations WHERE account_id = ?", + numericAccountId)) + .isEqualTo(0L); invalidateBootstrapSession(numericAccountId, passwordBootstrap); - HttpResponse expiredPassword = bootstrapWorlds(passwordBootstrap); - assertThat(expiredPassword.statusCode()).isEqualTo(401); - assertThat(expiredPassword.body()).contains("CONNECT_CONTEXT_INVALID"); + assertThat(realAccountSessions.isAccountSessionActive(numericAccountId, passwordBootstrap)) + .isFalse(); accountService.requestEmailVerification(email); String verificationToken = @@ -1296,9 +678,14 @@ void ordinaryUuidPasswordOtpBootstrapAndScopeJourneysPreservePersistedIdentity() "Expected challenge-count record") .get(0, Long.class)) .isZero(); - assertThat(bootstrapWorlds(otpBootstrap).statusCode()).isEqualTo(200); + assertThat(otpClaims.getAudience()).containsExactly("player-bootstrap"); + assertThat(realAccountSessions.isAccountSessionActive(numericAccountId, otpBootstrap)).isTrue(); + HttpResponse heldOtpWorlds = bootstrapWorlds(otpBootstrap); + assertThat(heldOtpWorlds.statusCode()).isEqualTo(503); + assertThat(heldOtpWorlds.body()).contains("AUTH_UNAVAILABLE"); invalidateBootstrapSession(numericAccountId, otpBootstrap); - assertThat(bootstrapWorlds(otpBootstrap).statusCode()).isEqualTo(401); + assertThat(realAccountSessions.isAccountSessionActive(numericAccountId, otpBootstrap)) + .isFalse(); // Obtain a fresh real challenge: bootstrap issuance consumed the preceding one. accountService.requestEmailLoginOtp(email); @@ -1397,182 +784,28 @@ void ordinaryUuidPasswordOtpBootstrapAndScopeJourneysPreservePersistedIdentity() } @Test - void browserAndControlledDirectScopesRetainUuidClaimsAndPrivateJoinRows() throws Exception { + void retainedProfileUuidProjectionAndControlAuthorizationPreservePersistedIdentity() + throws Exception { String suffix = UUID.randomUUID().toString().substring(0, 8); - String username = "scope-" + suffix; + String username = "profile-" + suffix; var account = accountService.createAccount( - new net.firedevops.firemud.accountservice.dto.CreateAccountRequest( - username, username + "@example.com", "password123")); - var persistedAccount = - java.util.Objects.requireNonNull( - dsl.fetchOne( - "SELECT id FROM accounts WHERE account_uuid=?", UUID.fromString(account.id())), - "Expected persisted Account"); + new CreateAccountRequest(username, username + "@example.com", "password123")); long row = - java.util.Objects.requireNonNull( - persistedAccount.get(0, Long.class), "Expected persisted Account storage key"); + Objects.requireNonNull( + dsl.fetchOne( + "SELECT id FROM accounts WHERE account_uuid = ?", + UUID.fromString(account.id()))) + .get(0, Long.class); long tenant = 500000000L + Integer.toUnsignedLong(suffix.hashCode()); + // Retained profile access checks relationship existence; this quarantined row grants no + // gameplay. dsl.execute( - "INSERT INTO subscription(account_id,plan_id,status,tenant_id,entitlement_version) VALUES(?,'scope-proof','active',?,1)", + "INSERT INTO account_tenant_membership (account_id, tenant_id, lifecycle_state, " + + "gameplay_admission_allowed, membership_version, membership_authority_generation, authority_provenance) " + + "VALUES (?, ?, 'LEGACY_UNVERIFIED', FALSE, 1, 1, 'LEGACY_UNVERIFIED')", row, tenant); - String realm = UUID.randomUUID().toString(); - String namespace = UUID.randomUUID().toString(); - var target = - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("scope-proof") - .setRealmSlug("production") - .setDisplayName("Scope proof") - .setTenantId(Long.toString(tenant)) - .setGameInstanceId("44") - .setRealmId(realm) - .setPlayableStateNamespaceId(namespace) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build(); - org.mockito.Mockito.when(gameSessionClient.listGameplayRealms("scope-proof")) - .thenReturn(java.util.List.of(target)); - org.mockito.Mockito.when( - gameSessionClient.getAdmissionPointer(tenant, "scope-proof", "production")) - .thenReturn( - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug("scope-proof") - .setRealmSlug("production") - .setTenantId(Long.toString(tenant)) - .setGameInstanceId("44") - .setRealmId(realm) - .setPlayableStateNamespaceId(namespace) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build()); - var bootstrap = accountService.issuePlayerBootstrap(username, "password123"); - String browser = - accountService - .listBootstrapRealms(bootstrap.bootstrapToken(), "scope-proof") - .getFirst() - .connectScopeId(); - var player = - net.firedevops.firemud.shared.v1.PlayerExecutionContext.newBuilder() - .setAccountId(account.id()) - .setTenantId(Long.toString(tenant)) - .setRealmId(realm) - .setPlayableStateNamespaceId(namespace) - .setPlayableStateScope("SHARED") - .setGameInstanceId("44") - .setSessionId("controlled-session") - .setRequestId("scope-direct-" + suffix) - .build(); - var request = - net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeRequest.newBuilder() - .setPlayerContext(player) - .setTenantId(Long.toString(tenant)) - .setRealmId(realm) - .setWorldSlug("scope-proof") - .setRealmSlug("production") - .setPlayableStateNamespaceId(namespace) - .setPlayableStateScope("SHARED") - .setGameInstanceId("44") - .setCatalogRevision(23L) - .setPointerVersion(17L) - .build(); - var response = - new java.util.concurrent.atomic.AtomicReference< - net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse>(); - var receiver = - new net.firedevops.firemud.accountservice.service.impl.AccountGrpcService( - org.mockito.Mockito.mock( - net.firedevops.firemud.accountservice.service.PingService.class), - accountService, - null, - "test"); - var context = - io.grpc.Context.ROOT.withValue( - net.firedevops.firemud.common.grpc.GrpcPeerIdentity.CONTEXT_KEY, - new net.firedevops.firemud.common.grpc.GrpcPeerIdentity( - "spiffe://firemud/ns/test/sa/game-session-service", - "test", - "game-session-service")); - context.run( - () -> - receiver.issueDirectTextConnectScope( - request, - new io.grpc.stub.StreamObserver<>() { - @Override - public void onNext( - net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse value) { - response.set(value); - } - - @Override - public void onError(Throwable error) { - org.junit.jupiter.api.Assertions.fail(error); - } - - @Override - public void onCompleted() {} - })); - var directResponse = - java.util.Objects.requireNonNull(response.get(), "Expected controlled direct response"); - assertThat(directResponse.hasError()).isFalse(); - String direct = directResponse.getConnectScopeId(); - var scopes = - new net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository(dsl); - for (String token : java.util.List.of(browser, direct)) { - var claims = jwtUtil.parseToken(token).getPayload(); - assertThat(claims.getSubject()).isEqualTo(account.id()); - assertThat(claims.get("accountId", String.class)).isEqualTo(account.id()); - var retained = scopes.find(token).orElseThrow(); - assertThat(retained.accountId()).isEqualTo(row); - assertThat(retained.snapshotDigest()) - .isEqualTo(net.firedevops.firemud.accountservice.dto.AccountJoinDigest.scope(retained)); - var held = - org.junit.jupiter.api.Assertions.assertThrows( - net.firedevops.firemud.accountservice.service.exception.AuthenticationException.class, - () -> - accountService.issueConnectToken( - bootstrap.bootstrapToken(), - new net.firedevops.firemud.accountservice.dto.ConnectTokenRequest( - token, "held-" + suffix))); - assertThat(held.getCode()).isEqualTo("AUTH_UNAVAILABLE"); - assertThat(scopes.find(token)).contains(retained); - } - var browserJoin = - new net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest( - browser, "scope-browser-" + suffix); - var first = accountService.joinPublicProduction(bootstrap.bootstrapToken(), browserJoin); - assertThat(first.success()).isTrue(); - assertThat(first.accountId()).isEqualTo(account.id()); - assertThat( - accountService.joinPublicProduction(bootstrap.bootstrapToken(), browserJoin).replayed()) - .isTrue(); - var caller = - new net.firedevops.firemud.accountservice.dto.DirectTextCallerContext( - row, - tenant, - UUID.fromString(realm), - namespace, - "SHARED", - 44L, - "controlled-session", - "scope-direct-" + suffix); - var directJoin = - new net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest( - direct, caller.requestId()); - assertThat(accountService.joinPublicProductionFromGameSession(caller, directJoin).success()) - .isTrue(); - assertThat(accountService.joinPublicProductionFromGameSession(caller, directJoin).replayed()) - .isTrue(); - assertThat(accountService.joinPublicProductionFromGameSession(caller, directJoin).accountId()) - .isEqualTo(account.id()); dsl.execute( "INSERT INTO profiles(account_id,tenant_id,display_name,bio,presence_visibility_policy) " + "VALUES(?,?,?,?, 'HIDDEN_STAFF')", @@ -1821,8 +1054,6 @@ public void onCompleted() {} "Expected retained private profile owner row") .get(0, Long.class)) .isEqualTo(row); - assertThat(scopes.find(browser)).isPresent(); - assertThat(scopes.find(direct)).isPresent(); } private void assertOrdinaryCredentialPreservesSocialGuildSelf( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java index 706cd84e0c..5bd793cce0 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java @@ -38,6 +38,7 @@ import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; import net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository; +import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback.LatestSourceSnapshot; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; @@ -785,7 +786,6 @@ private AccountServiceImpl newService( fixture.logoutAllOperations(), fixture.securityStateOperations(), fixture.sourceChanges(), - null, // audit outbox null, // connect scopes null, // join operations null, // email login challenges @@ -795,7 +795,8 @@ private AccountServiceImpl newService( null, // profiles null, // profile mapper null, // payment transactions - null, // subscriptions + // retained subscription evidence + org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), null, // external account identities fixture.tokens(), null, // email verification tokens @@ -806,8 +807,6 @@ private AccountServiceImpl newService( null, null, null, - null, - null, fixture.transactionManager()); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityCurrentnessIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityCurrentnessIntegrationTest.java index efbabc1e55..a77a2bbea1 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityCurrentnessIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityCurrentnessIntegrationTest.java @@ -1,7 +1,9 @@ package integration.net.firedevops.firemud.accountservice.repository; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.time.Duration; import java.time.Instant; import java.util.List; import java.util.Map; @@ -14,9 +16,12 @@ import java.util.concurrent.TimeUnit; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountRealmAccessGrant; -import net.firedevops.firemud.accountservice.entity.Subscription; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionCurrentReceipt; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Outcome; import net.firedevops.firemud.accountservice.repository.AccountRealmAccessGrantRepository; -import net.firedevops.firemud.accountservice.repository.SubscriptionRepository; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; @@ -29,7 +34,7 @@ import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.transaction.support.TransactionTemplate; -/** Physical V31/V32 currentness proof, isolated from Account lifecycle/source writers. */ +/** Canonical hosting lifecycle/source currentness and separate realm-grant tombstone/CAS proof. */ class AccountAuthorityCurrentnessIntegrationTest { private static final AccountPostgresIntegrationFixture postgres = new AccountPostgresIntegrationFixture(); @@ -59,39 +64,115 @@ void subscriptionAndRealmGrantMutationsAdvanceCurrentnessAndKeepRevocationTombst JdbcTemplate jdbc = new JdbcTemplate(dataSource); DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); - Long accountId = - Objects.requireNonNull( + var fixture = CanonicalHostingSubscriptionTestFixture.create(dataSource); + var claim = + fixture + .service() + .claimProvisioning(fixture.creation().requestId(), 1, UUID.randomUUID()) + .claim(); + UUID initialRequest = UUID.randomUUID(); + var initialCommit = + fixture + .service() + .reconcile( + initialRequest, + fixture.creation().requestId(), + claim.subscriptionRowVersion(), + fixture.providerId(), + claim.attemptId()); + assertThat(initialCommit.outcome()).isEqualTo(Outcome.COMMITTED); + var initial = fixture.service().readCurrent(fixture.tenantId()); + assertThat(initial.entitlementVersion()).isOne(); + assertCanonicalCheckpoint(fixture, initial); + int initialReads = fixture.transport().reads(); + assertThat( + fixture + .service() + .reconcile( + initialRequest, + fixture.creation().requestId(), + claim.subscriptionRowVersion(), + fixture.providerId(), + claim.attemptId())) + .isEqualTo(initialCommit); + assertThat(fixture.transport().reads()).isEqualTo(initialReads); + var initialRetry = fixture.service().readCurrent(fixture.tenantId()); + assertThat(initialRetry.receiptRequestId()).isEqualTo(initial.receiptRequestId()); + assertThat(initialRetry.tenantAuthorityEvent().payload()) + .isEqualTo(initial.tenantAuthorityEvent().payload()); + + fixture.clock().advance(Duration.ofSeconds(1)); + fixture.providerStatus("past_due"); + UUID changedRequest = UUID.randomUUID(); + var changedCommit = + fixture + .service() + .reconcile( + changedRequest, + fixture.creation().requestId(), + initial.current().rowVersion(), + fixture.providerId(), + null); + assertThat(changedCommit.outcome()).isEqualTo(Outcome.COMMITTED); + var changed = fixture.service().readCurrent(fixture.tenantId()); + assertThat(changed.rawProviderStatus()).isEqualTo("past_due"); + assertThat(changed.entitlementVersion()).isGreaterThan(initial.entitlementVersion()); + assertThat(changed.tenantBillingSequence()).isGreaterThan(initial.tenantBillingSequence()); + assertThat(changed.tenantAuthorityEvent().tenantAuthorityGeneration()) + .isGreaterThan(initial.tenantAuthorityEvent().tenantAuthorityGeneration()); + assertThat(changed.tenantAuthorityEvent().outboxSequence()) + .isGreaterThan(initial.tenantAuthorityEvent().outboxSequence()); + assertThat(changed.tenantAuthorityEvent().eventId()) + .isNotEqualTo(initial.tenantAuthorityEvent().eventId()); + assertCanonicalCheckpoint(fixture, changed); + + assertThatThrownBy( + () -> + jdbc.update( + "UPDATE subscription SET status = 'active', row_version = row_version + 1 WHERE subscription_id = ?", + fixture.creation().subscriptionId())) + .isInstanceOf(org.springframework.dao.DataIntegrityViolationException.class); + int changedReads = fixture.transport().reads(); + assertThat( + fixture + .service() + .reconcile( + changedRequest, + fixture.creation().requestId(), + initial.current().rowVersion(), + fixture.providerId(), + null)) + .isEqualTo(changedCommit); + assertThat(fixture.transport().reads()).isEqualTo(changedReads); + var changedRetry = fixture.service().readCurrent(fixture.tenantId()); + assertThat(changedRetry.current()).isEqualTo(changed.current()); + assertThat(changedRetry.receiptRequestId()).isEqualTo(changed.receiptRequestId()); + assertThat(changedRetry.tenantAuthorityEvent().payload()) + .isEqualTo(changed.tenantAuthorityEvent().payload()); + assertCanonicalCheckpoint(fixture, changedRetry); + assertThat( jdbc.queryForObject( - "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + "SELECT payload FROM account_authority_outbox_events WHERE outbox_stream_key = ? AND outbox_sequence = ?", + byte[].class, + initial.tenantAuthorityEvent().outboxStreamKey(), + initial.tenantAuthorityEvent().outboxSequence())) + .isEqualTo(initial.tenantAuthorityEvent().payload()); + assertThat( + jdbc.queryForObject( + "SELECT count(*) FROM account_authority_outbox_events WHERE outbox_stream_key = ?", Long.class, - "currentness-" + UUID.randomUUID(), - "currentness-" + UUID.randomUUID() + "@example.test", - "test-hash")); + changed.tenantAuthorityEvent().outboxStreamKey())) + .isEqualTo(2L); + assertThat( + jdbc.queryForObject( + "SELECT count(*) FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ?", + Long.class, + fixture.tenantId())) + .isEqualTo(2L); + // Realm grants retain their separate authority and numeric legacy scope in this existing proof. + long accountId = fixture.accountId(); long tenantId = 7_654_322L; - jdbc.update( - "INSERT INTO subscription (account_id, plan_id, status, tenant_id, entitlement_version) " - + "VALUES (?, 'test-plan', 'active', ?, 1)", - accountId, - tenantId); - SubscriptionRepository subscriptions = new SubscriptionRepository(dsl); - Subscription subscription = subscriptions.findByTenantId(tenantId).getFirst(); - UUID initialTenantGeneration = subscription.getTenantAuthorityGeneration(); - assertThat(initialTenantGeneration).isNotNull(); - assertThat(subscription.getEntitlementVersion()).isEqualTo(1L); - - subscription.setStatus("past_due"); - subscriptions.save(subscription); - Subscription repositoryUpdated = subscriptions.findByTenantId(tenantId).getFirst(); - assertThat(repositoryUpdated.getTenantAuthorityGeneration()) - .isNotEqualTo(initialTenantGeneration); - assertThat(repositoryUpdated.getEntitlementVersion()).isEqualTo(2L); - - jdbc.update("UPDATE subscription SET status = 'active' WHERE tenant_id = ?", tenantId); - Subscription directlyUpdated = subscriptions.findByTenantId(tenantId).getFirst(); - assertThat(directlyUpdated.getTenantAuthorityGeneration()) - .isNotEqualTo(repositoryUpdated.getTenantAuthorityGeneration()); - assertThat(directlyUpdated.getEntitlementVersion()).isEqualTo(3L); Account account = new Account(); account.setId(accountId); @@ -141,6 +222,57 @@ void subscriptionAndRealmGrantMutationsAdvanceCurrentnessAndKeepRevocationTombst .isFalse(); } + private static void assertCanonicalCheckpoint( + CanonicalHostingSubscriptionTestFixture.Fixture fixture, + AccountHostingSubscriptionCurrentReceipt receipt) { + var event = receipt.tenantAuthorityEvent(); + assertThat(event.tenantId()).isEqualTo(fixture.tenantId()); + assertThat(event.tenantBillingSequence()).isEqualTo(receipt.tenantBillingSequence()); + assertThat(event.tenantBillingEventId()).isEqualTo(receipt.billingEventId()); + assertThat(event.tenantBillingEventDigest()).isEqualTo(receipt.billingEventDigest()); + fixture + .transaction() + .executeWithoutResult( + status -> { + var currentGeneration = + new AccountAuthorityGenerationRepository(fixture.dsl()) + .read(AuthorityScope.tenant(fixture.tenantId())); + assertThat(currentGeneration.generation()) + .isEqualTo(event.tenantAuthorityGeneration()); + assertThat(currentGeneration.sourceVersion()) + .isEqualTo(event.tenantAuthoritySourceVersion()); + var checkpoint = + new AccountAuthorityOutboxRepository(fixture.dsl()) + .readCheckpoint(event.outboxStreamKey()) + .orElseThrow(); + assertThat(checkpoint.outboxSequence()).isEqualTo(event.outboxSequence()); + assertThat(checkpoint.sourceEventId()).isEqualTo(event.eventId().toString()); + assertThat(checkpoint.sourceEventDigest()).isEqualTo(event.eventDigest()); + assertThat( + fixture + .jdbc() + .queryForObject( + "SELECT event_digest FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ? AND tenant_billing_sequence = ? AND event_id = ?", + String.class, + fixture.tenantId(), + receipt.tenantBillingSequence(), + receipt.billingEventId())) + .isEqualTo(receipt.billingEventDigest()); + assertThat( + fixture + .jdbc() + .queryForMap( + "SELECT current_generation, tenant_billing_sequence, last_outbox_sequence, " + + "last_event_id, last_event_digest FROM account_tenant_authority_source_records WHERE tenant_uuid = ?", + fixture.tenantId())) + .containsEntry("current_generation", event.tenantAuthorityGeneration()) + .containsEntry("tenant_billing_sequence", receipt.tenantBillingSequence()) + .containsEntry("last_outbox_sequence", checkpoint.outboxSequence()) + .containsEntry("last_event_id", event.eventId()) + .containsEntry("last_event_digest", event.eventDigest()); + }); + } + @Test void concurrentRealmGrantWritersCannotOverwriteAnObservedGeneration() throws Exception { String schema = "account_grant_cas_" + UUID.randomUUID().toString().replace("-", ""); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java index caba218cf3..a052837a81 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java @@ -123,7 +123,6 @@ void preV40RetainedPasswordResetFailsTypedAndRollsBackWithoutInventingSource() { .AccountSecurityStateOperationRepository(dsl), new net.firedevops.firemud.accountservice.service .AccountPasswordResetDraftSourceChangeRepository(dsl), - null, // audit outbox null, null, null, @@ -144,8 +143,6 @@ void preV40RetainedPasswordResetFailsTypedAndRollsBackWithoutInventingSource() { null, null, null, - null, - null, manager); // remote clients/JWT/session are not used by reset UUID accountUuid = accounts.findById(accountId).orElseThrow().getAccountUuid(); var beforeToken = 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..2feb2678c8 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java @@ -0,0 +1,653 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +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.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.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.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 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 recoveredAttemptWithNoPreviousDispatchStillCannotCreateAndExpiredLeaseRefusesReadback() { + Fixture f = fixture("1032"); + var first = claim(f, 1); + f.tx().executeWithoutResult(s -> f.owner().deferUnresolved(first)); + f.clock().advance(Duration.ofSeconds(2)); + var second = claim(f, first.subscriptionRowVersion()); + var prepared = + f.tx().execute(s -> f.owner().prepareProviderDispatch(second, UUID.randomUUID())); + assertThat(f.tx().execute(s -> f.owner().readProviderDispatch(prepared)).initialCallAllowed()) + .isFalse(); + f.clock().advance(Duration.ofSeconds(10)); + assertThatThrownBy(() -> f.tx().execute(s -> f.owner().readProviderDispatch(prepared))) + .isInstanceOf(RuntimeException.class); + } + + @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 realInitialSdkCreateFlowsThroughExistingLifecycleCommitAndIndependentCurrentRead() { + Fixture f = fixture("1032"); + var result = + (AccountHostingSubscriptionProvisioningService.Committed) + service(f).provision(claim(f, 1), 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); + assertThat(f.transport().subscriptionReads).isGreaterThanOrEqualTo(3); + } + + @Test + void lostCreateResponseRecoversSameResourceWithoutRecreatingAndRetainsItsOriginalIdentity() { + Fixture f = fixture("1032"); + f.transport().loseCreateResponse = true; + var first = claim(f, 1); + assertThat(service(f).provision(first, UUID.randomUUID(), UUID.randomUUID())) + .isInstanceOf(AccountHostingSubscriptionProvisioningService.Pending.class); + assertThat(f.transport().creates).isEqualTo(1); + f.clock().advance(Duration.ofSeconds(2)); + 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); + } + + 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) { + return Objects.requireNonNull( + f.tx() + .execute( + s -> + f.owner().claim(f.creation().requestId(), version, UUID.randomUUID()).claim())); + } + + private static AccountHostingSubscriptionProvisioningService service(Fixture f) { + var stripe = new com.stripe.StripeClient(f.transport()); + var lifecycle = + new AccountHostingSubscriptionLifecycleService( + f.owner(), + new StripeHostingSubscriptionObserver(stripe, f.clock()), + new DataSourceTransactionManager(f.source())); + return new AccountHostingSubscriptionProvisioningService( + f.owner(), + new StripeHostingSubscriptionProvisioner(stripe, f.clock(), false), + lifecycle, + new DataSourceTransactionManager(f.source())); + } + + private static Fixture fixture(String target) { + 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, Duration.ofSeconds(10), Duration.ofSeconds(1), Duration.ofHours(1)), + 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) { + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration", "classpath:db/migration/saga") + .target(target) + .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; + } + + private void advance(Duration duration) { + now = now.plus(duration); + } + + @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 loseCreateResponse; + private int creates; + private int subscriptionReads; + + 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")) { + assertThat(params.get("query").toString()) + .contains( + creation.subscriptionProvisioningRequestId().toString(), + creation.subscriptionId().toString()); + response = + "{\"object\":\"search_result\",\"has_more\":false,\"data\":[" + + (exists ? subscription() : "") + + "]}"; + } else if (path.equals("/v1/subscriptions") && method == RequestMethod.POST) { + creates++; + exists = true; + assertThat(options.getIdempotencyKey()) + .isEqualTo(creation.subscriptionProvisioningRequestId().toString()); + assertThat(params) + .containsEntry("customer", creation.providerCustomerId()) + .containsEntry("default_payment_method", paymentMethod); + assertThat(params.get("items")) + .isEqualTo( + List.of( + Map.of( + "price", + creation.planQuote().providerPriceId(), + "quantity", + creation.planQuote().providerQuantity()))); + if (loseCreateResponse) { + throw org.mockito.Mockito.mock(StripeException.class); + } + response = subscription(); + } else if (path.equals("/v1/subscriptions/sub_exact")) { + subscriptionReads++; + response = subscription(); + } else { + throw new AssertionError("Unexpected provider path " + path); + } + return (T) com.stripe.net.ApiResource.GSON.fromJson(response, type); + } + + private String subscription() { + return "{\"object\":\"subscription\",\"id\":\"sub_exact\",\"customer\":\"" + + creation.providerCustomerId() + + "\",\"default_payment_method\":\"" + + paymentMethod + + "\",\"livemode\":false,\"status\":\"active\",\"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..f386751468 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecyclePostgresIntegrationTest.java @@ -0,0 +1,1705 @@ +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 unauditedOwnerChangeDuringActualSdkReadIsRefusedBeforeAnyReceipt() { + 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())); + assertSqlState( + "23514", + () -> + f.service() + .reconcile( + UUID.randomUUID(), + 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 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 inFlightAndExpiredReceiptOrChangedSdkFactsNeverRefreshAnOldPositiveSnapshot() { + 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)); + assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + 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 + configuredRecoveryAndEffectiveCancellationAdvanceMonotonicCutoffWithoutPrematureReservationRelease() { + Context c = context("1030"); + Fixture f = fixture(c); + activate(f); + f.transport().json = response(f, "past_due"); + refresh(f); + assertThat(f.service().readCurrent(f.creation().tenantId()).subscriptionStatus()) + .isEqualTo(Status.PAST_DUE); + f.clock().advance(Duration.ofSeconds(60)); + refresh(f); + var grace = f.service().readCurrent(f.creation().tenantId()); + assertThat(grace.subscriptionStatus()).isEqualTo(Status.GRACE); + assertThat(grace.gameplayAvailable()).isTrue(); + assertThat(grace.allowPublicJoin()).isFalse(); + assertThat(grace.allowNewInstanceStarts()).isFalse(); + f.clock().advance(Duration.ofSeconds(120)); + refresh(f); + var suspended = f.service().readCurrent(f.creation().tenantId()); + assertThat(suspended.subscriptionStatus()).isEqualTo(Status.SUSPENDED); + assertThat(suspended.gameplayAvailable()).isFalse(); + assertThat(suspended.tenantBillingSequence()).isEqualTo(4); + assertThat( + new String( + one( + c, + "SELECT payload FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ? AND tenant_billing_sequence = 4", + f.creation().tenantId()) + .get("payload", byte[].class), + java.nio.charset.StandardCharsets.UTF_8)) + .contains("TenantBillingStateChanged"); + assertThat(suspended.cutoffAt()).isEqualTo(f.clock().instant()); + f.transport().json = response(f, "active"); + refresh(f); + Instant cancellation = f.clock().instant().plusSeconds(2); + f.transport().json = + response(f, "active") + .replace("\"cancel_at\":null", "\"cancel_at\":" + cancellation.getEpochSecond()); + refresh(f); + f.clock().advance(Duration.ofSeconds(2)); + 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.tenantBillingSequence()).isEqualTo(7); + 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(8); + 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(8); + 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 + 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(f.request.actorAccountId()); + 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); + 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), + 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/AccountRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java index eb3bc68da2..8e9c5d1650 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.sql.SQLException; import java.time.Duration; @@ -521,28 +522,36 @@ void auditAttemptTimesUseUtcLocalDateTimeUnderNonUtcDatabaseSession() { } @Test - void subscriptionForUpdateLocksOnlySubscriptionAndKeepsThatLockThroughTransaction() - throws Exception { + void canonicalSubscriptionOriginalBindingLocksRequiredOwnerChainThroughCommit() throws Exception { + var fixture = CanonicalHostingSubscriptionTestFixture.create(dataSource); + var claim = + fixture + .service() + .claimProvisioning(fixture.creation().requestId(), 1, UUID.randomUUID()) + .claim(); + assertThat( + fixture + .service() + .reconcile( + UUID.randomUUID(), + fixture.creation().requestId(), + claim.subscriptionRowVersion(), + fixture.providerId(), + claim.attemptId()) + .outcome()) + .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Outcome.COMMITTED); + var receipt = fixture.service().readCurrent(fixture.tenantId()); JdbcTemplate jdbc = new JdbcTemplate(dataSource); - long accountId = + long unrelatedAccountId = Objects.requireNonNull( jdbc.queryForObject( "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", Long.class, - "subscription-lock", - "subscription-lock@example.com", + "unrelated-subscription-lock", + "unrelated-subscription-lock@example.com", "hash")); - long tenantId = 7654321L; - jdbc.update( - "INSERT INTO subscription (account_id, plan_id, status, tenant_id, entitlement_version) " - + "VALUES (?, 'test-plan', 'active', ?, 1)", - accountId, - tenantId); - TransactionAwareDataSourceProxy transactionAwareDataSource = new TransactionAwareDataSourceProxy(dataSource); - DSLContext transactionDsl = DSL.using(transactionAwareDataSource, SQLDialect.POSTGRES); - SubscriptionRepository subscriptions = new SubscriptionRepository(transactionDsl); TransactionTemplate lockTransaction = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); CountDownLatch subscriptionLocked = new CountDownLatch(1); @@ -553,7 +562,15 @@ void subscriptionForUpdateLocksOnlySubscriptionAndKeepsThatLockThroughTransactio () -> lockTransaction.executeWithoutResult( status -> { - assertThat(subscriptions.findByTenantIdForUpdate(tenantId)).hasSize(1); + assertThat( + fixture + .intents() + .lockForLifecycle( + fixture.creation().requestId(), + receipt.current().rowVersion())) + .isEqualTo(receipt.current()); + assertThat(fixture.intents().findCreation(fixture.creation().requestId())) + .contains(fixture.creation()); subscriptionLocked.countDown(); try { if (!releaseSubscriptionLock.await(10, TimeUnit.SECONDS)) { @@ -572,16 +589,33 @@ void subscriptionForUpdateLocksOnlySubscriptionAndKeepsThatLockThroughTransactio TransactionTemplate conflictingTransaction = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); JdbcTemplate conflictingJdbc = new JdbcTemplate(transactionAwareDataSource); - assertThatThrownBy( - () -> - conflictingTransaction.executeWithoutResult( - status -> { - conflictingJdbc.execute("SET LOCAL lock_timeout = '250ms'"); - conflictingJdbc.update( - "UPDATE subscription SET status = status WHERE tenant_id = ?", - tenantId); - })) - .hasMessageContaining("lock timeout"); + // These are the mutable rows actually locked by the canonical original-binding reader. + // Creation intent is immutable and validated above; it is not a competing mutable row. + Map lockedRows = + Map.of( + "SELECT 1 FROM accounts WHERE account_uuid = ? FOR UPDATE", fixture.accountUuid(), + "SELECT 1 FROM billing_customer WHERE account_uuid = ? FOR UPDATE", + fixture.accountUuid(), + "SELECT 1 FROM payment_instrument WHERE instrument_uuid = ? FOR UPDATE", + fixture.instrument().instrumentUuid(), + "SELECT 1 FROM account_tenant_billing_owners WHERE tenant_uuid = ? FOR UPDATE", + fixture.tenantId(), + "SELECT 1 FROM subscription WHERE subscription_id = ? FOR UPDATE", + fixture.creation().subscriptionId(), + "SELECT 1 FROM subscription_instrument_reservations WHERE request_id = ? FOR UPDATE", + fixture.creation().requestId()); + for (var row : lockedRows.entrySet()) { + assertThatThrownBy( + () -> + conflictingTransaction.executeWithoutResult( + status -> { + conflictingJdbc.execute("SET LOCAL lock_timeout = '250ms'"); + conflictingJdbc.queryForObject( + row.getKey(), Integer.class, row.getValue()); + })) + .as("owner-chain lock retained: %s", row.getKey()) + .hasMessageContaining("lock timeout"); + } Integer updatedAccounts = conflictingTransaction.execute( @@ -589,8 +623,8 @@ void subscriptionForUpdateLocksOnlySubscriptionAndKeepsThatLockThroughTransactio conflictingJdbc.execute("SET LOCAL lock_timeout = '2s'"); return conflictingJdbc.update( "UPDATE accounts SET email = ? WHERE id = ?", - "subscription-lock-updated@example.com", - accountId); + "unrelated-subscription-lock-updated@example.com", + unrelatedAccountId); }); assertThat(updatedAccounts).isEqualTo(1); } finally { @@ -601,6 +635,19 @@ void subscriptionForUpdateLocksOnlySubscriptionAndKeepsThatLockThroughTransactio executor.shutdownNow(); } } + // The same real owner operation succeeds from an independent transaction after holder commit. + lockTransaction.executeWithoutResult( + status -> { + jdbc.execute("SET LOCAL lock_timeout = '2s'"); + assertThat( + fixture + .intents() + .lockForLifecycle( + fixture.creation().requestId(), receipt.current().rowVersion())) + .isEqualTo(receipt.current()); + }); + assertThat(fixture.intents().findCreation(fixture.creation().requestId())) + .contains(fixture.creation()); } @Test @@ -643,16 +690,13 @@ void privateRealmGrantRevocationRetainsMonotonicCurrentnessForRevalidation() { null, null, null, - null, grants, null, null, null, null, null, - null, - null, - null, + org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), null, null, null, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSecuritySourceOwnerGuardPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSecuritySourceOwnerGuardPostgresIntegrationTest.java index 37e1cfda6f..e00336b1cc 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSecuritySourceOwnerGuardPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSecuritySourceOwnerGuardPostgresIntegrationTest.java @@ -26,6 +26,7 @@ import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; import net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository; +import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; import net.firedevops.firemud.accountservice.service.AccountLogoutAllAuthorityEventProducer; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; @@ -302,7 +303,6 @@ private AccountServiceImpl newPasswordResetService( logoutOperations, securityOperations, resetSourceChanges, - null, // audit outbox null, // connect scopes null, // join operations null, // email login challenges @@ -312,7 +312,8 @@ private AccountServiceImpl newPasswordResetService( null, // profiles null, // profile mapper null, // payment transactions - null, // subscriptions + // retained subscription evidence + org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), null, // external account identities tokens, null, // email verification tokens @@ -323,8 +324,6 @@ private AccountServiceImpl newPasswordResetService( null, null, null, - null, - null, context.transactionManager()); } 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..b5265f0885 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentPostgresIntegrationTest.java @@ -0,0 +1,1751 @@ +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.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)); + Instant start = created.createdAt().plusSeconds(1); + UUID attemptId = UUID.randomUUID(); + var first = + Objects.requireNonNull( + c.tx().execute(s -> lifecycle(c, start).claim(created.requestId(), 1, attemptId))) + .claim(); + assertThat(first.creation()).isEqualTo(created); + assertThat(first.subscriptionRowVersion()).isEqualTo(2); + assertThat(first.reconciliationRequiredBeforeCreate()).isFalse(); + 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, start).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(); + var waiting = + Objects.requireNonNull( + c.tx() + .execute( + s -> + lifecycle(c, start.plusSeconds(5)) + .claim(created.requestId(), 2, UUID.randomUUID()))); + assertThat(waiting.disposition()) + .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Disposition.WAITING); + Instant recoveryTime = start.plusSeconds(12); + var recovered = + Objects.requireNonNull( + c.tx() + .execute( + s -> + lifecycle(c, recoveryTime) + .claim(created.requestId(), 2, UUID.randomUUID()))) + .claim(); + assertThat(recovered.reconciliationRequiredBeforeCreate()).isTrue(); + 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, recoveryTime).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)); + Instant start = created.createdAt().plusSeconds(1); + var first = + Objects.requireNonNull( + c.tx() + .execute( + s -> lifecycle(c, start).claim(created.requestId(), 1, UUID.randomUUID()))) + .claim(); + var firstDeferred = c.tx().execute(s -> lifecycle(c, start).deferUnresolved(first)); + assertThat(firstDeferred) + .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Disposition.WAITING); + Instant retryAt = start.plusSeconds(1); + var second = + Objects.requireNonNull( + c.tx() + .execute( + s -> + lifecycle(c, retryAt).claim(created.requestId(), 2, UUID.randomUUID()))) + .claim(); + var exhausted = c.tx().execute(s -> lifecycle(c, retryAt).deferUnresolved(second)); + assertThat(exhausted) + .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Disposition.TERMINAL_FAILURE); + var exhaustedReplay = c.tx().execute(s -> lifecycle(c, retryAt).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")); + } + + @Test + void claimRollbackAndStaleReservedWalletCannotLeaveProvisioningWork() { + Context c = context(); + configuration(c).target("1030").load().migrate(); + Seed seed = seed(c); + var created = create(c, request(seed, UUID.randomUUID(), 1, null)); + Instant start = created.createdAt().plusSeconds(1); + c.tx() + .executeWithoutResult( + s -> { + lifecycle(c, start).claim(created.requestId(), 1, UUID.randomUUID()); + s.setRollbackOnly(); + }); + assertThat(count(c, "subscription_provisioning_work")).isZero(); + assertThat(count(c, "subscription_provisioning_attempts")).isZero(); + assertThat(c.repository().findCurrentByTenant(seed.tenant()).orElseThrow().status()) + .isEqualTo("pending"); + c.tx() + .executeWithoutResult( + s -> advanceWallet(c, seed.instrument().instrumentUuid(), UUID.randomUUID())); + assertThatThrownBy( + () -> + c.tx() + .execute( + s -> lifecycle(c, start).claim(created.requestId(), 1, UUID.randomUUID()))) + .isInstanceOf(FenceRejectedException.class); + assertThat(count(c, "subscription_provisioning_work")).isZero(); + assertThat(c.repository().findCurrentByTenant(seed.tenant()).orElseThrow().rowVersion()) + .isOne(); + } + + @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)); + Instant start = created.createdAt().plusSeconds(1); + Supplier attempt = + () -> { + try { + return Objects.requireNonNull( + c.tx() + .execute( + s -> + lifecycle(c, start) + .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)); + var expired = + Objects.requireNonNull( + c.tx() + .execute( + s -> + lifecycle(c, created.createdAt().plusSeconds(3600)) + .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, Instant now) { + return new AccountHostingSubscriptionLifecycleRepository( + c.dsl(), + c.repository(), + Clock.fixed(now, ZoneOffset.UTC), + new AccountHostingSubscriptionLifecycleRepository.ReconciliationLimits( + 2, 3, Duration.ofSeconds(10), Duration.ofSeconds(1), Duration.ofHours(1)), + new AccountHostingSubscriptionLifecyclePolicy( + Duration.ofSeconds(15), + new AccountHostingSubscriptionLifecyclePolicy.RecoveryTiming( + Duration.ofSeconds(60), Duration.ofSeconds(120))), + "prod", + false); + } + + @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 attempted = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + var executor = Executors.newFixedThreadPool(2); + try { + var holder = + executor.submit( + () -> + c.tx() + .executeWithoutResult( + s -> { + 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( + () -> { + attempted.countDown(); + return attemptCreate(c, request); + }); + assertThat(attempted.await(5, TimeUnit.SECONDS)).isTrue(); + release.countDown(); + holder.get(15, TimeUnit.SECONDS); + assertThat(contender.get(15, TimeUnit.SECONDS)).isEqualTo("FENCED"); + } finally { + release.countDown(); + executor.shutdownNow(); + } + } + + /** 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..62f15145c9 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionPostgresIntegrationTest.java @@ -0,0 +1,351 @@ +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") + .target("1030") + .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/repository/CanonicalHostingSubscriptionTestFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java new file mode 100644 index 0000000000..b1793e93d5 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java @@ -0,0 +1,470 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +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.time.Clock; +import java.time.Duration; +import java.time.Instant; +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.atomic.AtomicLong; +import java.util.function.Supplier; +import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountBillingCustomerRecord; +import net.firedevops.firemud.accountservice.repository.AccountBillingCustomerRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingPlanCatalog; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy.RecoveryTiming; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReconciliationLimits; +import net.firedevops.firemud.accountservice.repository.AccountInitialTenantBillingOwnerRepository; +import net.firedevops.firemud.accountservice.repository.AccountPaymentInstrumentRecord; +import net.firedevops.firemud.accountservice.repository.AccountPaymentInstrumentRecord.DisplayMetadata; +import net.firedevops.firemud.accountservice.repository.AccountPaymentInstrumentRecord.State; +import net.firedevops.firemud.accountservice.repository.AccountPaymentInstrumentRepository; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.OwnerFence; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.ProducerEvidence; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreationRecord; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +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 org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Controlled local source setup plus the real hosting lifecycle owner and Stripe SDK read path. The + * caller must migrate its isolated Account schema before using this fixture. The fresh-tenant, + * creator/consent, customer, wallet, and transport inputs are controlled; they do not qualify their + * authenticated producers, PKI, Stripe, runtime registration, or production entitlement use. + */ +public final class CanonicalHostingSubscriptionTestFixture { + private static final String DIGEST = "sha256:" + "a".repeat(64); + private static final AtomicLong GAME_ROWS = new AtomicLong(20_000); + + private CanonicalHostingSubscriptionTestFixture() {} + + public static Fixture create(DataSource source) { + Objects.requireNonNull(source, "migrated Account datasource is required"); + JdbcTemplate jdbc = new JdbcTemplate(source); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(source)); + AccountHostingPlanCatalog catalog = + new AccountHostingPlanCatalog( + List.of( + new AccountHostingPlanCatalog.ConfiguredPlan( + "hosting", "price_controlled", "1", "100", "2", "1048576"))); + AccountSubscriptionIntentRepository intents = + new AccountSubscriptionIntentRepository(dsl, catalog); + + long row = GAME_ROWS.incrementAndGet(); + var accountRow = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO accounts (username, email, password_hash) " + + "VALUES (?, ?, 'controlled-hash') RETURNING id, account_uuid", + "hosting-fixture-" + row, + "hosting-fixture-" + row + "@example.test")); + long accountId = accountRow.get("id", Long.class); + UUID accountUuid = accountRow.get("account_uuid", UUID.class); + + UUID tenantId = UUID.randomUUID(); + UUID tenantCreateRequest = UUID.randomUUID(); + UUID tenantCreateOperation = UUID.randomUUID(); + String tenantKey = "hosting-fixture-game-" + row; + String tenantRequestDigest = + GameTenantCreationDigest.requestDigest( + "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, + State.ATTACHABLE, + new 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))); + + MutableClock clock = new MutableClock(creation.createdAt().plusSeconds(1)); + ControlledStripeTransport transport = new ControlledStripeTransport(); + var lifecycleRepository = + new AccountHostingSubscriptionLifecycleRepository( + 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); + var observer = + new StripeHostingSubscriptionObserver(new com.stripe.StripeClient(transport), clock); + var service = + new AccountHostingSubscriptionLifecycleService( + lifecycleRepository, observer, new DataSourceTransactionManager(source)); + Fixture fixture = + new Fixture( + jdbc, + dsl, + transaction, + accountId, + accountUuid, + tenantId, + creation, + intents, + instrument, + "sub_" + row, + clock, + transport, + service, + lifecycleRepository, + observer); + fixture.providerStatus("active"); + return fixture; + } + + private static T in(TransactionTemplate transaction, Supplier body) { + return Objects.requireNonNull(transaction.execute(status -> body.get())); + } + + public static final class Fixture { + private final JdbcTemplate jdbc; + private final DSLContext dsl; + private final TransactionTemplate transaction; + private final long accountId; + private final UUID accountUuid; + private final UUID tenantId; + private final AccountSubscriptionCreationRecord creation; + private final AccountSubscriptionIntentRepository intents; + private final AccountPaymentInstrumentRecord instrument; + private final String providerId; + private final MutableClock clock; + private final ControlledStripeTransport transport; + private final AccountHostingSubscriptionLifecycleService service; + private final AccountHostingSubscriptionLifecycleRepository lifecycleRepository; + private final StripeHostingSubscriptionObserver observer; + + private Fixture( + JdbcTemplate jdbc, + DSLContext dsl, + TransactionTemplate transaction, + long accountId, + UUID accountUuid, + UUID tenantId, + AccountSubscriptionCreationRecord creation, + AccountSubscriptionIntentRepository intents, + AccountPaymentInstrumentRecord instrument, + String providerId, + MutableClock clock, + ControlledStripeTransport transport, + AccountHostingSubscriptionLifecycleService service, + AccountHostingSubscriptionLifecycleRepository lifecycleRepository, + StripeHostingSubscriptionObserver observer) { + this.jdbc = jdbc; + this.dsl = dsl; + this.transaction = transaction; + this.accountId = accountId; + this.accountUuid = accountUuid; + this.tenantId = tenantId; + this.creation = creation; + this.intents = intents; + this.instrument = instrument; + this.providerId = providerId; + this.clock = clock; + this.transport = transport; + this.service = service; + this.lifecycleRepository = lifecycleRepository; + this.observer = observer; + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "Integration tests intentionally inspect the fixture's actual JdbcTemplate and datasource; copying it would change the physical SQL boundary.") + public JdbcTemplate jdbc() { + return jdbc; + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "Integration tests intentionally use this exact datasource-backed DSLContext for physical SQL assertions; a copy would change the fixture boundary.") + public DSLContext dsl() { + return dsl; + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "Integration tests intentionally use this exact TransactionTemplate to exercise the fixture's real transaction boundary; a copy would change it.") + public TransactionTemplate transaction() { + return transaction; + } + + public long accountId() { + return accountId; + } + + public UUID accountUuid() { + return accountUuid; + } + + public UUID tenantId() { + return tenantId; + } + + public AccountSubscriptionCreationRecord creation() { + return creation; + } + + public AccountSubscriptionIntentRepository intents() { + return intents; + } + + public AccountPaymentInstrumentRecord instrument() { + return instrument; + } + + public String providerId() { + return providerId; + } + + public MutableClock clock() { + return clock; + } + + public ControlledStripeTransport transport() { + return transport; + } + + public AccountHostingSubscriptionLifecycleService service() { + return service; + } + + /** Actual source collaborators for explicit prepare/observe/final-transaction tests. */ + public AccountHostingSubscriptionLifecycleRepository lifecycleRepository() { + return lifecycleRepository; + } + + public StripeHostingSubscriptionObserver observer() { + return observer; + } + + public void providerStatus(String status) { + transport.json = response(this, status); + } + } + + public static final class MutableClock extends Clock { + private Instant current; + + private MutableClock(Instant current) { + this.current = current; + } + + public void advance(Duration duration) { + current = current.plus(duration); + } + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return current; + } + } + + public static final class ControlledStripeTransport implements StripeResponseGetter { + private String json; + private int reads; + + public int reads() { + return 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++; + 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 Stripe streaming or provider mutations are allowed"); + } + } + + @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 fixture, String status) { + String endedAt = + "canceled".equals(status) + ? Long.toString(fixture.clock().instant().getEpochSecond()) + : "null"; + 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":%s, + "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( + fixture.providerId(), + fixture.creation().providerCustomerId(), + fixture.instrument().providerPaymentMethodId(), + status, + endedAt, + fixture.creation().subscriptionProvisioningRequestId(), + fixture.creation().subscriptionId(), + fixture.providerId(), + fixture.creation().createdAt().getEpochSecond(), + fixture.creation().createdAt().getEpochSecond() + 3600, + fixture.creation().planQuote().providerPriceId()); + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/RetainedSubscriptionEvidencePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/RetainedSubscriptionEvidencePostgresIntegrationTest.java new file mode 100644 index 0000000000..fa81372c91 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/RetainedSubscriptionEvidencePostgresIntegrationTest.java @@ -0,0 +1,233 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +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.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Populated, combined-history forward upgrade; no generated or synthetic canonical subscription. + */ +@Testcontainers(disabledWithoutDocker = true) +class RetainedSubscriptionEvidencePostgresIntegrationTest { + private static final String EVIDENCE = "account_retained_subscription_evidence"; + + @Container + private static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void forwardUpgradePreservesEveryValueHeapIdentityXminAndPublishedFlywayHistory() { + Context context = predecessor(); + DSLContext dsl = context.dsl(); + List> before = rows(dsl, "subscription"); + List> history = history(dsl); + Long originalOid = relationOid(dsl, "subscription"); + List> accounts = + dsl.fetch( + "SELECT row_to_json(a)::text AS value, xmin::text AS xmin FROM accounts a ORDER BY id") + .intoMaps(); + + configuration(context).load().migrate(); + + assertThat(rows(dsl, EVIDENCE)).isEqualTo(before); + assertThat(relationOid(dsl, EVIDENCE)).isEqualTo(originalOid); + var afterHistory = history(dsl); + assertThat(afterHistory).hasSize(history.size() + 4); + assertThat(afterHistory.subList(history.size(), afterHistory.size())) + .extracting(row -> row.get("version")) + .containsExactly("1027", "1027.1", "1027.2", "1028"); + assertThat(afterHistory.subList(0, history.size())).containsExactlyElementsOf(history); + assertThat(history(dsl).getLast().get("version")).isEqualTo("1028"); + assertThat( + dsl.fetch( + "SELECT version FROM flyway_schema_history WHERE version IN ('1000', '1001', '1002')")) + .hasSize(3); + assertThat( + dsl.fetch( + "SELECT row_to_json(a)::text AS value, xmin::text AS xmin FROM accounts a ORDER BY id") + .intoMaps()) + .isEqualTo(accounts); + assertThat(scalar(dsl, "SELECT to_regclass('subscription')", String.class)).isNull(); + assertThat( + scalar( + dsl, + "SELECT to_regprocedure('advance_subscription_authority_generation()')", + String.class)) + .isNull(); + assertThat( + dsl.fetch( + "SELECT conname FROM pg_constraint WHERE conrelid = ?::regclass ORDER BY conname", + EVIDENCE) + .getValues(0, String.class)) + .containsExactly( + "account_retained_subscription_evidence_account_fk", + "account_retained_subscription_evidence_generation_non_nil", + "account_retained_subscription_evidence_pkey", + "account_retained_subscription_evidence_version_positive", + "subscription_account_id_not_null", + "subscription_entitlement_version_not_null", + "subscription_id_not_null", + "subscription_plan_id_not_null", + "subscription_status_not_null", + "subscription_tenant_authority_generation_not_null", + "subscription_tenant_id_not_null"); + assertThat( + dsl.fetch( + "SELECT indexname FROM pg_indexes WHERE schemaname = current_schema() AND tablename = ?", + EVIDENCE) + .getValues(0, String.class)) + .containsExactlyInAnyOrder( + "account_retained_subscription_evidence_pkey", + "idx_account_retained_subscription_evidence_account", + "idx_account_retained_subscription_evidence_tenant"); + assertThat( + scalar( + dsl, + "SELECT to_regclass('account_retained_subscription_evidence_id_seq')", + String.class)) + .isNotNull(); + configuration(context).load().validate(); + } + + @Test + void archiveRefusesAllMutationIncludingNoOpEmptyStatementsAndTruncateCascade() { + Context context = predecessor(); + configuration(context).load().migrate(); + DSLContext dsl = context.dsl(); + var before = rows(dsl, EVIDENCE); + for (String sql : + List.of( + "INSERT INTO " + EVIDENCE + " SELECT * FROM " + EVIDENCE + " WHERE false", + "INSERT INTO " + + EVIDENCE + + " (id, account_id, plan_id, status, tenant_id) VALUES (9999, " + + context.accountId() + + ", 'forbidden', 'active', 7)", + "UPDATE " + EVIDENCE + " SET status = status", + "UPDATE " + EVIDENCE + " SET tenant_id = 99 WHERE false", + "DELETE FROM " + EVIDENCE + " WHERE false", + "DELETE FROM " + EVIDENCE, + "TRUNCATE " + EVIDENCE, + "TRUNCATE " + EVIDENCE + " RESTART IDENTITY CASCADE")) { + assertThatThrownBy(() -> dsl.execute(sql)) + .hasMessageContaining("Retained subscription evidence is immutable and non-authorizing"); + assertThat(rows(dsl, EVIDENCE)).isEqualTo(before); + } + // Account FK remains restrictive even for terminal-looking historical rows. + assertThatThrownBy(() -> dsl.execute("DELETE FROM accounts WHERE id = ?", context.accountId())) + .hasMessageContaining("account_retained_subscription_evidence_account_fk"); + // Other retained Account families can refuse first; no cascade may erase this evidence. + assertThatThrownBy(() -> dsl.execute("TRUNCATE accounts CASCADE")) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(rows(dsl, EVIDENCE)).isEqualTo(before); + } + + @Test + void historicalRepositoryReadsOnlyTheRequestedAccountWithoutChoosingATenantWinner() { + Context context = predecessor(); + configuration(context).load().migrate(); + var repository = new RetainedSubscriptionEvidenceRepository(context.dsl()); + var history = repository.findHistoryByAccountId(context.accountId()); + assertThat(history).hasSize(4); + assertThat(history) + .extracting(row -> row.status()) + .containsExactly("active", "canceled", "grace", "provider_unknown"); + assertThat(history).extracting(row -> row.accountId()).containsOnly(context.accountId()); + assertThat(history).extracting(row -> row.tenantId()).containsExactly(7L, 7L, 8L, 8L); + assertThat(repository.findHistoryByAccountId(-1L)).isEmpty(); + assertThat(rows(context.dsl(), EVIDENCE)).hasSize(6); + } + + private static List> rows(DSLContext dsl, String relation) { + return dsl.fetch( + "SELECT row_to_json(s)::text AS value, xmin::text AS xmin, ctid::text AS ctid FROM " + + relation + + " s ORDER BY id") + .intoMaps(); + } + + private static List> history(DSLContext dsl) { + return dsl.fetch("SELECT * FROM flyway_schema_history ORDER BY installed_rank").intoMaps(); + } + + private static T scalar(DSLContext dsl, String sql, Class type, Object... bindings) { + return Objects.requireNonNull(dsl.fetchOne(sql, bindings)).get(0, type); + } + + private static Long relationOid(DSLContext dsl, String relation) { + return scalar(dsl, "SELECT ?::regclass::oid::bigint", Long.class, relation); + } + + private static FluentConfiguration configuration(Context context) { + return Flyway.configure() + .dataSource(context.source()) + .target("1028") + .schemas(context.schema()) + .defaultSchema(context.schema()) + .placeholders(Map.of("serviceSchema", context.schema())) + .locations("classpath:db/migration", "classpath:db/migration/saga"); + } + + private static Context predecessor() { + String schema = "subscription_retention_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + source.setSchema(schema); + DSLContext dsl = DSL.using(source, SQLDialect.POSTGRES); + var empty = new Context(source, schema, dsl, 0L); + configuration(empty).target("1026").load().migrate(); + Long accountId = + Objects.requireNonNull( + scalar( + dsl, + "INSERT INTO accounts(username,email,password_hash) VALUES ('retained','retained@example.test','hash') RETURNING id", + Long.class)); + Long otherAccount = + Objects.requireNonNull( + scalar( + dsl, + "INSERT INTO accounts(username,email,password_hash) VALUES ('other','other@example.test','hash') RETURNING id", + Long.class)); + dsl.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,?::uuid)," + + "(92,?,'retained-canceled','canceled',NULL,'2025-02-03 04:05:06.654321',7,21,?::uuid)," + + "(93,?,'grace','grace',NULL,NULL,8,1,?::uuid)," + + "(94,?,'unknown','provider_unknown',NULL,NULL,8,2,?::uuid)," + + "(95,?,'other-account','active',NULL,NULL,7,5,?::uuid)", + accountId, + UUID.randomUUID(), + accountId, + UUID.randomUUID(), + accountId, + UUID.randomUUID(), + accountId, + UUID.randomUUID(), + otherAccount, + UUID.randomUUID()); + // Preserve V5's numeric default as historical evidence, not canonical tenant provenance. + dsl.execute( + "INSERT INTO subscription(id,account_id,plan_id,status) VALUES (96,?,'default-tenant','active')", + otherAccount); + return new Context(source, schema, dsl, accountId); + } + + private record Context( + DriverManagerDataSource source, String schema, DSLContext dsl, Long accountId) {} +} 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..8bc09e456e --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerPostgresIntegrationTest.java @@ -0,0 +1,271 @@ +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 net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +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 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)); + 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(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(); + f.service() + .reconcile( + UUID.randomUUID(), + f.creation().requestId(), + claim.subscriptionRowVersion(), + f.providerId(), + claim.attemptId()); + String marker = "capture_marker_" + UUID.randomUUID().toString().replace("-", ""); + assertThatThrownBy( + () -> + f.service() + .readCurrentAndCapture( + f.tenantId(), + receipt -> { + 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"); + assertThat(f.dsl().fetchOne("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") + .target("1030") + .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/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java index 43a3e85b93..ad7f8f1ff4 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java @@ -31,6 +31,7 @@ import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; import net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository; +import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; @@ -440,7 +441,6 @@ public Account updatePasswordHashForLockedAccount(Account expected, String passw logoutAllOperations, securityStateOperations, resetSourceChanges, - null, // Audit outbox is not used by credential/reset owner tests. null, // Connect scopes are not used by credential/reset owner tests. null, // JOIN operations are not used by credential/reset owner tests. challenges, @@ -450,7 +450,8 @@ public Account updatePasswordHashForLockedAccount(Account expected, String passw null, // Profiles are not used by primary authentication. null, // Profile mapper is not used by primary authentication. null, // Payment transactions are not used by primary authentication. - null, // Subscriptions are not used by primary authentication. + // Retained evidence is not read by primary authentication. + org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), null, // External identities are not used by primary authentication. resetTokens, null, // Email verification tokens are not used by primary authentication. @@ -458,8 +459,6 @@ public Account updatePasswordHashForLockedAccount(Account expected, String passw null, // Email delivery is not used by primary authentication. null, // Mail properties are not used by primary authentication. null, // Token properties are not used by primary authentication. - null, // JWT auth properties are not used by primary authentication. - null, // Game Session client is not used by primary authentication. null, // Entity Management client is not used by primary authentication. null, // JWT utility is not used by primary authentication. null, // Session service is not used by primary authentication. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java index 62ee56af53..22d0ca18e9 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java @@ -70,6 +70,7 @@ import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; import net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository; +import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountGenerationProjection; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; @@ -2507,7 +2508,6 @@ private static AccountServiceImpl primaryCredentialAuthority( null, null, null, - null, challenges, null, null, @@ -2515,9 +2515,7 @@ private static AccountServiceImpl primaryCredentialAuthority( null, null, null, - null, - null, - null, + org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), null, null, null, @@ -3116,7 +3114,6 @@ private static void commitPasswordResetAuthorityChange( logoutAllOperations, securityStateOperations, sourceChanges, - null, // audit outbox null, // connect scopes null, // join operations null, // email login challenges @@ -3126,7 +3123,8 @@ private static void commitPasswordResetAuthorityChange( null, // profiles null, // profile mapper null, // payment transactions - null, // subscriptions + // retained subscription evidence + org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), null, // external account identities resetTokens, null, // email verification tokens @@ -3137,8 +3135,6 @@ private static void commitPasswordResetAuthorityChange( null, null, null, - null, - null, context.manager()); inTransaction( context, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierPostgresIntegrationTest.java index 696ffe803a..124b9a3fac 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierPostgresIntegrationTest.java @@ -31,6 +31,7 @@ import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.accountservice.service.session.AccountGameplayCanonicalLoginOwner; @@ -294,7 +295,6 @@ private static Harness harness(String authModes, boolean expired) { null, null, null, - null, challenges, null, null, @@ -302,9 +302,7 @@ private static Harness harness(String authModes, boolean expired) { null, null, null, - null, - null, - null, + org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), null, null, null, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java index d11ddd6fad..8731b20cf2 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java @@ -37,13 +37,13 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; 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.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; @@ -1892,7 +1892,6 @@ private static Context contextAtVersion( mock(AccountSecurityStateOperationRepository.class), mock(AccountPasswordResetDraftSourceChangeRepository.class), mock(AccountAuditOutboxRepository.class), - mock(AccountConnectScopeRepository.class), mock(AccountJoinOperationRepository.class), challenges, null, @@ -1901,9 +1900,7 @@ private static Context contextAtVersion( null, null, null, - null, - null, - null, + org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), null, null, null, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionPostgresIntegrationTest.java index be5a5fdb41..0b6d5c792c 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionPostgresIntegrationTest.java @@ -22,13 +22,13 @@ 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.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.test.TestContainerImages; @@ -513,7 +513,6 @@ private static Context context() { mock(AccountSecurityStateOperationRepository.class), mock(AccountPasswordResetDraftSourceChangeRepository.class), mock(AccountAuditOutboxRepository.class), - mock(AccountConnectScopeRepository.class), mock(AccountJoinOperationRepository.class), challenges, null, @@ -522,9 +521,7 @@ private static Context context() { null, null, null, - null, - null, - null, + org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), null, null, null, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java index 95aabd3c51..0d552450fc 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java @@ -42,7 +42,6 @@ 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.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountInitialTenantBillingOwnerRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; @@ -55,6 +54,7 @@ import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountCreatorMembershipSourceReader; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapAuthorizationSource; @@ -1267,7 +1267,6 @@ private static StorageContext storageContext(int recentAgeSeconds, int maxClockS mock(AccountSecurityStateOperationRepository.class), mock(AccountPasswordResetDraftSourceChangeRepository.class), mock(AccountAuditOutboxRepository.class), - mock(AccountConnectScopeRepository.class), mock(AccountJoinOperationRepository.class), challenges, null, @@ -1276,9 +1275,7 @@ private static StorageContext storageContext(int recentAgeSeconds, int maxClockS null, null, null, - null, - null, - null, + org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), null, null, null, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationSourceOrderPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationSourceOrderPostgresIntegrationTest.java index 78248339c5..d8c9ba3a53 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationSourceOrderPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationSourceOrderPostgresIntegrationTest.java @@ -49,13 +49,13 @@ 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.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; @@ -916,7 +916,6 @@ private static Context context() { mock(AccountSecurityStateOperationRepository.class), mock(AccountPasswordResetDraftSourceChangeRepository.class), mock(AccountAuditOutboxRepository.class), - mock(AccountConnectScopeRepository.class), mock(AccountJoinOperationRepository.class), challenges, null, @@ -925,9 +924,7 @@ private static Context context() { null, null, null, - null, - null, - null, + org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), null, null, null, 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..92237d1a78 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisionerTest.java @@ -0,0 +1,280 @@ +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.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.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.options.get(3).getIdempotencyKey()).isEqualTo(OPERATION.toString()); + assertThat(transport.options.get(3).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("")); + assertThat(adapter(missing).provision(dispatch(false))) + .isInstanceOf(StripeHostingSubscriptionProvisioner.Pending.class); + assertThat(missing.methods).doesNotContain(RequestMethod.POST); + Transport lost = transport(search(""), subscription()); + lost.failureAt = 3; + lost.failure = mock(StripeException.class); + assertThat(adapter(lost).provision(dispatch(true))) + .isInstanceOf(StripeHostingSubscriptionProvisioner.Pending.class); + Transport recovered = transport(search(subscription()), subscription()); + assertThat(adapter(recovered).provision(dispatch(false))) + .isInstanceOf(StripeHostingSubscriptionProvisioner.Located.class); + assertThat(recovered.methods).doesNotContain(RequestMethod.POST); + } + + @Test + void searchFailureDuplicatesAndIndependentBindingMismatchRemainNonterminal() { + Transport failed = transport(search("")); + failed.failureAt = 2; + failed.failure = mock(StripeException.class); + assertThat(adapter(failed).provision(dispatch(true))) + .isInstanceOf(StripeHostingSubscriptionProvisioner.Pending.class); + assertThat(failed.methods).doesNotContain(RequestMethod.POST); + Transport duplicate = transport(search(subscription() + "," + subscription())); + assertThat(adapter(duplicate).provision(dispatch(true))) + .isInstanceOf(StripeHostingSubscriptionProvisioner.Pending.class); + assertThat(duplicate.methods).doesNotContain(RequestMethod.POST); + Transport mismatch = + transport(search(subscription()), subscription().replace("pm_exact", "pm_wrong")); + assertThat(adapter(mismatch).provision(dispatch(false))) + .isInstanceOf(StripeHostingSubscriptionProvisioner.Pending.class); + } + + @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); + assertThat(expired.provision(dispatch(true))) + .isInstanceOf(StripeHostingSubscriptionProvisioner.Pending.class); + assertThat(transport.paths).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))) + .isInstanceOf(StripeHostingSubscriptionProvisioner.Pending.class); + assertThat(mismatch.paths).hasSize(2); + 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(); + } 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); + } + + 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 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/data/TestDataSeederTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/data/TestDataSeederTest.java index b76fe71ace..d019d7fc47 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/data/TestDataSeederTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/data/TestDataSeederTest.java @@ -4,9 +4,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; @@ -14,17 +11,13 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import java.time.LocalDateTime; -import java.util.List; import java.util.Optional; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; import net.firedevops.firemud.accountservice.entity.Profile; -import net.firedevops.firemud.accountservice.entity.Subscription; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.ProfileRepository; -import net.firedevops.firemud.accountservice.repository.SubscriptionRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -36,7 +29,6 @@ class TestDataSeederTest { @Mock AccountRepository accountRepository; @Mock AccountTenantMembershipRepository accountTenantMembershipRepository; @Mock ProfileRepository profileRepository; - @Mock SubscriptionRepository subscriptionRepository; private TestDataSeeder seeder; @@ -44,15 +36,11 @@ class TestDataSeederTest { void setup() { MockitoAnnotations.openMocks(this); seeder = - new TestDataSeeder( - accountRepository, - accountTenantMembershipRepository, - profileRepository, - subscriptionRepository); + new TestDataSeeder(accountRepository, accountTenantMembershipRepository, profileRepository); } @Test - void runSeedsDemoAccountMembershipProfileAndSubscriptionWhenMissing() { + void runSeedsDemoAccountMembershipAndProfileWhenMissing() { Account account = new Account(); account.setId(1L); account.setEmail("demo@example.com"); @@ -62,23 +50,12 @@ void runSeedsDemoAccountMembershipProfileAndSubscriptionWhenMissing() { when(accountTenantMembershipRepository.findByAccountIdAndTenantId(1L, 1L)) .thenReturn(Optional.empty()); when(profileRepository.findByAccountIdAndTenantId(1L, 1L)).thenReturn(Optional.empty()); - when(subscriptionRepository.findByTenantId(1L)).thenReturn(List.of()); seeder.run(new DefaultApplicationArguments(new String[] {})); verify(accountRepository).save(any(Account.class)); verify(accountTenantMembershipRepository).save(any(AccountTenantMembership.class)); verify(profileRepository).save(any(Profile.class)); - ArgumentCaptor subscriptionCaptor = ArgumentCaptor.forClass(Subscription.class); - verify(subscriptionRepository).save(subscriptionCaptor.capture()); - Subscription seededSubscription = subscriptionCaptor.getValue(); - assertAll( - () -> assertSame(account, seededSubscription.getAccount()), - () -> assertEquals("local-smoke", seededSubscription.getPlanId()), - () -> assertEquals("active", seededSubscription.getStatus()), - () -> assertNotNull(seededSubscription.getStartedAt()), - () -> assertNull(seededSubscription.getEndedAt()), - () -> assertEquals(1L, seededSubscription.getTenantId())); } @Test @@ -96,7 +73,6 @@ void runReassertsExistingDemoAccountWithoutOverwritingExplicitJoin() throws Exce .thenReturn(Optional.of(explicitJoin)); when(profileRepository.findByAccountIdAndTenantId(1L, 1L)) .thenReturn(Optional.of(new Profile())); - when(subscriptionRepository.findByTenantId(1L)).thenReturn(List.of()); seeder.run(new DefaultApplicationArguments(new String[] {})); @@ -126,7 +102,6 @@ void runReassertsExistingDemoAccountWithoutOverwritingExplicitJoin() throws Exce org.junit.jupiter.api.Assertions.assertEquals( "EXPLICIT_JOIN", explicitJoin.getAuthorityProvenance())); verify(profileRepository, never()).save(any(Profile.class)); - verify(subscriptionRepository).save(any(Subscription.class)); } @Test @@ -136,11 +111,6 @@ void runIsIdempotentWhenInvokedTwice() { account.setEmail("demo@example.com"); AccountTenantMembership seededMembership = membership(account, 1L, "ACTIVE", "SEEDED_DEMO", true); - Subscription seededSubscription = new Subscription(); - seededSubscription.setAccount(account); - seededSubscription.setPlanId("local-smoke"); - seededSubscription.setStatus("active"); - seededSubscription.setTenantId(1L); when(accountRepository.findByEmail("demo@example.com")) .thenReturn(Optional.empty(), Optional.of(account)); @@ -149,33 +119,22 @@ void runIsIdempotentWhenInvokedTwice() { .thenReturn(Optional.empty(), Optional.of(seededMembership)); when(profileRepository.findByAccountIdAndTenantId(1L, 1L)) .thenReturn(Optional.empty(), Optional.of(new Profile())); - when(subscriptionRepository.findByTenantId(1L)) - .thenReturn(List.of(), List.of(seededSubscription)); seeder.run(new DefaultApplicationArguments(new String[] {})); seeder.run(new DefaultApplicationArguments(new String[] {})); verify(accountTenantMembershipRepository, times(1)).save(any(AccountTenantMembership.class)); verify(profileRepository, times(1)).save(any(Profile.class)); - verify(subscriptionRepository, times(1)).save(any(Subscription.class)); } @Test - void runRetainsExistingSubscriptionWithoutOverwritingItsStatus() { + void runDoesNotOverwriteExplicitJoinWhenReassertingDemoAccount() { Account account = new Account(); account.setId(1L); account.setEmail("demo@example.com"); - Account billingOwner = new Account(); - billingOwner.setId(2L); AccountTenantMembership explicitJoin = membership(account, 1L, "ACTIVE", "EXPLICIT_JOIN", true); explicitJoin.setMembershipVersion(4L); explicitJoin.setMembershipAuthorityGeneration(8L); - Subscription existingSubscription = new Subscription(); - existingSubscription.setAccount(billingOwner); - existingSubscription.setPlanId("billing-owned-plan"); - existingSubscription.setStatus("canceled"); - existingSubscription.setEndedAt(LocalDateTime.of(2025, 1, 2, 3, 4)); - existingSubscription.setTenantId(1L); when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); when(accountRepository.save(any(Account.class))).thenReturn(account); @@ -183,48 +142,10 @@ void runRetainsExistingSubscriptionWithoutOverwritingItsStatus() { .thenReturn(Optional.of(explicitJoin)); when(profileRepository.findByAccountIdAndTenantId(1L, 1L)) .thenReturn(Optional.of(new Profile())); - when(subscriptionRepository.findByTenantId(1L)).thenReturn(List.of(existingSubscription)); seeder.run(new DefaultApplicationArguments(new String[] {})); - assertAll( - () -> assertSame(billingOwner, existingSubscription.getAccount()), - () -> assertEquals("canceled", existingSubscription.getStatus()), - () -> assertEquals("billing-owned-plan", existingSubscription.getPlanId()), - () -> assertEquals(LocalDateTime.of(2025, 1, 2, 3, 4), existingSubscription.getEndedAt())); - verify(accountTenantMembershipRepository, never()).save(any(AccountTenantMembership.class)); - verify(subscriptionRepository, never()).save(any(Subscription.class)); - } - - @Test - void runFailsClosedWhenExistingTenantSubscriptionsAreAmbiguous() { - Account account = new Account(); - account.setId(1L); - account.setEmail("demo@example.com"); - AccountTenantMembership explicitJoin = membership(account, 1L, "ACTIVE", "EXPLICIT_JOIN", true); - Subscription active = new Subscription(); - active.setStatus("active"); - active.setTenantId(1L); - Subscription canceled = new Subscription(); - canceled.setStatus("canceled"); - canceled.setTenantId(1L); - - when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); - when(accountRepository.save(any(Account.class))).thenReturn(account); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(1L, 1L)) - .thenReturn(Optional.of(explicitJoin)); - when(profileRepository.findByAccountIdAndTenantId(1L, 1L)) - .thenReturn(Optional.of(new Profile())); - when(subscriptionRepository.findByTenantId(1L)).thenReturn(List.of(active, canceled)); - - IllegalStateException exception = - assertThrows( - IllegalStateException.class, - () -> seeder.run(new DefaultApplicationArguments(new String[] {}))); - - assertTrue(exception.getMessage().contains("ambiguous subscription authority")); verify(accountTenantMembershipRepository, never()).save(any(AccountTenantMembership.class)); - verify(subscriptionRepository, never()).save(any(Subscription.class)); } @Test 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 13653f632a..fd4c88886f 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 @@ -1,5 +1,6 @@ package net.firedevops.firemud.accountservice.repository; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; @@ -47,6 +48,51 @@ void claimAndSettlementRequireWritableOwnerTransactionBeforeSql() { verifyNoInteractions(dsl); } + @Test + void terminalResolutionCaptureAndApplyRequireWritableOwnerTransactionBeforeSql() { + assertThatThrownBy(() -> repository.prepareTerminalResolution(null)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> repository.applyTerminalResolution(null, null, null)) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertThatThrownBy(() -> repository.prepareTerminalResolution(null)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> repository.applyTerminalResolution(null, null, null)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(dsl); + } + + @Test + void terminalResolutionReasonIsCanonicalBoundedScalarComparisonData() { + var first = terminalRequest("e\u0301 reason"); + assertThat(first.auditReason()).isEqualTo("é reason"); + assertThat(first.payload()).isNotEmpty(); + for (String invalid : + List.of("", "\u0085\u00a0", "nul\u0000reason", "\ud800", "é".repeat(501))) { + assertThatThrownBy(() -> terminalRequest(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThat(terminalRequest("é".repeat(500)).auditReason()).hasSize(500); + } + + private static AccountHostingSubscriptionTerminalResolution.Request terminalRequest( + String reason) { + return new AccountHostingSubscriptionTerminalResolution.Request( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + 4, + 3, + UUID.randomUUID(), + UUID.randomUUID(), + "a".repeat(64), + UUID.randomUUID(), + reason); + } + private void assertTransactionRefusal() { assertThatThrownBy(() -> repository.claim(UUID.randomUUID(), 1, UUID.randomUUID())) .isInstanceOf(IllegalStateException.class) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantOperationEntitlementWorkloadGuardTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantOperationEntitlementWorkloadGuardTest.java new file mode 100644 index 0000000000..491e712c7f --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantOperationEntitlementWorkloadGuardTest.java @@ -0,0 +1,119 @@ +package net.firedevops.firemud.accountservice.security; + +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.when; + +import io.grpc.Attributes; +import io.grpc.Context; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import javax.net.ssl.SSLSession; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.AccountTenantOperationEntitlementReadServiceGrpc; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +class AccountTenantOperationEntitlementWorkloadGuardTest { + private final AccountTenantOperationEntitlementWorkloadGuard guard = + new AccountTenantOperationEntitlementWorkloadGuard("firemud"); + + @AfterEach + void clear() { + SessionContext.clear(); + } + + @Test + void onlyExactTlsWorldAndMethodCanInstallPrivateAssertion() throws Exception { + var method = + AccountTenantOperationEntitlementReadServiceGrpc.getReadTenantOperationEntitlementMethod(); + assertThat(invoke(method, tls("firemud", "world-management-service"))).isNull(); + assertThatThrownBy(guard::requireAuthenticatedWorldCaller) + .isInstanceOf(StatusRuntimeException.class); + assertThat(invoke(method, tls("other", "world-management-service")).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(invoke(method, tls("firemud", "account-service")).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + invoke( + AccountServiceGrpc.getGetProfileMethod(), + tls("firemud", "world-management-service")) + .getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } + + @Test + void arbitraryPeerContextAndSessionClaimsNeverAuthenticate() throws Exception { + var method = + AccountTenantOperationEntitlementReadServiceGrpc.getReadTenantOperationEntitlementMethod(); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/firemud/sa/world-management-service") + .orElseThrow()) + .run( + () -> { + assertThat(invoke(method, null).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThatThrownBy(guard::requireAuthenticatedWorldCaller) + .isInstanceOf(StatusRuntimeException.class); + }); + for (boolean internal : List.of(true, false)) { + if (internal) + SessionContext.setContext( + null, List.of(), Map.of(), true, "world-management-service", "instance"); + else SessionContext.setContext("caller", List.of(), Map.of()); + assertThat(invoke(method, tls("firemud", "world-management-service")).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + SessionContext.clear(); + } + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private Status invoke(MethodDescriptor method, SSLSession ssl) { + ServerCall call = mock(ServerCall.class); + when(call.getMethodDescriptor()).thenReturn(method); + when(call.getAttributes()) + .thenReturn( + ssl == null + ? Attributes.EMPTY + : Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, ssl).build()); + AtomicInteger starts = new AtomicInteger(); + ServerCallHandler next = + (ignored, headers) -> { + assertThat(guard.requireAuthenticatedWorldCaller()) + .isEqualTo("spiffe://firemud/ns/firemud/sa/world-management-service"); + starts.incrementAndGet(); + return new ServerCall.Listener() {}; + }; + guard.interceptCall(call, new Metadata(), next); + var captured = ArgumentCaptor.forClass(Status.class); + verify(call, org.mockito.Mockito.atMostOnce()).close(captured.capture(), any(Metadata.class)); + assertThat(starts.get()).isEqualTo(captured.getAllValues().isEmpty() ? 1 : 0); + return captured.getAllValues().isEmpty() ? null : captured.getValue(); + } + + private static SSLSession tls(String namespace, String service) throws Exception { + var leaf = mock(X509Certificate.class); + when(leaf.getSubjectAlternativeNames()) + .thenReturn(List.of(List.of(6, "spiffe://firemud/ns/" + namespace + "/sa/" + service))); + var ssl = mock(SSLSession.class); + when(ssl.getPeerCertificates()).thenReturn(new Certificate[] {leaf}); + return ssl; + } +} 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..24c37e5949 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java @@ -0,0 +1,127 @@ +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.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 org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +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); + } + + @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/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index ff8ba33dbe..52ef20b55e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -4,7 +4,6 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.verifyNoInteractions; @@ -19,29 +18,20 @@ import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.firedevops.firemud.account.AuthenticationErrorCodes; -import net.firedevops.firemud.accountservice.client.EntityManagementClient; -import net.firedevops.firemud.accountservice.client.GameSessionClient; import net.firedevops.firemud.accountservice.config.AccountTokenProperties; import net.firedevops.firemud.accountservice.config.MailProperties; import net.firedevops.firemud.accountservice.dto.AccountDto; import net.firedevops.firemud.accountservice.dto.AuthenticationResult; import net.firedevops.firemud.accountservice.dto.ConnectTokenRequest; -import net.firedevops.firemud.accountservice.dto.ConnectTokenResult; import net.firedevops.firemud.accountservice.dto.CreateAccountRequest; -import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; -import net.firedevops.firemud.accountservice.dto.DirectTextJoinScope; -import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; -import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; import net.firedevops.firemud.accountservice.dto.PasswordResetRequest; import net.firedevops.firemud.accountservice.dto.PlayerBootstrapResult; import net.firedevops.firemud.accountservice.dto.RealmAccessGrantRequest; import net.firedevops.firemud.accountservice.dto.UpdateAccountLoginAuthModesRequest; -import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; @@ -51,14 +41,13 @@ import net.firedevops.firemud.accountservice.entity.EmailVerificationToken; import net.firedevops.firemud.accountservice.entity.Profile; import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; -import net.firedevops.firemud.accountservice.entity.Subscription; +import net.firedevops.firemud.accountservice.entity.RetainedSubscriptionEvidence; import net.firedevops.firemud.accountservice.mapper.AccountMapper; import net.firedevops.firemud.accountservice.mapper.ProfileMapper; 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.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; @@ -71,7 +60,7 @@ import net.firedevops.firemud.accountservice.repository.ExternalAccountRepository; import net.firedevops.firemud.accountservice.repository.PaymentTransactionRepository; import net.firedevops.firemud.accountservice.repository.ProfileRepository; -import net.firedevops.firemud.accountservice.repository.SubscriptionRepository; +import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; import net.firedevops.firemud.accountservice.service.EmailService; import net.firedevops.firemud.accountservice.service.NotificationService; @@ -82,32 +71,22 @@ import net.firedevops.firemud.common.security.JwtAuthProperties; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.common.security.ReloadableJwtUtil; -import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.EnumSource; -import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; import org.mapstruct.factory.Mappers; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.slf4j.LoggerFactory; -import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.annotation.Propagation; -import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.SimpleTransactionStatus; class AccountServiceImplTest { private static final String JWT_SECRET = "mysecretkey123456789012345678901"; - private static final String REALM_ID = "4c4b57d8-e3a2-48fe-9977-e7df0fdce901"; - private static final String PLAYABLE_STATE_NAMESPACE_ID = "c6ed6a44-c7e7-4f18-81fc-078a74e67c07"; - private static final String PLAYABLE_STATE_NAMESPACE_ID_TENANT_8 = - "a741a4b8-a2cb-405e-a330-8fbf3dfb841f"; @Mock private AccountRepository accountRepository; @Mock private AccountAuthorityGenerationRepository accountAuthorityGenerationRepository; @Mock private AccountAuthoritySourceEvidenceRepository accountAuthoritySourceEvidenceRepository; @@ -121,7 +100,6 @@ class AccountServiceImplTest { accountPasswordResetDraftSourceChangeRepository; @Mock private AccountAuditOutboxRepository accountAuditOutboxRepository; - @Mock private AccountConnectScopeRepository accountConnectScopeRepository; @Mock private AccountJoinOperationRepository accountJoinOperationRepository; @Mock private AccountEmailLoginChallengeRepository accountEmailLoginChallengeRepository; @Mock private AccountRealmAccessGrantRepository accountRealmAccessGrantRepository; @@ -133,11 +111,9 @@ class AccountServiceImplTest { @Mock private MailProperties mailProperties; private final AccountTokenProperties tokenProperties = new AccountTokenProperties(); private final JwtAuthProperties jwtAuthProperties = new JwtAuthProperties(); - @Mock private GameSessionClient gameSessionClient; - @Mock private EntityManagementClient entityManagementClient; @Mock private SessionService sessionService; @Mock private PaymentTransactionRepository paymentTransactionRepository; - @Mock private SubscriptionRepository subscriptionRepository; + @Mock private RetainedSubscriptionEvidenceRepository retainedSubscriptionEvidenceRepository; @Mock private ExternalAccountRepository externalAccountRepository; @Mock private PlatformTransactionManager transactionManager; @@ -156,18 +132,6 @@ void setup() { when(transactionManager.getTransaction( org.mockito.ArgumentMatchers.any(TransactionDefinition.class))) .thenAnswer(invocation -> new SimpleTransactionStatus()); - Subscription explicitActiveEntitlement = new Subscription(); - explicitActiveEntitlement.setId(1L); - explicitActiveEntitlement.setTenantId(7L); - explicitActiveEntitlement.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)) - .thenReturn(java.util.List.of(explicitActiveEntitlement)); - Subscription explicitActiveEntitlementForSecondTenant = new Subscription(); - explicitActiveEntitlementForSecondTenant.setId(2L); - explicitActiveEntitlementForSecondTenant.setTenantId(8L); - explicitActiveEntitlementForSecondTenant.setStatus("active"); - when(subscriptionRepository.findByTenantId(8L)) - .thenReturn(java.util.List.of(explicitActiveEntitlementForSecondTenant)); AccountMapper mapper = Mappers.getMapper(AccountMapper.class); jwtUtil = org.mockito.Mockito.spy(new ReloadableJwtUtil(JWT_SECRET, 3600000L)); jwtAuthProperties.setJwtSecret(JWT_SECRET); @@ -175,51 +139,6 @@ void setup() { tokenProperties.setConnectScopeExpirationMs(120000L); tokenProperties.setConnectTokenExpirationMs(30000L); tokenProperties.setSessionExpirationMs(3600000L); - when(gameSessionClient.listGameplayWorlds()) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() - .setWorldSlug("demo") - .setDisplayName("Demo World") - .build())); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("production") - .setDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) - .thenReturn( - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug("demo") - .setWorldDisplayName("Demo World") - .setRealmSlug("production") - .setRealmDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build()); when(mailProperties.getResetUrl()).thenReturn("http://reset/%s"); when(mailProperties.getVerificationUrl()).thenReturn("http://verify/%s"); service = @@ -233,7 +152,6 @@ void setup() { accountSecurityStateOperationRepository, accountPasswordResetDraftSourceChangeRepository, accountAuditOutboxRepository, - accountConnectScopeRepository, accountJoinOperationRepository, accountEmailLoginChallengeRepository, accountRealmAccessGrantRepository, @@ -242,7 +160,7 @@ void setup() { profileRepository, profileMapper, paymentTransactionRepository, - subscriptionRepository, + retainedSubscriptionEvidenceRepository, externalAccountRepository, passwordResetTokenRepository, emailVerificationTokenRepository, @@ -251,8 +169,6 @@ void setup() { mailProperties, tokenProperties, jwtAuthProperties, - gameSessionClient, - entityManagementClient, jwtUtil, sessionService, transactionManager); @@ -265,6 +181,109 @@ private enum OrdinaryIssuance { PLAYER_BOOTSTRAP } + private enum PublicGameplayOperation { + WORLDS, + REALMS, + CHARACTERS, + BROWSER_JOIN, + DIRECT_SCOPE, + DIRECT_JOIN, + CONNECT_TOKEN + } + + /** The complete canonical positive fixtures remain in the public-facade successor. */ + @ParameterizedTest + @EnumSource(PublicGameplayOperation.class) + void publicGameplayRemainsUnavailableBeforeReadingAnyCallerOrAuthority( + PublicGameplayOperation operation) { + AuthenticationException unavailable = + assertThrows( + AuthenticationException.class, + () -> invokePublicGameplayOperation(operation, null, null)); + + assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); + verifyPublicGameplayHasNoIo(); + } + + @ParameterizedTest + @EnumSource( + value = PublicGameplayOperation.class, + names = "DIRECT_SCOPE", + mode = EnumSource.Mode.EXCLUDE) + void retainedNumericSignedCarriersCannotReenablePublicGameplay( + PublicGameplayOperation operation) { + String bootstrap = + jwtUtil.generateToken("11", 300000L, Map.of("aud", "player-bootstrap", "accountId", "11")); + String scope = + jwtUtil.generateToken( + "11", + 120000L, + Map.of( + "aud", + "bootstrap-connect-scope", + "accountId", + "11", + "tenantId", + "7", + "gameInstanceId", + "44")); + org.mockito.Mockito.clearInvocations(jwtUtil); + + AuthenticationException unavailable = + assertThrows( + AuthenticationException.class, + () -> invokePublicGameplayOperation(operation, bootstrap, scope)); + + assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); + verifyPublicGameplayHasNoIo(); + } + + private void invokePublicGameplayOperation( + PublicGameplayOperation operation, String bootstrap, String scope) { + JoinPublicProductionRequest join = + scope == null ? null : new JoinPublicProductionRequest(scope, UUID.randomUUID().toString()); + switch (operation) { + case WORLDS -> service.listBootstrapWorlds(bootstrap); + case REALMS -> service.listBootstrapRealms(bootstrap, "demo"); + case CHARACTERS -> service.listBootstrapCharacters(bootstrap, "demo", "production", scope); + case BROWSER_JOIN -> service.joinPublicProduction(bootstrap, join); + case DIRECT_SCOPE -> service.issueDirectTextConnectScope(null, null); + case DIRECT_JOIN -> service.joinPublicProductionFromGameSession(null, join); + case CONNECT_TOKEN -> + service.issueConnectToken( + bootstrap, + scope == null ? null : new ConnectTokenRequest(scope, UUID.randomUUID().toString())); + } + } + + private void verifyPublicGameplayHasNoIo() { + verifyNoInteractions( + accountRepository, + accountAuthorityGenerationRepository, + accountAuthoritySourceEvidenceRepository, + accountAuthorityOutboxRepository, + accountPasswordResetOperationRepository, + accountLogoutAllOperationRepository, + accountSecurityStateOperationRepository, + accountPasswordResetDraftSourceChangeRepository, + accountAuditOutboxRepository, + accountJoinOperationRepository, + accountEmailLoginChallengeRepository, + accountRealmAccessGrantRepository, + accountTenantMembershipRepository, + retainedSubscriptionEvidenceRepository, + paymentTransactionRepository, + profileRepository, + externalAccountRepository, + passwordResetTokenRepository, + emailVerificationTokenRepository, + notificationService, + emailService, + sessionService, + transactionManager, + jwtUtil); + } + private enum IdentityFailure { MISSING_UUID, NIL_UUID, @@ -686,5234 +705,675 @@ void createAccountMapsSpringDataIntegrityConflict() { } @Test - void joinPublicProductionRetainsReceiptAfterProjectionFailureAndReplaysWithoutDuplicateEffects() { + void emailLoginOtpRequestIsNeutralForUnknownEmail() { + when(accountRepository.findByEmail("unknown@example.com")).thenReturn(Optional.empty()); + + service.requestEmailLoginOtp("unknown@example.com"); + + verifyNoInteractions(emailService, accountEmailLoginChallengeRepository); + } + + @ParameterizedTest + @EnumSource( + value = AccountLifecycleState.class, + names = {"SECURITY_LOCKED", "DEACTIVATED_PENDING_DELETE", "DELETED"}) + void emailLoginOtpRequestIsNeutralForIneligibleLifecycleState( + AccountLifecycleState lifecycleState) { Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(sessionService.isAccountSessionActive( - org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) - .thenReturn(true); - AtomicReference joinedMembership = new AtomicReference<>(); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenAnswer(invocation -> Optional.ofNullable(joinedMembership.get())); - when(accountTenantMembershipRepository.save(org.mockito.ArgumentMatchers.any())) + account.setId(9L); + account.setEmail("verified@example.com"); + account.setEmailVerified(true); + account.setLifecycleState(lifecycleState); + when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); + + service.requestEmailLoginOtp("verified@example.com"); + + verifyNoInteractions( + accountTenantMembershipRepository, accountEmailLoginChallengeRepository, emailService); + } + + @Test + void emailLoginOtpRequestPersistsOnlyHashedChallengeAndSendsSixDigitCode() { + Account account = new Account(); + account.setId(9L); + account.setEmail("verified@example.com"); + account.setEmailVerified(true); + when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); + when(accountEmailLoginChallengeRepository.findByAccountId(9L)).thenReturn(Optional.empty()); + when(accountEmailLoginChallengeRepository.save(org.mockito.ArgumentMatchers.any())) .thenAnswer( invocation -> { - AccountTenantMembership membership = invocation.getArgument(0); - membership.setId(701L); - joinedMembership.set(membership); - return membership; + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = + invocation.getArgument(0); + challenge.setId(3L); + return challenge; }); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of(active)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - String requestId = "j".repeat(128); - assertEquals(128, requestId.length()); - JoinPublicProductionRequest request = - new JoinPublicProductionRequest(connectScopeId, requestId); - org.mockito.Mockito.doAnswer( - invocation -> { - when(accountRepository.findByAccountUuid(account.getAccountUuid())) - .thenReturn(Optional.empty()); - return null; - }) - .when(transactionManager) - .commit(org.mockito.ArgumentMatchers.any()); - AuthenticationException firstProjectionFailure = - assertThrows( - AuthenticationException.class, - () -> service.joinPublicProduction(bootstrap.bootstrapToken(), request)); - assertEquals("AUTH_UNAVAILABLE", firstProjectionFailure.getCode()); - assertEquals("COMMITTED", retainedOperation.get().status()); - org.mockito.Mockito.verify(transactionManager, org.mockito.Mockito.never()) - .rollback(org.mockito.ArgumentMatchers.any()); - org.mockito.Mockito.doNothing() - .when(transactionManager) - .commit(org.mockito.ArgumentMatchers.any()); - when(accountRepository.findByAccountUuid(account.getAccountUuid())) - .thenReturn(Optional.of(account)); - JoinPublicProductionResult recovered = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - assertTrue(recovered.replayed()); - JoinPublicProductionResult first = recovered; - assertEquals(account.getAccountUuid().toString(), recovered.accountId()); - var committedOperation = retainedOperation.get(); - org.mockito.Mockito.clearInvocations(transactionManager, gameSessionClient); - JoinPublicProductionResult retried = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - - var normalReplayOrder = org.mockito.Mockito.inOrder(transactionManager, gameSessionClient); - normalReplayOrder - .verify(transactionManager) - .getTransaction(org.mockito.ArgumentMatchers.any(TransactionDefinition.class)); - normalReplayOrder.verify(transactionManager).commit(org.mockito.ArgumentMatchers.any()); - normalReplayOrder.verify(gameSessionClient).listGameplayRealms("demo"); + service.requestEmailLoginOtp("verified@example.com"); - org.mockito.Mockito.doThrow( - new DataAccessResourceFailureException("terminal operation lock read failed")) - .when(accountJoinOperationRepository) - .findForUpdate(requestId); - org.mockito.Mockito.clearInvocations(transactionManager, gameSessionClient); - JoinPublicProductionResult readbackReplay = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - - var readbackReplayOrder = org.mockito.Mockito.inOrder(transactionManager, gameSessionClient); - readbackReplayOrder - .verify(transactionManager) - .getTransaction(org.mockito.ArgumentMatchers.any(TransactionDefinition.class)); - readbackReplayOrder.verify(transactionManager).rollback(org.mockito.ArgumentMatchers.any()); - readbackReplayOrder.verify(gameSessionClient).listGameplayRealms("demo"); - - org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.times(1)) - .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(4)) - .findByTenantIdForUpdate(7L); - org.mockito.Mockito.clearInvocations( - sessionService, - accountTenantMembershipRepository, - gameSessionClient, - subscriptionRepository); - AuthenticationException connectTokenUnavailable = - assertThrows( - AuthenticationException.class, - () -> - service.issueConnectToken( - bootstrap.bootstrapToken(), - new ConnectTokenRequest(connectScopeId, "first-play-after-join"))); - - assertTrue(first.success()); - assertEquals(account.getAccountUuid().toString(), first.accountId()); - assertEquals("JOINED", first.outcomeCode()); - assertEquals(701L, first.membershipId()); - assertEquals(1L, first.membershipVersion()); - assertTrue(retried.success()); - assertTrue(retried.replayed()); - assertTrue(readbackReplay.success()); - assertTrue(readbackReplay.replayed()); - assertEquals(committedOperation, retainedOperation.get()); - assertEquals("AUTH_UNAVAILABLE", connectTokenUnavailable.getCode()); - assertNoLegacyConnectTokenEffects(); - assertEquals(REALM_ID, retainedScope.get().realmId().toString()); - assertEquals( - first, - new JoinPublicProductionResult( - retried.success(), - retried.outcomeCode(), - retried.accountId(), - retried.tenantId(), - retried.membershipId(), - retried.membershipVersion(), - retried.membershipAuthorityGeneration(), - true)); - org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.times(1)) - .bindPolicyEvidence( - org.mockito.ArgumentMatchers.eq(requestId), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.eq(1L), - org.mockito.ArgumentMatchers.eq(true)); - org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.times(1)) - .finish( - org.mockito.ArgumentMatchers.eq(requestId), - org.mockito.ArgumentMatchers.eq("COMMITTED"), - org.mockito.ArgumentMatchers.eq("JOINED"), - org.mockito.ArgumentMatchers.eq(701L), - org.mockito.ArgumentMatchers.eq(1L), - org.mockito.ArgumentMatchers.eq(1L)); - org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) - .recordAttemptFailure( - org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentCaptor< + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge> + challengeCaptor = + org.mockito.ArgumentCaptor.forClass( + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge.class); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository) + .save(challengeCaptor.capture()); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(9L); + assertEquals(9L, challengeCaptor.getValue().getAccountId()); + assertFalse(challengeCaptor.getValue().getCodeHash().matches("\\d{6}")); + org.mockito.Mockito.verify(emailService) + .sendEmail( + org.mockito.ArgumentMatchers.eq("verified@example.com"), org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString()); - org.mockito.Mockito.verify(accountAuditOutboxRepository, org.mockito.Mockito.times(1)) - .append( - org.mockito.ArgumentMatchers.any(java.util.UUID.class), - org.mockito.ArgumentMatchers.eq("tenant"), - org.mockito.ArgumentMatchers.eq(7L), - org.mockito.ArgumentMatchers.eq("ACCOUNT_JOINED_PUBLIC_PRODUCTION"), - org.mockito.ArgumentMatchers.contains(requestId)); - assertEquals("COMMITTED", retainedOperation.get().status()); - - AuthenticationException changedDigest = - assertThrows( - AuthenticationException.class, - () -> - service.joinPublicProduction( - bootstrap.bootstrapToken(), - new JoinPublicProductionRequest("different-scope", requestId))); - assertEquals("IDEMPOTENCY_CONFLICT", changedDigest.getCode()); - - when(accountRepository.findByAccountUuid(account.getAccountUuid())) - .thenReturn(Optional.of(account), Optional.empty()); - AuthenticationException projectionFailure = - assertThrows( - AuthenticationException.class, - () -> service.joinPublicProduction(bootstrap.bootstrapToken(), request)); - assertEquals("AUTH_UNAVAILABLE", projectionFailure.getCode()); - assertEquals(committedOperation, retainedOperation.get()); - when(accountRepository.findByAccountUuid(account.getAccountUuid())) - .thenReturn(Optional.of(account)); - assertEquals( - account.getAccountUuid().toString(), - service.joinPublicProduction(bootstrap.bootstrapToken(), request).accountId()); + org.mockito.ArgumentMatchers.matches(".*\\b\\d{6}\\b.*")); + verifyNoInteractions(accountTenantMembershipRepository); } @Test - void joinPublicProductionRejectsRequestIdLongerThan128BeforeIntentLookupOrMutation() { - Account account = directTextAccount(); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - String requestId = "j".repeat(129); - DirectTextCallerContext baseCaller = directTextCaller(); - DirectTextCallerContext caller = - new DirectTextCallerContext( - baseCaller.accountId(), - baseCaller.tenantId(), - baseCaller.realmId(), - baseCaller.playableStateNamespaceId(), - baseCaller.playableStateScope(), - baseCaller.gameInstanceId(), - baseCaller.sessionId(), - requestId); + void emailLoginOtpVerificationAuthenticatesAndConsumesMatchingChallenge() { + Account account = new Account(); + account.setId(9L); + setPersistedAuthenticationIdentity(account); + account.setEmail("verified@example.com"); + account.setEmailVerified(true); + account.setRole("player"); + when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); + when(accountEmailLoginChallengeRepository.findByAccountId(9L)).thenReturn(Optional.empty()); + when(accountEmailLoginChallengeRepository.save(org.mockito.ArgumentMatchers.any())) + .thenAnswer(invocation -> invocation.getArgument(0)); - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> - service.joinPublicProductionFromGameSession( - caller, new JoinPublicProductionRequest("retained-scope", requestId))); + service.requestEmailLoginOtp("verified@example.com"); - assertEquals("INVALID_ARGUMENT", exception.getCode()); - verifyNoInteractions( - accountJoinOperationRepository, - accountTenantMembershipRepository, - accountAuditOutboxRepository); + org.mockito.ArgumentCaptor< + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge> + challengeCaptor = + org.mockito.ArgumentCaptor.forClass( + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge.class); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository) + .save(challengeCaptor.capture()); + org.mockito.ArgumentCaptor emailBodyCaptor = + org.mockito.ArgumentCaptor.forClass(String.class); + org.mockito.Mockito.verify(emailService) + .sendEmail( + org.mockito.ArgumentMatchers.eq("verified@example.com"), + org.mockito.ArgumentMatchers.anyString(), + emailBodyCaptor.capture()); + Matcher codeMatcher = Pattern.compile("\\b(\\d{6})\\b").matcher(emailBodyCaptor.getValue()); + assertTrue(codeMatcher.find()); + when(accountEmailLoginChallengeRepository.findByAccountId(9L)) + .thenReturn(Optional.of(challengeCaptor.getValue())); + + AuthenticationResult result = + service.verifyEmailLoginOtp("verified@example.com", codeMatcher.group(1)); + + assertEquals(account.getAccountUuid().toString(), result.accountId()); + assertNotNull(result.authToken()); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository) + .delete(challengeCaptor.getValue()); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession( + org.mockito.ArgumentMatchers.eq(9L), + org.mockito.ArgumentMatchers.eq(result.authToken()), + org.mockito.ArgumentMatchers.eq(jwtAuthProperties.getJwtExpirationMs())); + verifyNoInteractions(accountTenantMembershipRepository); } - @ParameterizedTest - @CsvSource({ - "SECURITY_LOCKED, AUTH_ACCOUNT_LOCKED", - "DEACTIVATED_PENDING_DELETE, AUTH_INVALID_CREDENTIALS" - }) - void joinPublicProductionRejectsStillActiveBootstrapForIneligibleLifecycleState( - AccountLifecycleState lifecycleState, String expectedCode) { + @Test + void authenticateUsesMatchingEmailLoginOtpBeforePasswordFallback() { Account account = new Account(); - account.setId(11L); + account.setId(9L); setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); + account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(sessionService.isAccountSessionActive( - org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) - .thenReturn(true); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - account.setLifecycleState(lifecycleState); + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = + new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); + challenge.setId(3L); + challenge.setAccountId(9L); + challenge.setCodeHash(hash("123456")); + challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); + when(accountEmailLoginChallengeRepository.findByAccountId(9L)) + .thenReturn(Optional.of(challenge)); - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> - service.joinPublicProduction( - bootstrap.bootstrapToken(), - new JoinPublicProductionRequest(connectScopeId, "join-ineligible-1"))); + AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "123456"); - assertEquals(expectedCode, exception.getCode()); - verifyNoInteractions( - accountJoinOperationRepository, - accountTenantMembershipRepository, - accountAuditOutboxRepository); + assertEquals(account.getAccountUuid().toString(), result.accountId()); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).delete(challenge); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession(9L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); + verifyNoInteractions(accountTenantMembershipRepository); } @Test - void closedPublicJoinRetainsFailureAndCannotCreateMembershipOrAudit() { + void authenticateFallsBackToPasswordWithoutBurningUnmatchedEmailLoginOtp() { Account account = new Account(); - account.setId(11L); + account.setId(9L); setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); + account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(sessionService.isAccountSessionActive( - org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) - .thenReturn(true); - Subscription grace = new Subscription(); - grace.setId(22L); - grace.setTenantId(7L); - grace.setStatus("grace"); - when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of(grace)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(grace)); - JoinPublicProductionRequest request = - new JoinPublicProductionRequest(connectScopeId, "join-closed-1"); - - JoinPublicProductionResult denied = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - JoinPublicProductionResult retry = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - - assertFalse(denied.success()); - assertEquals("PUBLIC_PRODUCTION_ADMISSION_DENIED", denied.outcomeCode()); - assertFalse(retry.success()); - assertTrue(retry.replayed()); - assertEquals(denied.outcomeCode(), retry.outcomeCode()); - assertEquals("FAILED", retainedOperation.get().status()); - var storedDeniedOperation = retainedOperation.get(); - when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of()); - JoinPublicProductionResult unavailableAuthorityReplay = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - assertFalse(unavailableAuthorityReplay.success()); - assertFalse(unavailableAuthorityReplay.replayed()); - assertEquals("ENTITLEMENT_UNAVAILABLE", unavailableAuthorityReplay.outcomeCode()); - assertEquals(storedDeniedOperation, retainedOperation.get()); - org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) - .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); - org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) - .findByTenantIdForUpdate(7L); + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = + new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); + challenge.setId(3L); + challenge.setAccountId(9L); + challenge.setCodeHash(hash("123456")); + challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); + when(accountEmailLoginChallengeRepository.findByAccountId(9L)) + .thenReturn(Optional.of(challenge)); + + AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "password"); + + assertEquals(account.getAccountUuid().toString(), result.accountId()); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) + .delete(challenge); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) + .save(challenge); } @Test - void committedJoinRetryRejectsChangedPolicyWithoutMutatingStoredOutcomeOrMembership() { + void authenticateCountsFailedMixedModeSecretAgainstActiveEmailLoginOtp() { Account account = new Account(); - account.setId(11L); + account.setId(9L); setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(sessionService.isAccountSessionActive( - org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) - .thenReturn(true); - AtomicReference joinedMembership = new AtomicReference<>(); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenAnswer(invocation -> Optional.ofNullable(joinedMembership.get())); - when(accountTenantMembershipRepository.save(org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - AccountTenantMembership membership = invocation.getArgument(0); - membership.setId(701L); - joinedMembership.set(membership); - return membership; - }); - Subscription originalPolicy = new Subscription(); - originalPolicy.setId(22L); - originalPolicy.setTenantId(7L); - originalPolicy.setStatus("active"); - originalPolicy.setEntitlementVersion(5L); - Subscription changedPolicy = new Subscription(); - changedPolicy.setId(22L); - changedPolicy.setTenantId(7L); - changedPolicy.setStatus("active"); - changedPolicy.setEntitlementVersion(6L); - when(subscriptionRepository.findByTenantIdForUpdate(7L)) - .thenReturn(java.util.List.of(originalPolicy), java.util.List.of(changedPolicy)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(originalPolicy)); - JoinPublicProductionRequest request = - new JoinPublicProductionRequest(connectScopeId, "join-terminal-policy-change-1"); - - JoinPublicProductionResult joined = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - var committedOperation = retainedOperation.get(); - AccountTenantMembership membership = joinedMembership.get(); - JoinPublicProductionResult retry = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - - assertTrue(joined.success()); - assertFalse(retry.success()); - assertFalse(retry.replayed()); - assertEquals("IDEMPOTENCY_CONFLICT", retry.outcomeCode()); - assertEquals(committedOperation, retainedOperation.get()); - assertEquals("COMMITTED", retainedOperation.get().status()); - assertEquals("JOINED", retainedOperation.get().outcome()); - assertEquals(5L, retainedOperation.get().entitlementVersion()); - assertEquals(membership, joinedMembership.get()); - assertEquals("ACTIVE", membership.getLifecycleState()); - assertEquals(1L, membership.getMembershipVersion()); - when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of()); - JoinPublicProductionResult unavailableAuthorityRetry = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - assertFalse(unavailableAuthorityRetry.success()); - assertFalse(unavailableAuthorityRetry.replayed()); - assertEquals("ENTITLEMENT_UNAVAILABLE", unavailableAuthorityRetry.outcomeCode()); - assertEquals(committedOperation, retainedOperation.get()); - assertEquals(membership, joinedMembership.get()); - org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.times(1)) - .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); - org.mockito.Mockito.verify(accountAuditOutboxRepository, org.mockito.Mockito.times(1)) - .append( - org.mockito.ArgumentMatchers.any(java.util.UUID.class), - org.mockito.ArgumentMatchers.eq("tenant"), - org.mockito.ArgumentMatchers.eq(7L), - org.mockito.ArgumentMatchers.eq("ACCOUNT_JOINED_PUBLIC_PRODUCTION"), - org.mockito.ArgumentMatchers.contains("join-terminal-policy-change-1")); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(3)) - .findByTenantIdForUpdate(7L); - } - - @ParameterizedTest - @MethodSource("unavailableJoinReads") - void unavailableEntitlementRetainsJoinReceiptAndRecoversOnce( - boolean lockedRead, UnavailableEntitlement failure) { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(sessionService.isAccountSessionActive( - org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) - .thenReturn(true); - Subscription recovered = new Subscription(); - recovered.setId(22L); - recovered.setTenantId(7L); - recovered.setStatus("active"); - recovered.setEntitlementVersion(1L); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.empty()); - when(accountTenantMembershipRepository.save(org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - AccountTenantMembership membership = invocation.getArgument(0); - membership.setId(701L); - return membership; - }); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - AtomicBoolean authorityRecovered = new AtomicBoolean(); - when(subscriptionRepository.findByTenantId(7L)) - .thenAnswer( - invocation -> - lockedRead || authorityRecovered.get() - ? java.util.List.of(recovered) - : failure.rows()); - when(subscriptionRepository.findByTenantIdForUpdate(7L)) - .thenAnswer( - invocation -> authorityRecovered.get() ? java.util.List.of(recovered) : failure.rows()); - org.mockito.Mockito.clearInvocations(accountConnectScopeRepository); - JoinPublicProductionRequest request = - new JoinPublicProductionRequest(connectScopeId, "join-unavailable-1"); - - JoinPublicProductionResult first = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - assertFalse(first.success()); - assertEquals("ENTITLEMENT_UNAVAILABLE", first.outcomeCode()); - assertEquals("PENDING", retainedOperation.get().status()); - assertEquals(null, retainedOperation.get().outcome()); - assertEquals("ENTITLEMENT_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); - assertEquals("UNAVAILABLE", retainedOperation.get().lastAttemptAuthorityAvailability()); - assertNotNull(retainedOperation.get().intentDigest()); - String intentDigest = retainedOperation.get().intentDigest(); - String boundDigest = retainedOperation.get().requestDigest(); - if (lockedRead) { - assertEquals( - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.request( - retainedScope.get(), retainedOperation.get().callerBinding(), true, 1L), - boundDigest); - assertEquals(1, retainedOperation.get().requestDigestVersion()); - assertEquals(true, retainedOperation.get().allowPublicJoin()); - assertEquals(1L, retainedOperation.get().entitlementVersion()); - assertEquals("AVAILABLE", retainedOperation.get().entitlementAuthorityAvailability()); - } else { - assertNull(boundDigest); - assertNull(retainedOperation.get().requestDigestVersion()); - assertNull(retainedOperation.get().allowPublicJoin()); - assertNull(retainedOperation.get().entitlementVersion()); - } - verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); - org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) - .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); - - JoinPublicProductionResult stillUnavailable = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - assertEquals("ENTITLEMENT_UNAVAILABLE", stillUnavailable.outcomeCode()); - assertEquals("PENDING", retainedOperation.get().status()); - assertEquals(intentDigest, retainedOperation.get().intentDigest()); - assertEquals(boundDigest, retainedOperation.get().requestDigest()); - assertEquals(lockedRead ? Boolean.TRUE : null, retainedOperation.get().allowPublicJoin()); - assertEquals( - lockedRead ? Long.valueOf(1L) : null, retainedOperation.get().entitlementVersion()); - verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); - - authorityRecovered.set(true); - JoinPublicProductionResult retriedAfterRecovery = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - - assertTrue(retriedAfterRecovery.success()); - assertEquals("JOINED", retriedAfterRecovery.outcomeCode()); - assertEquals("COMMITTED", retainedOperation.get().status()); - assertEquals("AVAILABLE", retainedOperation.get().entitlementAuthorityAvailability()); - assertEquals(1L, retainedOperation.get().entitlementVersion()); - assertEquals(true, retainedOperation.get().allowPublicJoin()); - assertNotNull(retainedOperation.get().requestDigest()); - assertEquals(intentDigest, retainedOperation.get().intentDigest()); - if (lockedRead) { - assertEquals(boundDigest, retainedOperation.get().requestDigest()); - } - JoinPublicProductionResult replay = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - assertTrue(replay.success()); - assertTrue(replay.replayed()); - org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.times(1)) - .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); - org.mockito.Mockito.verify(accountAuditOutboxRepository, org.mockito.Mockito.times(1)) - .append( - org.mockito.ArgumentMatchers.any(java.util.UUID.class), - org.mockito.ArgumentMatchers.eq("tenant"), - org.mockito.ArgumentMatchers.eq(7L), - org.mockito.ArgumentMatchers.eq("ACCOUNT_JOINED_PUBLIC_PRODUCTION"), - org.mockito.ArgumentMatchers.contains("join-unavailable-1")); - org.mockito.Mockito.verify( - subscriptionRepository, org.mockito.Mockito.times(lockedRead ? 4 : 2)) - .findByTenantIdForUpdate(7L); - } - - private static java.util.stream.Stream unavailableJoinReads() { - return java.util.stream.Stream.of(false, true) - .flatMap( - locked -> - java.util.Arrays.stream(UnavailableEntitlement.values()) - .filter(failure -> failure.cause == null) - .map(failure -> Arguments.of(locked, failure))); - } - - private static java.util.stream.Stream storageJoinReads() { - return java.util.stream.Stream.of(false, true) - .flatMap( - locked -> - java.util.Arrays.stream(UnavailableEntitlement.values()) - .filter(failure -> failure.cause != null) - .map(failure -> Arguments.of(locked, failure))); - } - - @ParameterizedTest - @MethodSource("storageJoinReads") - void joinStorageOutageRollsBackBeforeRecordingFailureAndRecoversOriginalOnce( - boolean lockedRead, UnavailableEntitlement failure) { - Account account = directTextAccount(); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String scope = - service - .issueDirectTextConnectScope(directTextCaller(), directTextTarget()) - .connectScopeId(); - AtomicBoolean recovered = new AtomicBoolean(); - Subscription available = new Subscription(); - available.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)) - .thenAnswer( - invocation -> lockedRead || recovered.get() ? List.of(available) : failure.rows()); - when(subscriptionRepository.findByTenantIdForUpdate(7L)) - .thenAnswer(invocation -> recovered.get() ? List.of(available) : failure.rows()); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.empty()); - when(accountTenantMembershipRepository.save(org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - AccountTenantMembership membership = invocation.getArgument(0); - membership.setId(701L); - return membership; - }); - org.mockito.Mockito.clearInvocations( - transactionManager, accountConnectScopeRepository, accountJoinOperationRepository); - var request = new JoinPublicProductionRequest(scope, directTextCaller().requestId()); - - var unavailable = service.joinPublicProductionFromGameSession(directTextCaller(), request); - - assertFalse(unavailable.success()); - assertEquals("ENTITLEMENT_UNAVAILABLE", unavailable.outcomeCode()); - assertEquals("PENDING", retainedOperation.get().status()); - assertNull(retainedOperation.get().outcome()); - assertEquals("ENTITLEMENT_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); - assertEquals("UNAVAILABLE", retainedOperation.get().lastAttemptAuthorityAvailability()); - String originalIntent = retainedOperation.get().intentDigest(); - assertNotNull(originalIntent); - var order = org.mockito.Mockito.inOrder(transactionManager, accountJoinOperationRepository); - order.verify(transactionManager).rollback(org.mockito.ArgumentMatchers.any()); - order - .verify(transactionManager) - .getTransaction(org.mockito.ArgumentMatchers.any(TransactionDefinition.class)); - order.verify(accountJoinOperationRepository).findForUpdate(request.requestId()); - order - .verify(accountJoinOperationRepository) - .recordAttemptFailure(request.requestId(), "UNAVAILABLE", "ENTITLEMENT_UNAVAILABLE"); - order.verify(transactionManager).commit(org.mockito.ArgumentMatchers.any()); - verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); - org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) - .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); - // AtomicReference fixtures do not physically roll back policy writes; PostgreSQL proves that. - recovered.set(true); - var joined = service.joinPublicProductionFromGameSession(directTextCaller(), request); - assertTrue(joined.success()); - assertFalse(joined.replayed()); - assertEquals(originalIntent, retainedOperation.get().intentDigest()); - var committed = retainedOperation.get(); - assertTrue(service.joinPublicProductionFromGameSession(directTextCaller(), request).replayed()); - assertEquals(committed, retainedOperation.get()); - org.mockito.Mockito.verify(accountTenantMembershipRepository) - .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); - org.mockito.Mockito.verify(accountAuditOutboxRepository) - .append( - org.mockito.ArgumentMatchers.any(UUID.class), - org.mockito.ArgumentMatchers.eq("tenant"), - org.mockito.ArgumentMatchers.eq(7L), - org.mockito.ArgumentMatchers.eq("ACCOUNT_JOINED_PUBLIC_PRODUCTION"), - org.mockito.ArgumentMatchers.anyString()); - } - - @ParameterizedTest - @MethodSource("terminalJoinReadFailures") - void terminalJoinEntitlementOutagePreservesCompleteOriginal( - UnavailableEntitlement failure, String programmingFault) { - Account account = directTextAccount(); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String scope = - service - .issueDirectTextConnectScope(directTextCaller(), directTextTarget()) - .connectScopeId(); - Subscription available = new Subscription(); - available.setStatus("active"); - when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(List.of(available)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.empty()); - when(accountTenantMembershipRepository.save(org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - AccountTenantMembership membership = invocation.getArgument(0); - membership.setId(701L); - return membership; - }); - var request = new JoinPublicProductionRequest(scope, directTextCaller().requestId()); - var originalResult = service.joinPublicProductionFromGameSession(directTextCaller(), request); - assertTrue(originalResult.success()); - var original = retainedOperation.get(); - var originalScope = retainedScope.get(); - AtomicBoolean recovered = new AtomicBoolean(); - when(subscriptionRepository.findByTenantIdForUpdate(7L)) - .thenAnswer( - invocation -> { - if (recovered.get()) { - return List.of(available); - } - if (programmingFault != null) { - throw entitlementProgrammingFault(programmingFault); - } - return failure.rows(); - }); - org.mockito.Mockito.clearInvocations( - accountTenantMembershipRepository, - accountAuditOutboxRepository, - accountJoinOperationRepository, - accountConnectScopeRepository); - - var unavailable = service.joinPublicProductionFromGameSession(directTextCaller(), request); - - assertFalse(unavailable.success()); - assertFalse(unavailable.replayed()); - assertEquals( - programmingFault == null ? "ENTITLEMENT_UNAVAILABLE" : "AUTH_UNAVAILABLE", - unavailable.outcomeCode()); - assertEquals(original, retainedOperation.get()); - assertEquals(originalScope, retainedScope.get()); - recovered.set(true); - var replay = service.joinPublicProductionFromGameSession(directTextCaller(), request); - assertTrue(replay.success()); - assertTrue(replay.replayed()); - assertEquals(originalResult.accountId(), replay.accountId()); - assertEquals(originalResult.membershipId(), replay.membershipId()); - assertEquals(originalResult.membershipVersion(), replay.membershipVersion()); - assertEquals( - originalResult.membershipAuthorityGeneration(), replay.membershipAuthorityGeneration()); - assertEquals(originalResult.outcomeCode(), replay.outcomeCode()); - assertEquals(original, retainedOperation.get()); - verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); - org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) - .recordAttemptFailure( - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString()); - org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) - .bindPolicyEvidence( - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyBoolean()); - org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) - .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); - } - - private static java.util.stream.Stream terminalJoinReadFailures() { - return java.util.stream.Stream.concat( - java.util.Arrays.stream(UnavailableEntitlement.values()) - .map(failure -> Arguments.of(failure, null)), - java.util.stream.Stream.of("mapping", "configuration") - .map(fault -> Arguments.of(null, fault))); - } - - @ParameterizedTest - @CsvSource({"false,mapping", "true,mapping", "false,configuration", "true,configuration"}) - void joinMappingAndConfigurationFaultsRetainUnexpectedFailureBoundary( - boolean lockedRead, String fault) { - Account account = directTextAccount(); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String scope = - service - .issueDirectTextConnectScope(directTextCaller(), directTextTarget()) - .connectScopeId(); - RuntimeException cause = entitlementProgrammingFault(fault); - if (lockedRead) { - when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenThrow(cause); - } else { - when(subscriptionRepository.findByTenantId(7L)).thenThrow(cause); - } - org.mockito.Mockito.clearInvocations(transactionManager, accountConnectScopeRepository); - - AuthenticationException unavailable = - assertThrows( - AuthenticationException.class, - () -> - service.joinPublicProductionFromGameSession( - directTextCaller(), - new JoinPublicProductionRequest(scope, directTextCaller().requestId()))); - - assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); - assertSame(cause, unavailable.getCause()); - assertEquals("PENDING", retainedOperation.get().status()); - assertNotNull(retainedOperation.get().intentDigest()); - assertNull(retainedOperation.get().outcome()); - assertEquals("AUTH_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); - org.mockito.Mockito.verify(transactionManager).rollback(org.mockito.ArgumentMatchers.any()); - verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); - org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) - .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); - } - - @Test - void lateDuplicateRealmKeepsJoinPendingWithoutMembershipEffects() { - Account account = directTextAccount(); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String scope = - service - .issueDirectTextConnectScope(directTextCaller(), directTextTarget()) - .connectScopeId(); - var realm = gameSessionClient.listGameplayRealms("demo").getFirst(); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn(List.of(realm), List.of(realm, realm)); - org.mockito.Mockito.clearInvocations(subscriptionRepository, accountConnectScopeRepository); - - JoinPublicProductionResult result = - service.joinPublicProductionFromGameSession( - directTextCaller(), - new JoinPublicProductionRequest(scope, directTextCaller().requestId())); - - assertFalse(result.success()); - assertEquals("ADMISSION_POINTER_UNAVAILABLE", result.outcomeCode()); - assertEquals("PENDING", retainedOperation.get().status()); - assertEquals(true, retainedOperation.get().allowPublicJoin()); - assertEquals(1L, retainedOperation.get().entitlementVersion()); - assertNotNull(retainedOperation.get().requestDigest()); - assertEquals("ADMISSION_POINTER_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); - verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.never()) - .findByTenantIdForUpdate(7L); - org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) - .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); - } - - private static RuntimeException entitlementProgrammingFault(String fault) { - return "mapping".equals(fault) - ? new org.jooq.exception.MappingException("subscription mapping fault") - : new org.jooq.exception.ConfigurationException("subscription configuration fault"); - } - - private enum UnavailableEntitlement { - MISSING, - AMBIGUOUS, - NULL_LIST, - NULL_ROW, - ZERO_VERSION, - NEGATIVE_VERSION, - JOOQ_STORAGE(new org.jooq.exception.DataAccessException("subscription store unavailable")), - SPRING_STORAGE(new DataAccessResourceFailureException("subscription store unavailable")); - - private final RuntimeException cause; - - UnavailableEntitlement() { - this(null); - } - - UnavailableEntitlement(RuntimeException cause) { - this.cause = cause; - } - - private List rows() { - if (cause != null) { - throw cause; - } - return switch (this) { - case MISSING -> List.of(); - case AMBIGUOUS -> List.of(new Subscription(), new Subscription()); - case NULL_LIST -> null; - case NULL_ROW -> java.util.Collections.singletonList(null); - case ZERO_VERSION, NEGATIVE_VERSION -> { - Subscription invalid = new Subscription(); - invalid.setStatus("active"); - invalid.setEntitlementVersion(this == ZERO_VERSION ? 0L : -1L); - yield List.of(invalid); - } - default -> throw new IllegalStateException("Storage failure must have a cause"); - }; - } - } - - @Test - void joinPublicProductionRevalidatesPolicyAtTheMembershipCommitGate() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(sessionService.isAccountSessionActive( - org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) - .thenReturn(true); - Subscription initialPolicy = new Subscription(); - initialPolicy.setId(22L); - initialPolicy.setTenantId(7L); - initialPolicy.setStatus("active"); - initialPolicy.setEntitlementVersion(5L); - Subscription changedPolicy = new Subscription(); - changedPolicy.setId(22L); - changedPolicy.setTenantId(7L); - changedPolicy.setStatus("active"); - changedPolicy.setEntitlementVersion(6L); - when(subscriptionRepository.findByTenantIdForUpdate(7L)) - .thenReturn(java.util.List.of(changedPolicy)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.empty()); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(initialPolicy)); - org.mockito.Mockito.clearInvocations(gameSessionClient, subscriptionRepository); - - JoinPublicProductionResult result = - service.joinPublicProduction( - bootstrap.bootstrapToken(), - new JoinPublicProductionRequest(connectScopeId, "join-race-1")); - - assertFalse(result.success()); - assertEquals("IDEMPOTENCY_CONFLICT", result.outcomeCode()); - assertEquals("FAILED", retainedOperation.get().status()); - assertEquals("IDEMPOTENCY_CONFLICT", retainedOperation.get().outcome()); - assertEquals(5L, retainedOperation.get().entitlementVersion()); - assertEquals(true, retainedOperation.get().allowPublicJoin()); - assertEquals(1, retainedOperation.get().requestDigestVersion()); - assertNotNull(retainedOperation.get().requestDigest()); - assertEquals(null, retainedOperation.get().lastAttemptFailureCode()); - org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) - .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); - org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(1)) - .findByTenantIdForUpdate(7L); - var order = org.mockito.Mockito.inOrder(gameSessionClient, subscriptionRepository); - order.verify(gameSessionClient).listGameplayRealms("demo"); - order.verify(gameSessionClient).getAdmissionPointer(7L, "demo", "production"); - order.verify(subscriptionRepository).findByTenantId(7L); - order.verify(gameSessionClient).listGameplayRealms("demo"); - order.verify(gameSessionClient).getAdmissionPointer(7L, "demo", "production"); - order.verify(subscriptionRepository).findByTenantIdForUpdate(7L); - org.mockito.Mockito.verifyNoMoreInteractions(gameSessionClient); - } - - @Test - void changedPolicyOnRetryTerminalizesPreviouslyBoundPendingJoin() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(sessionService.isAccountSessionActive( - org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) - .thenReturn(true); - Subscription initialPolicy = new Subscription(); - initialPolicy.setId(22L); - initialPolicy.setTenantId(7L); - initialPolicy.setStatus("active"); - initialPolicy.setEntitlementVersion(5L); - Subscription changedPolicy = new Subscription(); - changedPolicy.setId(22L); - changedPolicy.setTenantId(7L); - changedPolicy.setStatus("active"); - changedPolicy.setEntitlementVersion(6L); - when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of()); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - when(subscriptionRepository.findByTenantId(7L)) - .thenReturn(java.util.List.of(initialPolicy), java.util.List.of(changedPolicy)); - JoinPublicProductionRequest request = - new JoinPublicProductionRequest(connectScopeId, "join-policy-retry-1"); - - JoinPublicProductionResult pending = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - String boundDigest = retainedOperation.get().requestDigest(); - String intentDigest = retainedOperation.get().intentDigest(); - - assertFalse(pending.success()); - assertEquals("ENTITLEMENT_UNAVAILABLE", pending.outcomeCode()); - assertEquals("PENDING", retainedOperation.get().status()); - assertEquals(5L, retainedOperation.get().entitlementVersion()); - assertEquals("ENTITLEMENT_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); - - JoinPublicProductionResult changedPolicyRetry = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - - assertFalse(changedPolicyRetry.success()); - assertEquals("IDEMPOTENCY_CONFLICT", changedPolicyRetry.outcomeCode()); - assertEquals("FAILED", retainedOperation.get().status()); - assertEquals("IDEMPOTENCY_CONFLICT", retainedOperation.get().outcome()); - assertEquals(intentDigest, retainedOperation.get().intentDigest()); - assertEquals(boundDigest, retainedOperation.get().requestDigest()); - assertEquals(5L, retainedOperation.get().entitlementVersion()); - assertEquals(true, retainedOperation.get().allowPublicJoin()); - assertEquals(null, retainedOperation.get().lastAttemptFailureCode()); - org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) - .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); - org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(1)) - .findByTenantIdForUpdate(7L); - } - - @Test - void unboundFailedJoinReplaysOnlyAfterCurrentScopeAndAuthorityChecks() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(sessionService.isAccountSessionActive( - org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) - .thenReturn(true); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - var exactRealm = gameSessionClient.listGameplayRealms("demo").getFirst(); - var exactPointer = gameSessionClient.getAdmissionPointer(7L, "demo", "production"); - var changedRealm = exactRealm.toBuilder().setPointerVersion(18L).build(); - var changedPointer = exactPointer.toBuilder().setPointerVersion(18L).build(); - when(gameSessionClient.listGameplayRealms("demo")).thenReturn(java.util.List.of(changedRealm)); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) - .thenReturn(changedPointer); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of(active)); - org.mockito.Mockito.clearInvocations(gameSessionClient, subscriptionRepository); - JoinPublicProductionRequest request = - new JoinPublicProductionRequest(connectScopeId, "join-unbound-failure-1"); - - JoinPublicProductionResult originalFailure = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - var storedFailure = retainedOperation.get(); - - assertFalse(originalFailure.success()); - assertEquals("CONNECT_SCOPE_MISMATCH", originalFailure.outcomeCode()); - assertEquals("FAILED", storedFailure.status()); - assertEquals(originalFailure.outcomeCode(), storedFailure.outcome()); - assertNull(storedFailure.requestDigest()); - - JoinPublicProductionResult changedTargetDenial = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - - assertFalse(changedTargetDenial.success()); - assertFalse(changedTargetDenial.replayed()); - assertEquals("CONNECT_SCOPE_MISMATCH", changedTargetDenial.outcomeCode()); - assertEquals(storedFailure, retainedOperation.get()); - - when(gameSessionClient.listGameplayRealms("demo")).thenReturn(java.util.List.of(exactRealm)); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")).thenReturn(exactPointer); - JoinPublicProductionResult replay = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - - assertFalse(replay.success()); - assertTrue(replay.replayed()); - assertEquals(originalFailure.outcomeCode(), replay.outcomeCode()); - assertEquals(storedFailure, retainedOperation.get()); - - VerifiedJoinScope originalScope = retainedScope.get(); - VerifiedJoinScope alteredScopeWithoutDigest = - new VerifiedJoinScope( - originalScope.connectScopeId(), - originalScope.accountId(), - originalScope.tenantId(), - originalScope.realmId(), - originalScope.worldSlug(), - originalScope.realmSlug(), - originalScope.playableStateNamespaceId(), - originalScope.playableStateScope(), - originalScope.gameInstanceId(), - originalScope.catalogRevision(), - originalScope.pointerVersion() + 1, - originalScope.evaluatedAt(), - originalScope.connectScopeExpiresAt(), - ""); - retainedScope.set( - new VerifiedJoinScope( - alteredScopeWithoutDigest.connectScopeId(), - alteredScopeWithoutDigest.accountId(), - alteredScopeWithoutDigest.tenantId(), - alteredScopeWithoutDigest.realmId(), - alteredScopeWithoutDigest.worldSlug(), - alteredScopeWithoutDigest.realmSlug(), - alteredScopeWithoutDigest.playableStateNamespaceId(), - alteredScopeWithoutDigest.playableStateScope(), - alteredScopeWithoutDigest.gameInstanceId(), - alteredScopeWithoutDigest.catalogRevision(), - alteredScopeWithoutDigest.pointerVersion(), - alteredScopeWithoutDigest.evaluatedAt(), - alteredScopeWithoutDigest.connectScopeExpiresAt(), - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.scope( - alteredScopeWithoutDigest))); - - AuthenticationException changedScope = - assertThrows( - AuthenticationException.class, - () -> service.joinPublicProduction(bootstrap.bootstrapToken(), request)); - assertEquals("IDEMPOTENCY_CONFLICT", changedScope.getCode()); - assertEquals(storedFailure, retainedOperation.get()); - - retainedScope.set(originalScope); - when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of()); - JoinPublicProductionResult unavailableAuthority = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - - assertFalse(unavailableAuthority.success()); - assertFalse(unavailableAuthority.replayed()); - assertEquals("ENTITLEMENT_UNAVAILABLE", unavailableAuthority.outcomeCode()); - assertEquals(storedFailure, retainedOperation.get()); - org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) - .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); - org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) - .findByTenantIdForUpdate(7L); - } - - @Test - void joinIntentCommitsSeparatelyWhenPolicyTransactionRollsBack() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(sessionService.isAccountSessionActive( - org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) - .thenReturn(true); - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - when(subscriptionRepository.findByTenantId(7L)) - .thenThrow(new IllegalStateException("entitlement storage unavailable")); - - AuthenticationException unavailable = - assertThrows( - AuthenticationException.class, - () -> - service.joinPublicProduction( - bootstrap.bootstrapToken(), - new JoinPublicProductionRequest(connectScopeId, "join-txn-boundary-1"))); - - assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); - assertEquals("PENDING", retainedOperation.get().status()); - assertEquals(null, retainedOperation.get().outcome()); - assertNotNull(retainedOperation.get().intentDigest()); - assertEquals(null, retainedOperation.get().requestDigest()); - assertEquals("AUTH_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); - org.mockito.Mockito.verify(transactionManager, org.mockito.Mockito.times(2)) - .commit(org.mockito.ArgumentMatchers.any()); - org.mockito.Mockito.verify(transactionManager, org.mockito.Mockito.times(1)) - .rollback(org.mockito.ArgumentMatchers.any()); - org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) - .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); - org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); - } - - @Test - void expiredPersistedPendingJoinFailsTerminallyWithoutAuthorityOrMembershipTransition() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(sessionService.isAccountSessionActive( - org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) - .thenReturn(true); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String connectScopeId = "expired-connect-scope"; - JoinPublicProductionRequest request = - new JoinPublicProductionRequest(connectScopeId, "join-expired-pending-1"); - - VerifiedJoinScope expiredScope = - new VerifiedJoinScope( - connectScopeId, - 11L, - 7L, - UUID.fromString(REALM_ID), - "demo", - "production", - PLAYABLE_STATE_NAMESPACE_ID, - "SHARED", - 44L, - 23L, - 17L, - "1999-12-31T23:59:00Z", - "2000-01-01T00:00:00Z", - ""); - expiredScope = - new VerifiedJoinScope( - expiredScope.connectScopeId(), - expiredScope.accountId(), - expiredScope.tenantId(), - expiredScope.realmId(), - expiredScope.worldSlug(), - expiredScope.realmSlug(), - expiredScope.playableStateNamespaceId(), - expiredScope.playableStateScope(), - expiredScope.gameInstanceId(), - expiredScope.catalogRevision(), - expiredScope.pointerVersion(), - expiredScope.evaluatedAt(), - expiredScope.connectScopeExpiresAt(), - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.scope(expiredScope)); - retainedScope.set(expiredScope); - String callerBinding = - new JwtUtil(JWT_SECRET, 300000L) - .parseToken(bootstrap.bootstrapToken()) - .getPayload() - .get("jti") - .toString(); - retainedOperation.set( - new AccountJoinOperationRepository.JoinOperation( - expiredScope.accountId(), - expiredScope.tenantId(), - expiredScope.realmId(), - callerBinding, - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash(connectScopeId), - expiredScope.snapshotDigest(), - "UNAVAILABLE", - null, - null, - null, - null, - "PENDING", - null, - null, - null, - null, - 1, - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.intent( - request.requestId(), expiredScope, callerBinding), - "ENTITLEMENT_UNAVAILABLE", - "UNAVAILABLE")); - - JoinPublicProductionResult expiredRetry = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - var expiredTerminalOperation = retainedOperation.get(); - JoinPublicProductionResult terminalReadback = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - - assertFalse(expiredRetry.success()); - assertEquals("CONNECT_SCOPE_INVALID", expiredRetry.outcomeCode()); - assertFalse(terminalReadback.success()); - assertFalse(terminalReadback.replayed()); - assertEquals("CONNECT_SCOPE_INVALID", terminalReadback.outcomeCode()); - assertEquals(expiredTerminalOperation, retainedOperation.get()); - assertEquals("FAILED", retainedOperation.get().status()); - assertEquals("CONNECT_SCOPE_INVALID", retainedOperation.get().outcome()); - org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.times(1)) - .finish( - org.mockito.ArgumentMatchers.eq(request.requestId()), - org.mockito.ArgumentMatchers.eq("FAILED"), - org.mockito.ArgumentMatchers.eq("CONNECT_SCOPE_INVALID"), - org.mockito.ArgumentMatchers.isNull(), - org.mockito.ArgumentMatchers.isNull(), - org.mockito.ArgumentMatchers.isNull()); - verifyNoInteractions( - subscriptionRepository, accountTenantMembershipRepository, accountAuditOutboxRepository); - } - - @Test - void expiredTerminalJoinScopeFailsClosedWithoutReplayingStoredSuccess() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(sessionService.isAccountSessionActive( - org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) - .thenReturn(true); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String connectScopeId = "expired-committed-connect-scope"; - JoinPublicProductionRequest request = - new JoinPublicProductionRequest(connectScopeId, "join-expired-committed-1"); - VerifiedJoinScope unsignedExpiredScope = - new VerifiedJoinScope( - connectScopeId, - 11L, - 7L, - UUID.fromString(REALM_ID), - "demo", - "production", - PLAYABLE_STATE_NAMESPACE_ID, - "SHARED", - 44L, - 23L, - 17L, - "1999-12-31T23:59:00Z", - "2000-01-01T00:00:00Z", - ""); - VerifiedJoinScope expiredScope = - new VerifiedJoinScope( - unsignedExpiredScope.connectScopeId(), - unsignedExpiredScope.accountId(), - unsignedExpiredScope.tenantId(), - unsignedExpiredScope.realmId(), - unsignedExpiredScope.worldSlug(), - unsignedExpiredScope.realmSlug(), - unsignedExpiredScope.playableStateNamespaceId(), - unsignedExpiredScope.playableStateScope(), - unsignedExpiredScope.gameInstanceId(), - unsignedExpiredScope.catalogRevision(), - unsignedExpiredScope.pointerVersion(), - unsignedExpiredScope.evaluatedAt(), - unsignedExpiredScope.connectScopeExpiresAt(), - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.scope( - unsignedExpiredScope)); - retainedScope.set(expiredScope); - String callerBinding = - new JwtUtil(JWT_SECRET, 300000L) - .parseToken(bootstrap.bootstrapToken()) - .getPayload() - .get("jti") - .toString(); - var committedOperation = - new AccountJoinOperationRepository.JoinOperation( - expiredScope.accountId(), - expiredScope.tenantId(), - expiredScope.realmId(), - callerBinding, - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash(connectScopeId), - expiredScope.snapshotDigest(), - "AVAILABLE", - true, - 1L, - 1, - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.request( - expiredScope, callerBinding, true, 1L), - "COMMITTED", - "JOINED", - 701L, - 1L, - 1L, - 1, - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.intent( - request.requestId(), expiredScope, callerBinding), - null, - "AVAILABLE"); - retainedOperation.set(committedOperation); - - JoinPublicProductionResult retry = - service.joinPublicProduction(bootstrap.bootstrapToken(), request); - - assertFalse(retry.success()); - assertFalse(retry.replayed()); - assertEquals("CONNECT_SCOPE_INVALID", retry.outcomeCode()); - assertEquals(committedOperation, retainedOperation.get()); - assertEquals("COMMITTED", retainedOperation.get().status()); - assertEquals("JOINED", retainedOperation.get().outcome()); - assertEquals(701L, retainedOperation.get().membershipId()); - org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) - .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); - org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) - .finish( - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.nullable(Long.class), - org.mockito.ArgumentMatchers.nullable(Long.class), - org.mockito.ArgumentMatchers.nullable(Long.class)); - verifyNoInteractions(subscriptionRepository, accountAuditOutboxRepository); - } - - @ParameterizedTest - @ValueSource(strings = {"PENDING", "COMMITTED", "FAILED"}) - void joinPublicProductionHidesAnotherAccountsGlobalRequestIdEvidence(String originalStatus) { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(sessionService.isAccountSessionActive( - org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) - .thenReturn(true); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - VerifiedJoinScope scope = retainedScope.get(); - String requestId = "join-global-collision-" + originalStatus.toLowerCase(); - String originalOutcome = - switch (originalStatus) { - case "COMMITTED" -> "JOINED"; - case "FAILED" -> "PUBLIC_PRODUCTION_ADMISSION_DENIED"; - default -> null; - }; - Long originalMembershipId = "COMMITTED".equals(originalStatus) ? 812L : null; - AccountJoinOperationRepository.JoinOperation originalOperation = - new AccountJoinOperationRepository.JoinOperation( - 12L, - scope.tenantId(), - scope.realmId(), - "different-caller", - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash(connectScopeId), - scope.snapshotDigest(), - "COMMITTED".equals(originalStatus) || "FAILED".equals(originalStatus) - ? "AVAILABLE" - : "NOT_EVALUATED", - "PENDING".equals(originalStatus) ? null : true, - "PENDING".equals(originalStatus) ? null : 7L, - "PENDING".equals(originalStatus) ? null : 1, - "PENDING".equals(originalStatus) ? null : "original-request-digest", - originalStatus, - originalOutcome, - originalMembershipId, - originalMembershipId == null ? null : 9L, - originalMembershipId == null ? null : 5L, - 1, - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.intent( - requestId, scope, "different-caller"), - null, - "AVAILABLE"); - retainedOperation.set(originalOperation); - - AuthenticationException conflict = - assertThrows( - AuthenticationException.class, - () -> - service.joinPublicProduction( - bootstrap.bootstrapToken(), - new JoinPublicProductionRequest(connectScopeId, requestId))); - - assertEquals("IDEMPOTENCY_CONFLICT", conflict.getCode()); - assertEquals("JOIN request ID was reused with different input", conflict.getMessage()); - assertFalse(conflict.getMessage().contains("JOINED")); - assertFalse(conflict.getMessage().contains("PUBLIC_PRODUCTION_ADMISSION_DENIED")); - assertFalse(conflict.getMessage().contains("812")); - assertEquals(originalOperation, retainedOperation.get()); - assertEquals(originalStatus, retainedOperation.get().status()); - assertEquals(originalOutcome, retainedOperation.get().outcome()); - assertEquals(originalMembershipId, retainedOperation.get().membershipId()); - org.mockito.Mockito.verify(accountJoinOperationRepository) - .find(org.mockito.ArgumentMatchers.eq(requestId)); - org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) - .insertIntent( - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString()); - org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) - .bindPolicyEvidence( - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyBoolean()); - org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) - .finish( - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.nullable(Long.class), - org.mockito.ArgumentMatchers.nullable(Long.class), - org.mockito.ArgumentMatchers.nullable(Long.class)); - verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); - } - - @Test - void reclaimedScopeRaceReturnsConnectScopeInvalid() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(sessionService.isAccountSessionActive( - org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) - .thenReturn(true); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - VerifiedJoinScope scope = retainedScope.get(); - org.mockito.Mockito.clearInvocations( - subscriptionRepository, accountTenantMembershipRepository, accountAuditOutboxRepository); - when(accountConnectScopeRepository.find(connectScopeId)) - .thenReturn(Optional.of(scope), Optional.empty()); - org.mockito.Mockito.doThrow(new org.jooq.exception.DataAccessException("scope reclaimed")) - .when(accountJoinOperationRepository) - .insertIntent( - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString()); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> - service.joinPublicProduction( - bootstrap.bootstrapToken(), - new JoinPublicProductionRequest(connectScopeId, "join-reclaimed-scope"))); - - assertEquals("CONNECT_SCOPE_INVALID", exception.getCode()); - verifyNoInteractions( - subscriptionRepository, accountTenantMembershipRepository, accountAuditOutboxRepository); - } - - @Test - void quarantinedLegacyMembershipIsNeverRestoredByPublicJoin() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(sessionService.isAccountSessionActive( - org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) - .thenReturn(true); - AccountTenantMembership quarantined = membership(account, 7L); - quarantined.setLifecycleState("LEGACY_UNVERIFIED"); - quarantined.setGameplayAdmissionAllowed(false); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(quarantined)); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of(active)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - AtomicReference retainedScope = new AtomicReference<>(); - AtomicReference retainedOperation = - new AtomicReference<>(); - retainJoinEvidence(retainedScope, retainedOperation); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - - JoinPublicProductionResult result = - service.joinPublicProduction( - bootstrap.bootstrapToken(), - new JoinPublicProductionRequest(connectScopeId, "join-legacy-1")); - - assertFalse(result.success()); - assertEquals("MEMBERSHIP_RECONCILIATION_REQUIRED", result.outcomeCode()); - assertEquals("LEGACY_UNVERIFIED", quarantined.getLifecycleState()); - assertFalse(quarantined.isGameplayAdmissionAllowed()); - org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) - .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); - org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); - } - - private void retainJoinEvidence( - AtomicReference retainedScope, - AtomicReference retainedOperation) { - org.mockito.Mockito.doAnswer( - invocation -> { - retainedScope.set(invocation.getArgument(0)); - return null; - }) - .when(accountConnectScopeRepository) - .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); - when(accountConnectScopeRepository.find(org.mockito.ArgumentMatchers.anyString())) - .thenAnswer(invocation -> Optional.ofNullable(retainedScope.get())); - when(accountJoinOperationRepository.find(org.mockito.ArgumentMatchers.anyString())) - .thenAnswer(invocation -> Optional.ofNullable(retainedOperation.get())); - when(accountJoinOperationRepository.findForUpdate(org.mockito.ArgumentMatchers.anyString())) - .thenAnswer(invocation -> Optional.ofNullable(retainedOperation.get())); - org.mockito.Mockito.doAnswer( - invocation -> { - String requestId = invocation.getArgument(0); - VerifiedJoinScope scope = invocation.getArgument(1); - String callerBinding = invocation.getArgument(2); - String intentDigest = invocation.getArgument(3); - retainedOperation.set( - new AccountJoinOperationRepository.JoinOperation( - scope.accountId(), - scope.tenantId(), - scope.realmId(), - callerBinding, - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash( - scope.connectScopeId()), - scope.snapshotDigest(), - "NOT_EVALUATED", - null, - null, - null, - null, - "PENDING", - null, - null, - null, - null, - 1, - intentDigest, - null, - "NOT_EVALUATED")); - return true; - }) - .when(accountJoinOperationRepository) - .insertIntent( - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString()); - org.mockito.Mockito.doAnswer( - invocation -> { - var pending = retainedOperation.get(); - retainedOperation.set( - new AccountJoinOperationRepository.JoinOperation( - pending.accountId(), - pending.tenantId(), - pending.realmId(), - pending.callerBinding(), - pending.scopeTokenHash(), - pending.connectScopeDigest(), - "AVAILABLE", - invocation.getArgument(3), - invocation.getArgument(2), - 1, - invocation.getArgument(1), - pending.status(), - pending.outcome(), - pending.membershipId(), - pending.membershipVersion(), - pending.membershipAuthorityGeneration(), - pending.intentDigestVersion(), - pending.intentDigest(), - null, - "AVAILABLE")); - return null; - }) - .when(accountJoinOperationRepository) - .bindPolicyEvidence( - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyBoolean()); - org.mockito.Mockito.doAnswer( - invocation -> { - var pending = retainedOperation.get(); - String availability = invocation.getArgument(1); - retainedOperation.set( - new AccountJoinOperationRepository.JoinOperation( - pending.accountId(), - pending.tenantId(), - pending.realmId(), - pending.callerBinding(), - pending.scopeTokenHash(), - pending.connectScopeDigest(), - pending.requestDigest() == null - ? availability - : pending.entitlementAuthorityAvailability(), - pending.allowPublicJoin(), - pending.entitlementVersion(), - pending.requestDigestVersion(), - pending.requestDigest(), - pending.status(), - pending.outcome(), - pending.membershipId(), - pending.membershipVersion(), - pending.membershipAuthorityGeneration(), - pending.intentDigestVersion(), - pending.intentDigest(), - invocation.getArgument(2), - availability)); - return null; - }) - .when(accountJoinOperationRepository) - .recordAttemptFailure( - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString()); - org.mockito.Mockito.doAnswer( - invocation -> { - var pending = retainedOperation.get(); - retainedOperation.set( - new AccountJoinOperationRepository.JoinOperation( - pending.accountId(), - pending.tenantId(), - pending.realmId(), - pending.callerBinding(), - pending.scopeTokenHash(), - pending.connectScopeDigest(), - pending.entitlementAuthorityAvailability(), - pending.allowPublicJoin(), - pending.entitlementVersion(), - pending.requestDigestVersion(), - pending.requestDigest(), - invocation.getArgument(1), - invocation.getArgument(2), - invocation.getArgument(3), - invocation.getArgument(4), - invocation.getArgument(5), - pending.intentDigestVersion(), - pending.intentDigest(), - null, - pending.lastAttemptAuthorityAvailability())); - return null; - }) - .when(accountJoinOperationRepository) - .finish( - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.nullable(Long.class), - org.mockito.ArgumentMatchers.nullable(Long.class), - org.mockito.ArgumentMatchers.nullable(Long.class)); - } - - @Test - void emailLoginOtpRequestIsNeutralForUnknownEmail() { - when(accountRepository.findByEmail("unknown@example.com")).thenReturn(Optional.empty()); - - service.requestEmailLoginOtp("unknown@example.com"); - - verifyNoInteractions(emailService, accountEmailLoginChallengeRepository); - } - - @ParameterizedTest - @EnumSource( - value = AccountLifecycleState.class, - names = {"SECURITY_LOCKED", "DEACTIVATED_PENDING_DELETE", "DELETED"}) - void emailLoginOtpRequestIsNeutralForIneligibleLifecycleState( - AccountLifecycleState lifecycleState) { - Account account = new Account(); - account.setId(9L); - account.setEmail("verified@example.com"); - account.setEmailVerified(true); - account.setLifecycleState(lifecycleState); - when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); - - service.requestEmailLoginOtp("verified@example.com"); - - verifyNoInteractions( - accountTenantMembershipRepository, accountEmailLoginChallengeRepository, emailService); - } - - @Test - void emailLoginOtpRequestPersistsOnlyHashedChallengeAndSendsSixDigitCode() { - Account account = new Account(); - account.setId(9L); - account.setEmail("verified@example.com"); - account.setEmailVerified(true); - when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); - when(accountEmailLoginChallengeRepository.findByAccountId(9L)).thenReturn(Optional.empty()); - when(accountEmailLoginChallengeRepository.save(org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = - invocation.getArgument(0); - challenge.setId(3L); - return challenge; - }); - - service.requestEmailLoginOtp("verified@example.com"); - - org.mockito.ArgumentCaptor< - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge> - challengeCaptor = - org.mockito.ArgumentCaptor.forClass( - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge.class); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository) - .save(challengeCaptor.capture()); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(9L); - assertEquals(9L, challengeCaptor.getValue().getAccountId()); - assertFalse(challengeCaptor.getValue().getCodeHash().matches("\\d{6}")); - org.mockito.Mockito.verify(emailService) - .sendEmail( - org.mockito.ArgumentMatchers.eq("verified@example.com"), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.matches(".*\\b\\d{6}\\b.*")); - verifyNoInteractions(accountTenantMembershipRepository); - } - - @Test - void emailLoginOtpVerificationAuthenticatesAndConsumesMatchingChallenge() { - Account account = new Account(); - account.setId(9L); - setPersistedAuthenticationIdentity(account); - account.setEmail("verified@example.com"); - account.setEmailVerified(true); - account.setRole("player"); - when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); - when(accountEmailLoginChallengeRepository.findByAccountId(9L)).thenReturn(Optional.empty()); - when(accountEmailLoginChallengeRepository.save(org.mockito.ArgumentMatchers.any())) - .thenAnswer(invocation -> invocation.getArgument(0)); - - service.requestEmailLoginOtp("verified@example.com"); - - org.mockito.ArgumentCaptor< - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge> - challengeCaptor = - org.mockito.ArgumentCaptor.forClass( - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge.class); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository) - .save(challengeCaptor.capture()); - org.mockito.ArgumentCaptor emailBodyCaptor = - org.mockito.ArgumentCaptor.forClass(String.class); - org.mockito.Mockito.verify(emailService) - .sendEmail( - org.mockito.ArgumentMatchers.eq("verified@example.com"), - org.mockito.ArgumentMatchers.anyString(), - emailBodyCaptor.capture()); - Matcher codeMatcher = Pattern.compile("\\b(\\d{6})\\b").matcher(emailBodyCaptor.getValue()); - assertTrue(codeMatcher.find()); - when(accountEmailLoginChallengeRepository.findByAccountId(9L)) - .thenReturn(Optional.of(challengeCaptor.getValue())); - - AuthenticationResult result = - service.verifyEmailLoginOtp("verified@example.com", codeMatcher.group(1)); - - assertEquals(account.getAccountUuid().toString(), result.accountId()); - assertNotNull(result.authToken()); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository) - .delete(challengeCaptor.getValue()); - org.mockito.Mockito.verify(sessionService) - .storeAccountSession( - org.mockito.ArgumentMatchers.eq(9L), - org.mockito.ArgumentMatchers.eq(result.authToken()), - org.mockito.ArgumentMatchers.eq(jwtAuthProperties.getJwtExpirationMs())); - verifyNoInteractions(accountTenantMembershipRepository); - } - - @Test - void authenticateUsesMatchingEmailLoginOtpBeforePasswordFallback() { - Account account = new Account(); - account.setId(9L); - setPersistedAuthenticationIdentity(account); - account.setEmail("demo@example.com"); - account.setPasswordHash(hash("password")); - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = - new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); - challenge.setId(3L); - challenge.setAccountId(9L); - challenge.setCodeHash(hash("123456")); - challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); - when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); - when(accountEmailLoginChallengeRepository.findByAccountId(9L)) - .thenReturn(Optional.of(challenge)); - - AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "123456"); - - assertEquals(account.getAccountUuid().toString(), result.accountId()); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).delete(challenge); - org.mockito.Mockito.verify(sessionService) - .storeAccountSession(9L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); - verifyNoInteractions(accountTenantMembershipRepository); - } - - @Test - void authenticateFallsBackToPasswordWithoutBurningUnmatchedEmailLoginOtp() { - Account account = new Account(); - account.setId(9L); - setPersistedAuthenticationIdentity(account); - account.setEmail("demo@example.com"); - account.setPasswordHash(hash("password")); - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = - new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); - challenge.setId(3L); - challenge.setAccountId(9L); - challenge.setCodeHash(hash("123456")); - challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); - when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); - when(accountEmailLoginChallengeRepository.findByAccountId(9L)) - .thenReturn(Optional.of(challenge)); - - AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "password"); - - assertEquals(account.getAccountUuid().toString(), result.accountId()); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) - .delete(challenge); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) - .save(challenge); - } - - @Test - void authenticateCountsFailedMixedModeSecretAgainstActiveEmailLoginOtp() { - Account account = new Account(); - account.setId(9L); - setPersistedAuthenticationIdentity(account); - account.setEmail("demo@example.com"); - account.setPasswordHash(hash("password")); - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = - new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); - challenge.setId(3L); - challenge.setAccountId(9L); - challenge.setCodeHash(hash("123456")); - challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); - when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); - when(accountEmailLoginChallengeRepository.findByAccountId(9L)) - .thenReturn(Optional.of(challenge)); - when(accountEmailLoginChallengeRepository.save(challenge)).thenReturn(challenge); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.authenticateForGameplay("demo@example.com", "wrong")); - - assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, exception.getCode()); - assertEquals(1, challenge.getInvalidAttemptCount()); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).save(challenge); - verifyNoInteractions(sessionService); - } - - @Test - void passwordOnlyAccountsDoNotIssueEmailLoginChallenges() { - Account account = new Account(); - account.setId(9L); - account.setEmail("verified@example.com"); - account.setEmailVerified(true); - account.setLoginAuthModes("PASSWORD"); - when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); - - service.requestEmailLoginOtp("verified@example.com"); - - verifyNoInteractions( - accountTenantMembershipRepository, accountEmailLoginChallengeRepository, emailService); - } - - @ParameterizedTest - @EnumSource(AccountIdentityProvenance.class) - void gameplayAuthenticationAcceptsEveryRecognizedPersistedUuidProvenance( - AccountIdentityProvenance provenance) { - Account account = new Account(); - account.setId(31L); - account.setEmail("retained@example.com"); - account.setPasswordHash(hash("password")); - setPersistedAuthenticationIdentity(account, provenance); - when(accountRepository.findByEmail("retained@example.com")).thenReturn(Optional.of(account)); - - AuthenticationResult result = - service.authenticateForGameplay("retained@example.com", "password"); - var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); - - assertEquals(account.getAccountUuid().toString(), result.accountId()); - assertEquals(account.getAccountUuid().toString(), claims.getSubject()); - assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); - assertFalse(claims.containsKey("tenantId")); - org.mockito.Mockito.verify(sessionService) - .storeAccountSession(31L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); - } - - @ParameterizedTest - @EnumSource(InvalidAuthenticationIdentity.class) - void gameplayAuthenticationRejectsUnprovedIdentityBeforeConsumingOtpOrMinting( - InvalidAuthenticationIdentity invalidIdentity) { - Account account = new Account(); - account.setId(32L); - account.setEmail("unproved@example.com"); - assignInvalidAuthenticationIdentity(account, invalidIdentity); - var challenge = new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); - challenge.setId(8L); - challenge.setAccountId(32L); - challenge.setCodeHash(hash("123456")); - challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); - when(accountRepository.findByEmail("unproved@example.com")).thenReturn(Optional.of(account)); - when(accountEmailLoginChallengeRepository.findByAccountId(32L)) - .thenReturn(Optional.of(challenge)); - - AuthenticationException unavailable = - assertThrows( - AuthenticationException.class, - () -> service.authenticateForGameplay("unproved@example.com", "123456")); - assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); - - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(32L); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).findByAccountId(32L); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) - .delete(challenge); - verifyNoInteractions(sessionService); - } - - @Test - void emailLoginOtpVerificationFailsClosedForUnknownEmail() { - when(accountRepository.findByEmail("unknown@example.com")).thenReturn(Optional.empty()); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.verifyEmailLoginOtp("unknown@example.com", "123456")); - - assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, exception.getCode()); - verifyNoInteractions(accountEmailLoginChallengeRepository, sessionService); - } - - @Test - void emailLoginOtpVerificationLocksChallengeBeforeConsumingIt() { - Account account = new Account(); - account.setId(9L); - setPersistedAuthenticationIdentity(account); - account.setEmail("verified@example.com"); - account.setRole("player"); - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = - new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); - challenge.setId(5L); - challenge.setAccountId(9L); - challenge.setCodeHash(hash("123456")); - challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(10)); - challenge.setInvalidAttemptCount(0); - when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); - when(accountEmailLoginChallengeRepository.findByAccountId(9L)) - .thenReturn(Optional.of(challenge)); - - AuthenticationResult result = service.verifyEmailLoginOtp("verified@example.com", "123456"); - - assertEquals(account.getAccountUuid().toString(), result.accountId()); - var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); - assertEquals("account-service", claims.getAudience().iterator().next()); - assertEquals(account.getAccountUuid().toString(), claims.getSubject()); - assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); - org.mockito.InOrder inOrder = org.mockito.Mockito.inOrder(accountEmailLoginChallengeRepository); - inOrder.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(9L); - inOrder.verify(accountEmailLoginChallengeRepository).findByAccountId(9L); - inOrder.verify(accountEmailLoginChallengeRepository).delete(challenge); - } - - @Test - void authenticateReturnsControlUiTokenWithoutGameplayMembership() { - Account account = new Account(); - account.setId(1L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - - AuthenticationResult result = service.authenticate("demo", "password"); - - assertNotNull(result.authToken()); - assertEquals(account.getAccountUuid().toString(), result.accountId()); - var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); - assertEquals("control-ui", claims.getAudience().iterator().next()); - assertEquals(account.getAccountUuid().toString(), claims.getSubject()); - assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); - assertEquals(java.util.List.of(), claims.get("globalRoles")); - assertNotNull(claims.get("jti")); - assertFalse(claims.containsKey("tenantId")); - org.mockito.Mockito.verify(sessionService) - .storeAccountSession(1L, result.authToken(), 3600000L); - verifyNoInteractions(accountTenantMembershipRepository); - } - - @ParameterizedTest - @CsvSource({ - "SECURITY_LOCKED, AUTH_ACCOUNT_LOCKED", - "DEACTIVATED_PENDING_DELETE, AUTH_INVALID_CREDENTIALS", - "DELETED, AUTH_INVALID_CREDENTIALS" - }) - void authenticateRejectsIneligibleLifecycleState( - AccountLifecycleState lifecycleState, String expectedCode) { - Account account = new Account(); - account.setId(1L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - account.setLifecycleState(lifecycleState); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - - AuthenticationException exception = - assertThrows(AuthenticationException.class, () -> service.authenticate("demo", "password")); - - assertEquals(expectedCode, exception.getCode()); - verifyNoInteractions(sessionService); - } - - @Test - void authenticateForGameplayReturnsTokenWhenPasswordMatches() { - Account account = new Account(); - account.setId(1L); - setPersistedAuthenticationIdentity(account); - account.setEmail("demo@example.com"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); - jwtAuthProperties.setJwtSecret(null); - - AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "password"); - - assertNotNull(result.authToken()); - assertEquals(account.getAccountUuid().toString(), result.accountId()); - var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); - assertEquals("account-service", claims.getAudience().iterator().next()); - assertEquals(account.getAccountUuid().toString(), claims.getSubject()); - assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); - assertEquals(java.util.List.of(), claims.get("globalRoles")); - assertNotNull(claims.get("jti")); - org.mockito.Mockito.verify(sessionService) - .storeAccountSession(1L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); - verifyNoInteractions(accountTenantMembershipRepository); - } - - @Test - void issuePlayerBootstrapReturnsShortLivedToken() { - Account account = new Account(); - account.setId(7L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - account.setLoginAuthModes("PASSWORD"); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - jwtAuthProperties.setJwtSecret(null); - - PlayerBootstrapResult result = service.issuePlayerBootstrap("demo", "password"); - - assertEquals(account.getAccountUuid().toString(), result.accountId()); - assertNotNull(result.bootstrapToken()); - assertNotNull(result.issuedAt()); - assertNotNull(result.expiresAt()); - org.mockito.Mockito.verify(sessionService) - .storeAccountSession( - org.mockito.ArgumentMatchers.eq(7L), - org.mockito.ArgumentMatchers.eq(result.bootstrapToken()), - org.mockito.ArgumentMatchers.eq(300000L)); - var claims = new JwtUtil(JWT_SECRET, 300000L).parseToken(result.bootstrapToken()).getPayload(); - assertEquals("player-bootstrap", claims.getAudience().iterator().next()); - assertEquals(account.getAccountUuid().toString(), claims.getSubject()); - assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); - assertFalse(claims.containsKey("tenantId")); - assertEquals(300000L, claims.getExpiration().getTime() - claims.getIssuedAt().getTime()); - when(sessionService.isAccountSessionActive(7L, result.bootstrapToken())).thenReturn(true); - var worlds = service.listBootstrapWorlds(result.bootstrapToken()); - assertEquals("demo", worlds.getFirst().worldSlug()); - org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.times(2)) - .findByAccountUuid(account.getAccountUuid()); - org.mockito.Mockito.verify(sessionService).isAccountSessionActive(7L, result.bootstrapToken()); - verifyNoInteractions(accountEmailLoginChallengeRepository); - } - - @ParameterizedTest - @EnumSource(InvalidAuthenticationIdentity.class) - void issuePlayerBootstrapRejectsUnprovedIdentityBeforeConsumingOtpOrMinting( - InvalidAuthenticationIdentity invalidIdentity) { - Account account = new Account(); - account.setId(50L); - account.setUsername("demo"); - account.setLoginAuthModes("EMAIL_OTP"); - assignInvalidAuthenticationIdentity(account, invalidIdentity); - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = - new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); - challenge.setAccountId(50L); - challenge.setCodeHash(hash("123456")); - challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountEmailLoginChallengeRepository.findByAccountId(50L)) - .thenReturn(Optional.of(challenge)); - - AuthenticationException unavailable = - assertThrows( - AuthenticationException.class, () -> service.issuePlayerBootstrap("demo", "123456")); - assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); - - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(50L); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).findByAccountId(50L); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) - .delete(challenge); - verifyNoInteractions(sessionService); - } - - @Test - void issuePlayerBootstrapPrefersEmailLookupOverCollidingUsername() { - Account emailAccount = new Account(); - emailAccount.setId(7L); - setPersistedAuthenticationIdentity(emailAccount); - emailAccount.setUsername("email-owner"); - emailAccount.setEmail("player@example.com"); - emailAccount.setPasswordHash(hash("password")); - emailAccount.setLoginAuthModes("PASSWORD"); - when(accountRepository.findByEmail("player@example.com")).thenReturn(Optional.of(emailAccount)); - - PlayerBootstrapResult result = - service.issuePlayerBootstrap(" PLAYER@EXAMPLE.COM ", "password"); - - assertEquals(emailAccount.getAccountUuid().toString(), result.accountId()); - org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) - .findByUsername(org.mockito.ArgumentMatchers.anyString()); - } - - @Test - void issuePlayerBootstrapAcceptsAndConsumesEmailLoginOtp() { - Account account = new Account(); - account.setId(7L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setEmail("demo@example.com"); - account.setLoginAuthModes("EMAIL_OTP"); - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = - new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); - challenge.setAccountId(7L); - challenge.setCodeHash(hash("123456")); - challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountEmailLoginChallengeRepository.findByAccountId(7L)) - .thenReturn(Optional.of(challenge)); - - PlayerBootstrapResult result = service.issuePlayerBootstrap("demo", "123456"); - - assertEquals(account.getAccountUuid().toString(), result.accountId()); - org.mockito.InOrder inOrder = org.mockito.Mockito.inOrder(accountEmailLoginChallengeRepository); - inOrder.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(7L); - inOrder.verify(accountEmailLoginChallengeRepository).findByAccountId(7L); - inOrder.verify(accountEmailLoginChallengeRepository).delete(challenge); - org.mockito.Mockito.verify(sessionService) - .storeAccountSession(7L, result.bootstrapToken(), 300000L); - } - - private static java.util.stream.Stream - invalidBootstrapAccountClaims() { - String valid = "10000000-0000-4000-8000-00000000000a"; - return java.util.stream.Stream.of( - org.junit.jupiter.params.provider.Arguments.of("11", "11"), - org.junit.jupiter.params.provider.Arguments.of((String) null, valid), - org.junit.jupiter.params.provider.Arguments.of( - valid.toUpperCase(java.util.Locale.ROOT), valid), - org.junit.jupiter.params.provider.Arguments.of(" " + valid, valid), - org.junit.jupiter.params.provider.Arguments.of(valid, (Object) null), - org.junit.jupiter.params.provider.Arguments.of(valid, ""), - org.junit.jupiter.params.provider.Arguments.of(valid, 11L), - org.junit.jupiter.params.provider.Arguments.of(valid, "11"), - org.junit.jupiter.params.provider.Arguments.of( - valid, "00000000-0000-0000-0000-000000000000"), - org.junit.jupiter.params.provider.Arguments.of( - "00000000-0000-0000-0000-000000000000", valid), - org.junit.jupiter.params.provider.Arguments.of(valid, "not-a-uuid"), - org.junit.jupiter.params.provider.Arguments.of( - valid, valid.toUpperCase(java.util.Locale.ROOT)), - org.junit.jupiter.params.provider.Arguments.of(valid, " " + valid), - org.junit.jupiter.params.provider.Arguments.of( - valid, "10000000-0000-4000-8000-000000000002")); - } - - @ParameterizedTest - @org.junit.jupiter.params.provider.MethodSource("invalidBootstrapAccountClaims") - void bootstrapReaderRejectsNonUuidOrContradictoryIdentityBeforeOwnerOrSessionUse( - String subject, Object accountClaim) { - Map claims = new java.util.HashMap<>(); - claims.put("aud", "player-bootstrap"); - if (accountClaim != null) { - claims.put("accountId", accountClaim); - } - String token = new JwtUtil(JWT_SECRET, 300000L).generateToken(subject, claims); - - AuthenticationException denied = - assertThrows(AuthenticationException.class, () -> service.listBootstrapWorlds(token)); - - assertEquals("CONNECT_CONTEXT_INVALID", denied.getCode()); - verifyNoInteractions(accountRepository, sessionService); - } - - @ParameterizedTest - @ValueSource(strings = {"missing", "wrong-owner-uuid", "unavailable"}) - void bootstrapReaderReportsOwnerReadbackFailureBeforeSessionUse(String failure) { - UUID uuid = UUID.fromString("10000000-0000-4000-8000-000000000001"); - if (failure.equals("unavailable")) { - when(accountRepository.findByAccountUuid(uuid)) - .thenThrow( - new org.springframework.dao.DataAccessResourceFailureException("private detail")); - } else if (failure.equals("wrong-owner-uuid")) { - Account owner = new Account(); - owner.setId(11L); - owner.setAccountUuid(UUID.randomUUID()); - owner.setAccountUuidSourceNumericId(11L); - owner.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); - when(accountRepository.findByAccountUuid(uuid)).thenReturn(Optional.of(owner)); - } - String token = - new JwtUtil(JWT_SECRET, 300000L) - .generateToken( - uuid.toString(), Map.of("aud", "player-bootstrap", "accountId", uuid.toString())); - - AuthenticationException denied = - assertThrows(AuthenticationException.class, () -> service.listBootstrapWorlds(token)); - - assertEquals("AUTH_UNAVAILABLE", denied.getCode()); - assertEquals("Account authority is unavailable", denied.getMessage()); - verifyNoInteractions(sessionService); - } - - @Test - void bootstrapReaderResolvesUuidBeforeReadingPrivateAccountSession() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - String uuid = account.getAccountUuid().toString(); - String token = - new JwtUtil(JWT_SECRET, 300000L) - .generateToken(uuid, Map.of("aud", "player-bootstrap", "accountId", uuid)); - when(sessionService.isAccountSessionActive(11L, token)).thenReturn(true); - - assertFalse(service.listBootstrapWorlds(token).isEmpty()); - - org.mockito.InOrder reads = org.mockito.Mockito.inOrder(accountRepository, sessionService); - reads.verify(accountRepository).findByAccountUuid(account.getAccountUuid()); - reads.verify(sessionService).isAccountSessionActive(11L, token); - } - - @Test - void listBootstrapWorldsRejectsInactiveAccountBootstrapToken() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - String accountUuid = account.getAccountUuid().toString(); - String bootstrapToken = - new JwtUtil(JWT_SECRET, 300000L) - .generateToken( - accountUuid, Map.of("aud", "player-bootstrap", "accountId", accountUuid)); - - AuthenticationException ex = - assertThrows( - AuthenticationException.class, () -> service.listBootstrapWorlds(bootstrapToken)); - - assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); - assertEquals("Bootstrap token expired", ex.getMessage()); - org.mockito.Mockito.verify(sessionService).isAccountSessionActive(11L, bootstrapToken); - } - - @ParameterizedTest - @ValueSource( - strings = { - "not-a-uuid", - "abc", - "0", - "00000000-0000-0000-0000-000000000000", - "4C4B57D8-E3A2-48FE-9977-E7DF0FDCE901", - " 4c4b57d8-e3a2-48fe-9977-e7df0fdce901", - "4c4b57d8-e3a2-48fe-9977-e7df0fdce901 " - }) - void listBootstrapWorldsRejectsMalformedOrNoncanonicalBootstrapAccountUuid(String accountUuid) { - String malformedBootstrapToken = - new JwtUtil(JWT_SECRET, 300000L) - .generateToken( - accountUuid, Map.of("aud", "player-bootstrap", "accountId", accountUuid)); - - AuthenticationException ex = - assertThrows( - AuthenticationException.class, - () -> service.listBootstrapWorlds(malformedBootstrapToken)); - - assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); - verifyNoInteractions(accountRepository, sessionService); - } - - @Test - void listBootstrapWorldsRejectsBootstrapTokenAccountSubjectMismatch() { - String malformedBootstrapToken = - new JwtUtil(JWT_SECRET, 300000L) - .generateToken( - REALM_ID, - Map.of("aud", "player-bootstrap", "accountId", PLAYABLE_STATE_NAMESPACE_ID)); - - AuthenticationException ex = - assertThrows( - AuthenticationException.class, - () -> service.listBootstrapWorlds(malformedBootstrapToken)); - - assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); - verifyNoInteractions(accountRepository, sessionService); - } - - @Test - void listBootstrapWorldsRejectsLegacyNumericBootstrapTokenClaims() { - String malformedBootstrapToken = - new JwtUtil(JWT_SECRET, 300000L) - .generateToken("11", Map.of("aud", "player-bootstrap", "accountId", "11")); - - AuthenticationException ex = - assertThrows( - AuthenticationException.class, - () -> service.listBootstrapWorlds(malformedBootstrapToken)); - - assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); - } - - @Test - void listBootstrapWorldsRejectsBootstrapTokenWithoutAudience() { - String malformedBootstrapToken = - new JwtUtil(JWT_SECRET, 300000L).generateToken("11", Map.of("accountId", "11")); - - AuthenticationException ex = - assertThrows( - AuthenticationException.class, - () -> service.listBootstrapWorlds(malformedBootstrapToken)); - - assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); - } - - @Test - void listBootstrapWorldsDoesNotMaskUnexpectedJwtParserRuntimeFailure() { - JwtUtil jwtUtil = org.mockito.Mockito.mock(JwtUtil.class); - when(jwtUtil.parseToken("boom-token")).thenThrow(new IllegalStateException("boom")); - service = - new AccountServiceImpl( - accountRepository, - accountAuthorityGenerationRepository, - accountAuthoritySourceEvidenceRepository, - accountAuthorityOutboxRepository, - accountPasswordResetOperationRepository, - accountLogoutAllOperationRepository, - accountSecurityStateOperationRepository, - accountPasswordResetDraftSourceChangeRepository, - accountAuditOutboxRepository, - accountConnectScopeRepository, - accountJoinOperationRepository, - accountEmailLoginChallengeRepository, - accountRealmAccessGrantRepository, - accountTenantMembershipRepository, - Mappers.getMapper(AccountMapper.class), - profileRepository, - profileMapper, - paymentTransactionRepository, - subscriptionRepository, - externalAccountRepository, - passwordResetTokenRepository, - emailVerificationTokenRepository, - notificationService, - emailService, - mailProperties, - tokenProperties, - jwtAuthProperties, - gameSessionClient, - entityManagementClient, - jwtUtil, - sessionService, - transactionManager); - - IllegalStateException ex = - assertThrows(IllegalStateException.class, () -> service.listBootstrapWorlds("boom-token")); - - assertEquals("boom", ex.getMessage()); - } - - @Test - void listBootstrapWorldsRejectsWorldWithMalformedRuntimeRealmRow() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.Arrays.asList( - null, - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("broken") - .setDisplayName("Broken Realm") - .setTenantId("bad") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.listBootstrapWorlds(bootstrap.bootstrapToken())); - - assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); - } - - @Test - void listBootstrapRealmsMapsZeroPublicAuthorityFromGameSession() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(gameSessionClient.listGameplayRealms("demo")) - .thenThrow( - new IllegalStateException( - "Gameplay realm discovery failed: invalid public realm cardinality")); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); - - assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); - } - - @Test - void listBootstrapWorldsRejectsWorldWithUnknownStateScope() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("production") - .setDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("UNKNOWN") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.listBootstrapWorlds(bootstrap.bootstrapToken())); - - assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); - } - - @Test - void listBootstrapRealmsRejectsMultipleVisiblePublicRealms() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - var firstPublicRealm = gameSessionClient.listGameplayRealms("demo").getFirst(); - var secondPublicRealm = - firstPublicRealm.toBuilder() - .setRealmSlug("production-alt") - .setRealmId("57c58f36-c5ea-4aa8-8ef7-91a45e407f01") - .setGameInstanceId("45") - .build(); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn(java.util.List.of(firstPublicRealm, secondPublicRealm)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); - - assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); - } - - @Test - void listBootstrapRealmsAcceptsExactlyOneVisiblePublicRealm() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - - var realms = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); - - assertEquals(1, realms.size()); - assertEquals("production", realms.getFirst().realmSlug()); - } - - @Test - void bootstrapRealmDiscoveryAndDirectTextScopeIssuanceSuspendIncomingTransactions() - throws NoSuchMethodException { - Transactional listRealms = - AccountServiceImpl.class - .getMethod("listBootstrapRealms", String.class, String.class) - .getAnnotation(Transactional.class); - Transactional issueDirectTextScope = - AccountServiceImpl.class - .getMethod( - "issueDirectTextConnectScope", - DirectTextCallerContext.class, - DirectTextJoinTarget.class) - .getAnnotation(Transactional.class); - - assertNotNull(listRealms); - assertNotNull(issueDirectTextScope); - assertEquals(Propagation.NOT_SUPPORTED, listRealms.propagation()); - assertEquals(Propagation.NOT_SUPPORTED, issueDirectTextScope.propagation()); - } - - @Test - void listBootstrapRealmsDoesNotIssueScopeWhenPublicPointerBecomesPrivateBeforeFinalRead() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( - 11L, 7L, "demo", "production")) - .thenReturn(true); - - var initiallyPublic = gameSessionClient.listGameplayRealms("demo").getFirst(); - var currentlyPrivate = initiallyPublic.toBuilder().setPublicProductionRealm(false).build(); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn(java.util.List.of(initiallyPublic), java.util.List.of(currentlyPrivate)); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) - .thenReturn( - admissionPointer( - 7L, "demo", "production", "44", 17L, true, false, "SHARED", "ALLOW_NEW")); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); - - assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); - org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) - .insert(org.mockito.ArgumentMatchers.any()); - } - - @Test - void listBootstrapRealmsDoesNotIssueScopeWhenPointerChangesDuringDiscovery() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - - var initiallyDiscovered = gameSessionClient.listGameplayRealms("demo").getFirst(); - var changedRealmId = "57c58f36-c5ea-4aa8-8ef7-91a45e407f01"; - var currentRealm = - initiallyDiscovered.toBuilder().setRealmId(changedRealmId).setPointerVersion(18L).build(); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn(java.util.List.of(initiallyDiscovered), java.util.List.of(currentRealm)); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) - .thenReturn( - admissionPointer(7L, "demo", "production", "44", 18L, true, true, "SHARED", "ALLOW_NEW") - .toBuilder() - .setRealmId(changedRealmId) - .build()); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); - - assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); - org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) - .insert(org.mockito.ArgumentMatchers.any()); - } - - @ParameterizedTest - @ValueSource(strings = {"101", "not-a-uuid", "4C4B57D8-E3A2-48FE-9977-E7DF0FDCE901"}) - void listBootstrapRealmsRejectsNoncanonicalRealmIds(String realmId) { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("production") - .setDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(realmId) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); - - assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); - } - - @Test - void issueConnectTokenRejectsMalformedConnectScopeId() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - - AuthenticationException ex = - assertThrows( - AuthenticationException.class, - () -> - service.issueConnectToken( - bootstrap.bootstrapToken(), new ConnectTokenRequest("bad", "req-err"))); - - assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); - } - - @Test - void issueConnectTokenRejectsNumericSignedConnectCarrierWithoutReplayMutation() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String numericConnectScopeId = - new JwtUtil(JWT_SECRET, 120000L) - .generateToken( - "11", - Map.ofEntries( - Map.entry("aud", "bootstrap-connect-scope"), - Map.entry("accountId", "11"), - Map.entry("tenantId", "7"), - Map.entry("realmId", REALM_ID), - Map.entry("worldSlug", "demo"), - Map.entry("realmSlug", "production"), - Map.entry("playableStateNamespaceId", PLAYABLE_STATE_NAMESPACE_ID), - Map.entry("playableStateScope", "SHARED"), - Map.entry("gameInstanceId", "44"), - Map.entry("catalogRevision", "23"), - Map.entry("pointerVersion", "17"), - Map.entry("evaluatedAt", java.time.Instant.now().toString()), - Map.entry( - "connectScopeExpiresAt", - java.time.Instant.now().plusSeconds(60).toString()), - Map.entry("jti", "numeric-account-id"))); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> - service.issueConnectToken( - bootstrap.bootstrapToken(), - new ConnectTokenRequest(numericConnectScopeId, "req-numeric-account-id"))); - - assertEquals("CONNECT_SCOPE_INVALID", exception.getCode()); - org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) - .getConnectTokenReplay( - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString()); - org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) - .storeConnectTokenReplay( - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.any(), - org.mockito.ArgumentMatchers.anyLong()); - } - - @Test - void issueConnectTokenRejectsBlankConnectScopeId() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - - AuthenticationException ex = - assertThrows( - AuthenticationException.class, - () -> - service.issueConnectToken( - bootstrap.bootstrapToken(), new ConnectTokenRequest(" ", "req-blank-scope"))); - - assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); - } - - @Test - void issueConnectTokenRejectsNonPositiveConnectScopeClaims() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String malformedConnectScopeId = - new JwtUtil(JWT_SECRET, 120000L) - .generateToken( - account.getAccountUuid().toString(), - Map.of( - "aud", - "bootstrap-connect-scope", - "accountId", - account.getAccountUuid().toString(), - "tenantId", - "7", - "worldSlug", - "demo", - "realmSlug", - "production", - "gameInstanceId", - "0", - "pointerVersion", - "17", - "connectScopeExpiresAt", - java.time.Instant.now().plusSeconds(3600).toString(), - "jti", - "invalid")); - - AuthenticationException ex = - assertThrows( - AuthenticationException.class, - () -> - service.issueConnectToken( - bootstrap.bootstrapToken(), - new ConnectTokenRequest(malformedConnectScopeId, "req-err2"))); - - assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); - } - - @Test - void issueConnectTokenRejectsMalformedConnectScopeClaims() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String malformedConnectScopeId = - new JwtUtil(JWT_SECRET, 120000L) - .generateToken( - account.getAccountUuid().toString(), - Map.of( - "aud", - "bootstrap-connect-scope", - "accountId", - "abc", - "tenantId", - "7", - "worldSlug", - "demo", - "realmSlug", - "production", - "gameInstanceId", - "44", - "pointerVersion", - "17", - "connectScopeExpiresAt", - java.time.Instant.now().plusSeconds(3600).toString(), - "jti", - "invalid")); - - AuthenticationException ex = - assertThrows( - AuthenticationException.class, - () -> - service.issueConnectToken( - bootstrap.bootstrapToken(), - new ConnectTokenRequest(malformedConnectScopeId, "req-err3"))); - - assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); - } - - @ParameterizedTest - @ValueSource(strings = {"101", "not-a-uuid", "4C4B57D8-E3A2-48FE-9977-E7DF0FDCE901"}) - void issueConnectTokenRejectsNoncanonicalRealmIdClaims(String realmId) { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String malformedConnectScopeId = - new JwtUtil(JWT_SECRET, 120000L) - .generateToken( - account.getAccountUuid().toString(), - Map.ofEntries( - Map.entry("aud", "bootstrap-connect-scope"), - Map.entry("accountId", account.getAccountUuid().toString()), - Map.entry("tenantId", "7"), - Map.entry("realmId", realmId), - Map.entry("worldSlug", "demo"), - Map.entry("realmSlug", "production"), - Map.entry("playableStateNamespaceId", PLAYABLE_STATE_NAMESPACE_ID), - Map.entry("playableStateScope", "SHARED"), - Map.entry("gameInstanceId", "44"), - Map.entry("catalogRevision", "23"), - Map.entry("pointerVersion", "17"), - Map.entry("evaluatedAt", java.time.Instant.now().toString()), - Map.entry( - "connectScopeExpiresAt", - java.time.Instant.now().plusSeconds(3600).toString()), - Map.entry("jti", "invalid-realm-id"))); - - AuthenticationException ex = - assertThrows( - AuthenticationException.class, - () -> - service.issueConnectToken( - bootstrap.bootstrapToken(), - new ConnectTokenRequest(malformedConnectScopeId, "req-invalid-realm-id"))); - - assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); - verifyNoInteractions(accountConnectScopeRepository); - } - - @Test - void issueConnectTokenRejectsConnectScopeAccountSubjectMismatch() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String malformedConnectScopeId = - new JwtUtil(JWT_SECRET, 120000L) - .generateToken( - "4d3e9d15-a02e-41db-8648-0d2c68d0f0a3", - Map.of( - "aud", - "bootstrap-connect-scope", - "accountId", - account.getAccountUuid().toString(), - "tenantId", - "7", - "worldSlug", - "demo", - "realmSlug", - "production", - "gameInstanceId", - "44", - "pointerVersion", - "17", - "connectScopeExpiresAt", - java.time.Instant.now().plusSeconds(3600).toString(), - "jti", - "invalid")); - - AuthenticationException ex = - assertThrows( - AuthenticationException.class, - () -> - service.issueConnectToken( - bootstrap.bootstrapToken(), - new ConnectTokenRequest(malformedConnectScopeId, "req-subject-mismatch"))); - - assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); - } - - @Test - void issueConnectTokenRejectsBlankWorldSlugConnectScopeClaims() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String malformedConnectScopeId = - new JwtUtil(JWT_SECRET, 120000L) - .generateToken( - account.getAccountUuid().toString(), - Map.of( - "aud", - "bootstrap-connect-scope", - "accountId", - account.getAccountUuid().toString(), - "tenantId", - "7", - "worldSlug", - " ", - "realmSlug", - "production", - "gameInstanceId", - "44", - "pointerVersion", - "17", - "connectScopeExpiresAt", - java.time.Instant.now().plusSeconds(3600).toString(), - "jti", - "invalid")); - - AuthenticationException ex = - assertThrows( - AuthenticationException.class, - () -> - service.issueConnectToken( - bootstrap.bootstrapToken(), - new ConnectTokenRequest(malformedConnectScopeId, "req-err4"))); - - assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); - } - - @Test - void issueConnectTokenRejectsZeroPointerVersionInConnectScopeClaims() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String malformedConnectScopeId = - new JwtUtil(JWT_SECRET, 120000L) - .generateToken( - account.getAccountUuid().toString(), - Map.of( - "aud", - "bootstrap-connect-scope", - "accountId", - account.getAccountUuid().toString(), - "tenantId", - "7", - "worldSlug", - "demo", - "realmSlug", - "production", - "gameInstanceId", - "44", - "pointerVersion", - "0", - "connectScopeExpiresAt", - java.time.Instant.now().plusSeconds(3600).toString(), - "jti", - "invalid")); - - AuthenticationException ex = - assertThrows( - AuthenticationException.class, - () -> - service.issueConnectToken( - bootstrap.bootstrapToken(), - new ConnectTokenRequest(malformedConnectScopeId, "req-err5"))); - - assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); - } - - @Test - void authenticateForGameplayUsesNormalizedEmailLookup() { - Account account = new Account(); - account.setId(1L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setEmail("demo@example.com"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); - - AuthenticationResult result = - service.authenticateForGameplay(" DEMO@example.com ", "password"); - - assertNotNull(result.authToken()); - assertEquals(account.getAccountUuid().toString(), result.accountId()); - org.mockito.Mockito.verify(sessionService) - .storeAccountSession(1L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); - verifyNoInteractions(accountTenantMembershipRepository); - org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) - .findByUsername(org.mockito.ArgumentMatchers.anyString()); - } - - @Test - void authenticateThrowsWhenInvalid() { - when(accountRepository.findByEmail("demo")).thenReturn(Optional.empty()); - AuthenticationException exception = - assertThrows( - AuthenticationException.class, () -> service.authenticateForGameplay("demo", "bad")); - assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, exception.getCode()); - } - - @Test - void authenticateDoesNotUseGlobalAccountFallback() { - when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.empty()); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.authenticateForGameplay("demo@example.com", "password")); - - assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, exception.getCode()); - org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) - .findByUsername(org.mockito.ArgumentMatchers.anyString()); - } - - @Test - void authenticateAllowsGlobalIdentityWithoutTenantMembership() { - Account account = new Account(); - account.setId(7L); - setPersistedAuthenticationIdentity(account); - account.setEmail("demo@example.com"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); - AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "password"); - - assertEquals(account.getAccountUuid().toString(), result.accountId()); - assertNotNull(result.authToken()); - org.mockito.Mockito.verify(sessionService) - .storeAccountSession(7L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); - verifyNoInteractions(accountTenantMembershipRepository); - } - - @Test - void getTenantMembershipForRuntimeReturnsAdmissionAllowedForExistingAccount() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setEmail("demo@example.com"); - account.setPasswordHash(hash("password")); - AccountTenantMembership activeMembership = membership(account, 7L); - activeMembership.setMembershipVersion(17L); - activeMembership.setMembershipAuthorityGeneration(29L); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(activeMembership)); - - var dto = service.getTenantMembershipForRuntime(11L, 7L, "req-1"); - - assertEquals(11L, dto.accountId()); - assertEquals(7L, dto.tenantId()); - assertTrue(dto.membershipExists()); - assertTrue(dto.gameplayAdmissionAllowed()); - assertEquals(17L, dto.membershipVersion()); - assertEquals("ACTIVE", dto.membershipLifecycleState()); - assertEquals(29L, dto.membershipAuthorityGeneration()); - assertNotNull(dto.evaluatedAt()); - } - - @Test - void getTenantMembershipForRuntimeReturnsCoherentMissingMembershipForExistingAccount() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setEmail("demo@example.com"); - account.setPasswordHash(hash("password")); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.empty()); - - var dto = service.getTenantMembershipForRuntime(11L, 7L, "req-1"); - - assertEquals(11L, dto.accountId()); - assertEquals(7L, dto.tenantId()); - assertFalse(dto.membershipExists()); - assertFalse(dto.gameplayAdmissionAllowed()); - assertEquals(0L, dto.membershipVersion()); - assertEquals("MISSING", dto.membershipLifecycleState()); - assertEquals(0L, dto.membershipAuthorityGeneration()); - assertNotNull(dto.evaluatedAt()); - } - - @Test - void getTenantMembershipForRuntimeReturnsInactiveMembershipWithIndependentGenerations() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setEmail("demo@example.com"); - account.setPasswordHash(hash("password")); - AccountTenantMembership inactiveMembership = membership(account, 7L); - inactiveMembership.setGameplayAdmissionAllowed(false); - inactiveMembership.setLifecycleState("INACTIVE"); - inactiveMembership.setMembershipVersion(23L); - inactiveMembership.setMembershipAuthorityGeneration(41L); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(inactiveMembership)); - - var dto = service.getTenantMembershipForRuntime(11L, 7L, "req-1"); - - assertEquals(11L, dto.accountId()); - assertEquals(7L, dto.tenantId()); - assertTrue(dto.membershipExists()); - assertFalse(dto.gameplayAdmissionAllowed()); - assertEquals(23L, dto.membershipVersion()); - assertEquals("INACTIVE", dto.membershipLifecycleState()); - assertEquals(41L, dto.membershipAuthorityGeneration()); - assertNotNull(dto.evaluatedAt()); - } - - @Test - void getTenantMembershipForRuntimeRejectsMissingAccount() { - when(accountRepository.findById(11L)).thenReturn(Optional.empty()); - - assertThrows( - IllegalArgumentException.class, - () -> service.getTenantMembershipForRuntime(11L, 7L, "req-1")); - } - - @Test - void getTenantMembershipForRuntimeRejectsCrossTenantAccount() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setEmail("demo@example.com"); - account.setPasswordHash(hash("password")); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - - var dto = service.getTenantMembershipForRuntime(11L, 7L, "req-1"); - - assertEquals(11L, dto.accountId()); - assertEquals(7L, dto.tenantId()); - assertTrue(!dto.membershipExists()); - assertTrue(!dto.gameplayAdmissionAllowed()); - } - - @ParameterizedTest - @CsvSource({ - "active,true,true", - "trialing,true,true", - "past_due,true,true", - "grace,true,false", - "canceled,false,false", - "unknown,false,false" - }) - void getTenantEntitlementsForRuntimeUsesCurrentSubscriptions( - String status, boolean gameplayAvailable, boolean allowPublicJoin) { - Subscription active = new Subscription(); - active.setId(31L); - active.setTenantId(7L); - active.setStatus(status); - active.setEntitlementVersion(9L); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - - var dto = service.getTenantEntitlementsForRuntime(7L, "req-2"); - - assertEquals(7L, dto.tenantId()); - assertEquals(gameplayAvailable, dto.gameplayAvailable()); - assertEquals(allowPublicJoin, dto.allowPublicJoin()); - assertEquals(9L, dto.entitlementVersion()); - assertEquals(9L, dto.tenantBillingSequence()); - assertNotNull(dto.evaluatedAt()); - } - - @Test - void getTenantEntitlementsForRuntimeTreatsMissingSubscriptionAsUnavailable() { - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of()); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.getTenantEntitlementsForRuntime(7L, "req-missing-entitlement")); - - assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); - } - - @Test - void getTenantEntitlementsForRuntimeTreatsMixedSubscriptionRowsAsUnavailable() { - Subscription active = new Subscription(); - active.setId(31L); - active.setTenantId(7L); - active.setStatus("active"); - Subscription canceled = new Subscription(); - canceled.setId(32L); - canceled.setTenantId(7L); - canceled.setStatus("canceled"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active, canceled)); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.getTenantEntitlementsForRuntime(7L, "req-ambiguous-entitlement")); - - assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); - } - - @Test - void issueDirectTextConnectScopeRejectsUnavailableEntitlementWithoutRetainingScope() { - Account account = directTextAccount(); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of()); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.issueDirectTextConnectScope(directTextCaller(), directTextTarget())); - - assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); - org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) - .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); - } - - @ParameterizedTest - @ValueSource(strings = {"", " "}) - void issueDirectTextConnectScopeRejectsBlankRequestIdBeforeAuthorityOrScopeWork( - String requestId) { - DirectTextCallerContext caller = - new DirectTextCallerContext( - 11L, - 7L, - UUID.fromString(REALM_ID), - PLAYABLE_STATE_NAMESPACE_ID, - "SHARED", - 44L, - "session-1", - requestId); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.issueDirectTextConnectScope(caller, directTextTarget())); - - assertEquals("CONNECT_SCOPE_INVALID", exception.getCode()); - verifyNoInteractions(accountRepository, subscriptionRepository, accountConnectScopeRepository); - } - - @Test - void issueDirectTextConnectScopeRejectsBillingBlockedEntitlementWithoutRetainingScope() { - Account account = directTextAccount(); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - Subscription canceled = new Subscription(); - canceled.setId(31L); - canceled.setTenantId(7L); - canceled.setStatus("canceled"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(canceled)); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.issueDirectTextConnectScope(directTextCaller(), directTextTarget())); - - assertEquals("TENANT_BILLING_BLOCKED", exception.getCode()); - assertEquals("Gameplay is not available for this tenant", exception.getMessage()); - org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) - .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); - } - - @Test - void issueDirectTextConnectScopeRetainsScopeForActiveEntitlement() { - Account account = directTextAccount(); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - - DirectTextJoinScope result = - service.issueDirectTextConnectScope(directTextCaller(), directTextTarget()); - - var claims = jwtUtil.parseToken(result.connectScopeId()).getPayload(); - assertEquals(account.getAccountUuid().toString(), claims.getSubject()); - assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); - assertNotNull(result.connectScopeId()); - assertNotNull(result.connectScopeExpiresAt()); - assertEquals(result.evaluatedAt(), claims.get("evaluatedAt", String.class)); - var retained = org.mockito.ArgumentCaptor.forClass(VerifiedJoinScope.class); - org.mockito.Mockito.verify(accountConnectScopeRepository).insert(retained.capture()); - assertEquals(result.evaluatedAt(), retained.getValue().evaluatedAt()); - assertEquals(result.connectScopeExpiresAt(), retained.getValue().connectScopeExpiresAt()); - } - - @Test - void graceAllowsDirectScopeDiscoveryWithoutPublicJoinAuthority() { - Account account = directTextAccount(); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - Subscription grace = new Subscription(); - grace.setTenantId(7L); - grace.setStatus("grace"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(List.of(grace)); - - var entitlement = service.getTenantEntitlementsForRuntime(7L, "grace-discovery"); - DirectTextJoinScope scope = - service.issueDirectTextConnectScope(directTextCaller(), directTextTarget()); - - assertTrue(entitlement.gameplayAvailable()); - assertFalse(entitlement.allowPublicJoin()); - assertNotNull(scope.connectScopeId()); - org.mockito.Mockito.verify(accountConnectScopeRepository) - .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); - verifyNoInteractions( - accountJoinOperationRepository, - accountTenantMembershipRepository, - accountAuditOutboxRepository); - } - - @Test - void bothScopeProducersBindPersistedUuidWhileRetainedRowsKeepPrivateAccountKey() { - Account account = directTextAccount(); - account.setUsername("demo"); + account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String browser = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - String direct = - service - .issueDirectTextConnectScope(directTextCaller(), directTextTarget()) - .connectScopeId(); - for (String token : java.util.List.of(browser, direct)) { - var claims = jwtUtil.parseToken(token).getPayload(); - assertEquals(account.getAccountUuid().toString(), claims.getSubject()); - assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); - AuthenticationException held = - assertThrows( - AuthenticationException.class, - () -> - service.issueConnectToken( - bootstrap.bootstrapToken(), new ConnectTokenRequest(token, "held-proof"))); - assertEquals("AUTH_UNAVAILABLE", held.getCode()); - } - var retained = org.mockito.ArgumentCaptor.forClass(VerifiedJoinScope.class); - org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.times(2)) - .insert(retained.capture()); - for (VerifiedJoinScope row : retained.getAllValues()) { - assertEquals(11L, row.accountId()); - assertEquals( - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.scope(row), - row.snapshotDigest()); - } - } - - @Test - void scopeReaderOwnerFailureIsUnavailableAndNumericScopesNeverReachOwnerLookup() { - Account account = directTextAccount(); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - String scope = - service - .issueDirectTextConnectScope(directTextCaller(), directTextTarget()) - .connectScopeId(); - var decoded = new java.util.HashMap(jwtUtil.parseToken(scope).getPayload()); - decoded.remove("iat"); - decoded.remove("exp"); - decoded.put("sub", "11"); - decoded.put("accountId", "11"); - String numeric = new JwtUtil(JWT_SECRET, 120000L).generateToken("11", decoded); - org.mockito.Mockito.clearInvocations(accountRepository); - AuthenticationException invalid = - assertThrows( - AuthenticationException.class, - () -> - service.joinPublicProductionFromGameSession( - directTextCaller(), - new JoinPublicProductionRequest(numeric, directTextCaller().requestId()))); - assertEquals("CONNECT_SCOPE_INVALID", invalid.getCode()); - org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) - .findByAccountUuid(org.mockito.ArgumentMatchers.any()); - when(accountRepository.findByAccountUuid(account.getAccountUuid())) - .thenThrow( - new org.springframework.dao.DataAccessResourceFailureException("private detail")); - AuthenticationException unavailable = - assertThrows( - AuthenticationException.class, - () -> - service.joinPublicProductionFromGameSession( - directTextCaller(), - new JoinPublicProductionRequest(scope, directTextCaller().requestId()))); - assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); - } - - @ParameterizedTest - @EnumSource(UnavailableEntitlement.class) - void runtimeAndDirectScopeTreatUnsafeEntitlementAsUnavailable(UnavailableEntitlement failure) { - when(subscriptionRepository.findByTenantId(7L)).thenAnswer(invocation -> failure.rows()); + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = + new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); + challenge.setId(3L); + challenge.setAccountId(9L); + challenge.setCodeHash(hash("123456")); + challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); + when(accountEmailLoginChallengeRepository.findByAccountId(9L)) + .thenReturn(Optional.of(challenge)); + when(accountEmailLoginChallengeRepository.save(challenge)).thenReturn(challenge); AuthenticationException exception = assertThrows( AuthenticationException.class, - () -> service.getTenantEntitlementsForRuntime(7L, "req-entitlement-store-failure")); - - assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); - assertSame(failure.cause, exception.getCause()); - - Account account = directTextAccount(); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - AuthenticationException scopeFailure = - assertThrows( - AuthenticationException.class, - () -> service.issueDirectTextConnectScope(directTextCaller(), directTextTarget())); - assertEquals("ENTITLEMENT_UNAVAILABLE", scopeFailure.getCode()); - assertSame(failure.cause, scopeFailure.getCause()); - org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) - .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); - verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); - } - - @ParameterizedTest - @ValueSource(strings = {"mapping", "configuration"}) - void runtimeAndDirectScopePropagateEntitlementProgrammingFaults(String fault) { - RuntimeException cause = entitlementProgrammingFault(fault); - when(subscriptionRepository.findByTenantId(7L)).thenThrow(cause); - - assertSame( - cause, - assertThrows( - cause.getClass(), () -> service.getTenantEntitlementsForRuntime(7L, "req-fault"))); - Account account = directTextAccount(); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - assertSame( - cause, - assertThrows( - cause.getClass(), - () -> service.issueDirectTextConnectScope(directTextCaller(), directTextTarget()))); - org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) - .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); - verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); - } - - @Test - void issueConnectTokenFailsClosedBeforeLegacyIssuanceOrReplayState() { - ConnectScopeFixture fixture = prepareConnectScopeForIssue(); - org.mockito.Mockito.clearInvocations( - sessionService, - accountTenantMembershipRepository, - gameSessionClient, - subscriptionRepository); - - AuthenticationException unavailable = - assertThrows( - AuthenticationException.class, - () -> - service.issueConnectToken( - fixture.bootstrapToken(), - new ConnectTokenRequest(fixture.connectScopeId(), "req-unavailable"))); + () -> service.authenticateForGameplay("demo@example.com", "wrong")); - assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); - assertNoLegacyConnectTokenEffects(); + assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, exception.getCode()); + assertEquals(1, challenge.getInvalidAttemptCount()); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).save(challenge); + verifyNoInteractions(sessionService); } @Test - void issueConnectTokenDoesNotReturnCachedLegacySuccess() { - ConnectScopeFixture fixture = prepareConnectScopeForIssue(); - org.mockito.Mockito.clearInvocations( - sessionService, - accountTenantMembershipRepository, - gameSessionClient, - subscriptionRepository); - ConnectTokenResult cachedLegacySuccess = - new ConnectTokenResult( - 11L, - 7L, - 44L, - "production", - fixture.connectScopeId(), - "legacy-hmac-connect-token", - "legacy-jti", - "req-cached-success", - "2026-10-14T00:00:00Z", - "2026-10-14T00:00:30Z", - false); - when(sessionService.getConnectTokenReplay( - 7L, 11L, fixture.connectScopeId(), "req-cached-success")) - .thenReturn( - Optional.of(new SessionService.ConnectTokenReplay(true, cachedLegacySuccess, "", ""))); - - AuthenticationException unavailable = - assertThrows( - AuthenticationException.class, - () -> - service.issueConnectToken( - fixture.bootstrapToken(), - new ConnectTokenRequest(fixture.connectScopeId(), "req-cached-success"))); - - assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); - assertNoLegacyConnectTokenEffects(); - } - - private ConnectScopeFixture prepareConnectScopeForIssue() { + void passwordOnlyAccountsDoNotIssueEmailLoginChallenges() { Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - return new ConnectScopeFixture(bootstrap.bootstrapToken(), connectScopeId); - } - - private void assertNoLegacyConnectTokenEffects() { - org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) - .getConnectTokenReplay( - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString()); - org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) - .storeConnectTokenReplay( - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.any(SessionService.ConnectTokenReplay.class), - org.mockito.ArgumentMatchers.anyLong()); - org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) - .storeSession( - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyLong()); - verifyNoInteractions(accountTenantMembershipRepository); - org.mockito.Mockito.verify(gameSessionClient, org.mockito.Mockito.never()) - .getAdmissionPointer( - org.mockito.ArgumentMatchers.anyLong(), - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString()); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.never()) - .findByTenantId(org.mockito.ArgumentMatchers.anyLong()); - } + account.setId(9L); + account.setEmail("verified@example.com"); + account.setEmailVerified(true); + account.setLoginAuthModes("PASSWORD"); + when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); - private record ConnectScopeFixture(String bootstrapToken, String connectScopeId) {} + service.requestEmailLoginOtp("verified@example.com"); - @Test - void listBootstrapCharactersUsesEntityManagementForResolvedRealm() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - net.firedevops.firemud.entitymanagement.v1.Character character = - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("char-1") - .setName("Mara") - .setLevel(12) - .build(); - when(entityManagementClient.listCharactersByAccount( - 7L, account.getAccountUuid(), 44L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .thenReturn(java.util.List.of(character)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - - var characters = - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "demo", "production", connectScopeId); - - assertEquals(1, characters.size()); - assertEquals("char-1", characters.getFirst().characterId()); - assertEquals("Mara", characters.getFirst().characterName()); - assertEquals("SHARED", characters.getFirst().stateScope()); - assertEquals("ALLOW_NEW", characters.getFirst().characterCreationPolicy()); - org.mockito.Mockito.verify(entityManagementClient) - .listCharactersByAccount( - 7L, account.getAccountUuid(), 44L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + verifyNoInteractions( + accountTenantMembershipRepository, accountEmailLoginChallengeRepository, emailService); } @ParameterizedTest - @CsvSource({"false", "true"}) - void listBootstrapCharactersDistinguishesMissingAndNonAdmittingMembership( - boolean membershipExists) { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - if (membershipExists) { - AccountTenantMembership membership = membership(account, 7L); - membership.setGameplayAdmissionAllowed(false); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership)); - } else { - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.empty()); - } - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); - - if (membershipExists) { - assertEquals("CONNECT_TOKEN_REJECTED", exception.getCode()); - assertEquals("Gameplay admission is not allowed for this account", exception.getMessage()); - } else { - assertEquals("JOIN_REQUIRED", exception.getCode()); - assertEquals("Join the selected world before discovering characters", exception.getMessage()); - } - verifyNoInteractions(entityManagementClient); - org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) - .saveAndFlush(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); - } - - @Test - void listBootstrapCharactersChecksPublicJoinPolicyBeforeReturningJoinRequired() { + @EnumSource(AccountIdentityProvenance.class) + void gameplayAuthenticationAcceptsEveryRecognizedPersistedUuidProvenance( + AccountIdentityProvenance provenance) { Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); + account.setId(31L); + account.setEmail("retained@example.com"); account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - Subscription grace = new Subscription(); - grace.setId(22L); - grace.setTenantId(7L); - grace.setStatus("grace"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(grace)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + setPersistedAuthenticationIdentity(account, provenance); + when(accountRepository.findByEmail("retained@example.com")).thenReturn(Optional.of(account)); - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); + AuthenticationResult result = + service.authenticateForGameplay("retained@example.com", "password"); + var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); - assertEquals("PUBLIC_PRODUCTION_ADMISSION_DENIED", exception.getCode()); - org.mockito.InOrder order = - org.mockito.Mockito.inOrder(subscriptionRepository, accountTenantMembershipRepository); - order.verify(subscriptionRepository, org.mockito.Mockito.times(2)).findByTenantId(7L); - order.verify(accountTenantMembershipRepository).findByAccountIdAndTenantId(11L, 7L); - verifyNoInteractions(entityManagementClient); + assertEquals(account.getAccountUuid().toString(), result.accountId()); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); + assertFalse(claims.containsKey("tenantId")); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession(31L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); } @ParameterizedTest - @CsvSource({"active, JOIN_REQUIRED", "grace, PUBLIC_PRODUCTION_ADMISSION_DENIED"}) - void listBootstrapCharactersClassifiesInactivePublicMembershipByJoinPolicy( - String subscriptionStatus, String expectedCode) { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - AccountTenantMembership inactiveMembership = membership(account, 7L); - inactiveMembership.setLifecycleState("INACTIVE"); - inactiveMembership.setGameplayAdmissionAllowed(false); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(inactiveMembership)); - Subscription subscription = new Subscription(); - subscription.setId(22L); - subscription.setTenantId(7L); - subscription.setStatus(subscriptionStatus); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(subscription)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); - - assertEquals(expectedCode, exception.getCode()); - if ("JOIN_REQUIRED".equals(expectedCode)) { - assertEquals("Join the selected world before discovering characters", exception.getMessage()); - } else { - assertEquals("Public joining is not allowed for the selected game", exception.getMessage()); - } - verifyNoInteractions(entityManagementClient); - } - - @Test - void listBootstrapCharactersKeepsSelectedTargetFailClosedWhenEntitlementsAreUnavailable() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)) - .thenReturn(java.util.List.of(active), java.util.List.of()); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + @EnumSource(InvalidAuthenticationIdentity.class) + void gameplayAuthenticationRejectsUnprovedIdentityBeforeConsumingOtpOrMinting( + InvalidAuthenticationIdentity invalidIdentity) { + Account account = new Account(); + account.setId(32L); + account.setEmail("unproved@example.com"); + assignInvalidAuthenticationIdentity(account, invalidIdentity); + var challenge = new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); + challenge.setId(8L); + challenge.setAccountId(32L); + challenge.setCodeHash(hash("123456")); + challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); + when(accountRepository.findByEmail("unproved@example.com")).thenReturn(Optional.of(account)); + when(accountEmailLoginChallengeRepository.findByAccountId(32L)) + .thenReturn(Optional.of(challenge)); - AuthenticationException exception = + AuthenticationException unavailable = assertThrows( AuthenticationException.class, - () -> - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); + () -> service.authenticateForGameplay("unproved@example.com", "123456")); + assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); - assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) - .findByTenantId(7L); - verifyNoInteractions(accountTenantMembershipRepository, entityManagementClient); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(32L); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).findByAccountId(32L); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) + .delete(challenge); + verifyNoInteractions(sessionService); } @Test - void listBootstrapCharactersDoesNotUsePublicJoinForPrivateMembershipLostAfterDiscovery() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L)), Optional.empty()); - when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( - 11L, 7L, "demo", "production")) - .thenReturn(true); - var privateRealm = - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("production") - .setDisplayName("Private Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(false) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build(); - when(gameSessionClient.listGameplayRealms("demo")).thenReturn(java.util.List.of(privateRealm)); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) - .thenReturn( - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug("demo") - .setWorldDisplayName("Demo World") - .setRealmSlug("production") - .setRealmDisplayName("Private Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(false) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build()); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + void emailLoginOtpVerificationFailsClosedForUnknownEmail() { + when(accountRepository.findByEmail("unknown@example.com")).thenReturn(Optional.empty()); AuthenticationException exception = assertThrows( AuthenticationException.class, - () -> - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); + () -> service.verifyEmailLoginOtp("unknown@example.com", "123456")); - assertEquals("NON_PUBLIC_ENROLLMENT_REQUIRED", exception.getCode()); - assertEquals( - "Existing game membership is required for this non-public realm", exception.getMessage()); - verifyNoInteractions(entityManagementClient); + assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, exception.getCode()); + verifyNoInteractions(accountEmailLoginChallengeRepository, sessionService); } @Test - void listBootstrapCharactersRejectsAmbiguousRealmBeforeAdmissionFiltering() { + void emailLoginOtpVerificationLocksChallengeBeforeConsumingIt() { Account account = new Account(); - account.setId(11L); + account.setId(9L); setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - var visibleRealm = - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("production") - .setDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build(); - var hiddenDuplicate = - visibleRealm.toBuilder().setVisible(false).setPublicProductionRealm(false).build(); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn(java.util.List.of(visibleRealm, hiddenDuplicate)); - - AuthenticationException ex = - assertThrows( - AuthenticationException.class, - () -> - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); + account.setEmail("verified@example.com"); + account.setRole("player"); + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = + new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); + challenge.setId(5L); + challenge.setAccountId(9L); + challenge.setCodeHash(hash("123456")); + challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(10)); + challenge.setInvalidAttemptCount(0); + when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); + when(accountEmailLoginChallengeRepository.findByAccountId(9L)) + .thenReturn(Optional.of(challenge)); - assertEquals("ADMISSION_POINTER_UNAVAILABLE", ex.getCode()); - verifyNoInteractions(entityManagementClient); - } + AuthenticationResult result = service.verifyEmailLoginOtp("verified@example.com", "123456"); - @Test - void listBootstrapCharactersSkipsMalformedUnrelatedRealm() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - var visibleRealm = - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("production") - .setDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build(); - var malformedUnrelatedRealm = - visibleRealm.toBuilder().setRealmSlug("broken").setTenantId("bad").build(); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn(java.util.List.of(malformedUnrelatedRealm, visibleRealm)); - - var characters = - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "demo", "production", connectScopeId); - - assertTrue(characters.isEmpty()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); + var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); + assertEquals("account-service", claims.getAudience().iterator().next()); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); + org.mockito.InOrder inOrder = org.mockito.Mockito.inOrder(accountEmailLoginChallengeRepository); + inOrder.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(9L); + inOrder.verify(accountEmailLoginChallengeRepository).findByAccountId(9L); + inOrder.verify(accountEmailLoginChallengeRepository).delete(challenge); } @Test - void listBootstrapRealmsIncludesRealmStatePolicy() { + void authenticateReturnsControlUiTokenWithoutGameplayMembership() { Account account = new Account(); - account.setId(11L); + account.setId(1L); setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - var realms = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); + AuthenticationResult result = service.authenticate("demo", "password"); - assertEquals(1, realms.size()); - assertEquals(REALM_ID, realms.getFirst().realmId()); - var scopeClaims = - new JwtUtil(JWT_SECRET, 300000L) - .parseToken(realms.getFirst().connectScopeId()) - .getPayload(); - assertEquals(account.getAccountUuid().toString(), scopeClaims.getSubject()); - assertEquals(account.getAccountUuid().toString(), scopeClaims.get("accountId", String.class)); - assertEquals( - REALM_ID, - new JwtUtil(JWT_SECRET, 300000L) - .parseToken(realms.getFirst().connectScopeId()) - .getPayload() - .get("realmId")); - assertEquals("SHARED", realms.getFirst().stateScope()); - assertEquals(23L, realms.getFirst().catalogRevision()); - assertEquals(PLAYABLE_STATE_NAMESPACE_ID, realms.getFirst().playableStateNamespaceId()); - assertEquals("PLAYABLE_STATE_SCOPE_SHARED", realms.getFirst().playableStateScope()); - assertEquals("ALLOW_NEW", realms.getFirst().characterCreationPolicy()); + assertNotNull(result.authToken()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); + var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); + assertEquals("control-ui", claims.getAudience().iterator().next()); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); + assertEquals(java.util.List.of(), claims.get("globalRoles")); + assertNotNull(claims.get("jti")); + assertFalse(claims.containsKey("tenantId")); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession(1L, result.authToken(), 3600000L); + verifyNoInteractions(accountTenantMembershipRepository); } @ParameterizedTest - @ValueSource( - strings = { - "shared-live", - "C6ED6A44-C7E7-4F18-81FC-078A74E67C07", - "c6ed6a44c7e74f1881fc078a74e67c07" - }) - void listBootstrapRealmsRejectsNoncanonicalPlayableStateNamespaceIdFromReachableRealm( - String namespaceId) { + @CsvSource({ + "SECURITY_LOCKED, AUTH_ACCOUNT_LOCKED", + "DEACTIVATED_PENDING_DELETE, AUTH_INVALID_CREDENTIALS", + "DELETED, AUTH_INVALID_CREDENTIALS" + }) + void authenticateRejectsIneligibleLifecycleState( + AccountLifecycleState lifecycleState, String expectedCode) { Account account = new Account(); - account.setId(11L); + account.setId(1L); setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); + account.setLifecycleState(lifecycleState); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("production") - .setDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(namespaceId) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); - - assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); - verifyNoInteractions(accountConnectScopeRepository); - } - - @Test - void listBootstrapRealmsReadsFreshEntitlementsAndReusesVerifiedAccountIdentity() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("production") - .setDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build(), - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("preview") - .setDisplayName("Private Preview Realm") - .setTenantId("7") - .setGameInstanceId("45") - .setRealmId("ce814357-64ad-44e8-b004-828a9ae37c13") - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(18L) - .setVisible(true) - .setPublicProductionRealm(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( - 11L, 7L, "demo", "preview")) - .thenReturn(true); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "preview")) - .thenReturn( - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug("demo") - .setWorldDisplayName("Demo World") - .setRealmSlug("preview") - .setRealmDisplayName("Private Preview Realm") - .setTenantId("7") - .setGameInstanceId("45") - .setRealmId("ce814357-64ad-44e8-b004-828a9ae37c13") - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(18L) - .setVisible(true) - .setPublicProductionRealm(false) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build()); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - - var firstCall = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(1)) - .findByTenantId(7L); - org.mockito.Mockito.clearInvocations(accountRepository); - var secondCall = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); - - assertEquals(2, firstCall.size()); - assertEquals(2, secondCall.size()); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) - .findByTenantId(7L); - org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.times(1 + secondCall.size())) - .findByAccountUuid(account.getAccountUuid()); - org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()).findById(11L); - JwtUtil tokenReader = new JwtUtil(JWT_SECRET, 3600000L); - for (var realm : secondCall) { - var claims = tokenReader.parseToken(realm.connectScopeId()).getPayload(); - assertEquals(account.getAccountUuid().toString(), claims.getSubject()); - assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); - } - } + assertThrows(AuthenticationException.class, () -> service.authenticate("demo", "password")); - @Test - void listBootstrapWorldsReadsFreshEntitlementsOncePerTenantPerInvocation() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(gameSessionClient.listGameplayWorlds()) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() - .setWorldSlug("demo") - .setDisplayName("Demo World") - .build(), - net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() - .setWorldSlug("sandbox") - .setDisplayName("Sandbox World") - .build())); - when(gameSessionClient.listGameplayRealms("sandbox")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("sandbox") - .setRealmSlug("production") - .setDisplayName("Sandbox Realm") - .setTenantId("7") - .setGameInstanceId("45") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(18L) - .setVisible(true) - .setPublicProductionRealm(true) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - - var firstCall = service.listBootstrapWorlds(bootstrap.bootstrapToken()); - var secondCall = service.listBootstrapWorlds(bootstrap.bootstrapToken()); - - assertEquals(2, firstCall.size()); - assertEquals(2, secondCall.size()); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) - .findByTenantId(7L); + assertEquals(expectedCode, exception.getCode()); + verifyNoInteractions(sessionService); } @Test - void listBootstrapWorldsOmitsCanceledTenantAndFailsWhenEntitlementIsUnavailable() { + void authenticateForGameplayReturnsTokenWhenPasswordMatches() { Account account = new Account(); - account.setId(11L); + account.setId(1L); setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); + account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - Subscription activeDemo = new Subscription(); - activeDemo.setId(1L); - activeDemo.setTenantId(7L); - activeDemo.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(activeDemo)); - when(gameSessionClient.listGameplayWorlds()) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() - .setWorldSlug("demo") - .setDisplayName("Demo World") - .build(), - net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() - .setWorldSlug("sandbox") - .setDisplayName("Sandbox World") - .build())); - when(gameSessionClient.listGameplayRealms("sandbox")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("sandbox") - .setRealmSlug("production") - .setDisplayName("Sandbox Realm") - .setTenantId("8") - .setGameInstanceId("45") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID_TENANT_8) - .setCatalogRevision(23L) - .setPointerVersion(18L) - .setVisible(true) - .setPublicProductionRealm(true) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - Subscription canceledSandbox = new Subscription(); - canceledSandbox.setId(2L); - canceledSandbox.setTenantId(8L); - canceledSandbox.setStatus("canceled"); - when(subscriptionRepository.findByTenantId(8L)).thenReturn(java.util.List.of(canceledSandbox)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - - var worldsWithCanceledTenant = service.listBootstrapWorlds(bootstrap.bootstrapToken()); - - assertEquals( - java.util.List.of("demo"), - worldsWithCanceledTenant.stream().map(world -> world.worldSlug()).toList()); - - when(subscriptionRepository.findByTenantId(8L)).thenReturn(java.util.List.of()); - AuthenticationException unavailableSandbox = - assertThrows( - AuthenticationException.class, - () -> service.listBootstrapWorlds(bootstrap.bootstrapToken())); - - assertEquals("ENTITLEMENT_UNAVAILABLE", unavailableSandbox.getCode()); - - Subscription activeSandbox = new Subscription(); - activeSandbox.setId(3L); - activeSandbox.setTenantId(8L); - activeSandbox.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of()); - when(subscriptionRepository.findByTenantId(8L)).thenReturn(java.util.List.of(activeSandbox)); + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); + jwtAuthProperties.setJwtSecret(null); - AuthenticationException unavailable = - assertThrows( - AuthenticationException.class, - () -> service.listBootstrapWorlds(bootstrap.bootstrapToken())); + AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "password"); - assertEquals("ENTITLEMENT_UNAVAILABLE", unavailable.getCode()); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(3)) - .findByTenantId(7L); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) - .findByTenantId(8L); + assertNotNull(result.authToken()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); + var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); + assertEquals("account-service", claims.getAudience().iterator().next()); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); + assertEquals(java.util.List.of(), claims.get("globalRoles")); + assertNotNull(claims.get("jti")); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession(1L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); + verifyNoInteractions(accountTenantMembershipRepository); } @Test - void listBootstrapRealmsPropagatesUnavailableEntitlements() { + void issuePlayerBootstrapReturnsShortLivedToken() { Account account = new Account(); - account.setId(11L); + account.setId(7L); setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); + account.setLoginAuthModes("PASSWORD"); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of()); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + jwtAuthProperties.setJwtSecret(null); - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + PlayerBootstrapResult result = service.issuePlayerBootstrap("demo", "password"); - assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); + assertNotNull(result.bootstrapToken()); + assertNotNull(result.issuedAt()); + assertNotNull(result.expiresAt()); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession( + org.mockito.ArgumentMatchers.eq(7L), + org.mockito.ArgumentMatchers.eq(result.bootstrapToken()), + org.mockito.ArgumentMatchers.eq(300000L)); + var claims = new JwtUtil(JWT_SECRET, 300000L).parseToken(result.bootstrapToken()).getPayload(); + assertEquals("player-bootstrap", claims.getAudience().iterator().next()); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); + assertFalse(claims.containsKey("tenantId")); + assertEquals(300000L, claims.getExpiration().getTime() - claims.getIssuedAt().getTime()); + org.mockito.Mockito.verify(accountRepository).findByAccountUuid(account.getAccountUuid()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .isAccountSessionActive( + org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyString()); + verifyNoInteractions(accountEmailLoginChallengeRepository); } - @Test - void listBootstrapWorldsFailsInsteadOfReturningIncompleteWorldDiscovery() { + @ParameterizedTest + @EnumSource(InvalidAuthenticationIdentity.class) + void issuePlayerBootstrapRejectsUnprovedIdentityBeforeConsumingOtpOrMinting( + InvalidAuthenticationIdentity invalidIdentity) { Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); + account.setId(50L); account.setUsername("demo"); - account.setPasswordHash(hash("password")); + account.setLoginAuthModes("EMAIL_OTP"); + assignInvalidAuthenticationIdentity(account, invalidIdentity); + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = + new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); + challenge.setAccountId(50L); + challenge.setCodeHash(hash("123456")); + challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(gameSessionClient.listGameplayWorlds()) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() - .setWorldSlug("demo") - .setDisplayName("Demo World") - .build(), - net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() - .setWorldSlug("sandbox") - .setDisplayName("Sandbox World") - .build())); - when(gameSessionClient.listGameplayRealms("sandbox")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("sandbox") - .setRealmSlug("production") - .setDisplayName("Sandbox Realm") - .setTenantId("8") - .setGameInstanceId("45") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID_TENANT_8) - .setCatalogRevision(23L) - .setPointerVersion(18L) - .setVisible(true) - .setPublicProductionRealm(true) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of()); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + when(accountEmailLoginChallengeRepository.findByAccountId(50L)) + .thenReturn(Optional.of(challenge)); AuthenticationException unavailable = assertThrows( - AuthenticationException.class, - () -> service.listBootstrapWorlds(bootstrap.bootstrapToken())); + AuthenticationException.class, () -> service.issuePlayerBootstrap("demo", "123456")); + assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); - assertEquals("ENTITLEMENT_UNAVAILABLE", unavailable.getCode()); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(1)) - .findByTenantId(7L); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.never()) - .findByTenantId(8L); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(50L); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).findByAccountId(50L); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) + .delete(challenge); + verifyNoInteractions(sessionService); } @Test - void listBootstrapRealmsRethrowsOtherAuthenticationErrors() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("preview") - .setDisplayName("Private Preview Realm") - .setTenantId("7") - .setGameInstanceId("45") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(18L) - .setVisible(true) - .setPublicProductionRealm(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - AuthenticationException authorityError = - new AuthenticationException("AUTH_UNAVAILABLE", "Membership authority is unavailable"); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenThrow(authorityError); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + void issuePlayerBootstrapPrefersEmailLookupOverCollidingUsername() { + Account emailAccount = new Account(); + emailAccount.setId(7L); + setPersistedAuthenticationIdentity(emailAccount); + emailAccount.setUsername("email-owner"); + emailAccount.setEmail("player@example.com"); + emailAccount.setPasswordHash(hash("password")); + emailAccount.setLoginAuthModes("PASSWORD"); + when(accountRepository.findByEmail("player@example.com")).thenReturn(Optional.of(emailAccount)); - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + PlayerBootstrapResult result = + service.issuePlayerBootstrap(" PLAYER@EXAMPLE.COM ", "password"); - assertEquals("AUTH_UNAVAILABLE", exception.getCode()); + assertEquals(emailAccount.getAccountUuid().toString(), result.accountId()); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) + .findByUsername(org.mockito.ArgumentMatchers.anyString()); } @Test - void listBootstrapRealmsRejectsRealmWithMalformedTenantId() { + void issuePlayerBootstrapAcceptsAndConsumesEmailLoginOtp() { Account account = new Account(); - account.setId(11L); + account.setId(7L); setPersistedAuthenticationIdentity(account); account.setUsername("demo"); - account.setPasswordHash(hash("password")); + account.setEmail("demo@example.com"); + account.setLoginAuthModes("EMAIL_OTP"); + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = + new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); + challenge.setAccountId(7L); + challenge.setCodeHash(hash("123456")); + challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("broken") - .setDisplayName("Broken Realm") - .setTenantId("bad") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build(), - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("production") - .setDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + when(accountEmailLoginChallengeRepository.findByAccountId(7L)) + .thenReturn(Optional.of(challenge)); - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + PlayerBootstrapResult result = service.issuePlayerBootstrap("demo", "123456"); - assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); + org.mockito.InOrder inOrder = org.mockito.Mockito.inOrder(accountEmailLoginChallengeRepository); + inOrder.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(7L); + inOrder.verify(accountEmailLoginChallengeRepository).findByAccountId(7L); + inOrder.verify(accountEmailLoginChallengeRepository).delete(challenge); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession(7L, result.bootstrapToken(), 300000L); } @Test - void listBootstrapRealmsRejectsRealmWithUnknownStateScope() { + void authenticateForGameplayUsesNormalizedEmailLookup() { Account account = new Account(); - account.setId(11L); + account.setId(1L); setPersistedAuthenticationIdentity(account); account.setUsername("demo"); + account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("production") - .setDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("UNKNOWN") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); - - assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); - } + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); - @Test - void listBootstrapCharactersUsesIsolatedRealmRoster() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); + AuthenticationResult result = + service.authenticateForGameplay(" DEMO@example.com ", "password"); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("production") - .setDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("91") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("ISOLATED") - .setCharacterCreationPolicy("COPIED_ONLY") - .build())); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) - .thenReturn( - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug("demo") - .setWorldDisplayName("Demo World") - .setRealmSlug("production") - .setRealmDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("91") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("ISOLATED") - .setCharacterCreationPolicy("COPIED_ONLY") - .build()); - net.firedevops.firemud.entitymanagement.v1.Character character = - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("char-iso-1") - .setName("ForkMara") - .setLevel(4) - .build(); - when(entityManagementClient.listCharactersByAccount( - 7L, account.getAccountUuid(), 91L, PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) - .thenReturn(java.util.List.of(character)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - - var characters = - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "demo", "production", connectScopeId); - - assertEquals(1, characters.size()); - assertEquals("char-iso-1", characters.getFirst().characterId()); - assertEquals("ForkMara", characters.getFirst().characterName()); - assertEquals("ISOLATED", characters.getFirst().stateScope()); - assertEquals("COPIED_ONLY", characters.getFirst().characterCreationPolicy()); + assertNotNull(result.authToken()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession(1L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); + verifyNoInteractions(accountTenantMembershipRepository); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) + .findByUsername(org.mockito.ArgumentMatchers.anyString()); } @Test - void listBootstrapCharactersRejectsAdmissionPointerWithMalformedGameInstanceId() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) - .thenReturn( - admissionPointer( - 7L, "demo", "production", "44", 17L, true, true, "SHARED", "ALLOW_NEW"), - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug("demo") - .setWorldDisplayName("Demo World") - .setRealmSlug("production") - .setRealmDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("bad") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build()); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - - AuthenticationException ex = + void authenticateThrowsWhenInvalid() { + when(accountRepository.findByEmail("demo")).thenReturn(Optional.empty()); + AuthenticationException exception = assertThrows( - AuthenticationException.class, - () -> - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); - - assertEquals("ADMISSION_POINTER_UNAVAILABLE", ex.getCode()); - org.mockito.Mockito.verifyNoInteractions(entityManagementClient); + AuthenticationException.class, () -> service.authenticateForGameplay("demo", "bad")); + assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, exception.getCode()); } @Test - void listBootstrapCharactersRejectsAdmissionPointerWithUnknownStateScope() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) - .thenReturn( - admissionPointer( - 7L, "demo", "production", "44", 17L, true, true, "SHARED", "ALLOW_NEW"), - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug("demo") - .setWorldDisplayName("Demo World") - .setRealmSlug("production") - .setRealmDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("UNKNOWN") - .setCharacterCreationPolicy("ALLOW_NEW") - .build()); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + void authenticateDoesNotUseGlobalAccountFallback() { + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.empty()); AuthenticationException exception = assertThrows( AuthenticationException.class, - () -> - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); + () -> service.authenticateForGameplay("demo@example.com", "password")); - assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); - verifyNoInteractions(entityManagementClient); + assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, exception.getCode()); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) + .findByUsername(org.mockito.ArgumentMatchers.anyString()); } @Test - void listBootstrapCharactersUsesWorldQualifiedPointerLookupWhenRealmSlugDuplicatesAcrossWorlds() { + void authenticateAllowsGlobalIdentityWithoutTenantMembership() { Account account = new Account(); - account.setId(11L); + account.setId(7L); setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); + account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - - when(gameSessionClient.listGameplayRealms("sandbox")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("sandbox") - .setRealmSlug("production") - .setDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("91") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("ISOLATED") - .setCharacterCreationPolicy("COPIED_ONLY") - .build())); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) - .thenReturn( - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug("demo") - .setWorldDisplayName("Demo World") - .setRealmSlug("production") - .setRealmDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build()); - when(gameSessionClient.getAdmissionPointer(7L, "sandbox", "production")) - .thenReturn( - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug("sandbox") - .setWorldDisplayName("Builder Sandbox") - .setRealmSlug("production") - .setRealmDisplayName("Live Realm") - .setTenantId("7") - .setGameInstanceId("91") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setRequiresCharacterSelection(false) - .setStateScope("ISOLATED") - .setCharacterCreationPolicy("COPIED_ONLY") - .build()); - net.firedevops.firemud.entitymanagement.v1.Character character = - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("char-sandbox-1") - .setName("BuilderMara") - .setLevel(9) - .build(); - when(entityManagementClient.listCharactersByAccount( - 7L, account.getAccountUuid(), 91L, PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) - .thenReturn(java.util.List.of(character)); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service - .listBootstrapRealms(bootstrap.bootstrapToken(), "sandbox") - .getFirst() - .connectScopeId(); - - var characters = - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "sandbox", "production", connectScopeId); - - assertEquals(1, characters.size()); - assertEquals("char-sandbox-1", characters.getFirst().characterId()); - assertEquals("BuilderMara", characters.getFirst().characterName()); - assertEquals("ISOLATED", characters.getFirst().stateScope()); - org.mockito.Mockito.verify(gameSessionClient, org.mockito.Mockito.times(2)) - .getAdmissionPointer(7L, "sandbox", "production"); - } + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); + AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "password"); - @Test - void listBootstrapCharactersUsesSignedScopeToDisambiguateTenantIdentity() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId( - org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyLong())) - .thenReturn(Optional.of(membership(account, 7L))); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("production") - .setDisplayName("Tenant Seven") - .setTenantId("7") - .setGameInstanceId("44") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build(), - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("production") - .setDisplayName("Tenant Eight") - .setTenantId("8") - .setGameInstanceId("45") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID_TENANT_8) - .setCatalogRevision(23L) - .setPointerVersion(18L) - .setVisible(true) - .setPublicProductionRealm(true) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) - .thenReturn( - admissionPointer( - 7L, "demo", "production", "44", 17L, true, true, "SHARED", "ALLOW_NEW")); - when(gameSessionClient.getAdmissionPointer(8L, "demo", "production")) - .thenReturn( - admissionPointer( - 8L, "demo", "production", "45", 18L, true, true, "SHARED", "ALLOW_NEW")); - when(entityManagementClient.listCharactersByAccount( - 7L, account.getAccountUuid(), 44L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .thenReturn(java.util.List.of()); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").stream() - .filter(realm -> realm.tenantId() == 7L) - .findFirst() - .orElseThrow() - .connectScopeId(); - - var characters = - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "demo", "production", connectScopeId); - - assertTrue(characters.isEmpty()); - org.mockito.Mockito.verify(gameSessionClient, org.mockito.Mockito.times(2)) - .getAdmissionPointer(7L, "demo", "production"); - org.mockito.Mockito.verify(gameSessionClient).getAdmissionPointer(8L, "demo", "production"); + assertEquals(account.getAccountUuid().toString(), result.accountId()); + assertNotNull(result.authToken()); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession(7L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); + verifyNoInteractions(accountTenantMembershipRepository); } @Test - void listBootstrapCharactersRejectsPathThatDoesNotMatchSignedScope() { + void getTenantMembershipForRuntimeReturnsAdmissionAllowedForExistingAccount() { Account account = new Account(); account.setId(11L); setPersistedAuthenticationIdentity(account); account.setUsername("demo"); + account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + AccountTenantMembership activeMembership = membership(account, 7L); + activeMembership.setMembershipVersion(17L); + activeMembership.setMembershipAuthorityGeneration(29L); when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + .thenReturn(Optional.of(activeMembership)); - AuthenticationException ex = - assertThrows( - AuthenticationException.class, - () -> - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "sandbox", "production", connectScopeId)); + var dto = service.getTenantMembershipForRuntime(11L, 7L, "req-1"); - assertEquals("CONNECT_SCOPE_MISMATCH", ex.getCode()); - verifyNoInteractions(entityManagementClient); + assertEquals(11L, dto.accountId()); + assertEquals(7L, dto.tenantId()); + assertTrue(dto.membershipExists()); + assertTrue(dto.gameplayAdmissionAllowed()); + assertEquals(17L, dto.membershipVersion()); + assertEquals("ACTIVE", dto.membershipLifecycleState()); + assertEquals(29L, dto.membershipAuthorityGeneration()); + assertNotNull(dto.evaluatedAt()); } @Test - void listBootstrapCharactersRejectsChangedCanonicalRealmId() { + void getTenantMembershipForRuntimeReturnsCoherentMissingMembershipForExistingAccount() { Account account = new Account(); account.setId(11L); setPersistedAuthenticationIdentity(account); account.setUsername("demo"); + account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - String connectScopeId = - service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - net.firedevops.firemud.gamesession.v1.GameplayRealm changedRealm = - gameSessionClient.listGameplayRealms("demo").getFirst().toBuilder() - .setRealmId("57c58f36-c5ea-4aa8-8ef7-91a45e407f01") - .build(); - when(gameSessionClient.listGameplayRealms("demo")).thenReturn(java.util.List.of(changedRealm)); - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer changedAdmissionPointer = - gameSessionClient.getAdmissionPointer(7L, "demo", "production").toBuilder() - .setRealmId("57c58f36-c5ea-4aa8-8ef7-91a45e407f01") - .build(); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) - .thenReturn(changedAdmissionPointer); - - AuthenticationException ex = - assertThrows( - AuthenticationException.class, - () -> - service.listBootstrapCharacters( - bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); + .thenReturn(Optional.empty()); + + var dto = service.getTenantMembershipForRuntime(11L, 7L, "req-1"); - assertEquals("CONNECT_SCOPE_MISMATCH", ex.getCode()); - verifyNoInteractions(entityManagementClient); + assertEquals(11L, dto.accountId()); + assertEquals(7L, dto.tenantId()); + assertFalse(dto.membershipExists()); + assertFalse(dto.gameplayAdmissionAllowed()); + assertEquals(0L, dto.membershipVersion()); + assertEquals("MISSING", dto.membershipLifecycleState()); + assertEquals(0L, dto.membershipAuthorityGeneration()); + assertNotNull(dto.evaluatedAt()); } @Test - void listBootstrapRealmsExcludesNonPublicRealmWithoutGrant() { + void getTenantMembershipForRuntimeReturnsInactiveMembershipWithIndependentGenerations() { Account account = new Account(); account.setId(11L); setPersistedAuthenticationIdentity(account); account.setUsername("demo"); + account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + AccountTenantMembership inactiveMembership = membership(account, 7L); + inactiveMembership.setGameplayAdmissionAllowed(false); + inactiveMembership.setLifecycleState("INACTIVE"); + inactiveMembership.setMembershipVersion(23L); + inactiveMembership.setMembershipAuthorityGeneration(41L); when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.empty()); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("preview") - .setDisplayName("Preview Realm") - .setTenantId("7") - .setGameInstanceId("55") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(19L) - .setVisible(false) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "preview")) - .thenReturn( - admissionPointer( - 7L, "demo", "preview", "55", 19L, false, false, "SHARED", "ALLOW_NEW")); - - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + .thenReturn(Optional.of(inactiveMembership)); - var realms = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); + var dto = service.getTenantMembershipForRuntime(11L, 7L, "req-1"); - assertEquals(0, realms.size()); + assertEquals(11L, dto.accountId()); + assertEquals(7L, dto.tenantId()); + assertTrue(dto.membershipExists()); + assertFalse(dto.gameplayAdmissionAllowed()); + assertEquals(23L, dto.membershipVersion()); + assertEquals("INACTIVE", dto.membershipLifecycleState()); + assertEquals(41L, dto.membershipAuthorityGeneration()); + assertNotNull(dto.evaluatedAt()); } - @ParameterizedTest - @CsvSource({"true, false", "false, true"}) - void listBootstrapRealmsExcludesNonPublicRealmWithoutMembershipEvenWithGrant( - boolean visible, boolean publicProductionRealm) { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.empty()); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("preview") - .setDisplayName("Preview Realm") - .setTenantId("7") - .setGameInstanceId("55") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(19L) - .setVisible(visible) - .setPublicProductionRealm(publicProductionRealm) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "preview")) - .thenReturn( - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug("demo") - .setWorldDisplayName("Demo World") - .setRealmSlug("preview") - .setRealmDisplayName("Preview Realm") - .setTenantId("7") - .setGameInstanceId("55") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(19L) - .setVisible(visible) - .setPublicProductionRealm(publicProductionRealm) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build()); - when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( - 11L, 7L, "demo", "preview")) - .thenReturn(true); + @Test + void getTenantMembershipForRuntimeRejectsMissingAccount() { + when(accountRepository.findById(11L)).thenReturn(Optional.empty()); - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - assertTrue(service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").isEmpty()); + assertThrows( + IllegalArgumentException.class, + () -> service.getTenantMembershipForRuntime(11L, 7L, "req-1")); } - @ParameterizedTest - @CsvSource({"true, false", "false, true"}) - void listBootstrapRealmsIncludesNonPublicRealmWhenMembershipAndGrantPresent( - boolean visible, boolean publicProductionRealm) { + @Test + void getTenantMembershipForRuntimeRejectsCrossTenantAccount() { Account account = new Account(); account.setId(11L); setPersistedAuthenticationIdentity(account); account.setUsername("demo"); + account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); - when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); - Subscription active = new Subscription(); - active.setId(22L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - when(gameSessionClient.listGameplayRealms("demo")) - .thenReturn( - java.util.List.of( - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("preview") - .setDisplayName("Preview Realm") - .setTenantId("7") - .setGameInstanceId("55") - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) - .setPointerVersion(19L) - .setVisible(visible) - .setPublicProductionRealm(publicProductionRealm) - .setRequiresCharacterSelection(false) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build())); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "preview")) - .thenReturn( - admissionPointer( - 7L, - "demo", - "preview", - "55", - 19L, - visible, - publicProductionRealm, - "SHARED", - "ALLOW_NEW")); - when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( - 11L, 7L, "demo", "preview")) - .thenReturn(true); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + + var dto = service.getTenantMembershipForRuntime(11L, 7L, "req-1"); - PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); - when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + assertEquals(11L, dto.accountId()); + assertEquals(7L, dto.tenantId()); + assertTrue(!dto.membershipExists()); + assertTrue(!dto.gameplayAdmissionAllowed()); + } - var realms = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); + @Test + void getTenantEntitlementsForRuntimeFailsClosedBeforeReadingLegacyEvidence() { + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.getTenantEntitlementsForRuntime(7L, "req-current-entitlement")); - assertEquals(1, realms.size()); - assertEquals("preview", realms.getFirst().realmSlug()); - assertFalse(realms.getFirst().connectScopeId().isBlank()); + assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + verifyNoInteractions(retainedSubscriptionEvidenceRepository); } @Test @@ -6280,29 +1740,37 @@ void exportTenantDataUsesPublicAccountUuidAndRetainsTenantLocalFields() { void deleteAccountRefusesNonterminalSubscription() { Account account = new Account(); account.setId(2L); - Subscription subscription = new Subscription(); - subscription.setStatus("active"); - subscription.setAccount(account); - subscription.setTenantId(7L); + RetainedSubscriptionEvidence subscription = + new RetainedSubscriptionEvidence( + 91L, 2L, "unqualified", "active", null, null, 7L, 19L, UUID.randomUUID()); when(accountRepository.findById(2L)).thenReturn(Optional.of(account)); - when(subscriptionRepository.findByAccountId(2L)).thenReturn(java.util.List.of(subscription)); + when(retainedSubscriptionEvidenceRepository.findHistoryByAccountId(2L)) + .thenReturn(java.util.List.of(subscription)); AccountLifecycleException ex = assertThrows(AccountLifecycleException.class, () -> service.deleteAccount(2L)); assertEquals("ACCOUNT_DELETE_ACTIVE_BILLING_OWNER", ex.getCode()); + org.mockito.Mockito.verify(retainedSubscriptionEvidenceRepository).findHistoryByAccountId(2L); } @Test void deleteAccountRemainsUnavailableAfterTerminalSubscriptionsWithoutChildWrites() { Account account = new Account(); account.setId(2L); - Subscription subscription = new Subscription(); - subscription.setStatus("canceled"); - subscription.setEndedAt(java.time.LocalDateTime.now()); - subscription.setAccount(account); - subscription.setTenantId(7L); + RetainedSubscriptionEvidence subscription = + new RetainedSubscriptionEvidence( + 91L, + 2L, + "unqualified", + "canceled", + null, + java.time.LocalDateTime.now(), + 7L, + 19L, + UUID.randomUUID()); when(accountRepository.findById(2L)).thenReturn(Optional.of(account)); - when(subscriptionRepository.findByAccountId(2L)).thenReturn(java.util.List.of(subscription)); + when(retainedSubscriptionEvidenceRepository.findHistoryByAccountId(2L)) + .thenReturn(java.util.List.of(subscription)); AccountLifecycleException ex = assertThrows(AccountLifecycleException.class, () -> service.deleteAccount(2L)); @@ -6316,9 +1784,7 @@ void deleteAccountRemainsUnavailableAfterTerminalSubscriptionsWithoutChildWrites paymentTransactionRepository, profileRepository, accountTenantMembershipRepository); - org.mockito.Mockito.verify(subscriptionRepository).findByAccountId(2L); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.never()) - .deleteByAccountId(2L); + org.mockito.Mockito.verify(retainedSubscriptionEvidenceRepository).findHistoryByAccountId(2L); org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()).delete(account); } @@ -6932,14 +2398,6 @@ void updateLoginAuthModesFailsClosedBeforeReadingOrPersistingAccount() { org.mockito.Mockito.verifyNoInteractions(accountRepository); } - private Account directTextAccount() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - return account; - } - private void setPersistedAuthenticationIdentity(Account account) { setPersistedAuthenticationIdentity( account, AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); @@ -6975,31 +2433,6 @@ private enum InvalidAuthenticationIdentity { CONTRADICTORY_SOURCE_ROW } - private static DirectTextCallerContext directTextCaller() { - return new DirectTextCallerContext( - 11L, - 7L, - UUID.fromString(REALM_ID), - PLAYABLE_STATE_NAMESPACE_ID, - "SHARED", - 44L, - "session-1", - "direct-text-request-1"); - } - - private static DirectTextJoinTarget directTextTarget() { - return new DirectTextJoinTarget( - 7L, - UUID.fromString(REALM_ID), - "demo", - "production", - PLAYABLE_STATE_NAMESPACE_ID, - "SHARED", - 44L, - 23L, - 17L); - } - private static String hash(String password) { Argon2 argon2 = Argon2Factory.create(); char[] chars = password.toCharArray(); @@ -7010,47 +2443,6 @@ private static String hash(String password) { } } - private static net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer admissionPointer( - long tenantId, - String worldSlug, - String realmSlug, - String gameInstanceId, - long pointerVersion, - boolean visible, - boolean publicProductionRealm, - String stateScope, - String characterCreationPolicy) { - return net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug(worldSlug) - .setWorldDisplayName("demo".equals(worldSlug) ? "Demo World" : "Builder Sandbox") - .setRealmSlug(realmSlug) - .setRealmDisplayName("production".equals(realmSlug) ? "Live Realm" : "Preview Realm") - .setTenantId(Long.toString(tenantId)) - .setGameInstanceId(gameInstanceId) - .setRealmId(REALM_ID) - .setPlayableStateNamespaceId(playableStateNamespaceIdForTenant(tenantId)) - .setCatalogRevision(23L) - .setPointerVersion(pointerVersion) - .setVisible(visible) - .setPublicProductionRealm(publicProductionRealm) - .setRequiresCharacterSelection(false) - .setStateScope(stateScope) - .setCharacterCreationPolicy(characterCreationPolicy) - .build(); - } - - private static String playableStateNamespaceIdForTenant(long tenantId) { - return switch ((int) tenantId) { - case 7 -> PLAYABLE_STATE_NAMESPACE_ID; - case 8 -> PLAYABLE_STATE_NAMESPACE_ID_TENANT_8; - default -> - UUID.nameUUIDFromBytes( - ("playable-state-namespace-" + tenantId) - .getBytes(java.nio.charset.StandardCharsets.UTF_8)) - .toString(); - }; - } - private static AccountTenantMembership membership(Account account, long tenantId) { AccountTenantMembership membership = new AccountTenantMembership(); membership.setId(tenantId * 100 + (account.getId() == null ? 0L : account.getId())); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/LegacySubscriptionContainmentTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/LegacySubscriptionContainmentTest.java new file mode 100644 index 0000000000..a7236525c6 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/LegacySubscriptionContainmentTest.java @@ -0,0 +1,175 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.stub.StreamObserver; +import java.lang.reflect.Modifier; +import java.time.LocalDateTime; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeRequest; +import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.RetainedSubscriptionEvidence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; +import net.firedevops.firemud.accountservice.service.exception.AccountLifecycleException; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.transaction.PlatformTransactionManager; + +/** + * Local containment only; canonical positive producer and admission remain separate obligations. + */ +class LegacySubscriptionContainmentTest { + @Mock private AccountRepository accounts; + @Mock private AccountJoinOperationRepository joins; + @Mock private RetainedSubscriptionEvidenceRepository retained; + @Mock private AccountAuthorityOutboxRepository outbox; + @Mock private AccountPasswordResetOperationRepository resets; + @Mock private AccountLogoutAllOperationRepository logouts; + @Mock private AccountSecurityStateOperationRepository security; + @Mock private PlatformTransactionManager transactions; + @InjectMocks private AccountServiceImpl service; + private AutoCloseable mocks; + + @BeforeEach + void setUp() { + mocks = MockitoAnnotations.openMocks(this); + } + + @AfterEach + void tearDown() throws Exception { + mocks.close(); + } + + @ParameterizedTest + @ValueSource(strings = {"active", "trialing", "past_due", "grace", "canceled"}) + void retainedStatusAndCountersCannotProduceAPositiveServiceOrRuntimeRpc(String status) { + when(retained.findHistoryByAccountId(2L)).thenReturn(List.of(evidence(status, null))); + + AuthenticationException denied = + assertThrows( + AuthenticationException.class, + () -> service.getTenantEntitlementsForRuntime(7L, "retained-is-not-authority")); + assertThat(denied.getCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + + AccountGrpcService rpc = new AccountGrpcService(null, service, null, "test"); + AtomicReference response = new AtomicReference<>(); + var observer = + new StreamObserver() { + @Override + public void onNext(GetTenantEntitlementsForRuntimeResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable failure) { + throw new AssertionError( + "Expected the existing response-level unavailable outcome", failure); + } + + @Override + public void onCompleted() {} + }; + for (String workload : List.of("game-session-service", "world-management-service")) { + Context context = + Context.ROOT.withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity("spiffe://firemud/ns/test/sa/" + workload, "test", workload)); + context.run( + () -> + rpc.getTenantEntitlementsForRuntime( + GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("7") + .setRequestId("retained-is-not-authority") + .build(), + observer)); + assertThat(response.get()).isNotNull(); + assertThat(response.get().getError().getCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + assertThat(response.get().getGameplayAvailable()).isFalse(); + assertThat(response.get().getAllowPublicJoin()).isFalse(); + assertThat(response.get().getEntitlementVersion()).isZero(); + assertThat(response.get().getTenantBillingSequence()).isZero(); + assertThat(response.get().getEvaluatedAt()).isEmpty(); + } + verifyNoInteractions( + retained, accounts, joins, outbox, resets, logouts, security, transactions); + } + + @ParameterizedTest + @CsvSource({ + "active,false,ACCOUNT_DELETE_ACTIVE_BILLING_OWNER", + "canceled,false,ACCOUNT_DELETE_ACTIVE_BILLING_OWNER", + "canceled,true,ACCOUNT_DELETE_UNAVAILABLE", + "expired,true,ACCOUNT_DELETE_UNAVAILABLE" + }) + void deletionStillReadsHistoricalBlockersAndNeverGainsErasureAuthority( + String status, boolean ended, String expectedCode) { + Account account = new Account(); + account.setId(2L); + when(accounts.findById(2L)).thenReturn(Optional.of(account)); + when(retained.findHistoryByAccountId(2L)) + .thenReturn(List.of(evidence(status, ended ? LocalDateTime.of(2025, 1, 2, 3, 4) : null))); + + AccountLifecycleException denied = + assertThrows(AccountLifecycleException.class, () -> service.deleteAccount(2L)); + + assertThat(denied.getCode()).isEqualTo(expectedCode); + verify(retained).findHistoryByAccountId(2L); + verify(joins).hasRetainedOperation(2L); + verifyNoInteractions(outbox, resets, logouts, security, transactions); + } + + @Test + void retainedJoinReceiptKeepsItsEarlierDeletionDenialBeforeHistoricalBillingReads() { + Account account = new Account(); + account.setId(2L); + when(accounts.findById(2L)).thenReturn(Optional.of(account)); + when(joins.hasRetainedOperation(2L)).thenReturn(true); + + AccountLifecycleException denied = + assertThrows(AccountLifecycleException.class, () -> service.deleteAccount(2L)); + + assertThat(denied.getCode()).isEqualTo("ACCOUNT_DELETE_JOIN_RECEIPT_RETAINED"); + verifyNoInteractions(retained, outbox, resets, logouts, security, transactions); + } + + @Test + void historicalOwnerHasNoGenericMutationOrCurrentTenantAuthorityApi() { + assertThat(RetainedSubscriptionEvidence.class.isRecord()).isTrue(); + assertThat( + Arrays.stream(RetainedSubscriptionEvidenceRepository.class.getDeclaredMethods()) + .filter(method -> Modifier.isPublic(method.getModifiers())) + .map(method -> method.getName()) + .toList()) + .containsExactly("findHistoryByAccountId"); + } + + private static RetainedSubscriptionEvidence evidence(String status, LocalDateTime ended) { + return new RetainedSubscriptionEvidence( + 91L, 2L, "unqualified", status, null, ended, 7L, 19L, UUID.randomUUID()); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java index a6452f228b..ae2986a85d 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java @@ -11,7 +11,6 @@ import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.PaymentTransactionRepository; -import net.firedevops.firemud.accountservice.repository.SubscriptionRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -22,7 +21,6 @@ class PaymentServiceImplTest { @Mock private AccountRepository accountRepository; @Mock private AccountTenantMembershipRepository membershipRepository; @Mock private PaymentTransactionRepository txRepo; - @Mock private SubscriptionRepository subRepo; @Mock private StripeClient stripeClient; private PaymentServiceImpl service; @@ -30,9 +28,7 @@ class PaymentServiceImplTest { @BeforeEach void setup() { MockitoAnnotations.openMocks(this); - service = - new PaymentServiceImpl( - accountRepository, membershipRepository, txRepo, subRepo, stripeClient); + service = new PaymentServiceImpl(accountRepository, membershipRepository, txRepo, stripeClient); } @Test @@ -71,7 +67,7 @@ void createSubscriptionFailsBeforeCheckingMembershipOrMutatingAnything() { assertThrows(IllegalStateException.class, () -> service.createSubscription(2L, 1L, "plan")); assertEquals("Subscription creation is unavailable", error.getMessage()); - verifyNoInteractions(accountRepository, membershipRepository, txRepo, subRepo, stripeClient); + verifyNoInteractions(accountRepository, membershipRepository, txRepo, stripeClient); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierTest.java index cde168fd95..86c606f8ee 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierTest.java @@ -39,6 +39,7 @@ import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.GameplayLoginReplayState; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.accountservice.service.session.AccountGameplayCanonicalLoginOwner; @@ -107,8 +108,6 @@ class AccountGameplayPrimaryCredentialVerifierTest { net.firedevops.firemud.accountservice.service .AccountPasswordResetDraftSourceChangeRepository.class), mock(net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository.class), - mock( - net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository.class), mock( net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository .class), @@ -124,7 +123,7 @@ class AccountGameplayPrimaryCredentialVerifierTest { mock(net.firedevops.firemud.accountservice.repository.ProfileRepository.class), mock(net.firedevops.firemud.accountservice.mapper.ProfileMapper.class), mock(net.firedevops.firemud.accountservice.repository.PaymentTransactionRepository.class), - mock(net.firedevops.firemud.accountservice.repository.SubscriptionRepository.class), + org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), mock(net.firedevops.firemud.accountservice.repository.ExternalAccountRepository.class), mock(net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository.class), mock( @@ -135,8 +134,6 @@ class AccountGameplayPrimaryCredentialVerifierTest { mock(net.firedevops.firemud.accountservice.config.MailProperties.class), mock(net.firedevops.firemud.accountservice.config.AccountTokenProperties.class), mock(net.firedevops.firemud.common.security.JwtAuthProperties.class), - mock(net.firedevops.firemud.accountservice.client.GameSessionClient.class), - mock(net.firedevops.firemud.accountservice.client.EntityManagementClient.class), jwt, sessions, transactions); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionServiceTest.java new file mode 100644 index 0000000000..bf51ec80e1 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionServiceTest.java @@ -0,0 +1,484 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver.ExpectedBinding; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver.ObservedSubscription; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Outcome; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ResolutionPreparation; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.TransitionResult; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionTerminalResolution.Authorization; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionTerminalResolution.AuthorizedActor; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionTerminalResolution.LockedTarget; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionTerminalResolution.Request; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.FenceRejectedException; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiActorService.AccountAuthenticatedActor; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +class AccountHostingSubscriptionTerminalResolutionServiceTest { + private static final UUID ACCOUNT = UUID.randomUUID(); + private static final UUID ISSUANCE = UUID.randomUUID(); + private static final String TOKEN_HASH = "a".repeat(64); + private static final UUID RESOLUTION = UUID.randomUUID(); + private static final UUID FAILED_REQUEST = UUID.randomUUID(); + private static final UUID CREATION = UUID.randomUUID(); + private static final UUID SUBSCRIPTION = UUID.randomUUID(); + private static final UUID TENANT = UUID.randomUUID(); + private static final UUID AUDIT = UUID.randomUUID(); + private static final String CONTROL_UI_JWT = "controlled-test-jwt"; + private static final String EMAIL = "account@example.test"; + private static final String SECRET = "test-primary-secret"; + private static final Instant NOW = Instant.parse("2026-11-03T00:00:00Z"); + + @AfterEach + void clearAmbientTransactionState() { + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void providerReadSeparatesCurrentActorCaptureFromFinalPrimaryAuthenticationAndMutation() { + Fixture fixture = new Fixture(); + AccountAuthenticatedActor actor = actor(ACCOUNT, ISSUANCE, TOKEN_HASH); + fixture.currentActors(actor, actor); + fixture.prepare(null); + fixture.observeOutsideOwnerTransaction(); + fixture.applyAfterAuthorization(ACCOUNT); + fixture.primaryAuthenticatesAs(ACCOUNT); + + TransitionResult result = fixture.service.resolve(CONTROL_UI_JWT, EMAIL, SECRET, input()); + + assertThat(result).isSameAs(fixture.committed); + assertThat(fixture.events) + .containsSubsequence( + "prepare", + "provider-read", + "current-actor-2", + "apply", + "primary-authentication", + "resolution-write"); + assertThat(fixture.commits.commits).isEqualTo(2); + assertThat(fixture.resolutionWrites.get()).isEqualTo(1); + Request request = fixture.preparedRequest.get(); + assertThat(request.actorAccountId()).isEqualTo(ACCOUNT); + assertThat(request.controlUiIssuanceOperationId()).isEqualTo(ISSUANCE); + assertThat(request.controlUiTokenHash()).isEqualTo(TOKEN_HASH); + AuthorizedActor authorized = fixture.authorizedActor.get(); + assertThat(authorized.actorAccountId()).isEqualTo(ACCOUNT); + assertThat(authorized.controlUiIssuanceOperationId()).isEqualTo(ISSUANCE); + assertThat(authorized.controlUiTokenHash()).isEqualTo(TOKEN_HASH); + assertThat(authorized.authenticatedAt()).isEqualTo(NOW); + } + + @Test + void changedCurrentAccountIssuanceOrTokenSourceCannotReachResolutionAuthorization() { + List mismatches = + List.of( + actor(UUID.randomUUID(), ISSUANCE, TOKEN_HASH), + actor(ACCOUNT, UUID.randomUUID(), TOKEN_HASH), + actor(ACCOUNT, ISSUANCE, "b".repeat(64))); + + for (AccountAuthenticatedActor changedActor : mismatches) { + Fixture fixture = new Fixture(); + fixture.currentActors(actor(ACCOUNT, ISSUANCE, TOKEN_HASH), changedActor); + fixture.prepare(null); + fixture.observeOutsideOwnerTransaction(); + fixture.applyAfterAuthorization(ACCOUNT); + + Throwable failure = + catchThrowable(() -> fixture.service.resolve(CONTROL_UI_JWT, EMAIL, SECRET, input())); + + assertThat(failure).isInstanceOf(FenceRejectedException.class); + assertThat(fixture.events).contains("provider-read", "current-actor-2"); + assertThat(fixture.resolutionWrites).hasValue(0); + verify(fixture.repository, never()) + .applyTerminalResolution( + any(ResolutionPreparation.class), any(), any(Authorization.class)); + verifyNoInteractions(fixture.primaryAuthentication); + } + } + + @Test + void unavailableCurrentActorStopsBeforeProviderOrFinalAuthorization() { + Fixture beforeProvider = new Fixture(); + beforeProvider.currentActorUnavailableOnFirstCall(); + assertThatThrownBy(() -> beforeProvider.service.resolve(CONTROL_UI_JWT, EMAIL, SECRET, input())) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions( + beforeProvider.repository, beforeProvider.observer, beforeProvider.primaryAuthentication); + + Fixture afterProvider = new Fixture(); + afterProvider.currentActorAvailableThenUnavailable(actor(ACCOUNT, ISSUANCE, TOKEN_HASH)); + afterProvider.prepare(null); + afterProvider.observeOutsideOwnerTransaction(); + afterProvider.applyAfterAuthorization(ACCOUNT); + assertThatThrownBy(() -> afterProvider.service.resolve(CONTROL_UI_JWT, EMAIL, SECRET, input())) + .isInstanceOf(IllegalStateException.class); + assertThat(afterProvider.events) + .containsSubsequence("provider-read", "final-actor-unavailable"); + assertThat(afterProvider.resolutionWrites).hasValue(0); + verifyNoInteractions(afterProvider.primaryAuthentication); + verify(afterProvider.repository, never()) + .applyTerminalResolution(any(ResolutionPreparation.class), any(), any(Authorization.class)); + } + + @Test + void wrongLockedBillingOwnerOrPrimaryAccountCannotWriteResolution() { + Fixture wrongOwner = new Fixture(); + AccountAuthenticatedActor actor = actor(ACCOUNT, ISSUANCE, TOKEN_HASH); + wrongOwner.currentActors(actor, actor); + wrongOwner.prepare(null); + wrongOwner.observeOutsideOwnerTransaction(); + wrongOwner.applyAfterAuthorization(UUID.randomUUID()); + wrongOwner.primaryAuthenticatesAs(ACCOUNT); + + assertThatThrownBy(() -> wrongOwner.service.resolve(CONTROL_UI_JWT, EMAIL, SECRET, input())) + .isInstanceOf(FenceRejectedException.class) + .hasMessageContaining("billing-owner"); + assertThat(wrongOwner.resolutionWrites).hasValue(0); + verifyNoInteractions(wrongOwner.primaryAuthentication); + + Fixture wrongPrimaryAccount = new Fixture(); + wrongPrimaryAccount.currentActors(actor, actor); + wrongPrimaryAccount.prepare(null); + wrongPrimaryAccount.observeOutsideOwnerTransaction(); + wrongPrimaryAccount.applyAfterAuthorization(ACCOUNT); + wrongPrimaryAccount.primaryAuthenticatesAs(UUID.randomUUID()); + + assertThatThrownBy( + () -> wrongPrimaryAccount.service.resolve(CONTROL_UI_JWT, EMAIL, SECRET, input())) + .isInstanceOf(FenceRejectedException.class) + .hasMessageContaining("another Account"); + assertThat(wrongPrimaryAccount.resolutionWrites).hasValue(0); + assertThat(wrongPrimaryAccount.events).contains("primary-authentication"); + } + + @Test + void deniedPrimaryAuthenticationCommitsFailureAccountingBeforeGenericErrorReturns() { + Fixture fixture = new Fixture(); + AccountAuthenticatedActor actor = actor(ACCOUNT, ISSUANCE, TOKEN_HASH); + fixture.currentActors(actor, actor); + fixture.prepare(null); + fixture.observeOutsideOwnerTransaction(); + fixture.applyAfterAuthorization(ACCOUNT); + fixture.primaryAuthenticationDenied(); + + Throwable failure = + catchThrowable(() -> fixture.service.resolve(CONTROL_UI_JWT, EMAIL, SECRET, input())); + + assertThat(failure).isInstanceOf(AuthenticationException.class); + AuthenticationException error = (AuthenticationException) failure; + assertThat(error.getCode()).isEqualTo("INVALID_CREDENTIALS"); + assertThat(error).hasMessage("Account reauthentication failed"); + assertThat(error.getCause()).isNull(); + assertThat(error.toString()).doesNotContain(EMAIL, SECRET); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(fixture.failedAttemptCommitted).isTrue(); + assertThat(fixture.commits.commits).isEqualTo(2); + assertThat(fixture.resolutionWrites).hasValue(0); + assertThat(fixture.events) + .containsSubsequence( + "primary-authentication", "current-account-return-2", "failed-login-attempt-committed"); + } + + @Test + void exactAuthenticatedReplayReturnsWithoutAnotherProviderReadOrPrimaryAuthentication() { + Fixture fixture = new Fixture(); + fixture.currentActors(actor(ACCOUNT, ISSUANCE, TOKEN_HASH)); + TransitionResult replay = new TransitionResult(RESOLUTION, Outcome.COMMITTED, 12L, null); + fixture.prepare(replay); + + TransitionResult result = fixture.service.resolve(CONTROL_UI_JWT, null, null, input()); + + assertThat(result).isSameAs(replay); + Request request = fixture.preparedRequest.get(); + assertThat(request.actorAccountId()).isEqualTo(ACCOUNT); + assertThat(request.controlUiIssuanceOperationId()).isEqualTo(ISSUANCE); + assertThat(request.controlUiTokenHash()).isEqualTo(TOKEN_HASH); + assertThat(fixture.commits.commits).isEqualTo(1); + verifyNoInteractions(fixture.observer, fixture.primaryAuthentication); + verify(fixture.repository, never()) + .applyTerminalResolution(any(ResolutionPreparation.class), any(), any(Authorization.class)); + } + + @Test + void ambientTransactionOrSynchronizationRefusesBeforeAnyCollaborator() { + Fixture fixture = new Fixture(); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> fixture.service.resolve(CONTROL_UI_JWT, EMAIL, SECRET, input())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction"); + TransactionSynchronizationManager.setActualTransactionActive(false); + + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> fixture.service.resolve(CONTROL_UI_JWT, EMAIL, SECRET, input())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction"); + verifyNoInteractions( + fixture.actors, fixture.repository, fixture.observer, fixture.primaryAuthentication); + } + + private static AccountHostingSubscriptionTerminalResolutionService.Input input() { + return new AccountHostingSubscriptionTerminalResolutionService.Input( + RESOLUTION, + FAILED_REQUEST, + CREATION, + SUBSCRIPTION, + TENANT, + 7L, + 11L, + AUDIT, + "operator-confirmed provider cancellation"); + } + + private static AccountAuthenticatedActor actor( + UUID accountId, UUID issuanceId, String tokenHash) { + AccountAuthenticatedActor actor = mock(AccountAuthenticatedActor.class); + when(actor.accountId()).thenReturn(accountId); + when(actor.issuanceOperationId()).thenReturn(issuanceId); + when(actor.tokenHash()).thenReturn(tokenHash); + return actor; + } + + private static AccountServiceImpl.ControlUiPrimaryIdentity primaryIdentity(UUID accountId) { + AccountServiceImpl.ControlUiPrimaryIdentity identity = + mock(AccountServiceImpl.ControlUiPrimaryIdentity.class); + when(identity.accountId()).thenReturn(accountId); + return identity; + } + + private static final class Fixture { + private final AccountControlUiActorService actors = mock(AccountControlUiActorService.class); + private final AccountServiceImpl primaryAuthentication = mock(AccountServiceImpl.class); + private final AccountHostingSubscriptionLifecycleRepository repository = + mock(AccountHostingSubscriptionLifecycleRepository.class); + private final StripeHostingSubscriptionObserver observer = + mock(StripeHostingSubscriptionObserver.class); + private final LocalTransactions commits = new LocalTransactions(); + private final TransactionTemplate transaction = new TransactionTemplate(commits); + private final ResolutionPreparation preparation = mock(ResolutionPreparation.class); + private final ExpectedBinding binding = + new ExpectedBinding( + "sub_provider_exact", + SUBSCRIPTION, + "cus_provider_exact", + "pm_provider_exact", + "price_hosting_exact", + 1L, + StripeHostingSubscriptionObserver.OperationType.SUBSCRIPTION_PROVISIONING, + CREATION, + true); + private final ObservedSubscription observed = mock(ObservedSubscription.class); + private final TransitionResult committed = + new TransitionResult(RESOLUTION, Outcome.COMMITTED, 12L, null); + private final AtomicReference preparedRequest = new AtomicReference<>(); + private final AtomicReference authorizedActor = new AtomicReference<>(); + private final AtomicInteger resolutionWrites = new AtomicInteger(); + private final List events = new ArrayList<>(); + private boolean failedAttemptCommitted; + private final AccountHostingSubscriptionTerminalResolutionService service = + new AccountHostingSubscriptionTerminalResolutionService( + actors, primaryAuthentication, repository, observer, Clock.fixed(NOW, ZoneOffset.UTC)); + + private void currentActors(AccountAuthenticatedActor... currentActors) { + AtomicInteger calls = new AtomicInteger(); + doAnswer( + invocation -> { + int index = calls.getAndIncrement(); + if (index >= currentActors.length) { + throw new IllegalStateException("Unexpected current Account actor request"); + } + int ordinal = index + 1; + events.add("current-actor-" + ordinal); + @SuppressWarnings("unchecked") + Function action = invocation.getArgument(1); + return inOwnerTransaction( + () -> { + Object result = action.apply(currentActors[index]); + events.add("current-account-return-" + ordinal); + return result; + }); + }) + .when(actors) + .withCurrentAccount(eq(CONTROL_UI_JWT), any()); + } + + private void currentActorUnavailableOnFirstCall() { + doAnswer( + invocation -> { + events.add("initial-actor-unavailable"); + throw new IllegalStateException("current Account actor unavailable"); + }) + .when(actors) + .withCurrentAccount(eq(CONTROL_UI_JWT), any()); + } + + private void currentActorAvailableThenUnavailable(AccountAuthenticatedActor currentActor) { + AtomicInteger calls = new AtomicInteger(); + doAnswer( + invocation -> { + if (calls.getAndIncrement() > 0) { + events.add("final-actor-unavailable"); + throw new IllegalStateException("final current Account actor unavailable"); + } + events.add("current-actor-1"); + @SuppressWarnings("unchecked") + Function action = invocation.getArgument(1); + return inOwnerTransaction(() -> action.apply(currentActor)); + }) + .when(actors) + .withCurrentAccount(eq(CONTROL_UI_JWT), any()); + } + + private void prepare(TransitionResult replay) { + when(preparation.binding()).thenReturn(binding); + when(preparation.replayResult()).thenReturn(replay); + doAnswer(invocation -> preparedRequest.get()).when(preparation).request(); + doAnswer( + invocation -> { + assertWritableOwnerTransaction(); + Request request = invocation.getArgument(0); + preparedRequest.set(request); + events.add("prepare"); + doAnswer(ignored -> request).when(preparation).request(); + return preparation; + }) + .when(repository) + .prepareTerminalResolution(any(Request.class)); + } + + private void observeOutsideOwnerTransaction() { + doAnswer( + invocation -> { + assertNoTransactionOrSynchronization(); + assertThat(invocation.getArgument(0, ExpectedBinding.class)).isEqualTo(binding); + events.add("provider-read"); + return observed; + }) + .when(observer) + .observe(any(ExpectedBinding.class)); + } + + private void applyAfterAuthorization(UUID billingOwner) { + doAnswer( + invocation -> { + assertWritableOwnerTransaction(); + events.add("apply"); + ResolutionPreparation prepared = invocation.getArgument(0); + Authorization authorization = invocation.getArgument(2); + AuthorizedActor authorized = + authorization.requireAuthorized( + new LockedTarget(prepared.request(), billingOwner, 11L)); + authorizedActor.set(authorized); + resolutionWrites.incrementAndGet(); + events.add("resolution-write"); + return committed; + }) + .when(repository) + .applyTerminalResolution( + any(ResolutionPreparation.class), any(), any(Authorization.class)); + } + + private void primaryAuthenticatesAs(UUID accountId) { + AccountServiceImpl.ControlUiPrimaryIdentity identity = primaryIdentity(accountId); + doAnswer( + invocation -> { + assertThat(invocation.getArgument(0, String.class)).isEqualTo(EMAIL); + assertThat(invocation.getArgument(1, String.class)).isEqualTo(SECRET); + assertWritableOwnerTransaction(); + events.add("primary-authentication"); + return identity; + }) + .when(primaryAuthentication) + .authenticateControlUiPrimaryIdentity(EMAIL, SECRET); + } + + private void primaryAuthenticationDenied() { + doAnswer( + invocation -> { + assertWritableOwnerTransaction(); + events.add("primary-authentication"); + TransactionSynchronizationManager.registerSynchronization( + new TransactionSynchronization() { + @Override + public void afterCommit() { + failedAttemptCommitted = true; + events.add("failed-login-attempt-committed"); + } + }); + throw new AuthenticationException( + "INVALID_CREDENTIALS", "Rejected credential was " + SECRET); + }) + .when(primaryAuthentication) + .authenticateControlUiPrimaryIdentity(EMAIL, SECRET); + } + + private T inOwnerTransaction(Supplier action) { + return transaction.execute(status -> action.get()); + } + + private static void assertWritableOwnerTransaction() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + } + + private static void assertNoTransactionOrSynchronization() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } + } + + 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/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java index a8a0f9abff..16237e1204 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java @@ -56,6 +56,7 @@ import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountCreatorMembershipSourceReader; import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapAuthorizationSource; import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapService; @@ -351,9 +352,6 @@ final class AccountControlUiOwnerSourcesFixture { net.firedevops.firemud.accountservice.service .AccountPasswordResetDraftSourceChangeRepository.class), mock(AccountAuditOutboxRepository.class), - mock( - net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository - .class), mock(AccountJoinOperationRepository.class), challenges, null, // Realm grants are not used by primary authentication. @@ -362,7 +360,8 @@ final class AccountControlUiOwnerSourcesFixture { null, // Profiles are not used by primary authentication. null, // Profile mapper is not used by primary authentication. null, // Payment transactions are not used by primary authentication. - null, // Subscriptions are not used by primary authentication. + // Retained evidence is not read by primary authentication. + org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), null, // External identities are not used by primary authentication. null, // Password reset tokens are not used by primary authentication. null, // Email verification tokens are not used by primary authentication. @@ -370,8 +369,6 @@ final class AccountControlUiOwnerSourcesFixture { null, // Email delivery is not used by primary authentication. null, // Mail properties are not used by primary authentication. null, // Token properties are not used by primary authentication. - null, // JWT auth properties are not used by primary authentication. - null, // Game Session client is not used by primary authentication. null, // Entity Management client is not used by primary authentication. null, // JWT utility is not used by primary authentication. null, // Session service is not used by primary authentication. diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementEvidence.java new file mode 100644 index 0000000000..fdbe2d3000 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementEvidence.java @@ -0,0 +1,341 @@ +package net.firedevops.firemud.common.account.authority; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadConstraints; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.json.JsonFactory; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Closed canonical TENANT_OPERATION variant of Account's runtime entitlement evidence. + * + *

This value validates content, not source authenticity, transport authentication, freshness at + * use, capacity commitment, or player admission. Player-bound consumers must reject this variant. + * It has no account subject, issuer generation, membership, grant, or player-binding fields. + */ +public final class RuntimeTenantOperationEntitlementEvidence { + public static final String SCHEMA = "account-auth-evidence-bundle/v1"; + public static final String VARIANT = "TENANT_OPERATION"; + public static final int MAX_CANONICAL_BYTES = 64 * 1024; + private static final Pattern DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern DECIMAL = Pattern.compile("0|[1-9][0-9]{0,18}"); + private static final Set ROOT = + Set.of( + "schema", + "variant", + "bundleVersion", + "tenantId", + "requestId", + "callerWorkload", + "sourceKind", + "authorityAvailability", + "subscriptionStatus", + "provisioningStatus", + "gameplayAvailable", + "allowPublicJoin", + "allowNewGameplayBindings", + "allowNewInstanceStarts", + "quotas", + "entitlementVersion", + "tenantBillingSequence", + "tenantAuthorityGeneration", + "evaluatedAt", + "snapshotIdentity", + "evaluationIdentity", + "authorityTuple", + "outboxCheckpoints"); + private static final Set FLAGS = + Set.of( + "gameplayAvailable", + "allowPublicJoin", + "allowNewGameplayBindings", + "allowNewInstanceStarts"); + private static final Set STATUSES = + Set.of("trialing", "active", "past_due", "grace", "suspended", "canceled"); + private static final JsonMapper JSON = + JsonMapper.builder( + JsonFactory.builder() + .streamReadConstraints( + StreamReadConstraints.builder() + .maxNestingDepth(8) + .maxStringLength(2048) + .maxNumberLength(19) + .build()) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private final byte[] canonicalBytes; + + private RuntimeTenantOperationEntitlementEvidence(byte[] canonicalBytes) { + this.canonicalBytes = canonicalBytes.clone(); + } + + /** + * Production callers must derive every field inside the same locked Account source transaction. + */ + public static RuntimeTenantOperationEntitlementEvidence fromOwnerEvaluation( + Map fields) { + validate(fields); + return parseCanonical(canonicalize(fields)); + } + + public static RuntimeTenantOperationEntitlementEvidence parseCanonical(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_CANONICAL_BYTES) { + throw invalid("Bundle is absent or exceeds 64 KiB"); + } + String text; + try { + text = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException ex) { + throw invalid("Bundle must be strict UTF-8"); + } + Map fields = parse(text); + validate(fields); + if (!Arrays.equals(bytes, canonicalize(fields))) { + throw invalid("Bundle bytes must be canonical"); + } + return new RuntimeTenantOperationEntitlementEvidence(bytes); + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + /** A fresh decoded copy; changing it cannot change this immutable value. */ + public Map fields() { + return parse(new String(canonicalBytes, StandardCharsets.UTF_8)); + } + + /** Digest of exact canonical JSON, also used by Account's committed-source snapshot preimage. */ + public static String canonicalDigest(Map preimage) { + try { + return "sha256:" + + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(canonicalize(preimage))); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable", ex); + } + } + + private static void validate(Map root) { + exact(root, ROOT, "bundle"); + equal(root.get("schema"), SCHEMA, "schema"); + equal(root.get("variant"), VARIANT, "variant"); + equal(root.get("authorityAvailability"), "AVAILABLE", "authorityAvailability"); + equal(root.get("bundleVersion"), "1", "bundleVersion"); + String tenant = uuid(root.get("tenantId"), "tenantId"); + uuid(root.get("requestId"), "requestId"); + String workload = text(root.get("callerWorkload"), "callerWorkload"); + GrpcPeerIdentity peer = + GrpcPeerIdentity.parseUri(workload) + .filter(identity -> identity.uri().equals(workload)) + .orElseThrow(() -> invalid("callerWorkload must be canonical")); + equal(peer.service(), "world-management-service", "callerWorkload service"); + String kind = text(root.get("sourceKind"), "sourceKind"); + if (!Set.of("PAID_HOSTING", "NON_PAID_DEMO").contains(kind)) { + throw invalid("Unsupported sourceKind"); + } + for (String flag : FLAGS) { + if (!(root.get(flag) instanceof Boolean)) throw invalid(flag + " must be explicit boolean"); + } + Object provisioning = root.get("provisioningStatus"); + Object status = root.get("subscriptionStatus"); + if (provisioning != null) { + if (!Set.of("pending", "provisioning").contains(provisioning) + || status != null + || !"PAID_HOSTING".equals(kind) + || FLAGS.stream().anyMatch(flag -> Boolean.TRUE.equals(root.get(flag)))) { + throw invalid("Provisioning evidence cannot grant hosting authority"); + } + } else if ("PAID_HOSTING".equals(kind)) { + if (!(status instanceof String value) || !STATUSES.contains(value)) { + throw invalid("Paid evidence requires resolved subscriptionStatus"); + } + } else if (status != null) { + throw invalid("Demo evidence cannot assert a paid subscriptionStatus"); + } + for (String field : ROOT) { + if (!Set.of("subscriptionStatus", "provisioningStatus").contains(field) + && root.get(field) == null) throw invalid(field + " cannot be null"); + } + Map quotas = object(root.get("quotas"), "quotas"); + exact( + quotas, + Set.of("maxActiveSessions", "maxConcurrentGameInstances", "maxStorageBytes"), + "quotas"); + quotas.forEach((key, value) -> decimal(value, false, key)); + decimal(root.get("entitlementVersion"), true, "entitlementVersion"); + String billing = decimal(root.get("tenantBillingSequence"), true, "tenantBillingSequence"); + String generation = + decimal(root.get("tenantAuthorityGeneration"), true, "tenantAuthorityGeneration"); + String evaluated = text(root.get("evaluatedAt"), "evaluatedAt"); + try { + Instant instant = Instant.parse(evaluated); + if (!instant.toString().equals(evaluated) || !instant.isAfter(Instant.EPOCH)) { + throw invalid("evaluatedAt must be a canonical positive UTC instant"); + } + } catch (java.time.format.DateTimeParseException ex) { + throw invalid("evaluatedAt must be a canonical UTC instant"); + } + digest(root.get("snapshotIdentity"), "snapshotIdentity"); + digest(root.get("evaluationIdentity"), "evaluationIdentity"); + Map tuple = object(root.get("authorityTuple"), "authorityTuple"); + exact(tuple, Set.of("tenantAuthorityGeneration", "tenantBillingCutoff"), "authorityTuple"); + Map generations = + object(tuple.get("tenantAuthorityGeneration"), "tenant generations"); + exact(generations, Set.of(tenant), "tenant generations"); + equal(generations.get(tenant), generation, "tenant generation echo"); + Map cutoffs = object(tuple.get("tenantBillingCutoff"), "tenantBillingCutoff"); + exact(cutoffs, Set.of(tenant), "tenantBillingCutoff"); + Map cutoff = object(cutoffs.get(tenant), "tenant cutoff"); + exact( + cutoff, + Set.of( + "tenantAuthorityGeneration", + "tenantBillingSequence", + "outboxStreamKey", + "outboxSequence"), + "tenant cutoff"); + equal(cutoff.get("tenantAuthorityGeneration"), generation, "cutoff generation"); + equal(cutoff.get("tenantBillingSequence"), billing, "cutoff billing sequence"); + String stream = TenantAuthorityEventV1Codec.streamKey(UUID.fromString(tenant)); + equal(cutoff.get("outboxStreamKey"), stream, "cutoff stream"); + String sequence = decimal(cutoff.get("outboxSequence"), true, "cutoff sequence"); + if (!(root.get("outboxCheckpoints") instanceof List checkpoints) + || checkpoints.size() != 1) { + throw invalid("Exactly one applicable tenant authority checkpoint is required"); + } + Map checkpoint = object(checkpoints.getFirst(), "checkpoint"); + exact( + checkpoint, + Set.of("outboxStreamKey", "outboxSequence", "sourceEventId", "sourceEventDigest"), + "checkpoint"); + equal(checkpoint.get("outboxStreamKey"), stream, "checkpoint stream"); + equal(checkpoint.get("outboxSequence"), sequence, "checkpoint sequence"); + uuid(checkpoint.get("sourceEventId"), "checkpoint event ID"); + digest(checkpoint.get("sourceEventDigest"), "checkpoint event digest"); + } + + private static Map parse(String text) { + try { + return JSON.readValue(text, new TypeReference<>() {}); + } catch (RuntimeException ex) { + throw invalid("Bundle JSON is malformed"); + } + } + + private static byte[] canonicalize(Map fields) { + try { + byte[] bytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(fields)); + if (bytes.length > MAX_CANONICAL_BYTES) throw invalid("Canonical value exceeds 64 KiB"); + return bytes; + } catch (IOException ex) { + throw invalid("Cannot canonicalize bundle"); + } + } + + private static Map object(Object value, String field) { + if (!(value instanceof Map supplied)) throw invalid(field + " must be an object"); + Map result = new LinkedHashMap<>(); + supplied.forEach( + (key, item) -> { + if (!(key instanceof String name)) throw invalid(field + " contains a non-text key"); + result.put(name, item); + }); + return result; + } + + private static void exact(Map value, Set expected, String field) { + if (value == null || !value.keySet().equals(expected)) + throw invalid(field + " has missing or extra fields"); + } + + private static String text(Object value, String field) { + if (!(value instanceof String text) || text.isEmpty() || text.length() > 2048) { + throw invalid(field + " must be bounded text"); + } + return text; + } + + private static String uuid(Object value, String field) { + String text = text(value, field); + UUID parsed; + try { + parsed = UUID.fromString(text); + } catch (IllegalArgumentException ex) { + throw invalid(field + " must be a canonical non-nil UUID"); + } + if (!parsed.toString().equals(text) || parsed.equals(new UUID(0L, 0L))) { + throw invalid(field + " must be a canonical non-nil UUID"); + } + return text; + } + + private static String decimal(Object value, boolean positive, String field) { + String text = text(value, field); + if (!DECIMAL.matcher(text).matches()) throw invalid(field + " must be canonical decimal text"); + try { + if (Long.parseLong(text) < (positive ? 1 : 0)) throw invalid(field + " is outside bounds"); + } catch (NumberFormatException ex) { + throw invalid(field + " is outside BIGINT bounds"); + } + return text; + } + + private static void digest(Object value, String field) { + if (!(value instanceof String text) || !DIGEST.matcher(text).matches()) { + throw invalid(field + " must be a canonical SHA-256 digest"); + } + } + + private static void equal(Object supplied, Object expected, String field) { + if (!java.util.Objects.equals(supplied, expected)) throw invalid(field + " differs"); + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + @Override + public boolean equals(Object other) { + return this == other + || other instanceof RuntimeTenantOperationEntitlementEvidence value + && Arrays.equals(canonicalBytes, value.canonicalBytes); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes); + } + + @Override + public String toString() { + return "RuntimeTenantOperationEntitlementEvidence[TENANT_OPERATION, redacted]"; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementGrpcCodec.java new file mode 100644 index 0000000000..36ba5511fd --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementGrpcCodec.java @@ -0,0 +1,128 @@ +package net.firedevops.firemud.common.account.authority; + +import com.google.protobuf.ByteString; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ReadTenantOperationEntitlementRequest; +import net.firedevops.firemud.account.v1.ReadTenantOperationEntitlementResponse; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Closed wire mapping only; canonical content and selectors do not authenticate their source. */ +public final class RuntimeTenantOperationEntitlementGrpcCodec { + public static final int MAX_REQUEST_WIRE_BYTES = 1024; + public static final int MAX_RESPONSE_WIRE_BYTES = + RuntimeTenantOperationEntitlementEvidence.MAX_CANONICAL_BYTES + MAX_REQUEST_WIRE_BYTES + 32; + public static final long CALL_DEADLINE_SECONDS = 5L; + + private RuntimeTenantOperationEntitlementGrpcCodec() {} + + public enum SourceKind { + PAID_HOSTING, + NON_PAID_DEMO + } + + /** Comparison selectors, never an assertion of authenticated caller identity. */ + public record Request( + String targetNamespace, UUID tenantId, UUID requestId, SourceKind sourceKind) { + public Request { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical workload namespace required"); + } + nonNil(tenantId); + nonNil(requestId); + Objects.requireNonNull(sourceKind, "Explicit entitlement source required"); + } + + public String expectedWorldWorkload() { + return "spiffe://firemud/ns/" + targetNamespace + "/sa/world-management-service"; + } + } + + public static ReadTenantOperationEntitlementRequest toRequest(Request request) { + Objects.requireNonNull(request); + return ReadTenantOperationEntitlementRequest.newBuilder() + .addSchemaVersion(1) + .addTargetNamespace(request.targetNamespace()) + .addTenantId(request.tenantId().toString()) + .addRequestId(request.requestId().toString()) + .addSourceKind(request.sourceKind().name()) + .build(); + } + + public static Request parseRequest(ReadTenantOperationEntitlementRequest wire) { + if (wire == null + || wire.getSerializedSize() > MAX_REQUEST_WIRE_BYTES + || !wire.getUnknownFields().asMap().isEmpty() + || one(wire.getSchemaVersionList()) != 1) { + throw new IllegalArgumentException("Exact bounded tenant-operation request required"); + } + return new Request( + one(wire.getTargetNamespaceList()), uuid(one(wire.getTenantIdList())), + uuid(one(wire.getRequestIdList())), SourceKind.valueOf(one(wire.getSourceKindList()))); + } + + public static ReadTenantOperationEntitlementResponse toResponse( + Request request, RuntimeTenantOperationEntitlementEvidence evidence) { + requireBinding(request, evidence); + var response = + ReadTenantOperationEntitlementResponse.newBuilder() + .addRequest(toRequest(request)) + .addCanonicalEvidence(ByteString.copyFrom(evidence.canonicalBytes())) + .build(); + if (response.getSerializedSize() > MAX_RESPONSE_WIRE_BYTES) { + throw new IllegalArgumentException("Tenant-operation response exceeds wire bound"); + } + return response; + } + + public static RuntimeTenantOperationEntitlementEvidence requireResponse( + Request expected, ReadTenantOperationEntitlementResponse wire) { + Objects.requireNonNull(expected); + if (wire == null + || wire.getSerializedSize() > MAX_RESPONSE_WIRE_BYTES + || !wire.getUnknownFields().asMap().isEmpty() + || !expected.equals(parseRequest(one(wire.getRequestList())))) { + throw new IllegalArgumentException("Exact bounded tenant-operation response required"); + } + var evidence = + RuntimeTenantOperationEntitlementEvidence.parseCanonical( + one(wire.getCanonicalEvidenceList()).toByteArray()); + requireBinding(expected, evidence); + return evidence; + } + + private static void requireBinding( + Request request, RuntimeTenantOperationEntitlementEvidence evidence) { + Objects.requireNonNull(request); + Map fields = Objects.requireNonNull(evidence).fields(); + if (!request.tenantId().toString().equals(fields.get("tenantId")) + || !request.requestId().toString().equals(fields.get("requestId")) + || !request.sourceKind().name().equals(fields.get("sourceKind")) + || !request.expectedWorldWorkload().equals(fields.get("callerWorkload"))) { + throw new IllegalArgumentException( + "Tenant-operation evidence differs from exact request/workload"); + } + } + + private static T one(List values) { + if (values.size() != 1) + throw new IllegalArgumentException("Exactly one transport member required"); + return values.getFirst(); + } + + private static UUID uuid(String text) { + UUID value = UUID.fromString(text); + nonNil(value); + if (!value.toString().equals(text)) + throw new IllegalArgumentException("Canonical UUID required"); + return value; + } + + private static void nonNil(UUID value) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Non-nil UUID required"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementEvidenceTest.java new file mode 100644 index 0000000000..fde12c4549 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementEvidenceTest.java @@ -0,0 +1,233 @@ +package net.firedevops.firemud.common.account.authority; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +/** Content proof only; controlled values are not authenticated Account source evidence. */ +class RuntimeTenantOperationEntitlementEvidenceTest { + private static final String TENANT = "44444444-4444-4444-8444-444444444444"; + private static final String STREAM = "account:auth-authority:v1:tenant/" + TENANT; + private static final String DIGEST = "sha256:" + "a".repeat(64); + + @Test + void roundTripPreservesTenantOnlyShapeIndependentCountersAndImmutableValue() { + var value = RuntimeTenantOperationEntitlementEvidence.fromOwnerEvaluation(fields()); + assertThat(RuntimeTenantOperationEntitlementEvidence.parseCanonical(value.canonicalBytes())) + .isEqualTo(value); + assertThat(value.fields()) + .containsEntry("tenantAuthorityGeneration", "5") + .containsEntry("entitlementVersion", "7") + .containsEntry("tenantBillingSequence", "11"); + assertThat(tuple(value.fields())) + .containsOnlyKeys("tenantAuthorityGeneration", "tenantBillingCutoff"); + value.fields().put("tenantId", UUID.randomUUID().toString()); + byte[] copy = value.canonicalBytes(); + copy[0] = 0; + assertThat(value.fields()).containsEntry("tenantId", TENANT); + } + + @Test + void playerIssuerAccountClaimsAndUnknownVariantsCannotEnterTenantOperation() { + for (String field : + List.of("callerAccountId", "verifiedConnectScopeId", "issuer", "membershipVersion")) { + var fields = fields(); + fields.put(field, "injected"); + reject(fields); + } + for (String field : + List.of( + "issuerAuthGeneration", + "accountAuthorityGeneration", + "membershipAuthorityGeneration", + "privateRealmGrantVersions", + "accountSecurityCutoff")) { + var fields = fields(); + var tuple = new LinkedHashMap<>(tuple(fields)); + tuple.put(field, "1"); + fields.put("authorityTuple", tuple); + reject(fields); + } + var fields = fields(); + fields.put("variant", "PLAYER_ADMISSION"); + reject(fields); + } + + @Test + void cutoffAndExactPositiveCheckpointCannotBeReplacedByFlatBillingSequence() { + var fields = fields(); + fields.put("tenantBillingSequence", "12"); + reject(fields); + fields = fields(); + fields.put("tenantAuthorityGeneration", "6"); + reject(fields); + fields = fields(); + fields.put("outboxCheckpoints", List.of(checkpoint("0"))); + reject(fields); + fields = fields(); + fields.put("outboxCheckpoints", List.of(checkpoint("3"), checkpoint("3"))); + reject(fields); + fields = fields(); + fields.put( + "outboxCheckpoints", + List.of( + Map.of( + "outboxStreamKey", + TenantAuthorityEventV1Codec.tenantBillingStreamKey(UUID.fromString(TENANT)), + "outboxSequence", + "3", + "sourceEventId", + UUID.randomUUID().toString(), + "sourceEventDigest", + DIGEST))); + reject(fields); + } + + @Test + void statusesHaveExplicitPresenceAndProvisioningCannotGrantAdmission() { + var fields = fields(); + fields.remove("subscriptionStatus"); + reject(fields); + fields = fields(); + fields.put("subscriptionStatus", null); + fields.put("provisioningStatus", "pending"); + reject(fields); + for (String flag : + List.of( + "gameplayAvailable", + "allowPublicJoin", + "allowNewGameplayBindings", + "allowNewInstanceStarts")) { + fields.put(flag, false); + } + assertThat(RuntimeTenantOperationEntitlementEvidence.fromOwnerEvaluation(fields).fields()) + .containsEntry("provisioningStatus", "pending") + .containsEntry("subscriptionStatus", null); + fields.put("provisioningStatus", null); + fields.put("sourceKind", "NON_PAID_DEMO"); + assertThat(RuntimeTenantOperationEntitlementEvidence.fromOwnerEvaluation(fields).fields()) + .containsEntry("subscriptionStatus", null); + } + + @Test + void malformedUtf8DuplicatesUnknownSchemaOverflowAndNoncanonicalBytesFailClosed() { + byte[] canonical = + RuntimeTenantOperationEntitlementEvidence.fromOwnerEvaluation(fields()).canonicalBytes(); + String text = new String(canonical, StandardCharsets.UTF_8); + rejectBytes((" " + text).getBytes(StandardCharsets.UTF_8)); + rejectBytes( + text.replaceFirst("\\{", "{\"schema\":\"account-auth-evidence-bundle/v1\",") + .getBytes(StandardCharsets.UTF_8)); + rejectBytes(new byte[] {(byte) 0xc3, (byte) 0x28}); + rejectBytes(new byte[RuntimeTenantOperationEntitlementEvidence.MAX_CANONICAL_BYTES + 1]); + for (String decimal : List.of("01", "-1", "9223372036854775808")) { + var fields = fields(); + fields.put("entitlementVersion", decimal); + reject(fields); + } + var fields = fields(); + fields.put("schema", "account-auth-evidence-bundle/v2"); + reject(fields); + fields = fields(); + fields.put("tenantId", "44444444444444448444444444444444"); + reject(fields); + } + + @Test + void absentNullOrUnavailableAuthorityCannotProduceUsableEvidence() { + var absent = fields(); + absent.remove("authorityAvailability"); + reject(absent); + var missing = fields(); + missing.put("authorityAvailability", null); + reject(missing); + var unavailable = fields(); + unavailable.put("authorityAvailability", "UNAVAILABLE"); + reject(unavailable); + } + + private static Map fields() { + Map fields = new LinkedHashMap<>(); + fields.put("schema", RuntimeTenantOperationEntitlementEvidence.SCHEMA); + fields.put("authorityAvailability", "AVAILABLE"); + fields.put("variant", "TENANT_OPERATION"); + fields.put("bundleVersion", "1"); + fields.put("tenantId", TENANT); + fields.put("requestId", "11111111-1111-4111-8111-111111111111"); + fields.put("callerWorkload", "spiffe://firemud/ns/prod/sa/world-management-service"); + fields.put("sourceKind", "PAID_HOSTING"); + fields.put("subscriptionStatus", "active"); + fields.put("provisioningStatus", null); + fields.put("gameplayAvailable", true); + fields.put("allowPublicJoin", true); + fields.put("allowNewGameplayBindings", true); + fields.put("allowNewInstanceStarts", true); + fields.put( + "quotas", + Map.of( + "maxActiveSessions", + "100", + "maxConcurrentGameInstances", + "2", + "maxStorageBytes", + "1048576")); + fields.put("entitlementVersion", "7"); + fields.put("tenantBillingSequence", "11"); + fields.put("tenantAuthorityGeneration", "5"); + fields.put("evaluatedAt", "2026-11-02T12:00:00Z"); + fields.put("snapshotIdentity", DIGEST); + fields.put("evaluationIdentity", "sha256:" + "b".repeat(64)); + fields.put( + "authorityTuple", + Map.of( + "tenantAuthorityGeneration", + Map.of(TENANT, "5"), + "tenantBillingCutoff", + Map.of( + TENANT, + Map.of( + "tenantAuthorityGeneration", + "5", + "tenantBillingSequence", + "11", + "outboxStreamKey", + STREAM, + "outboxSequence", + "3")))); + fields.put("outboxCheckpoints", List.of(checkpoint("3"))); + return fields; + } + + private static Map checkpoint(String sequence) { + return Map.of( + "outboxStreamKey", + STREAM, + "outboxSequence", + sequence, + "sourceEventId", + "22222222-2222-4222-8222-222222222222", + "sourceEventDigest", + DIGEST); + } + + @SuppressWarnings("unchecked") + private static Map tuple(Map fields) { + return (Map) fields.get("authorityTuple"); + } + + private static void reject(Map fields) { + assertThatThrownBy(() -> RuntimeTenantOperationEntitlementEvidence.fromOwnerEvaluation(fields)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static void rejectBytes(byte[] bytes) { + assertThatThrownBy(() -> RuntimeTenantOperationEntitlementEvidence.parseCanonical(bytes)) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementGrpcCodecTest.java new file mode 100644 index 0000000000..05a52e836e --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementGrpcCodecTest.java @@ -0,0 +1,114 @@ +package net.firedevops.firemud.common.account.authority; + +import static net.firedevops.firemud.common.account.authority.TenantOperationEntitlementTransportFixture.evidence; +import static net.firedevops.firemud.common.account.authority.TenantOperationEntitlementTransportFixture.request; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ReadTenantOperationEntitlementRequest; +import net.firedevops.firemud.common.account.authority.RuntimeTenantOperationEntitlementGrpcCodec.SourceKind; +import org.junit.jupiter.api.Test; + +class RuntimeTenantOperationEntitlementGrpcCodecTest { + @Test + void bothExplicitSourcesPreserveExactCanonicalEvidence() { + for (var source : SourceKind.values()) { + var request = request(source); + var evidence = evidence(request); + assertThat( + RuntimeTenantOperationEntitlementGrpcCodec.parseRequest( + RuntimeTenantOperationEntitlementGrpcCodec.toRequest(request))) + .isEqualTo(request); + assertThat( + RuntimeTenantOperationEntitlementGrpcCodec.requireResponse( + request, + RuntimeTenantOperationEntitlementGrpcCodec.toResponse(request, evidence))) + .isEqualTo(evidence); + } + } + + @Test + void rejectsMissingDuplicateUnknownUnboundedAndNoncanonicalRequestMembers() throws Exception { + var wire = + RuntimeTenantOperationEntitlementGrpcCodec.toRequest(request(SourceKind.PAID_HOSTING)); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + for (var invalid : + new ReadTenantOperationEntitlementRequest[] { + wire.toBuilder().clearSourceKind().build(), + wire.toBuilder().addSourceKind("PAID_HOSTING").build(), + wire.toBuilder().addTenantId(wire.getTenantId(0)).build(), + wire.toBuilder().addRequestId(wire.getRequestId(0)).build(), + wire.toBuilder().addSchemaVersion(1).build(), + wire.toBuilder().addTargetNamespace("firemud").build(), + wire.toBuilder().setSourceKind(0, "DEFAULT").build(), + wire.toBuilder().setTenantId(0, "00000000-0000-0000-0000-000000000000").build(), + wire.toBuilder().setRequestId(0, "11111111111141118111111111111111").build(), + wire.toBuilder().setTargetNamespace(0, "a".repeat(2048)).build(), + wire.toBuilder().setUnknownFields(unknown).build() + }) { + assertThatThrownBy(() -> RuntimeTenantOperationEntitlementGrpcCodec.parseRequest(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + // Actual repeated protobuf field occurrences survive parsing for cardinality rejection. + byte[] bytes = wire.toByteArray(); + byte[] duplicate = new byte[bytes.length * 2]; + System.arraycopy(bytes, 0, duplicate, 0, bytes.length); + System.arraycopy(bytes, 0, duplicate, bytes.length, bytes.length); + assertThatThrownBy( + () -> + RuntimeTenantOperationEntitlementGrpcCodec.parseRequest( + ReadTenantOperationEntitlementRequest.parseFrom(duplicate))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsResponseCardinalityUnknownFieldsBindingsAndBadCanonicalValue() { + var request = request(SourceKind.PAID_HOSTING); + var evidence = evidence(request); + var wire = RuntimeTenantOperationEntitlementGrpcCodec.toResponse(request, evidence); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + for (var invalid : + java.util.List.of( + wire.toBuilder().clearRequest().build(), + wire.toBuilder().addRequest(wire.getRequest(0)).build(), + wire.toBuilder().addCanonicalEvidence(wire.getCanonicalEvidence(0)).build(), + wire.toBuilder().clearCanonicalEvidence().build(), + wire.toBuilder().setCanonicalEvidence(0, ByteString.copyFromUtf8("{}")).build(), + wire.toBuilder().setCanonicalEvidence(0, ByteString.copyFrom(new byte[65537])).build(), + wire.toBuilder().setUnknownFields(unknown).build(), + wire.toBuilder() + .setRequest(0, wire.getRequest(0).toBuilder().setSourceKind(0, "NON_PAID_DEMO")) + .build())) { + assertThatThrownBy( + () -> RuntimeTenantOperationEntitlementGrpcCodec.requireResponse(request, invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + for (var changed : + java.util.List.of( + new RuntimeTenantOperationEntitlementGrpcCodec.Request( + "other", request.tenantId(), request.requestId(), request.sourceKind()), + new RuntimeTenantOperationEntitlementGrpcCodec.Request( + "firemud", UUID.randomUUID(), request.requestId(), request.sourceKind()), + new RuntimeTenantOperationEntitlementGrpcCodec.Request( + "firemud", request.tenantId(), UUID.randomUUID(), request.sourceKind()), + request(SourceKind.NON_PAID_DEMO))) { + var substituted = + wire.toBuilder() + .setRequest(0, RuntimeTenantOperationEntitlementGrpcCodec.toRequest(changed)) + .build(); + assertThatThrownBy( + () -> + RuntimeTenantOperationEntitlementGrpcCodec.requireResponse(changed, substituted)) + .isInstanceOf(IllegalArgumentException.class); + } + } +} diff --git a/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/authority/TenantOperationEntitlementTransportFixture.java b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/authority/TenantOperationEntitlementTransportFixture.java new file mode 100644 index 0000000000..f2aad8b046 --- /dev/null +++ b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/authority/TenantOperationEntitlementTransportFixture.java @@ -0,0 +1,95 @@ +package net.firedevops.firemud.common.account.authority; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** Controlled transport fixture only, never genuine Account source or currentness proof. */ +public final class TenantOperationEntitlementTransportFixture { + private TenantOperationEntitlementTransportFixture() {} + + public static RuntimeTenantOperationEntitlementGrpcCodec.Request request( + RuntimeTenantOperationEntitlementGrpcCodec.SourceKind source) { + return new RuntimeTenantOperationEntitlementGrpcCodec.Request( + "firemud", + UUID.fromString("44444444-4444-4444-8444-444444444444"), + UUID.fromString("11111111-1111-4111-8111-111111111111"), + source); + } + + public static RuntimeTenantOperationEntitlementEvidence evidence( + RuntimeTenantOperationEntitlementGrpcCodec.Request request) { + String tenant = request.tenantId().toString(); + String stream = TenantAuthorityEventV1Codec.streamKey(request.tenantId()); + String digest = "sha256:" + "a".repeat(64); + Map fields = new LinkedHashMap<>(); + fields.put("schema", RuntimeTenantOperationEntitlementEvidence.SCHEMA); + fields.put("variant", "TENANT_OPERATION"); + fields.put("bundleVersion", "1"); + fields.put("authorityAvailability", "AVAILABLE"); + fields.put("tenantId", tenant); + fields.put("requestId", request.requestId().toString()); + fields.put("callerWorkload", request.expectedWorldWorkload()); + fields.put("sourceKind", request.sourceKind().name()); + fields.put( + "subscriptionStatus", + request.sourceKind() == RuntimeTenantOperationEntitlementGrpcCodec.SourceKind.PAID_HOSTING + ? "active" + : null); + fields.put("provisioningStatus", null); + for (String flag : + List.of( + "gameplayAvailable", + "allowPublicJoin", + "allowNewGameplayBindings", + "allowNewInstanceStarts")) { + fields.put(flag, true); + } + fields.put( + "quotas", + Map.of( + "maxActiveSessions", + "100", + "maxConcurrentGameInstances", + "2", + "maxStorageBytes", + "1048576")); + fields.put("entitlementVersion", "7"); + fields.put("tenantBillingSequence", "11"); + fields.put("tenantAuthorityGeneration", "5"); + fields.put("evaluatedAt", "2026-11-02T12:00:00Z"); + fields.put("snapshotIdentity", digest); + fields.put("evaluationIdentity", "sha256:" + "b".repeat(64)); + fields.put( + "authorityTuple", + Map.of( + "tenantAuthorityGeneration", + Map.of(tenant, "5"), + "tenantBillingCutoff", + Map.of( + tenant, + Map.of( + "tenantAuthorityGeneration", + "5", + "tenantBillingSequence", + "11", + "outboxStreamKey", + stream, + "outboxSequence", + "3")))); + fields.put( + "outboxCheckpoints", + List.of( + Map.of( + "outboxStreamKey", + stream, + "outboxSequence", + "3", + "sourceEventId", + "22222222-2222-4222-8222-222222222222", + "sourceEventDigest", + digest))); + return RuntimeTenantOperationEntitlementEvidence.fromOwnerEvaluation(fields); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClient.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClient.java new file mode 100644 index 0000000000..2a32457a99 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClient.java @@ -0,0 +1,119 @@ +package net.firedevops.firemud.worldmanagement.client; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.AccountTenantOperationEntitlementReadServiceGrpc; +import net.firedevops.firemud.common.account.authority.RuntimeTenantOperationEntitlementEvidence; +import net.firedevops.firemud.common.account.authority.RuntimeTenantOperationEntitlementGrpcCodec; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +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.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; + +/** Explicit, unregistered World consumer of Account's protected tenant-operation source read. */ +public final class AccountTenantOperationEntitlementClient + extends AbstractReloadingBlockingGrpcClient< + AccountTenantOperationEntitlementReadServiceGrpc + .AccountTenantOperationEntitlementReadServiceBlockingStub> { + private final String namespace; + + public AccountTenantOperationEntitlementClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String namespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties, "Tenant-operation entitlement reads"), + channelFactory, + AccountTenantOperationEntitlementClient.class); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical World workload namespace required"); + } + this.namespace = namespace; + } + + public void init() throws IOException { + initOnce( + "Tenant-operation entitlement client is closed", "Tenant-operation client has no stub"); + } + + /** Samples actual Account evidence; the owner of a later action must enforce its currentness. */ + public ProtectedRead read(RuntimeTenantOperationEntitlementGrpcCodec.Request request) { + requireNoAmbientSql("Account entitlement reads require no ambient World transaction"); + Objects.requireNonNull(request); + if (!namespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Entitlement request must target the configured namespace"); + } + var response = + requireInitializedStub("Tenant-operation entitlement client is unavailable") + .withDeadlineAfter( + RuntimeTenantOperationEntitlementGrpcCodec.CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readTenantOperationEntitlement( + RuntimeTenantOperationEntitlementGrpcCodec.toRequest(request)); + if (response == null) { + throw new IllegalStateException("Account returned no tenant-operation evidence"); + } + try { + return new ProtectedRead( + request, RuntimeTenantOperationEntitlementGrpcCodec.requireResponse(request, response)); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Account returned invalid tenant-operation evidence", invalid); + } + } + + /** + * Only a successful protected read can construct this provenance wrapper. Never admission + * authority. + */ + public static final class ProtectedRead { + private final RuntimeTenantOperationEntitlementGrpcCodec.Request request; + private final RuntimeTenantOperationEntitlementEvidence evidence; + + private ProtectedRead( + RuntimeTenantOperationEntitlementGrpcCodec.Request request, + RuntimeTenantOperationEntitlementEvidence evidence) { + this.request = request; + this.evidence = evidence; + } + + public RuntimeTenantOperationEntitlementGrpcCodec.Request request() { + return request; + } + + public RuntimeTenantOperationEntitlementEvidence evidence() { + return evidence; + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountTenantOperationEntitlementReadServiceGrpc + .AccountTenantOperationEntitlementReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String peer = "spiffe://firemud/ns/" + namespace + "/sa/account-service"; + return AccountTenantOperationEntitlementReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(peer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer)) + .withMaxInboundMessageSize( + RuntimeTenantOperationEntitlementGrpcCodec.MAX_RESPONSE_WIRE_BYTES) + .withMaxOutboundMessageSize( + RuntimeTenantOperationEntitlementGrpcCodec.MAX_REQUEST_WIRE_BYTES); + } +} diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClientMtlsTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClientMtlsTest.java new file mode 100644 index 0000000000..66c057cde2 --- /dev/null +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClientMtlsTest.java @@ -0,0 +1,303 @@ +package net.firedevops.firemud.worldmanagement.client; + +import static net.firedevops.firemud.common.account.authority.TenantOperationEntitlementTransportFixture.evidence; +import static net.firedevops.firemud.common.account.authority.TenantOperationEntitlementTransportFixture.request; +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.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Server; +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.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.nio.file.Path; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.AccountTenantOperationEntitlementReadServiceGrpc; +import net.firedevops.firemud.account.v1.ReadTenantOperationEntitlementRequest; +import net.firedevops.firemud.account.v1.ReadTenantOperationEntitlementResponse; +import net.firedevops.firemud.accountservice.service.AccountTenantOperationEntitlementOwner; +import net.firedevops.firemud.accountservice.service.impl.AccountTenantOperationEntitlementGrpcService; +import net.firedevops.firemud.common.account.authority.RuntimeTenantOperationEntitlementGrpcCodec; +import net.firedevops.firemud.common.account.authority.RuntimeTenantOperationEntitlementGrpcCodec.SourceKind; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import net.firedevops.firemud.test.LoopbackMtlsTestPki.IdentitySpec; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Real loopback mTLS with a controlled source owner; no physical source/currentness qualification. + */ +class AccountTenantOperationEntitlementClientMtlsTest { + @Test + void protectedReceiverDispatchesExplicitSourcesWithAuthenticatedWorkloadAndNoFallback( + @TempDir Path temporary) throws Exception { + var pki = pki(temporary); + var owner = mock(AccountTenantOperationEntitlementOwner.class); + var paid = request(SourceKind.PAID_HOSTING); + var demo = request(SourceKind.NON_PAID_DEMO); + when(owner.evaluatePaid(any())) + .thenAnswer( + invocation -> { + var actual = + (AccountTenantOperationEntitlementOwner.Request) invocation.getArgument(0); + assertThat(actual) + .isEqualTo( + new AccountTenantOperationEntitlementOwner.Request( + paid.tenantId(), paid.requestId(), paid.expectedWorldWorkload())); + return evidence(paid); + }); + when(owner.evaluateDemo(any())).thenReturn(evidence(demo)); + var receiver = new AccountTenantOperationEntitlementGrpcService(owner, "firemud"); + Server server = + receiver + .createUnregisteredServer( + "localhost:0", + pki.keyManagerFactory(pki.identity("account")), + pki.trustManagerFactory()) + .start(); + try { + try (var client = client(pki, temporary, "world", server.getPort())) { + assertThatThrownBy(() -> client.read(paid)).isInstanceOf(IllegalStateException.class); + client.init(); + var read = client.read(paid); + assertThat(read.request()).isEqualTo(paid); + assertThat(read.evidence()).isEqualTo(evidence(paid)); + assertThat(client.read(demo).evidence()).isEqualTo(evidence(demo)); + doThrow(new IllegalStateException("source unavailable")).when(owner).evaluatePaid(any()); + assertStatus(() -> client.read(paid), Status.Code.UNAVAILABLE); + verify(owner, org.mockito.Mockito.times(1)).evaluateDemo(any()); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.read(demo)).isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + } + for (String wrong : new String[] {"wrong-client", "other-world"}) { + try (var client = client(pki, temporary, wrong, server.getPort())) { + client.init(); + assertStatus(() -> client.read(paid), Status.Code.PERMISSION_DENIED); + } + } + } finally { + stop(server); + } + // Calling a handler directly, even with a syntactically valid request, supplies no TLS + // assertion. + var observer = new OutcomeObserver(); + receiver.readTenantOperationEntitlement( + RuntimeTenantOperationEntitlementGrpcCodec.toRequest(paid), observer); + assertThat(observer.failureCode).isEqualTo(Status.Code.UNAUTHENTICATED); + } + + @Test + void clientRefusesWrongOwnerBeforeSendingAndRejectsChangedOrMalformedEvidence( + @TempDir Path temporary) throws Exception { + var pki = pki(temporary); + var request = request(SourceKind.PAID_HOSTING); + var response = + new AtomicReference<>( + RuntimeTenantOperationEntitlementGrpcCodec.toResponse(request, evidence(request))); + var calls = new AtomicInteger(); + for (String alias : new String[] {"wrong-server", "other-account", "account"}) { + var identity = pki.identity(alias); + Server server = + NettyServerBuilder.forPort(0) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + new AccountTenantOperationEntitlementReadServiceGrpc + .AccountTenantOperationEntitlementReadServiceImplBase() { + @Override + public void readTenantOperationEntitlement( + ReadTenantOperationEntitlementRequest ignored, + StreamObserver observer) { + calls.incrementAndGet(); + observer.onNext(response.get()); + observer.onCompleted(); + } + }) + .build() + .start(); + try (var client = client(pki, temporary, "world", server.getPort())) { + client.init(); + if (!"account".equals(alias)) { + assertStatus(() -> client.read(request), Status.Code.UNAUTHENTICATED); + assertThat(calls).hasValue(0); + } else { + assertThat(client.read(request).evidence()).isEqualTo(evidence(request)); + var changed = + new RuntimeTenantOperationEntitlementGrpcCodec.Request( + "firemud", request.tenantId(), UUID.randomUUID(), request.sourceKind()); + response.set( + response.get().toBuilder() + .setCanonicalEvidence( + 0, + com.google.protobuf.ByteString.copyFrom(evidence(changed).canonicalBytes())) + .build()); + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + response.set( + response.get().toBuilder() + .addCanonicalEvidence(response.get().getCanonicalEvidence(0)) + .build()); + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + } + } finally { + stop(server); + } + } + } + + @Test + void clientRejectsPlaintextBeforeChannelCreation() { + var properties = new net.firedevops.firemud.common.grpc.CommonGrpcClientProperties(); + properties.setPlaintext(true); + var channels = mock(GrpcChannelFactory.class); + assertThatThrownBy( + () -> + new AccountTenantOperationEntitlementClient( + new ServiceEndpointsProperties(), properties, channels, "firemud")) + .isInstanceOf(IllegalArgumentException.class); + org.mockito.Mockito.verifyNoInteractions(channels); + } + + @Test + void receiverRejectsMalformedUnknownDuplicateWrongNamespaceAndOversizedRequestsBeforeSource( + @TempDir Path temporary) throws Exception { + var pki = pki(temporary); + var owner = mock(AccountTenantOperationEntitlementOwner.class); + var receiver = new AccountTenantOperationEntitlementGrpcService(owner, "firemud"); + Server server = + receiver + .createUnregisteredServer( + "localhost:0", + pki.keyManagerFactory(pki.identity("account")), + pki.trustManagerFactory()) + .start(); + var channel = + new GrpcChannelFactory() + .buildChannel( + "localhost:" + server.getPort(), + 6565, + pki.clientProperties(temporary, pki.identity("world")), + false); + try { + var stub = + AccountTenantOperationEntitlementReadServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(5, TimeUnit.SECONDS); + var wire = + RuntimeTenantOperationEntitlementGrpcCodec.toRequest(request(SourceKind.PAID_HOSTING)); + var unknown = + com.google.protobuf.UnknownFieldSet.newBuilder() + .addField( + 99, com.google.protobuf.UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + for (var invalid : + java.util.List.of( + wire.toBuilder().clearSourceKind().build(), + wire.toBuilder().addRequestId(wire.getRequestId(0)).build(), + wire.toBuilder().setUnknownFields(unknown).build())) { + assertStatus( + () -> stub.readTenantOperationEntitlement(invalid), Status.Code.INVALID_ARGUMENT); + } + assertStatus( + () -> + stub.readTenantOperationEntitlement( + wire.toBuilder().setTargetNamespace(0, "other").build()), + Status.Code.PERMISSION_DENIED); + assertThatThrownBy( + () -> + stub.readTenantOperationEntitlement( + wire.toBuilder().setSourceKind(0, "a".repeat(2048)).build())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isIn(Status.Code.RESOURCE_EXHAUSTED, Status.Code.INVALID_ARGUMENT)); + org.mockito.Mockito.verifyNoInteractions(owner); + } finally { + channel.shutdownNow(); + assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + stop(server); + } + } + + private static LoopbackMtlsTestPki.Pki pki(Path temporary) throws Exception { + return LoopbackMtlsTestPki.create( + temporary, + "Tenant operation transport test CA", + identity("account", "firemud", "account-service", true), + identity("wrong-server", "firemud", "game-session-service", true), + identity("other-account", "other", "account-service", true), + identity("world", "firemud", "world-management-service", false), + identity("wrong-client", "firemud", "game-session-service", false), + identity("other-world", "other", "world-management-service", false)); + } + + private static IdentitySpec identity( + String alias, String namespace, String service, boolean server) { + return new IdentitySpec(alias, "spiffe://firemud/ns/" + namespace + "/sa/" + service, server); + } + + private static AccountTenantOperationEntitlementClient client( + LoopbackMtlsTestPki.Pki pki, Path temporary, String alias, int port) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + port); + return new AccountTenantOperationEntitlementClient( + endpoints, + pki.clientProperties(temporary, pki.identity(alias)), + new GrpcChannelFactory(), + "firemud"); + } + + private static void assertStatus( + org.assertj.core.api.ThrowableAssert.ThrowingCallable action, Status.Code code) { + assertThatThrownBy(action) + .isInstanceOf(StatusRuntimeException.class) + .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code)); + } + + private static void stop(Server server) throws Exception { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + + private static final class OutcomeObserver + implements StreamObserver { + private Status.Code failureCode; + + @Override + public void onNext(ReadTenantOperationEntitlementResponse response) { + throw new AssertionError("Unauthenticated direct handler must not return evidence"); + } + + @Override + public void onError(Throwable failure) { + failureCode = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + throw new AssertionError("Unexpected completion"); + } + } +} From 91b76bcf1970d569fddaf786b4990f0b3802b68c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 3 Nov 2026 23:11:17 +1300 Subject: [PATCH 02/23] test: reconcile billing foundation migration proof boundaries --- .../player-access-and-session.md | 2 + ...rUuidEntityCompositionIntegrationTest.java | 614 ------------------ ...ntAuthorityCurrentnessIntegrationTest.java | 2 +- ...sionProtectionPostgresIntegrationTest.java | 8 +- 4 files changed, 10 insertions(+), 616 deletions(-) delete mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index c1ab76d5cc..04dd7ae9b1 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -18,6 +18,8 @@ The same receiving boundary carries the distinct TENANT_OPERATION evidence, Acco The existing public WORLDS/REALMS/CHARS, browser/direct JOIN, direct scope and connect-token facade paths temporarily return AUTH_UNAVAILABLE before legacy authority reads; the numeric runtime entitlement endpoint returns ENTITLEMENT_UNAVAILABLE. Complete canonical V2/JOIN/CHARS implementation and all positive compositions remain preserved in the separate public receiving source. This temporary boundary does not complete that work or permit dropping its positive obligations. Ordinary Account authentication, UUID player-bootstrap issuance, profile and retention/deletion protections remain in scope for receiving qualification. Private/ISOLATED/PLAYER_CREATED/AUTO positives, protected target currentness through commit, genuine installation delivery and private FRESH/CLOSED aggregation remain unfinished; registration/issuer/custody/activation holds remain. +Foundation draft #3389 at `fec647a5` fails its fresh source-built runtime at PLAY with `ENTITLEMENT_UNAVAILABLE`; authenticated teardown completes with no remaining project resources. The denied legacy numeric endpoint is intentional, but a qualified canonical runtime replacement is still required. Remote Validation also exposed a UUID/text readback assertion and an enabled-ALWAYS trigger expectation. Its obsolete numeric-subscription HTTP-to-Entity CHARS fixture belongs to the complete canonical public successor, where both replacement positive compositions pass; the foundation does not claim that positive boundary. These failures remain recorded, with current-head CI and runtime qualification outstanding. + ### Lifecycle-bound private realm-grant source preparation Local source includes [`RealmGrantMutation`](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/RealmGrantMutation.java), the [shared grant scope codec](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/GrantAuthorityScopeCodec.java), the [grant event codec](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RealmGrantAuthorityEventV1Codec.java), and Account's [lifecycle-bound grant repository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLifecycleBoundRealmGrantRepository.java) with [migration V1027.2](../../../services/account-service/src/main/resources/db/migration/V1027.2__lifecycle_bound_realm_grant_authority.sql). The composed read uses [`AccountCurrentLifecycleRealmGrantReadOwner`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/realm/AccountCurrentLifecycleRealmGrantReadOwner.java), [`GameSessionCurrentPrivatePlaytestLifecycleReadClient`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameSessionCurrentPrivatePlaytestLifecycleReadClient.java), and the shared [`CurrentPrivatePlaytestLifecycleReadGrpcCodec`](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CurrentPrivatePlaytestLifecycleReadGrpcCodec.java). Canonical grant/lifecycle behavior remains in [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#account-owned-playtest-grant-contract) and [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md), with the Game Session handoff recorded in [Realm Routing](./realm-routing-and-playable-state.md#initial-fresh-lifecycle-preparation). diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java deleted file mode 100644 index 1f5d79c7b6..0000000000 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java +++ /dev/null @@ -1,614 +0,0 @@ -package net.firedevops.firemud.accountservice; - -import static org.assertj.core.api.Assertions.assertThat; - -import io.grpc.ManagedChannel; -import io.grpc.Server; -import io.grpc.ServerInterceptors; -import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; -import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; -import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; -import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; -import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; -import io.micrometer.core.instrument.simple.SimpleMeterRegistry; -import java.io.IOException; -import java.net.URI; -import java.net.URLEncoder; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.security.cert.CertificateEncodingException; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.TimeUnit; -import net.firedevops.firemud.accountservice.client.GameSessionClient; -import net.firedevops.firemud.accountservice.client.LoggingAdminClient; -import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; -import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; -import net.firedevops.firemud.common.security.JwtUtil; -import net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus; -import net.firedevops.firemud.entitymanagement.mapper.CharacterMapper; -import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; -import net.firedevops.firemud.entitymanagement.service.PlayableStateKeyResolver; -import net.firedevops.firemud.entitymanagement.service.ScopedCharacterResolver; -import net.firedevops.firemud.entitymanagement.service.impl.CharacterServiceImpl; -import net.firedevops.firemud.entitymanagement.service.impl.EntityManagementGrpcService; -import net.firedevops.firemud.entitymanagement.v1.EntityManagementServiceGrpc; -import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountRequest; -import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; -import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; -import net.firedevops.firemud.test.GatewayTestProperties; -import net.firedevops.firemud.test.LoopbackMtlsTestPki; -import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; -import net.firedevops.firemud.test.TestContainerImages; -import org.flywaydb.core.Flyway; -import org.flywaydb.core.api.MigrationVersion; -import org.flywaydb.core.api.configuration.FluentConfiguration; -import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension; -import org.jooq.DSLContext; -import org.jooq.SQLDialect; -import org.jooq.impl.DSL; -import org.mapstruct.factory.Mappers; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.web.server.LocalServerPort; -import org.springframework.cache.concurrent.ConcurrentMapCacheManager; -import org.springframework.http.HttpHeaders; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.mail.javamail.JavaMailSender; -import org.springframework.test.context.DynamicPropertyRegistry; -import org.springframework.test.context.DynamicPropertySource; -import org.springframework.test.context.bean.override.mockito.MockitoBean; -import org.testcontainers.containers.GenericContainer; -import org.testcontainers.containers.PostgreSQLContainer; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; -import tools.jackson.databind.JsonNode; -import tools.jackson.databind.json.JsonMapper; - -/** - * Composes real Account bootstrap HTTP with its mTLS Entity roster client and real Entity storage. - * Game Session target reads, test-owned membership rows, and test PKI are controlled fixtures; this - * proves neither World-owned active lifecycle nor public admission or first OPEN. Entity RPCs not - * used by ordinary roster reads remain mocked. - */ -@Testcontainers(disabledWithoutDocker = true) -@SuppressWarnings("resource") -@SpringBootTest( - webEnvironment = WebEnvironment.RANDOM_PORT, - classes = AccountServiceApplication.class, - properties = { - "spring.config.import=classpath:account-main-application.yml", - "spring.grpc.server.port=0", - "firemud.grpc.workload-namespace=test", - GatewayTestProperties.SPRING_GRPC_SERVER_SSL_DISABLED, - "firemud.mail.verification-url=https://account.test/verify-email?token=%s" - }) -class BootstrapCharacterUuidEntityCompositionIntegrationTest { - private static final String TEST_NAMESPACE = "test"; - private static final String TEST_ACCOUNT_PEER = "spiffe://firemud/ns/test/sa/account-service"; - private static final String TEST_ENTITY_PEER = - "spiffe://firemud/ns/test/sa/entity-management-service"; - private static final long TARGET_TENANT_ID = 1L; - private static final long TARGET_GAME_INSTANCE_ID = 44L; - private static final String WORLD_SLUG = "uuid-bootstrap-proof"; - private static final String REALM_SLUG = "production"; - private static final UUID TARGET_REALM_ID = - UUID.fromString("d8f8de2e-89fd-4432-8cb4-93f241f56af6"); - private static final UUID TARGET_NAMESPACE_ID = - UUID.fromString("f711c0c9-c1fc-46fb-8ff2-1af7c4d96a67"); - private static final long RETAINED_NUMERIC_ACCOUNT_ID = 98765L; - - private static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient(); - private static final Path PKI_DIRECTORY = createTemporaryDirectory(); - private static final LoopbackMtlsTestPki.Pki TEST_PKI = createTestPki(); - private static final CommonGrpcClientProperties ACCOUNT_CLIENT_TLS = createAccountClientTls(); - private static final PostgreSQLContainer entityPostgres = - new PostgreSQLContainer<>(TestContainerImages.postgres()); - - @Container - static PostgreSQLContainer accountPostgres = - new PostgreSQLContainer<>(TestContainerImages.postgres()); - - @Container - static GenericContainer redis = - new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); - - private static volatile EntityRuntime entityRuntime; - - @DynamicPropertySource - static void configure(DynamicPropertyRegistry registry) { - PostgresBackedServiceTestSupport.registerPostgresService( - registry, accountPostgres, "account_service"); - PostgresBackedServiceTestSupport.registerRedisService(registry, redis); - registry.add("firemud.services.entity-management-service", () -> entityServiceTarget()); - registry.add("FIREMUD_GRPC_CERT_CHAIN_PATH", ACCOUNT_CLIENT_TLS::getCertChain); - registry.add("FIREMUD_GRPC_PRIVATE_KEY_PATH", ACCOUNT_CLIENT_TLS::getPrivateKey); - registry.add("FIREMUD_GRPC_CA_CERT_PATH", ACCOUNT_CLIENT_TLS::getCaCert); - } - - @LocalServerPort private int accountHttpPort; - @Autowired private DSLContext accountDsl; - @Autowired private JwtUtil jwtUtil; - - @MockitoBean private GameSessionClient gameSessionClient; - @MockitoBean private LoggingAdminClient loggingAdminClient; - @MockitoBean private JavaMailSender mailSender; - - private final JsonMapper jsonMapper = JsonMapper.builder().build(); - - @org.junit.jupiter.api.AfterAll - static void stopEntityRuntime() throws InterruptedException { - EntityRuntime runtime = entityRuntime; - if (runtime != null) { - runtime.server().shutdownNow(); - assertThat(runtime.server().awaitTermination(5, TimeUnit.SECONDS)).isTrue(); - runtime.meters().close(); - } - if (entityPostgres.isRunning()) { - entityPostgres.stop(); - } - } - - @org.junit.jupiter.api.Test - void bootstrapCharactersUsePersistedUuidAcrossHttpAndRealEntityOwnerReads() throws Exception { - stubControlledCurrentTarget(); - - String suffix = UUID.randomUUID().toString().substring(0, 8); - TestAccount ownerA = registerAccount("uuid-owner-a-" + suffix); - TestAccount ownerB = registerAccount("uuid-owner-b-" + suffix); - assertThat(ownerA.accountUuid()).isNotEqualTo(ownerB.accountUuid()); - seedAdmittingMembership(ownerA.storageId()); - seedAdmittingMembership(ownerB.storageId()); - seedActiveSubscription(ownerA.storageId()); - - EntityRuntime entity = requireEntityRuntime(); - String ownerACharacterName = "owned-by-a-" + suffix; - String ownerBCharacterName = "owned-by-b-" + suffix; - String wrongTenantCharacterName = "wrong-tenant-a-" + suffix; - var ownerACharacter = - saveOrdinaryCharacter( - entity, TARGET_TENANT_ID, ownerA.accountUuid(), ownerACharacterName, "shared-live"); - var ownerBCharacter = - saveOrdinaryCharacter( - entity, TARGET_TENANT_ID, ownerB.accountUuid(), ownerBCharacterName, "shared-live"); - var wrongTenantCharacter = - saveOrdinaryCharacter( - entity, - TARGET_TENANT_ID + 1, - ownerA.accountUuid(), - wrongTenantCharacterName, - "shared-live"); - - assertOrdinaryUuidRowIsQuarantined(entity, ownerACharacter.getId(), ownerA.accountUuid()); - assertOrdinaryUuidRowIsQuarantined(entity, ownerBCharacter.getId(), ownerB.accountUuid()); - assertOrdinaryUuidRowIsQuarantined(entity, wrongTenantCharacter.getId(), ownerA.accountUuid()); - - var retainedBefore = retainedNumericOwnerRow(entity); - assertThat(retainedBefore).hasSize(1); - - String ownerAToken = issuePlayerBootstrap(ownerA); - String ownerBToken = issuePlayerBootstrap(ownerB); - String ownerAScope = discoverConnectScope(ownerA, ownerAToken); - String ownerBScope = discoverConnectScope(ownerB, ownerBToken); - - JsonNode ownerACharacters = listBootstrapCharacters(ownerAToken, ownerAScope); - JsonNode ownerBCharacters = listBootstrapCharacters(ownerBToken, ownerBScope); - - assertThat(characterNames(ownerACharacters)).containsExactly(ownerACharacterName); - assertThat(characterNames(ownerACharacters)) - .doesNotContain(ownerBCharacterName, wrongTenantCharacterName); - assertThat(characterNames(ownerBCharacters)).containsExactly(ownerBCharacterName); - assertThat(characterNames(ownerBCharacters)).doesNotContain(ownerACharacterName); - - var retainedAccountIdRequest = - ListCharactersByAccountRequest.newBuilder() - .setTenantId(Long.toString(TARGET_TENANT_ID)) - .setAccountId(Long.toString(RETAINED_NUMERIC_ACCOUNT_ID)) - .setGameInstanceId(Long.toString(TARGET_GAME_INSTANCE_ID)) - .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) - .build(); - var retainedOwnerResponse = listCharactersDirectlyAsAccount(retainedAccountIdRequest); - assertThat(retainedOwnerResponse.hasError()).isTrue(); - assertThat(retainedOwnerResponse.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); - assertThat(retainedOwnerResponse.getCharactersList()).isEmpty(); - assertThat(retainedNumericOwnerRow(entity)).isEqualTo(retainedBefore); - } - - private TestAccount registerAccount(String username) throws Exception { - String email = username + "@example.com"; - HttpRequest request = - HttpRequest.newBuilder(URI.create(accountBaseUrl() + "/accounts")) - .header(HttpHeaders.CONTENT_TYPE, "application/json") - .POST( - HttpRequest.BodyPublishers.ofString( - jsonMapper.writeValueAsString( - Map.of("username", username, "email", email, "password", "password123")))) - .build(); - HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); - assertThat(response.statusCode()).as(response.body()).isEqualTo(200); - - String responseUuid = jsonMapper.readTree(response.body()).path("data").path("id").asText(); - UUID accountUuid = UUID.fromString(responseUuid); - Number accountId = - accountDsl - .resultQuery("SELECT id FROM accounts WHERE email = ?", email) - .fetchOne(0, Number.class); - assertThat(accountId).isNotNull(); - long storageId = accountId.longValue(); - assertThat( - accountDsl - .resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", storageId) - .fetchOne(0, UUID.class)) - .isEqualTo(accountUuid); - assertThat( - accountDsl - .resultQuery( - "SELECT account_uuid_source_numeric_id FROM accounts WHERE id = ?", storageId) - .fetchOne(0, Long.class)) - .isEqualTo(storageId); - assertThat( - accountDsl - .resultQuery("SELECT account_uuid_provenance FROM accounts WHERE id = ?", storageId) - .fetchOne(0, String.class)) - .isEqualTo("ACCOUNT_REPOSITORY_INSERT"); - return new TestAccount(username, email, storageId, accountUuid); - } - - private void seedAdmittingMembership(long accountId) { - // This is test-owned Account state for the existing roster guard, not canonical membership - // proof. - accountDsl.execute( - "INSERT INTO account_tenant_membership " - + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " - + "membership_version, membership_authority_generation, authority_provenance) " - + "VALUES (?, ?, TRUE, 'ACTIVE', 1, 1, 'SEEDED_DEMO')", - accountId, - TARGET_TENANT_ID); - } - - private void seedActiveSubscription(long accountId) { - accountDsl.execute( - "INSERT INTO subscription " - + "(account_id, plan_id, status, tenant_id, entitlement_version) " - + "VALUES (?, 'uuid-bootstrap-composition', 'active', ?, 1)", - accountId, - TARGET_TENANT_ID); - } - - private String issuePlayerBootstrap(TestAccount account) throws Exception { - HttpRequest request = - HttpRequest.newBuilder(URI.create(accountBaseUrl() + "/auth/player-bootstrap")) - .header(HttpHeaders.CONTENT_TYPE, "application/json") - .POST( - HttpRequest.BodyPublishers.ofString( - jsonMapper.writeValueAsString( - Map.of("accountIdentifier", account.username(), "secret", "password123")))) - .build(); - HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); - assertThat(response.statusCode()).as(response.body()).isEqualTo(200); - JsonNode data = jsonMapper.readTree(response.body()).path("data"); - assertThat(data.path("accountId").asText()).isEqualTo(account.accountUuid().toString()); - String bootstrapToken = data.path("bootstrapToken").asText(); - var claims = jwtUtil.parseToken(bootstrapToken).getPayload(); - assertThat(claims.getSubject()).isEqualTo(account.accountUuid().toString()); - assertThat(claims.get("accountId", String.class)).isEqualTo(account.accountUuid().toString()); - return bootstrapToken; - } - - private String discoverConnectScope(TestAccount account, String bootstrapToken) throws Exception { - HttpRequest request = - HttpRequest.newBuilder( - URI.create(accountBaseUrl() + "/auth/bootstrap/worlds/" + WORLD_SLUG + "/realms")) - .header(HttpHeaders.AUTHORIZATION, "Bearer " + bootstrapToken) - .GET() - .build(); - HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); - assertThat(response.statusCode()).as(response.body()).isEqualTo(200); - JsonNode realms = jsonMapper.readTree(response.body()).path("data"); - assertThat(realms.isArray()).isTrue(); - assertThat(realms.size()).isEqualTo(1); - JsonNode realm = realms.get(0); - assertThat(realm.path("tenantId").asLong()).isEqualTo(TARGET_TENANT_ID); - String scope = realm.path("connectScopeId").asText(); - var claims = jwtUtil.parseToken(scope).getPayload(); - assertThat(claims.getSubject()).isEqualTo(account.accountUuid().toString()); - assertThat(claims.get("accountId", String.class)).isEqualTo(account.accountUuid().toString()); - return scope; - } - - private JsonNode listBootstrapCharacters(String bootstrapToken, String connectScopeId) - throws Exception { - String encodedScope = URLEncoder.encode(connectScopeId, StandardCharsets.UTF_8); - HttpRequest request = - HttpRequest.newBuilder( - URI.create( - accountBaseUrl() - + "/auth/bootstrap/worlds/" - + WORLD_SLUG - + "/realms/" - + REALM_SLUG - + "/characters?connectScopeId=" - + encodedScope)) - .header(HttpHeaders.AUTHORIZATION, "Bearer " + bootstrapToken) - .GET() - .build(); - HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); - assertThat(response.statusCode()).as(response.body()).isEqualTo(200); - return jsonMapper.readTree(response.body()).path("data"); - } - - private ListCharactersByAccountResponse listCharactersDirectlyAsAccount( - ListCharactersByAccountRequest request) throws Exception { - EntityRuntime runtime = requireEntityRuntime(); - var identity = TEST_PKI.identity("account"); - ManagedChannel channel = - NettyChannelBuilder.forAddress("localhost", runtime.server().getPort()) - .sslContext( - GrpcSslContexts.forClient() - .trustManager(TEST_PKI.caCertificate()) - .keyManager( - identity.privateKey(), identity.certificate(), TEST_PKI.caCertificate()) - .build()) - .intercept(new GrpcServerPeerIdentityClientInterceptor(TEST_ENTITY_PEER)) - .build(); - try { - return EntityManagementServiceGrpc.newBlockingStub(channel) - .withDeadlineAfter(5, TimeUnit.SECONDS) - .listCharactersByAccount(request); - } finally { - channel.shutdownNow(); - assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); - } - } - - private void stubControlledCurrentTarget() { - var realm = - net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() - .setWorldSlug(WORLD_SLUG) - .setRealmSlug(REALM_SLUG) - .setDisplayName("Controlled UUID composition target") - .setTenantId(Long.toString(TARGET_TENANT_ID)) - .setGameInstanceId(Long.toString(TARGET_GAME_INSTANCE_ID)) - .setRealmId(TARGET_REALM_ID.toString()) - .setPlayableStateNamespaceId(TARGET_NAMESPACE_ID.toString()) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build(); - var pointer = - net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() - .setWorldSlug(WORLD_SLUG) - .setRealmSlug(REALM_SLUG) - .setTenantId(Long.toString(TARGET_TENANT_ID)) - .setGameInstanceId(Long.toString(TARGET_GAME_INSTANCE_ID)) - .setRealmId(TARGET_REALM_ID.toString()) - .setPlayableStateNamespaceId(TARGET_NAMESPACE_ID.toString()) - .setCatalogRevision(23L) - .setPointerVersion(17L) - .setVisible(true) - .setPublicProductionRealm(true) - .setStateScope("SHARED") - .setCharacterCreationPolicy("ALLOW_NEW") - .build(); - Mockito.when(gameSessionClient.listGameplayRealms(WORLD_SLUG)).thenReturn(List.of(realm)); - Mockito.when(gameSessionClient.getAdmissionPointer(TARGET_TENANT_ID, WORLD_SLUG, REALM_SLUG)) - .thenReturn(pointer); - } - - private static net.firedevops.firemud.entitymanagement.entity.Character saveOrdinaryCharacter( - EntityRuntime runtime, - long tenantId, - UUID accountUuid, - String name, - String playableStateKey) { - var character = new net.firedevops.firemud.entitymanagement.entity.Character(); - character.setTenantId(tenantId); - character.setAccountUuid(accountUuid); - character.setPlayableStateKey(playableStateKey); - character.setName(name); - return runtime.characterRepository().save(character); - } - - private static void assertOrdinaryUuidRowIsQuarantined( - EntityRuntime runtime, long characterId, UUID accountUuid) { - var persisted = runtime.characterRepository().findById(characterId).orElseThrow(); - assertThat(persisted.getAccountUuid()).isEqualTo(accountUuid); - assertThat(persisted.getAccountId()).isNull(); - assertThat(persisted.getActorIdentity().status()).isEqualTo(ActorIdentityStatus.QUARANTINED); - assertThat(persisted.getActorIdentity().tenantUuid()).isNull(); - assertThat(persisted.getActorIdentity().playableStateNamespaceId()).isNull(); - } - - private static List> retainedNumericOwnerRow(EntityRuntime runtime) { - return runtime - .jdbc() - .queryForList( - "SELECT *, xmin::text AS retained_xmin FROM characters WHERE account_id = ?", - RETAINED_NUMERIC_ACCOUNT_ID); - } - - private static List characterNames(JsonNode characters) { - return java.util.stream.StreamSupport.stream(characters.spliterator(), false) - .map(character -> character.path("characterName").asText()) - .toList(); - } - - private String accountBaseUrl() { - return "http://localhost:" + accountHttpPort; - } - - private static String entityServiceTarget() { - return "localhost:" + requireEntityRuntime().server().getPort(); - } - - private static synchronized EntityRuntime requireEntityRuntime() { - if (entityRuntime != null) { - return entityRuntime; - } - try { - if (!entityPostgres.isRunning()) { - entityPostgres.start(); - } - var dataSource = - new DriverManagerDataSource( - entityPostgres.getJdbcUrl(), - entityPostgres.getUsername(), - entityPostgres.getPassword()); - String migrationProperty = - System.getProperty("firemud.entity-management.migration-directory"); - if (migrationProperty == null || migrationProperty.isBlank()) { - throw new IllegalStateException("Entity migration directory property is missing or blank"); - } - Path migrationDirectory = Path.of(migrationProperty); - if (!Files.isDirectory(migrationDirectory)) { - throw new IllegalStateException( - "Entity migration directory is unavailable: " + migrationDirectory); - } - entityMigrationConfiguration(dataSource, migrationDirectory) - .target(MigrationVersion.fromVersion("1023")) - .load() - .migrate(); - var jdbc = new JdbcTemplate(dataSource); - jdbc.update( - "INSERT INTO characters (tenant_id, account_id, name) VALUES (?, ?, ?)", - TARGET_TENANT_ID, - RETAINED_NUMERIC_ACCOUNT_ID, - "retained-numeric-owner"); - entityMigrationConfiguration(dataSource, migrationDirectory).load().migrate(); - - DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); - var repository = new CharacterRepository(dsl); - var stateKeys = new PlayableStateKeyResolver(); - var meters = new SimpleMeterRegistry(); - var characterService = - new CharacterServiceImpl( - repository, - Mappers.getMapper(CharacterMapper.class), - new ConcurrentMapCacheManager("characterGraph"), - meters, - stateKeys, - new ScopedCharacterResolver(repository, stateKeys)); - var receiver = - new EntityManagementGrpcService( - Mockito.mock(net.firedevops.firemud.entitymanagement.service.PingService.class), - characterService, - Mockito.mock(net.firedevops.firemud.entitymanagement.service.ActorStateService.class), - Mockito.mock( - net.firedevops.firemud.entitymanagement.service.ActorConditionMutationService - .class), - Mockito.mock( - net.firedevops.firemud.entitymanagement.service.EntityDraftDesignDigestService - .class), - Mockito.mock(net.firedevops.firemud.entitymanagement.service.EquipmentService.class), - Mockito.mock(net.firedevops.firemud.entitymanagement.service.InventoryService.class), - Mockito.mock(net.firedevops.firemud.entitymanagement.service.ContainerService.class), - Mockito.mock(net.firedevops.firemud.entitymanagement.service.RoomEntityService.class), - Mockito.mock( - net.firedevops.firemud.entitymanagement.service.RuntimeInstanceCleanupService - .class), - Mockito.mock( - net.firedevops.firemud.entitymanagement.service.impl - .EntityMutationEffectReplayService.class), - Mockito.mock( - net.firedevops.firemud.entitymanagement.service.EntityUpgradeValidationService - .class), - Mockito.mock( - net.firedevops.firemud.entitymanagement.service.EntityTemplateReferenceService - .class), - Mockito.mock( - net.firedevops.firemud.common.security.GameplaySessionAttestationService.class), - meters, - Mockito.mock( - net.firedevops.firemud.entitymanagement.effect.EffectPayloadParser.class), - TEST_NAMESPACE); - var entityIdentity = TEST_PKI.identity("entity"); - Server server = - NettyServerBuilder.forPort(0) - .sslContext( - GrpcSslContexts.configure( - SslContextBuilder.forServer( - entityIdentity.privateKey(), entityIdentity.certificate())) - .trustManager(TEST_PKI.caCertificate()) - .clientAuth(ClientAuth.REQUIRE) - .build()) - .addService(ServerInterceptors.intercept(receiver, new GrpcPeerIdentityInterceptor())) - .build() - .start(); - entityRuntime = new EntityRuntime(repository, jdbc, server, meters); - return entityRuntime; - } catch (IOException | RuntimeException failure) { - if (entityPostgres.isRunning()) { - entityPostgres.stop(); - } - throw new IllegalStateException( - "Could not start the real Entity mTLS owner fixture", failure); - } - } - - private static FluentConfiguration entityMigrationConfiguration( - DriverManagerDataSource dataSource, Path migrationDirectory) { - FluentConfiguration configuration = - Flyway.configure() - .dataSource(dataSource) - .locations( - "filesystem:" + migrationDirectory, - "filesystem:" - + migrationDirectory - .resolve( - "../../../../../../common-saga/src/main/resources/db/migration/saga") - .normalize()) - .placeholders(Map.of("serviceSchema", "public")); - configuration - .getConfigurationExtension(PostgreSQLConfigurationExtension.class) - .setTransactionalLock(false); - return configuration; - } - - private static Path createTemporaryDirectory() { - try { - return Files.createTempDirectory("firemud-account-entity-composition-"); - } catch (Exception failure) { - throw new ExceptionInInitializerError(failure); - } - } - - private static LoopbackMtlsTestPki.Pki createTestPki() { - try { - return LoopbackMtlsTestPki.create( - PKI_DIRECTORY, - "Account-to-Entity composition proof CA", - new LoopbackMtlsTestPki.IdentitySpec("entity", TEST_ENTITY_PEER, true), - new LoopbackMtlsTestPki.IdentitySpec("account", TEST_ACCOUNT_PEER, false)); - } catch (Exception failure) { - throw new ExceptionInInitializerError(failure); - } - } - - private static CommonGrpcClientProperties createAccountClientTls() { - try { - return TEST_PKI.clientProperties(PKI_DIRECTORY, TEST_PKI.identity("account")); - } catch (CertificateEncodingException | java.io.IOException failure) { - throw new ExceptionInInitializerError(failure); - } - } - - private record TestAccount(String username, String email, long storageId, UUID accountUuid) {} - - private record EntityRuntime( - CharacterRepository characterRepository, - JdbcTemplate jdbc, - Server server, - SimpleMeterRegistry meters) {} -} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityCurrentnessIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityCurrentnessIntegrationTest.java index a77a2bbea1..9cdae492d6 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityCurrentnessIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityCurrentnessIntegrationTest.java @@ -268,7 +268,7 @@ private static void assertCanonicalCheckpoint( .containsEntry("current_generation", event.tenantAuthorityGeneration()) .containsEntry("tenant_billing_sequence", receipt.tenantBillingSequence()) .containsEntry("last_outbox_sequence", checkpoint.outboxSequence()) - .containsEntry("last_event_id", event.eventId()) + .containsEntry("last_event_id", event.eventId().toString()) .containsEntry("last_event_digest", event.eventDigest()); }); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java index 83e548e6dc..dbb5872a20 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java @@ -196,10 +196,16 @@ void actualDefaultLocationsFreshBootstrapAppliesFullCombinedHistoryAndEnabledGua var dsl = DSL.using(source, SQLDialect.POSTGRES); assertThat( dsl.fetchSingle( - "SELECT count(*) FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ? AND NOT t.tgisinternal AND t.tgenabled <> 'O'", + "SELECT count(*) FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ? AND NOT t.tgisinternal AND t.tgenabled NOT IN ('O', 'A')", schema) .get(0, Long.class)) .isZero(); + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ? AND c.relname = 'account_retained_subscription_evidence' AND t.tgname = 'account_retained_subscription_evidence_immutable' AND t.tgenabled = 'A'", + schema) + .get(0, Long.class)) + .isEqualTo(1L); for (String signature : List.of( "account_ss_admission_assert_current(account_start_session_admission_protections,boolean)", From c619f59ddc9eace350e65ec81e53960f41f42176 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 3 Nov 2026 22:23:13 +1300 Subject: [PATCH 03/23] test: reuse owned database connections in World composition proof --- .../AccountControlUiOriginalOrderFixture.java | 288 +++++---- .../AccountControlUiOwnerSourcesFixture.java | 570 ++++++++++-------- ...ationOwnerCompositionCrossServiceTest.java | 115 ++-- 3 files changed, 564 insertions(+), 409 deletions(-) diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java index bf743a2a40..ba354e4288 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java @@ -76,6 +76,30 @@ public AccountControlUiOriginalOrderFixture( Clock.systemUTC()); } + public AccountControlUiOriginalOrderFixture( + String jdbcUrl, + String username, + String password, + String redisHost, + int redisPort, + Path temporary, + UUID gameDesignTenant, + boolean ownedCompositionConnections) + throws Exception { + this( + jdbcUrl, + username, + password, + redisHost, + redisPort, + temporary, + gameDesignTenant, + Clock.systemUTC(), + null, + Clock.systemUTC(), + ownedCompositionConnections); + } + /** Actor clock is injectable for genuine signed-credential expiry recovery proof. */ public AccountControlUiOriginalOrderFixture( String jdbcUrl, @@ -142,112 +166,164 @@ public AccountControlUiOriginalOrderFixture( String migrationTarget, Clock serviceClock) throws Exception { + this( + jdbcUrl, + username, + password, + redisHost, + redisPort, + temporary, + gameDesignTenant, + actorClock, + migrationTarget, + serviceClock, + false); + } + + private AccountControlUiOriginalOrderFixture( + String jdbcUrl, + String username, + String password, + String redisHost, + int redisPort, + Path temporary, + UUID gameDesignTenant, + Clock actorClock, + String migrationTarget, + Clock serviceClock, + boolean ownedCompositionConnections) + throws Exception { this.temporary = temporary; Objects.requireNonNull(actorClock, "actorClock"); Objects.requireNonNull(serviceClock, "serviceClock"); f = new AccountControlUiOwnerSourcesFixture( - jdbcUrl, username, password, temporary, false, gameDesignTenant, migrationTarget); - signerFixture = new AccountControlUiSignerFixture(f, temporary, serviceClock); - var lifecycle = signerFixture; - lifecycle.commit(); - var originalSigner = f.tx(lifecycle.signer::captureCurrent); - assertThat(f.tx(() -> lifecycle.signer.requireOriginal(originalSigner.receipt())).receipt()) - .isEqualTo(originalSigner.receipt()); - custody("encryption", "enc1", 11); - custody("request-mac", "mac1", 29); - String PASSWORD = UUID.randomUUID().toString(); - var admin = RedisClient.create(RedisURI.Builder.redis(redisHost, redisPort).build()); - accountClient = - RedisClient.create( - RedisURI.Builder.redis(redisHost, redisPort) - .withAuthentication("account_coord_app", PASSWORD) - .build()); - accountClient.setOptions(ClientOptions.builder().autoReconnect(false).build()); - try (var connection = admin.connect(ByteArrayCodec.INSTANCE)) { - connection - .sync() - .aclSetuser( - "account_coord_app", - new io.lettuce.core.AclSetuserArgs() - .reset() - .on() - .addPassword(PASSWORD) - .keyPattern("session:auth:token:*") - .addCommand(io.lettuce.core.protocol.CommandType.HELLO) - .addCommand(io.lettuce.core.protocol.CommandType.PING) - .addCommand( - io.lettuce.core.protocol.CommandType.CLIENT, - io.lettuce.core.protocol.CommandKeyword.SETINFO) - .addCommand( - io.lettuce.core.protocol.CommandType.ACL, - io.lettuce.core.protocol.CommandKeyword.WHOAMI) - .addCommand( - io.lettuce.core.protocol.CommandType.SCRIPT, - io.lettuce.core.protocol.CommandKeyword.LOAD) - .addCommand(io.lettuce.core.protocol.CommandType.EVALSHA) - .addCommand(io.lettuce.core.protocol.CommandType.GET) - .addCommand(io.lettuce.core.protocol.CommandType.SET) - .addCommand(io.lettuce.core.protocol.CommandType.PEXPIRETIME) - .addCommand(io.lettuce.core.protocol.CommandType.TIME)); - connection - .sync() - .dispatch( - TestAclCommand.INSTANCE, - new io.lettuce.core.output.StatusOutput<>(ByteArrayCodec.INSTANCE), - new io.lettuce.core.protocol.CommandArgs<>(ByteArrayCodec.INSTANCE) - .add("SETUSER") - .add("account_coord_app") - .add("+waitaof")); - awaitLocalAndReplicaAof(connection.sync()); - - } finally { - admin.shutdown(); + jdbcUrl, + username, + password, + temporary, + false, + gameDesignTenant, + migrationTarget, + ownedCompositionConnections); + RedisClient allocatedClient = null; + try { + signerFixture = new AccountControlUiSignerFixture(f, temporary, serviceClock); + var lifecycle = signerFixture; + lifecycle.commit(); + var originalSigner = f.tx(lifecycle.signer::captureCurrent); + assertThat(f.tx(() -> lifecycle.signer.requireOriginal(originalSigner.receipt())).receipt()) + .isEqualTo(originalSigner.receipt()); + custody("encryption", "enc1", 11); + custody("request-mac", "mac1", 29); + String PASSWORD = UUID.randomUUID().toString(); + var admin = RedisClient.create(RedisURI.Builder.redis(redisHost, redisPort).build()); + accountClient = + RedisClient.create( + RedisURI.Builder.redis(redisHost, redisPort) + .withAuthentication("account_coord_app", PASSWORD) + .build()); + allocatedClient = accountClient; + accountClient.setOptions(ClientOptions.builder().autoReconnect(false).build()); + try (var connection = admin.connect(ByteArrayCodec.INSTANCE)) { + connection + .sync() + .aclSetuser( + "account_coord_app", + new io.lettuce.core.AclSetuserArgs() + .reset() + .on() + .addPassword(PASSWORD) + .keyPattern("session:auth:token:*") + .addCommand(io.lettuce.core.protocol.CommandType.HELLO) + .addCommand(io.lettuce.core.protocol.CommandType.PING) + .addCommand( + io.lettuce.core.protocol.CommandType.CLIENT, + io.lettuce.core.protocol.CommandKeyword.SETINFO) + .addCommand( + io.lettuce.core.protocol.CommandType.ACL, + io.lettuce.core.protocol.CommandKeyword.WHOAMI) + .addCommand( + io.lettuce.core.protocol.CommandType.SCRIPT, + io.lettuce.core.protocol.CommandKeyword.LOAD) + .addCommand(io.lettuce.core.protocol.CommandType.EVALSHA) + .addCommand(io.lettuce.core.protocol.CommandType.GET) + .addCommand(io.lettuce.core.protocol.CommandType.SET) + .addCommand(io.lettuce.core.protocol.CommandType.PEXPIRETIME) + .addCommand(io.lettuce.core.protocol.CommandType.TIME)); + connection + .sync() + .dispatch( + TestAclCommand.INSTANCE, + new io.lettuce.core.output.StatusOutput<>(ByteArrayCodec.INSTANCE), + new io.lettuce.core.protocol.CommandArgs<>(ByteArrayCodec.INSTANCE) + .add("SETUSER") + .add("account_coord_app") + .add("+waitaof")); + awaitLocalAndReplicaAof(connection.sync()); + + } finally { + admin.shutdown(); + } + coordination = + new AccountControlUiCoordination( + () -> accountClient.connect(ByteArrayCodec.INSTANCE), + new AcknowledgementRequirements(1, 1, 5000), + testCatalog()); + operations = + migrationTarget != null + && AccountControlUiOwnerSourcesFixture.HISTORICAL_MIGRATION_TARGETS.contains( + migrationTarget) + ? new AccountHistoricalControlUiIssuanceRepository(f.dsl) + : new AccountControlUiIssuanceRepository(f.dsl); + publicSource = + org.mockito.Mockito.spy( + new AccountJwtJwksTrustedSource( + lifecycle.client, + lifecycle.trust, + lifecycle.desired, + lifecycle.publication, + f.manager)); + actors = + new AccountControlUiActorService( + operations, + f.authority, + lifecycle.signer, + coordination, + publicSource, + f.fences, + f.manager, + actorClock); + issuance = + new AccountControlUiIssuanceService( + f.primary, + operations, + f.authority, + f.fences, + lifecycle.signer, + new AccountControlUiResponseCryptography( + new AccountControlUiKeyring(temporary.resolve("custody")), serviceClock), + coordination, + actors, + f.manager, + serviceClock, + 300_000L, + AccountControlUiOwnerSourcesFixture.CALLER); + } catch (Exception | Error failure) { + if (allocatedClient != null) { + try { + allocatedClient.shutdown(); + } catch (RuntimeException | Error cleanupFailure) { + failure.addSuppressed(cleanupFailure); + } + } + try { + f.closeOwnedConnections(); + } catch (RuntimeException | Error cleanupFailure) { + failure.addSuppressed(cleanupFailure); + } + throw failure; } - coordination = - new AccountControlUiCoordination( - () -> accountClient.connect(ByteArrayCodec.INSTANCE), - new AcknowledgementRequirements(1, 1, 5000), - testCatalog()); - operations = - migrationTarget != null - && AccountControlUiOwnerSourcesFixture.HISTORICAL_MIGRATION_TARGETS.contains( - migrationTarget) - ? new AccountHistoricalControlUiIssuanceRepository(f.dsl) - : new AccountControlUiIssuanceRepository(f.dsl); - publicSource = - org.mockito.Mockito.spy( - new AccountJwtJwksTrustedSource( - lifecycle.client, - lifecycle.trust, - lifecycle.desired, - lifecycle.publication, - f.manager)); - actors = - new AccountControlUiActorService( - operations, - f.authority, - lifecycle.signer, - coordination, - publicSource, - f.fences, - f.manager, - actorClock); - issuance = - new AccountControlUiIssuanceService( - f.primary, - operations, - f.authority, - f.fences, - lifecycle.signer, - new AccountControlUiResponseCryptography( - new AccountControlUiKeyring(temporary.resolve("custody")), serviceClock), - coordination, - actors, - f.manager, - serviceClock, - 300_000L, - AccountControlUiOwnerSourcesFixture.CALLER); } /** The same persistence layout used by this fixture's genuine issuance and actor owners. */ @@ -388,7 +464,17 @@ public byte[] originalDraftOwnerReadback(DraftAuthorizationFenceBinding original @Override public void close() { - accountClient.shutdown(); + try { + accountClient.shutdown(); + } catch (RuntimeException | Error failure) { + try { + f.closeOwnedConnections(); + } catch (RuntimeException | Error cleanupFailure) { + failure.addSuppressed(cleanupFailure); + } + throw failure; + } + f.closeOwnedConnections(); } private static RedisScriptCatalog testCatalog() { diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java index 16237e1204..3f2a920a59 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java @@ -108,6 +108,7 @@ final class AccountControlUiOwnerSourcesFixture { final AccountControlUiAuthority authority; final AccountControlUiIssuanceService service; final DataSourceTransactionManager manager; + private final com.zaxxer.hikari.HikariDataSource compositionPool; private final DriverManagerDataSource migrationSource; private final String migrationSchema; final DraftAuthorizationFenceRepository fences; @@ -148,6 +149,19 @@ final class AccountControlUiOwnerSourcesFixture { UUID tenant, String migrationTarget) throws Exception { + this(jdbcUrl, username, password, root, installNegativeIssuer, tenant, migrationTarget, false); + } + + AccountControlUiOwnerSourcesFixture( + String jdbcUrl, + String username, + String password, + Path root, + boolean installNegativeIssuer, + UUID tenant, + String migrationTarget, + boolean ownedCompositionConnections) + throws Exception { if (migrationTarget != null && !HISTORICAL_MIGRATION_TARGETS.contains(migrationTarget)) { throw new IllegalArgumentException( "Only the preserved 160.1 source-retention, 1006 parent, 1007 preliminary source-read, 1009 selected-owner predecessor, or 1010 selected-publication closure predecessor is supported"); @@ -161,274 +175,292 @@ final class AccountControlUiOwnerSourcesFixture { var migrations = migrationConfiguration(); if (migrationTarget != null) migrations.target(migrationTarget); migrations.load().migrate(); - manager = new DataSourceTransactionManager(dataSource); - transactions = new TransactionTemplate(manager); - transactions.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); - dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); - var generations = new AccountAuthorityGenerationRepository(dsl); - var outbox = new AccountAuthorityOutboxRepository(dsl); - var sourceEvidence = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); - accounts = new AccountRepository(dsl, sourceEvidence); - restrictionBirths = new AccountPlatformRestrictionBirthRepository(dsl); - restrictionOperations = - new AccountPlatformRestrictionOperationRepository( - dsl, generations, outbox, sourceEvidence, restrictionBirths); - account = - tx( - () -> { - Account candidate = new Account(); - String suffix = UUID.randomUUID().toString(); - candidate.setUsername("owner-" + suffix); - candidate.setEmail(suffix + "@example.test"); - candidate.setPasswordHash(hash("test-only-disabled-password")); - candidate.setLoginAuthModes("EMAIL_OTP"); - return accounts.save(candidate); - }); - var creator = testCreation(account.getAccountUuid(), tenant); - var fresh = new FreshTenantIdentityAssociationRepository(dsl, NAMESPACE); - tx( - () -> { - fresh.importVerified(creator.creationEvidence()); - generations.initializeTenantIfAbsent(tenant); - return null; - }); - var pairs = new AccountMembershipPairAuthorityRepository(dsl); - var memberships = new AccountTenantMembershipRepository(dsl, accounts, fresh, pairs); - var roles = new AccountTenantMembershipRoleSnapshotRepository(dsl); - var bootstrapOperations = new AccountTenantCreationBootstrapOperationRepository(dsl); - var reader = - new AccountCreatorMembershipSourceReader( - accounts, - new AccountJoinOperationRepository(dsl), - memberships, - pairs, - roles, - fresh, - generations, - outbox, - sourceEvidence, - bootstrapOperations); - var beans = new StaticListableBeanFactory(); - AccountTenantCreationBootstrapAuthorizationSource externalBootstrap = - (actual, mutation) -> { - if (!creator.equals(actual) - || !TransactionSynchronizationManager.isActualTransactionActive()) { - throw new IllegalStateException("Exact test-only external bootstrap fixture required"); - } - return mutation.get(); - }; - beans.addBean("testOnlyBootstrapAuthority", externalBootstrap); - var bootstrap = - new AccountTenantCreationBootstrapService( - accounts, - fresh, - reader, - pairs, - memberships, - roles, - outbox, - new AccountAuditOutboxRepository(dsl), - bootstrapOperations, - beans.getBeanProvider(AccountTenantCreationBootstrapAuthorizationSource.class)); - tx(() -> bootstrap.bootstrap(creator)); - var party = - new IndividualCreatorPartySource( - UUID.randomUUID(), - account.getAccountUuid(), - VerificationStatus.VERIFIED, - 1L, - "test-only-policy", - 1L, - "test-only-verification", - 1L, - 1L); - insertTestParty(dsl, party); - var parties = new IndividualCreatorPartyRepository(dsl, fresh, bootstrapOperations); - tx(() -> parties.associateFresh(UUID.randomUUID(), creator, party)); - fences = new DraftAuthorizationFenceRepository(dsl); - Map publications = new HashMap<>(); - Map actions = new HashMap<>(); - Map bindings = new HashMap<>(); - terms = - new AccountHostedTermsService( - manager, - new HostedTermsRepository(dsl), - parties, - fences, - id -> externalFixture(publications, id), - id -> externalFixture(actions, id), - new HostedTermsEnvironmentBindingRepository(dsl), - id -> externalFixture(bindings, id), - () -> { - requireOutsideTransaction(); - return boundary.get(); - }); - UUID publication = UUID.randomUUID(); - publications.put( - publication, - new AccountHostedTermsService.PublicationEvidence( - UUID.randomUUID(), - "Test-only Operator", - 1L, - bytes("Test-only initial terms"), - HostedTermsCatalogVersion.Materiality.INITIAL, - null, - null, - "test-only-publication-audit", - 1L, - "test-only-notice", - 1L, - Instant.now().minusSeconds(30).truncatedTo(ChronoUnit.MICROS))); - var catalog = terms.publish(publication).candidate(); - UUID action = UUID.randomUUID(); - actions.put( - action, - new AccountHostedTermsService.AcceptanceAction( - action, - true, - account.getAccountUuid(), - party.creatorPartyId(), - catalog.hostedScopeId(), - catalog.versionId(), - catalog.documentDigest(), - catalog.operatorLegalIdentity(), - catalog.operatorIdentityVersion(), - "test-only-affirmative-action", - 1L, - OffsetDateTime.now(ZoneOffset.UTC))); - terms.accept(action); - UUID binding = UUID.randomUUID(); - bindings.put( - binding, - new HostedTermsEnvironmentBinding.PublicationEvidence( - "test-production", - catalog.hostedScopeId(), - catalog.operatorLegalIdentity(), - catalog.operatorIdentityVersion(), - catalog.versionId(), - catalog.sourceVersion(), - "test-only-environment-publisher", - "test-only-environment-publication/" + binding, - null, - null)); - terms.publishEnvironmentBinding(binding); - authority = - new AccountControlUiAuthority( - new AccountDraftSourceCompositionService( - dsl, parties, bootstrap, terms, sourceEvidence), - accounts, - sourceEvidence, - restrictionOperations, - dsl); - challenges = new AccountEmailLoginChallengeRepository(dsl); - tx( - () -> { - var challenge = new AccountEmailLoginChallenge(); - var now = LocalDateTime.now().withNano(0); - challenge.setAccountId(account.getId()); - challenge.setCodeHash(hash(OTP)); - challenge.setExpiresAt(now.plusMinutes(5)); - challenge.setResendAvailableAt(now.plusMinutes(1)); - challenge.setCreatedAt(now); - challenge.setUpdatedAt(now); - return challenges.save(challenge); - }); - var primaryTarget = - new AccountServiceImpl( - accounts, - generations, - sourceEvidence, - outbox, - mock( - net.firedevops.firemud.accountservice.repository - .AccountPasswordResetOperationRepository.class), - mock( - net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository - .class), - mock( - net.firedevops.firemud.accountservice.repository - .AccountSecurityStateOperationRepository.class), - mock( - net.firedevops.firemud.accountservice.service - .AccountPasswordResetDraftSourceChangeRepository.class), - mock(AccountAuditOutboxRepository.class), - mock(AccountJoinOperationRepository.class), - challenges, - null, // Realm grants are not used by primary authentication. - null, // Tenant memberships are not used by primary authentication. - Mappers.getMapper(AccountMapper.class), - null, // Profiles are not used by primary authentication. - null, // Profile mapper is not used by primary authentication. - null, // Payment transactions are not used by primary authentication. - // Retained evidence is not read by primary authentication. - org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), - null, // External identities are not used by primary authentication. - null, // Password reset tokens are not used by primary authentication. - null, // Email verification tokens are not used by primary authentication. - null, // Notifications are not used by primary authentication. - null, // Email delivery is not used by primary authentication. - null, // Mail properties are not used by primary authentication. - null, // Token properties are not used by primary authentication. - null, // Entity Management client is not used by primary authentication. - null, // JWT utility is not used by primary authentication. - null, // Session service is not used by primary authentication. - manager); - // Exercise the real MANDATORY interceptor: noRollbackFor must not poison the owner callback. - var primaryProxy = new ProxyFactory(primaryTarget); - primaryProxy.setProxyTargetClass(true); - primaryProxy.addAdvice( - new TransactionInterceptor(manager, new AnnotationTransactionAttributeSource())); - primary = (AccountServiceImpl) primaryProxy.getProxy(); - if (!installNegativeIssuer) { - service = null; - return; + compositionPool = ownedCompositionConnections ? new com.zaxxer.hikari.HikariDataSource() : null; + try { + if (compositionPool != null) { + compositionPool.setPoolName("account-composition-" + schema); + compositionPool.setDataSource(dataSource); + compositionPool.setMaximumPoolSize(8); + compositionPool.setMinimumIdle(0); + } + javax.sql.DataSource ownerSource = compositionPool == null ? dataSource : compositionPool; + manager = new DataSourceTransactionManager(ownerSource); + transactions = new TransactionTemplate(manager); + transactions.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + dsl = DSL.using(new TransactionAwareDataSourceProxy(ownerSource), SQLDialect.POSTGRES); + var generations = new AccountAuthorityGenerationRepository(dsl); + var outbox = new AccountAuthorityOutboxRepository(dsl); + var sourceEvidence = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); + accounts = new AccountRepository(dsl, sourceEvidence); + restrictionBirths = new AccountPlatformRestrictionBirthRepository(dsl); + restrictionOperations = + new AccountPlatformRestrictionOperationRepository( + dsl, generations, outbox, sourceEvidence, restrictionBirths); + account = + tx( + () -> { + Account candidate = new Account(); + String suffix = UUID.randomUUID().toString(); + candidate.setUsername("owner-" + suffix); + candidate.setEmail(suffix + "@example.test"); + candidate.setPasswordHash(hash("test-only-disabled-password")); + candidate.setLoginAuthModes("EMAIL_OTP"); + return accounts.save(candidate); + }); + var creator = testCreation(account.getAccountUuid(), tenant); + var fresh = new FreshTenantIdentityAssociationRepository(dsl, NAMESPACE); + tx( + () -> { + fresh.importVerified(creator.creationEvidence()); + generations.initializeTenantIfAbsent(tenant); + return null; + }); + var pairs = new AccountMembershipPairAuthorityRepository(dsl); + var memberships = new AccountTenantMembershipRepository(dsl, accounts, fresh, pairs); + var roles = new AccountTenantMembershipRoleSnapshotRepository(dsl); + var bootstrapOperations = new AccountTenantCreationBootstrapOperationRepository(dsl); + var reader = + new AccountCreatorMembershipSourceReader( + accounts, + new AccountJoinOperationRepository(dsl), + memberships, + pairs, + roles, + fresh, + generations, + outbox, + sourceEvidence, + bootstrapOperations); + var beans = new StaticListableBeanFactory(); + AccountTenantCreationBootstrapAuthorizationSource externalBootstrap = + (actual, mutation) -> { + if (!creator.equals(actual) + || !TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Exact test-only external bootstrap fixture required"); + } + return mutation.get(); + }; + beans.addBean("testOnlyBootstrapAuthority", externalBootstrap); + var bootstrap = + new AccountTenantCreationBootstrapService( + accounts, + fresh, + reader, + pairs, + memberships, + roles, + outbox, + new AccountAuditOutboxRepository(dsl), + bootstrapOperations, + beans.getBeanProvider(AccountTenantCreationBootstrapAuthorizationSource.class)); + tx(() -> bootstrap.bootstrap(creator)); + var party = + new IndividualCreatorPartySource( + UUID.randomUUID(), + account.getAccountUuid(), + VerificationStatus.VERIFIED, + 1L, + "test-only-policy", + 1L, + "test-only-verification", + 1L, + 1L); + insertTestParty(dsl, party); + var parties = new IndividualCreatorPartyRepository(dsl, fresh, bootstrapOperations); + tx(() -> parties.associateFresh(UUID.randomUUID(), creator, party)); + fences = new DraftAuthorizationFenceRepository(dsl); + Map publications = new HashMap<>(); + Map actions = new HashMap<>(); + Map bindings = new HashMap<>(); + terms = + new AccountHostedTermsService( + manager, + new HostedTermsRepository(dsl), + parties, + fences, + id -> externalFixture(publications, id), + id -> externalFixture(actions, id), + new HostedTermsEnvironmentBindingRepository(dsl), + id -> externalFixture(bindings, id), + () -> { + requireOutsideTransaction(); + return boundary.get(); + }); + UUID publication = UUID.randomUUID(); + publications.put( + publication, + new AccountHostedTermsService.PublicationEvidence( + UUID.randomUUID(), + "Test-only Operator", + 1L, + bytes("Test-only initial terms"), + HostedTermsCatalogVersion.Materiality.INITIAL, + null, + null, + "test-only-publication-audit", + 1L, + "test-only-notice", + 1L, + Instant.now().minusSeconds(30).truncatedTo(ChronoUnit.MICROS))); + var catalog = terms.publish(publication).candidate(); + UUID action = UUID.randomUUID(); + actions.put( + action, + new AccountHostedTermsService.AcceptanceAction( + action, + true, + account.getAccountUuid(), + party.creatorPartyId(), + catalog.hostedScopeId(), + catalog.versionId(), + catalog.documentDigest(), + catalog.operatorLegalIdentity(), + catalog.operatorIdentityVersion(), + "test-only-affirmative-action", + 1L, + OffsetDateTime.now(ZoneOffset.UTC))); + terms.accept(action); + UUID binding = UUID.randomUUID(); + bindings.put( + binding, + new HostedTermsEnvironmentBinding.PublicationEvidence( + "test-production", + catalog.hostedScopeId(), + catalog.operatorLegalIdentity(), + catalog.operatorIdentityVersion(), + catalog.versionId(), + catalog.sourceVersion(), + "test-only-environment-publisher", + "test-only-environment-publication/" + binding, + null, + null)); + terms.publishEnvironmentBinding(binding); + authority = + new AccountControlUiAuthority( + new AccountDraftSourceCompositionService( + dsl, parties, bootstrap, terms, sourceEvidence), + accounts, + sourceEvidence, + restrictionOperations, + dsl); + challenges = new AccountEmailLoginChallengeRepository(dsl); + tx( + () -> { + var challenge = new AccountEmailLoginChallenge(); + var now = LocalDateTime.now().withNano(0); + challenge.setAccountId(account.getId()); + challenge.setCodeHash(hash(OTP)); + challenge.setExpiresAt(now.plusMinutes(5)); + challenge.setResendAvailableAt(now.plusMinutes(1)); + challenge.setCreatedAt(now); + challenge.setUpdatedAt(now); + return challenges.save(challenge); + }); + var primaryTarget = + new AccountServiceImpl( + accounts, + generations, + sourceEvidence, + outbox, + mock( + net.firedevops.firemud.accountservice.repository + .AccountPasswordResetOperationRepository.class), + mock( + net.firedevops.firemud.accountservice.repository + .AccountLogoutAllOperationRepository.class), + mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class), + mock( + net.firedevops.firemud.accountservice.service + .AccountPasswordResetDraftSourceChangeRepository.class), + mock(AccountAuditOutboxRepository.class), + mock(AccountJoinOperationRepository.class), + challenges, + null, // Realm grants are not used by primary authentication. + null, // Tenant memberships are not used by primary authentication. + Mappers.getMapper(AccountMapper.class), + null, // Profiles are not used by primary authentication. + null, // Profile mapper is not used by primary authentication. + null, // Payment transactions are not used by primary authentication. + // Retained evidence is not read by primary authentication. + org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), + null, // External identities are not used by primary authentication. + null, // Password reset tokens are not used by primary authentication. + null, // Email verification tokens are not used by primary authentication. + null, // Notifications are not used by primary authentication. + null, // Email delivery is not used by primary authentication. + null, // Mail properties are not used by primary authentication. + null, // Token properties are not used by primary authentication. + null, // Entity Management client is not used by primary authentication. + null, // JWT utility is not used by primary authentication. + null, // Session service is not used by primary authentication. + manager); + // Exercise the real MANDATORY interceptor: noRollbackFor must not poison the owner callback. + var primaryProxy = new ProxyFactory(primaryTarget); + primaryProxy.setProxyTargetClass(true); + primaryProxy.addAdvice( + new TransactionInterceptor(manager, new AnnotationTransactionAttributeSource())); + primary = (AccountServiceImpl) primaryProxy.getProxy(); + if (!installNegativeIssuer) { + service = null; + return; + } + var signerFixture = new AccountControlUiSignerFixture(this, root); + signerFixture.prepareInitialPrepublication(); + var signer = signerFixture.signer; + var operations = new AccountControlUiIssuanceRepository(dsl); + var crypto = + new AccountControlUiResponseCryptography( + new AccountControlUiKeyring(root.resolve("custody")), Clock.systemUTC()); + var registry = + new AccountControlUiCoordination( + () -> { + coordinationCalls.incrementAndGet(); + throw new IllegalStateException("No physical Redis fixture in this negative proof"); + }, + new AcknowledgementRequirements(1, 1, 1000), + RedisScriptCatalog.fromContributions(List.of())); + var publicSource = + new AccountJwtJwksTrustedSource( + signerFixture.client, + signerFixture.trust, + signerFixture.desired, + signerFixture.publication, + manager); + var actors = + new AccountControlUiActorService( + operations, + authority, + signer, + registry, + publicSource, + fences, + manager, + Clock.systemUTC()); + service = + new AccountControlUiIssuanceService( + primary, + operations, + authority, + fences, + signer, + crypto, + registry, + actors, + manager, + Clock.systemUTC(), + 300_000L, + CALLER); + } catch (Exception | Error failure) { + try { + closeOwnedConnections(); + } catch (RuntimeException | Error cleanupFailure) { + failure.addSuppressed(cleanupFailure); + } + throw failure; } - var signerFixture = new AccountControlUiSignerFixture(this, root); - signerFixture.prepareInitialPrepublication(); - var signer = signerFixture.signer; - var operations = new AccountControlUiIssuanceRepository(dsl); - var crypto = - new AccountControlUiResponseCryptography( - new AccountControlUiKeyring(root.resolve("custody")), Clock.systemUTC()); - var registry = - new AccountControlUiCoordination( - () -> { - coordinationCalls.incrementAndGet(); - throw new IllegalStateException("No physical Redis fixture in this negative proof"); - }, - new AcknowledgementRequirements(1, 1, 1000), - RedisScriptCatalog.fromContributions(List.of())); - var publicSource = - new AccountJwtJwksTrustedSource( - signerFixture.client, - signerFixture.trust, - signerFixture.desired, - signerFixture.publication, - manager); - var actors = - new AccountControlUiActorService( - operations, - authority, - signer, - registry, - publicSource, - fences, - manager, - Clock.systemUTC()); - service = - new AccountControlUiIssuanceService( - primary, - operations, - authority, - fences, - signer, - crypto, - registry, - actors, - manager, - Clock.systemUTC(), - 300_000L, - CALLER); } AccountControlUiIssuanceService.Request request(String secret) { @@ -739,6 +771,10 @@ private static String hash(String value) { } } + void closeOwnedConnections() { + if (compositionPool != null) compositionPool.close(); + } + /** Applies only the remaining real migrations, without rewriting retained fixture rows. */ void upgradeToCurrent() { migrationConfiguration().load().migrate(); 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 e13e919a54..7853ad742d 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; @@ -554,7 +555,8 @@ private void compose( REDIS.getHost(), REDIS.getMappedPort(6379), proofDirectory.resolve("account"), - tenant); + tenant, + true); var world = database(WORLD, "world-management-service", true); var gs = database(GS, "game-session-service", true)) { var issuer = @@ -2249,7 +2251,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) { @@ -4684,47 +4688,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 byte[] controlledInstallationArtifact(String schema) { @@ -4786,11 +4816,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"); + } } } From f5fd19cd79543f9593d62f73182ceb2d407b6c62 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 3 Nov 2026 23:55:47 +1300 Subject: [PATCH 04/23] test: qualify terminal cancellation with genuine Account authority --- .../player-access-and-session.md | 2 +- ...nonicalHostingSubscriptionTestFixture.java | 32 +- ...ionCompositionPostgresIntegrationTest.java | 537 ++++++++++++++++++ .../AccountControlUiOriginalOrderFixture.java | 23 + 4 files changed, 590 insertions(+), 4 deletions(-) create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionCompositionPostgresIntegrationTest.java diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 04dd7ae9b1..010177e52b 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -10,7 +10,7 @@ Account initial/current/final creation owners, explicit initial billing-owner co ### Canonical billing and retention receiving -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 provisioning and cancellation components keep actual Account actor/authentication and owner-local atomic receipt/fence/event checks; cancellation does not establish provider absence, transfer, a registered recovery route or closure of the accepted terminal-recovery Major. +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 provisioning and cancellation components keep actual Account actor/authentication and owner-local atomic receipt/fence/event checks; cancellation prepares one allowed safe outcome. Coupled356physical proof now passes through genuine certified ACCOUNT issuance/current actor, fresh primary OTP authentication and the guarded cancellation commit. Its five PostgreSQL/AOF-replica cases 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. Unchanged355regression passes20lifecycle and21original-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 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. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java index b1793e93d5..33ed0b6d34 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java @@ -25,6 +25,7 @@ import java.util.function.Supplier; import javax.sql.DataSource; import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountBillingCustomerRecord; import net.firedevops.firemud.accountservice.repository.AccountBillingCustomerRepository; @@ -71,6 +72,15 @@ public final class CanonicalHostingSubscriptionTestFixture { private CanonicalHostingSubscriptionTestFixture() {} public static Fixture create(DataSource source) { + return createInternal(source, null); + } + + /** Reuses the exact persisted Account of a genuine actor/authentication composition. */ + public static Fixture create(DataSource source, Account account) { + return createInternal(source, Objects.requireNonNull(account, "persisted Account required")); + } + + private static Fixture createInternal(DataSource source, Account existingAccount) { Objects.requireNonNull(source, "migrated Account datasource is required"); JdbcTemplate jdbc = new JdbcTemplate(source); DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); @@ -86,12 +96,18 @@ public static Fixture create(DataSource source) { long row = GAME_ROWS.incrementAndGet(); var accountRow = - Objects.requireNonNull( - dsl.fetchOne( + existingAccount == null + ? dsl.fetchOne( "INSERT INTO accounts (username, email, password_hash) " + "VALUES (?, ?, 'controlled-hash') RETURNING id, account_uuid", "hosting-fixture-" + row, - "hosting-fixture-" + row + "@example.test")); + "hosting-fixture-" + row + "@example.test") + : dsl.fetchOne( + "SELECT id, account_uuid FROM accounts WHERE id = ? AND account_uuid = ?", + Objects.requireNonNull(existingAccount.getId(), "persisted Account ID required"), + Objects.requireNonNull( + existingAccount.getAccountUuid(), "persisted Account UUID required")); + Objects.requireNonNull(accountRow, "Exact persisted Account row required"); long accountId = accountRow.get("id", Long.class); UUID accountUuid = accountRow.get("account_uuid", UUID.class); @@ -401,11 +417,18 @@ public Instant instant() { public static final class ControlledStripeTransport implements StripeResponseGetter { private String json; private int reads; + private Runnable duringRead; public int reads() { return reads; } + /** One-shot owner mutation while the real SDK request is outside Account SQL. */ + public void duringRead(Runnable action) { + if (duringRead != null) throw new IllegalStateException("A provider-read action is pending"); + duringRead = Objects.requireNonNull(action); + } + @Override @SuppressWarnings("unchecked") public T request( @@ -421,6 +444,9 @@ public T request( assertThat(method).isEqualTo(RequestMethod.GET); assertThat(path).startsWith("/v1/subscriptions/"); reads++; + Runnable action = duringRead; + duringRead = null; + if (action != null) action.run(); return (T) com.stripe.net.ApiResource.GSON.fromJson(json, type); } 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..45c1b8d33a --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionCompositionPostgresIntegrationTest.java @@ -0,0 +1,537 @@ +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.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 realAccountAuthorityAdvanceDuringSdkReadRejectsBeforeMutationAndKeepsOtp() 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"); + return issued.sources().accounts.save(account); + })); + assertThatThrownBy(() -> resolve(failed, issued.account().getEmail(), OTP)) + .isInstanceOf(RuntimeException.class); + 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(), + 2, + 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/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java index ba354e4288..14e01a13bd 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java @@ -390,6 +390,29 @@ record IssuedCreator( CapturedEnvironmentBoundary environment, AccountControlUiOwnerSourcesFixture sources) {} + /** Same-package reuse of genuine certified ACCOUNT issuance, separate from tenant creation. */ + IssuedAccount issueCertifiedAccount(String password) { + var account = f.createCertifiedGlobalAccount(password); + var request = + new AccountControlUiIssuanceService.AccountSignInRequest( + UUID.randomUUID(), account.getEmail(), password, UUID.randomUUID()); + String compact; + try (var peer = + AccountControlUiOwnerSourcesFixture.withPeer( + AccountControlUiOwnerSourcesFixture.CALLER); + var issued = issuance.issueAccount(request)) { + compact = new String(issued.compactBytes(), StandardCharsets.US_ASCII); + } + assertThat(actors.authenticateAccount(compact).accountId()).isEqualTo(account.getAccountUuid()); + return new IssuedAccount(account, compact, actors, f); + } + + record IssuedAccount( + net.firedevops.firemud.accountservice.entity.Account account, + String compact, + AccountControlUiActorService actors, + AccountControlUiOwnerSourcesFixture sources) {} + // These fixture entry points use actual Account owners with test-only creator/legal, // environment, signer-platform and Redis inputs. They confer no production authority. public net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderGrpcCodec.Request From d31b5fe5537f2e80cdbc81de820e04ccc56c5bdb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 4 Nov 2026 03:34:50 +1300 Subject: [PATCH 05/23] Prove delayed hosting reads preserve committed authority --- .../player-access-and-session.md | 2 +- ...ptionLifecyclePostgresIntegrationTest.java | 79 ++++++++++++++++++- 2 files changed, 77 insertions(+), 4 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 97fa7c3c64..b8069498be 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -28,7 +28,7 @@ Bounded source/storage proof passes: 24 shared codec/mutation unit cases and 10 ### Public bootstrap WORLDS source preparation -The local hosting lifecycle policy and receipt producer separate the committed provider/policy fact bound from each fresh SDK read's observation deadline under [Subscription Management](../../architecture/microservices/account-service/subscription-management.md#runtime-entitlement-contract). Receipt bytes and SQL readback retain the same committed bound; current read results still expire at their own observation deadline without a new lifecycle event. This correction requires focused delayed-read PostgreSQL qualification in the canonical subscription receiver; the front carrier does not contain its V1028–V1032 schema foundation. Existing receipts remain immutable, and current paid discovery/runtime support is not inferred from these source changes. +The local hosting lifecycle policy and receipt producer separate the committed provider/policy fact bound from each fresh SDK read's observation deadline under [Subscription Management](../../architecture/microservices/account-service/subscription-management.md#runtime-entitlement-contract). Receipt bytes and SQL readback retain the same committed bound; current read results still expire at their own observation deadline without a new lifecycle event. Proof392 passes all 26 selected physical cases: 21 lifecycle cases and five genuine terminal-recovery compositions, with no failures, errors or skips, plus enabled integration analysis, formatting and documentation checks. The delayed active/trialing reads use new real SDK observations after the original observation window, retain the original receipt and authority rows including xmin, and append no events; stale reads, changed facts, actual period and recovery boundaries still refuse. Proof390 separately passes 32 front policy/repository/service and Game Session published-read cases with enabled affected analysis and documentation checks. Proof389 failed compilation and proof391 failed a public-versus-private error-message assertion; both are retained and corrected. The front carrier does not contain the V1028–V1032 schema foundation and takes this physical qualification from the canonical receiver. Existing receipts remain immutable, and current paid discovery/runtime support is not inferred from these source changes. [`AccountPublicBootstrapWorldsOwner`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwner.java) composes [`AccountPlayerBootstrapCallerVerifier`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerBootstrapCallerVerifier.java), [`CanonicalGameplayAdmissionDecisionReadClient`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClient.java), and [`AccountPublicBootstrapEntitlementOwner`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwner.java). The caller is checked before source work and revalidated before return. Account requests the complete public target collection twice, evaluates current entitlement once per canonical tenant, rejects collection changes and duplicate or ambiguous target identities, and checks each observation deadline before returning. It emits only `gameplayAvailable` targets, ordered by world slug; `allowPublicJoin` does not filter discovery. Any required source failure, changed source, or expired evaluation fails the whole call without a partial list. 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 index f386751468..cde13e3bb2 100644 --- 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 @@ -655,7 +655,64 @@ void realInitialCanceledEvidenceRetiresOnlyItsHoldAndCommittedReceiptCannotBeDet } @Test - void inFlightAndExpiredReceiptOrChangedSdkFactsNeverRefreshAnOldPositiveSnapshot() { + 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 inFlightAndStaleObservationOrChangedSdkFactsNeverRefreshAnOldPositiveSnapshot() { Context c = context("1030"); Fixture f = fixture(c); activate(f); @@ -665,8 +722,14 @@ void inFlightAndExpiredReceiptOrChangedSdkFactsNeverRefreshAnOldPositiveSnapshot .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 = @@ -736,14 +799,24 @@ void unchangedInvalidEvidenceExhaustsFrozenStallBudgetOnceAndNeverReleasesBillin refresh(f); assertThat(f.service().readCurrent(f.creation().tenantId()).subscriptionStatus()) .isEqualTo(Status.PAST_DUE); - f.clock().advance(Duration.ofSeconds(60)); + f.clock().advance(Duration.ofSeconds(30)); + assertThat(f.service().readCurrent(f.creation().tenantId()).subscriptionStatus()) + .isEqualTo(Status.PAST_DUE); + f.clock().advance(Duration.ofSeconds(30)); + assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); refresh(f); var grace = f.service().readCurrent(f.creation().tenantId()); assertThat(grace.subscriptionStatus()).isEqualTo(Status.GRACE); assertThat(grace.gameplayAvailable()).isTrue(); assertThat(grace.allowPublicJoin()).isFalse(); assertThat(grace.allowNewInstanceStarts()).isFalse(); - f.clock().advance(Duration.ofSeconds(120)); + f.clock().advance(Duration.ofSeconds(30)); + assertThat(f.service().readCurrent(f.creation().tenantId()).subscriptionStatus()) + .isEqualTo(Status.GRACE); + f.clock().advance(Duration.ofSeconds(90)); + assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); refresh(f); var suspended = f.service().readCurrent(f.creation().tenantId()); assertThat(suspended.subscriptionStatus()).isEqualTo(Status.SUSPENDED); From 20c5c6896825a8c347ad6cb9388fc90ffca0b861 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 4 Nov 2026 04:02:26 +1300 Subject: [PATCH 06/23] Prove immutable hosting freshness across implemented reads --- .../player-access-and-session.md | 2 +- ...ptionLifecyclePostgresIntegrationTest.java | 71 +++++++++++++++++++ ...titlementOwnerPostgresIntegrationTest.java | 3 + 3 files changed, 75 insertions(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 5e5134e50e..9fd3d81f09 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -28,7 +28,7 @@ Bounded source/storage proof passes: 24 shared codec/mutation unit cases and 10 ### Public bootstrap WORLDS source preparation -The current-read source also supports a freshly confirmed terminal negative projection for the existing `CANCELED` marker after its retained observation deadline, under [Subscription Management](../../architecture/microservices/account-service/subscription-management.md#runtime-entitlement-contract). Original receipt/source bytes and fresh exact provider facts remain required; this source change needs delayed provider/effective-cancellation physical qualification at the canonical schema receiver before claiming discovery recovery. +The current-read source also supports a freshly confirmed terminal negative projection for the existing `CANCELED` marker after its retained observation deadline, under [Subscription Management](../../architecture/microservices/account-service/subscription-management.md#runtime-entitlement-contract). Original receipt/source bytes and fresh exact provider facts remain required. Proof396 passes 46 front policy/repository/service and Game Session discovery cases with enabled affected analysis, formatting and documentation checks. Proof397 passes 20 discovery/entitlement units and 27 physical lifecycle/terminal cases, including delayed provider-confirmed and effective-cancellation negative reads, stale/changed provider refusal and unchanged receipt/authority rows including xmin. The bounded shared-cause check covers every implemented hosting status and both paid/DEMO discovery branches: proof399 passes 37 physical lifecycle, terminal-recovery and DEMO cases, including delayed suspended reads and real grace/period cutoffs; proof400 passes four tenant-operation owner cases with a fresh SDK evaluation after the original observation window and stable committed snapshot identity. All have zero failures, errors or skips and enabled affected checks. TENANT_OPERATION remains an as-of, non-admitting source observation; this does not add currentness protection, capacity authority or default registration. The local hosting lifecycle policy and receipt producer separate the committed provider/policy fact bound from each fresh SDK read's observation deadline under [Subscription Management](../../architecture/microservices/account-service/subscription-management.md#runtime-entitlement-contract). Receipt bytes and SQL readback retain the same committed bound; current read results still expire at their own observation deadline without a new lifecycle event. Proof392 passes all 26 selected physical cases: 21 lifecycle cases and five genuine terminal-recovery compositions, with no failures, errors or skips, plus enabled integration analysis, formatting and documentation checks. The delayed active/trialing reads use new real SDK observations after the original observation window, retain the original receipt and authority rows including xmin, and append no events; stale reads, changed facts, actual period and recovery boundaries still refuse. Proof390 separately passes 32 front policy/repository/service and Game Session published-read cases with enabled affected analysis and documentation checks. Proof389 failed compilation and proof391 failed a public-versus-private error-message assertion; both are retained and corrected. The front carrier does not contain the V1028–V1032 schema foundation and takes this physical qualification from the canonical receiver. Existing receipts remain immutable, and current paid discovery/runtime support is not inferred from these source changes. 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 index cde13e3bb2..c62340e2bc 100644 --- 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 @@ -711,6 +711,68 @@ void freshReadsBeyondObservationAgePreserveCommittedReceiptAndAuthorityUntilReal } } + @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"); @@ -832,6 +894,15 @@ void unchangedInvalidEvidenceExhaustsFrozenStallBudgetOnceAndNeverReleasesBillin java.nio.charset.StandardCharsets.UTF_8)) .contains("TenantBillingStateChanged"); assertThat(suspended.cutoffAt()).isEqualTo(f.clock().instant()); + Instant originalSuspensionCutoff = suspended.cutoffAt(); + f.clock().advance(Duration.ofSeconds(30)); + var laterSuspended = f.service().readCurrent(f.creation().tenantId()); + assertThat(laterSuspended.subscriptionStatus()).isEqualTo(Status.SUSPENDED); + assertThat(laterSuspended.cutoffAt()).isEqualTo(originalSuspensionCutoff); + assertThat(laterSuspended.gameplayAvailable()).isFalse(); + assertThat(laterSuspended.validUntil()).isEqualTo(f.clock().instant().plusSeconds(15)); + assertThat(laterSuspended.tenantBillingSequence()).isEqualTo(4); + assertThat(count(c, "subscription_lifecycle_receipts")).isEqualTo(4); f.transport().json = response(f, "active"); refresh(f); Instant cancellation = f.clock().instant().plusSeconds(2); 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 index 8bc09e456e..354f299448 100644 --- 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 @@ -59,6 +59,7 @@ void paidUsesActualReceiptSdkAndAuthorityCheckpointWithFreshEvaluationOfSameSnap 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()) @@ -72,6 +73,8 @@ void paidUsesActualReceiptSdkAndAuthorityCheckpointWithFreshEvaluationOfSameSnap .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")) From 0e8d6fce7ce89dd04d397e6b923e83c4870e1e03 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 7 Nov 2026 04:08:05 +1300 Subject: [PATCH 07/23] Reject malformed preview head SHAs before lookup --- .github/workflows/preview.yml | 2 +- .../tests/hosted-identity-controller-workflow-contract.sh | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/.github/workflows/preview.yml b/.github/workflows/preview.yml index 5f27e41f6a..693b9bfd6a 100644 --- a/.github/workflows/preview.yml +++ b/.github/workflows/preview.yml @@ -126,7 +126,7 @@ jobs: echo "::error title=Missing preview head SHA::Manual preview dispatches must supply the current PR head SHA." >&2 exit 1 fi - if [[ "$HEAD_SHA" != "${HEAD_SHA,,}" ]]; then + if [[ ! "$HEAD_SHA" =~ ^[0-9a-f]{40}$ ]]; then echo "::error title=Noncanonical preview head SHA::Expected lowercase hexadecimal input." >&2 exit 1 fi diff --git a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh index c8467b09e1..1643550e98 100644 --- a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh @@ -3939,10 +3939,9 @@ if run_preview_derive_dispatch \ exit 1 fi grep -Fxq \ - '::error title=Stale preview head SHA::Supplied head SHA does not equal the current pull request head.' \ + '::error title=Noncanonical preview head SHA::Expected lowercase hexadecimal input.' \ "$preview_derive_invalid_error" -grep -Fxq 'api repos/example/FireMUD/pulls/901' \ - "${preview_derive_invalid_output}.gh.log" +test ! -e "${preview_derive_invalid_output}.gh.log" preview_derive_default_output="$TEMP_DIR/preview-derive-default.output" run_preview_derive_dispatch \ From 9a706a813ca0683f02038bd00201fa79e735bd7f Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 7 Nov 2026 12:57:20 +1300 Subject: [PATCH 08/23] Fix Account billing recovery and entitlement failure classification --- .../player-access-and-session.md | 2 + ...ostingSubscriptionLifecycleRepository.java | 32 ++-- ...ccountTenantOperationEntitlementOwner.java | 11 +- ...TenantOperationEntitlementGrpcService.java | 34 ++++- ...iptionDispatchPostgresIntegrationTest.java | 141 ++++++++++++++++-- ...ptionLifecyclePostgresIntegrationTest.java | 56 +++++++ ...ipeHostingSubscriptionProvisionerTest.java | 121 +++++++++++++-- ...antOperationEntitlementClientMtlsTest.java | 28 +++- 8 files changed, 383 insertions(+), 42 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 5c17f8df1f..77bb6b4353 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -12,6 +12,8 @@ Account initial/current/final creation owners, explicit initial billing-owner co 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 provisioning and cancellation components keep actual Account actor/authentication and owner-local atomic receipt/fence/event checks; cancellation prepares one allowed safe outcome. Coupled356physical proof now passes through genuine certified ACCOUNT issuance/current actor, fresh primary OTP authentication and the guarded cancellation commit. Its five PostgreSQL/AOF-replica cases 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. Unchanged355regression passes20lifecycle and21original-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. +Paid first-invoice confirmation remains an unfinished Account checkout obligation. Stripe `default_incomplete` creation and subscription polling do not confirm a required first payment; controlled active-subscription inputs are not live paid-checkout proof. Complete confirmation through 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. + 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 compilation328 passes. Focused331 executes203Account units, nine shared evidence/transport cases, four actual World→Account mTLS cases and80PostgreSQL cases; its aggregate fails two intent fixtures. Corrected336 passes all20intent cases (including the additional unaudited-update refusal), enabled affected static checks, formatting and documentation. Together these executions establish81unique focused PostgreSQL cases without failures/errors/skips; unchanged passing suites retain331attribution. Fresh-image/runtime and current-head CI/review remain required; controlled sources/PKI do not establish production custody or authenticated transfer. 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 fc97aefd17..8ff5f56d93 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 @@ -82,15 +82,24 @@ public ResolutionPreparation prepareTerminalResolution(Request request) { requireTransaction(); Objects.requireNonNull(request); var original = intents.findCreation(request.creationRequestId()).orElseThrow(); - var observedCurrent = intents.findCurrentByTenant(original.tenantId()).orElseThrow(); - var current = intents.lockForLifecycle(original.requestId(), observedCurrent.rowVersion()); - Record failed = operationForUpdate(request.failedRequestId()); Record journal = dsl.fetchOne( "SELECT * FROM subscription_lifecycle_terminal_resolutions WHERE resolution_request_id = ? FOR UPDATE", request.resolutionRequestId()); + // Exact committed-result disclosure belongs to the original authenticated actor. It must not + // select a successor subscription or require the canceled predecessor to remain current. + // Only a new mutation takes today's current-row/owner/instrument fence, in its original order. + long currentVersion; + if (journal == null) { + var observedCurrent = intents.findCurrentByTenant(original.tenantId()).orElseThrow(); + currentVersion = + intents.lockForLifecycle(original.requestId(), observedCurrent.rowVersion()).rowVersion(); + } else { + currentVersion = journal.get("result_row_version", Long.class); + } + Record failed = operationForUpdate(request.failedRequestId()); if (!request.tenantId().equals(original.tenantId()) - || !request.subscriptionId().equals(current.subscriptionId()) + || !request.subscriptionId().equals(original.subscriptionId()) || !request.actorAccountId().equals(original.owner().accountUuid()) || !request.creationRequestId().equals(failed.get("creation_request_id", UUID.class)) || !request.subscriptionId().equals(failed.get("subscription_id", UUID.class)) @@ -129,7 +138,7 @@ public ResolutionPreparation prepareTerminalResolution(Request request) { return new ResolutionPreparation( request, binding, - current.rowVersion(), + currentVersion, now(), now(), new TransitionResult( @@ -138,11 +147,11 @@ public ResolutionPreparation prepareTerminalResolution(Request request) { journal.get("result_row_version", Long.class), null)); } - if (request.expectedSubscriptionVersion() != current.rowVersion() + if (request.expectedSubscriptionVersion() != currentVersion || !request .failedRequestId() .equals( - links(current.subscriptionId()).get("lifecycle_inflight_request_id", UUID.class))) { + links(request.subscriptionId()).get("lifecycle_inflight_request_id", UUID.class))) { throw new FenceRejectedException("Terminal resolution lost its exact failed current fence"); } Instant captured = now(); @@ -150,8 +159,7 @@ public ResolutionPreparation prepareTerminalResolution(Request request) { earlier( captured.plus(limits.lease()), captured.plusMillis(failed.get("observation_age_millis", Long.class))); - return new ResolutionPreparation( - request, binding, current.rowVersion(), captured, deadline, null); + return new ResolutionPreparation(request, binding, currentVersion, captured, deadline, null); } /** @@ -1296,8 +1304,9 @@ public ClaimResult claim(UUID requestId, long expectedRowVersion, UUID attemptId /** * Inserts a separate immutable provider-dispatch boundary after revalidating the exact live - * private worker claim. Only a new first-attempt insertion may carry initial-call permission. - * Preexisting unknown migration guards and all replayed/recovered attempts reconcile only. + * private worker claim. Only a newly inserted first-dispatch receipt may carry initial-call + * permission, even if an earlier worker attempt expired without dispatching. Preexisting unknown + * migration guards and all replayed dispatches reconcile only. */ public ProviderDispatch prepareProviderDispatch(ProvisioningClaim supplied, UUID dispatchId) { requireTransaction(); @@ -1322,7 +1331,6 @@ public ProviderDispatch prepareProviderDispatch(ProvisioningClaim supplied, UUID requireDispatchBinding(retained, receipt); boolean initial = inserted == 1 - && retained.attemptNumber() == 1 && "FIRST_DISPATCH".equals(receipt.classification()) && retained.attemptId().equals(receipt.firstAttemptId()); return providerDispatch(retained, receipt, initial, false, transactionId()); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwner.java index c2d2b44b6d..e528c7e1a1 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwner.java @@ -306,8 +306,15 @@ private static void requireNoAmbientTransaction() { } } - private static IllegalStateException unavailable(String message) { - return new IllegalStateException("ENTITLEMENT_UNAVAILABLE: " + message); + private static SourceUnavailableException unavailable(String message) { + return new SourceUnavailableException(message); + } + + /** An evaluated source cannot supply current evidence; not a configuration or codec failure. */ + public static final class SourceUnavailableException extends IllegalStateException { + public SourceUnavailableException(String message) { + super("ENTITLEMENT_UNAVAILABLE: " + message); + } } /** Trusted transport assertion only; construction itself does not authenticate the caller. */ diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantOperationEntitlementGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantOperationEntitlementGrpcService.java index 705cba6dae..fe585d3476 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantOperationEntitlementGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantOperationEntitlementGrpcService.java @@ -1,10 +1,12 @@ package net.firedevops.firemud.accountservice.service.impl; +import com.google.protobuf.Any; import io.grpc.Server; import io.grpc.ServerInterceptors; import io.grpc.Status; import io.grpc.StatusRuntimeException; import io.grpc.TlsServerCredentials; +import io.grpc.protobuf.StatusProto; import io.grpc.stub.StreamObserver; import java.util.List; import java.util.Objects; @@ -14,10 +16,13 @@ import net.firedevops.firemud.account.v1.ReadTenantOperationEntitlementRequest; import net.firedevops.firemud.account.v1.ReadTenantOperationEntitlementResponse; import net.firedevops.firemud.accountservice.security.AccountTenantOperationEntitlementWorkloadGuard; +import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionLifecycleService; import net.firedevops.firemud.accountservice.service.AccountTenantOperationEntitlementOwner; +import net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException; import net.firedevops.firemud.common.account.authority.RuntimeTenantOperationEntitlementGrpcCodec; import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; +import net.firedevops.firemud.shared.v1.ErrorDetail; import org.springframework.transaction.support.TransactionSynchronizationManager; /** @@ -98,11 +103,19 @@ public void readTenantOperationEntitlement( case NON_PAID_DEMO -> owner.evaluateDemo(sourceRequest); }; response = RuntimeTenantOperationEntitlementGrpcCodec.toResponse(request, evidence); - } catch (RuntimeException unavailableSource) { - // No positive evidence, alternate source, or exception details escape an unavailable - // evaluation. + } catch (AccountTenantOperationEntitlementOwner.SourceUnavailableException + | AccountHostingSubscriptionLifecycleService.EntitlementUnavailableException + | DemoTenantEntitlementException + | org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException + | org.springframework.transaction.TransactionException unavailableSource) { fail(observer, Status.UNAVAILABLE); return; + } catch (RuntimeException internalFailure) { + // Configuration mismatches and unexpected construction/codec failures are not retryable + // source outages. Never disclose exception messages or internal identifiers. + fail(observer, Status.INTERNAL); + return; } try { observer.onNext(response); @@ -114,9 +127,18 @@ public void readTenantOperationEntitlement( } private static void fail(StreamObserver observer, Status status) { + String message = "Tenant-operation entitlement evidence is unavailable"; observer.onError( - Status.fromCode(status.getCode()) - .withDescription("Tenant-operation entitlement evidence is unavailable") - .asRuntimeException()); + StatusProto.toStatusRuntimeException( + com.google.rpc.Status.newBuilder() + .setCode(status.getCode().value()) + .setMessage(message) + .addDetails( + Any.pack( + ErrorDetail.newBuilder() + .setCode(status.getCode().name()) + .setMessage(message) + .build())) + .build())); } } 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 index 2feb2678c8..5ae666eeab 100644 --- 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 @@ -28,6 +28,7 @@ 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.ProviderDispatch; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProvisioningClaim; import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.OwnerFence; @@ -154,21 +155,47 @@ void uncommittedSameTransactionReadbackCannotProduceProviderPermission() { } @Test - void recoveredAttemptWithNoPreviousDispatchStillCannotCreateAndExpiredLeaseRefusesReadback() { + void recoveredUndispatchedAttemptMayOwnFirstDispatchButReplayAndExpiredReadbackCannot() { Fixture f = fixture("1032"); var first = claim(f, 1); - f.tx().executeWithoutResult(s -> f.owner().deferUnresolved(first)); - f.clock().advance(Duration.ofSeconds(2)); + // Simulate a crash after the worker claim commits but before any dispatch transaction. + f.clock().advance(Duration.ofSeconds(11)); + 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()) - .isFalse(); + .isTrue(); + assertThat(prepareAndRead(f, second).initialCallAllowed()).isFalse(); f.clock().advance(Duration.ofSeconds(10)); assertThatThrownBy(() -> f.tx().execute(s -> f.owner().readProviderDispatch(prepared))) .isInstanceOf(RuntimeException.class); } + @Test + void expiredUndispatchedFirstClaimRecoversThroughExactlyOneInitialCreate() { + Fixture f = fixture("1032"); + var first = claim(f, 1); + f.clock().advance(Duration.ofSeconds(11)); + 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(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"); @@ -204,20 +231,109 @@ void realInitialSdkCreateFlowsThroughExistingLifecycleCommitAndIndependentCurren } @Test - void lostCreateResponseRecoversSameResourceWithoutRecreatingAndRetainsItsOriginalIdentity() { + void lostCreateResponseRecoversAfterTransientEmptySearchWithoutRecreating() { Fixture f = fixture("1032"); f.transport().loseCreateResponse = true; var first = claim(f, 1); - assertThat(service(f).provision(first, UUID.randomUUID(), UUID.randomUUID())) - .isInstanceOf(AccountHostingSubscriptionProvisioningService.Pending.class); + 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().emptySearchesRemaining = 1; f.clock().advance(Duration.ofSeconds(2)); var second = claim(f, first.subscriptionRowVersion()); + var delayed = + (AccountHostingSubscriptionProvisioningService.Pending) + service(f).provision(second, UUID.randomUUID(), UUID.randomUUID()); + assertThat(delayed.disposition()).isEqualTo(Disposition.WAITING); + assertThat(delayed.providerResult()) + .isEqualTo( + new StripeHostingSubscriptionProvisioner.Pending("PROVIDER_LOOKUP_UNRESOLVED", null)); + assertThat(f.transport().creates).isEqualTo(1); + f.clock().advance(Duration.ofSeconds(2)); + var third = claim(f, second.subscriptionRowVersion()); var result = (AccountHostingSubscriptionProvisioningService.Committed) - service(f).provision(second, UUID.randomUUID(), UUID.randomUUID()); + service(f).provision(third, UUID.randomUUID(), UUID.randomUUID()); assertThat(result.current().current().providerSubscriptionId()).isEqualTo("sub_exact"); assertThat(f.transport().creates).isEqualTo(1); + assertThat(f.transport().searches).isEqualTo(3); + 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; + ProvisioningClaim previous = first; + for (int attempt = 2; attempt <= 3; attempt++) { + f.clock().advance(Duration.ofSeconds(2)); + 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().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"); } private static ProviderDispatch prepareAndRead(Fixture f, ProvisioningClaim claim) { @@ -536,6 +652,8 @@ private static final class Transport implements StripeResponseGetter { private final Clock clock; private boolean exists; private boolean loseCreateResponse; + private int emptySearchesRemaining; + private int searches; private int creates; private int subscriptionReads; @@ -578,13 +696,18 @@ public T request( + 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\":[" - + (exists ? subscription() : "") + + (visible ? subscription() : "") + "]}"; } else if (path.equals("/v1/subscriptions") && method == RequestMethod.POST) { creates++; 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 index c62340e2bc..baa50e2878 100644 --- 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 @@ -1057,6 +1057,62 @@ private static AccountHostingSubscriptionLifecycleRepository.ProvisioningClaim c 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() { 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 index 92237d1a78..bc268a615d 100644 --- 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 @@ -15,6 +15,7 @@ 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; @@ -22,6 +23,8 @@ 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; @@ -69,6 +72,13 @@ void initialCreateUsesExactDurableBindingsAndKeyThenIndependentlyReadsProvider() "/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.get(3).getIdempotencyKey()).isEqualTo(OPERATION.toString()); assertThat(transport.options.get(3).getMaxNetworkRetries()).isZero(); assertThat(transport.params.get(3)) @@ -91,17 +101,41 @@ void initialCreateUsesExactDurableBindingsAndKeyThenIndependentlyReadsProvider() void unknownOrExpiredIdempotencyOutcomeNeverAuthorizesAnotherCreate() { Transport missing = transport(search("")); assertThat(adapter(missing).provision(dispatch(false))) - .isInstanceOf(StripeHostingSubscriptionProvisioner.Pending.class); - assertThat(missing.methods).doesNotContain(RequestMethod.POST); + .isEqualTo( + new StripeHostingSubscriptionProvisioner.Pending("PROVIDER_LOOKUP_UNRESOLVED", null)); + assertThat(missing.paths) + .containsExactly( + "/v1/customers/cus_exact", "/v1/payment_methods/pm_exact", "/v1/subscriptions/search"); + assertThat(missing.methods) + .containsExactly(RequestMethod.GET, RequestMethod.GET, RequestMethod.GET); Transport lost = transport(search(""), subscription()); lost.failureAt = 3; lost.failure = mock(StripeException.class); assertThat(adapter(lost).provision(dispatch(true))) - .isInstanceOf(StripeHostingSubscriptionProvisioner.Pending.class); + .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.methods).doesNotContain(RequestMethod.POST); + 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 @@ -110,16 +144,72 @@ void searchFailureDuplicatesAndIndependentBindingMismatchRemainNonterminal() { failed.failureAt = 2; failed.failure = mock(StripeException.class); assertThat(adapter(failed).provision(dispatch(true))) - .isInstanceOf(StripeHostingSubscriptionProvisioner.Pending.class); - assertThat(failed.methods).doesNotContain(RequestMethod.POST); + .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))) - .isInstanceOf(StripeHostingSubscriptionProvisioner.Pending.class); - assertThat(duplicate.methods).doesNotContain(RequestMethod.POST); + .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))) - .isInstanceOf(StripeHostingSubscriptionProvisioner.Pending.class); + .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 @@ -135,8 +225,10 @@ void uncommittedDispatchAndExpiredLeaseRefuseBeforeSdkIo() { Clock.fixed(NOW.plusSeconds(20), ZoneOffset.UTC), false); assertThat(expired.provision(dispatch(true))) - .isInstanceOf(StripeHostingSubscriptionProvisioner.Pending.class); + .isEqualTo( + new StripeHostingSubscriptionProvisioner.Pending("DISPATCH_LEASE_EXPIRED", null)); assertThat(transport.paths).isEmpty(); + assertThat(transport.methods).isEmpty(); } @Test @@ -147,8 +239,12 @@ void mismatchedProviderInstrumentAndAmbientTransactionCannotReachCreate() { 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))) - .isInstanceOf(StripeHostingSubscriptionProvisioner.Pending.class); - assertThat(mismatch.paths).hasSize(2); + .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); @@ -156,6 +252,7 @@ void mismatchedProviderInstrumentAndAmbientTransactionCannotReachCreate() { 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); diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClientMtlsTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClientMtlsTest.java index 66c057cde2..93d72b6caa 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClientMtlsTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClientMtlsTest.java @@ -77,8 +77,34 @@ void protectedReceiverDispatchesExplicitSourcesWithAuthenticatedWorkloadAndNoFal assertThat(read.request()).isEqualTo(paid); assertThat(read.evidence()).isEqualTo(evidence(paid)); assertThat(client.read(demo).evidence()).isEqualTo(evidence(demo)); - doThrow(new IllegalStateException("source unavailable")).when(owner).evaluatePaid(any()); + doThrow( + new AccountTenantOperationEntitlementOwner.SourceUnavailableException( + "private source detail")) + .when(owner) + .evaluatePaid(any()); assertStatus(() -> client.read(paid), Status.Code.UNAVAILABLE); + for (RuntimeException failure : + new RuntimeException[] { + new IllegalArgumentException("private namespace mismatch"), + new NullPointerException("private codec failure") + }) { + doThrow(failure).when(owner).evaluatePaid(any()); + assertThatThrownBy(() -> client.read(paid)) + .satisfies( + thrown -> { + assertThat(Status.fromThrowable(thrown).getCode()) + .isEqualTo(Status.Code.INTERNAL); + var details = io.grpc.protobuf.StatusProto.fromThrowable(thrown); + assertThat(details).isNotNull(); + assertThat(details.getDetailsCount()).isEqualTo(1); + var detail = + details + .getDetails(0) + .unpack(net.firedevops.firemud.shared.v1.ErrorDetail.class); + assertThat(detail.getCode()).isEqualTo("INTERNAL"); + assertThat(detail.getMessage()).doesNotContain("private"); + }); + } verify(owner, org.mockito.Mockito.times(1)).evaluateDemo(any()); TransactionSynchronizationManager.setActualTransactionActive(true); try { From 3f9b6ef97e1a7a0e8e032cbcabf4b3280967b3e8 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 7 Nov 2026 14:51:46 +1300 Subject: [PATCH 09/23] Bound all hosting provisioning IO and align held receiving status Apply finite validated SDK timeouts and zero retries to prerequisite, search, create and observation calls, preserving create idempotency. Qualify all five request options, remove a duplicate misnamed membership test, and describe prepared JOIN components behind the held receiving facade accurately. Focused proof: 173 Account unit cases, integration compilation, affected main/test analysis, formatting, Markdown and link checks pass. The existing required runtime smoke remains blocked on canonical PLAY authority cutover; this change neither revives legacy entitlement authority nor bypasses smoke. --- .../player-access-and-session.md | 16 +++++------ .../StripeBillingPrerequisiteObserver.java | 14 ++++++++-- .../StripeHostingSubscriptionProvisioner.java | 27 ++++++++++++------- ...ipeHostingSubscriptionProvisionerTest.java | 15 +++++++---- .../service/impl/AccountServiceImplTest.java | 18 ------------- 5 files changed, 48 insertions(+), 42 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 1e60e02105..f347069c22 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -492,7 +492,7 @@ Account's persisted UUID now backs registration REST/gRPC output and the Account Internal Account-carrier typing is prepared in Game Session, while current producers, JWT claims/parsers, and numeric-only collaborators remain unchanged. This does not activate canonical Account UUID authentication or Entity roster/entry behavior and does not backfill historical command UUIDs; canonical identity/namespace targets remain [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md), [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), and [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). Focused unit proof covers fail-closed first-party retained-context lookup, unreadable presence lookup without index pruning, and bounded pre-mutation rejection of unreadable or wrong-type presence values for removal, AFK/activity updates, and registration. `RedisSessionContextService` mutation reads still expose raw `SerializationException`; mocked tests show unreadable session-alias reads abort before writes/deletes, but mixed-binary behavior, same-session-ID reauthentication/recovery, live Redis/runtime, and fresh-image proof remain unproved. #2898 is not fixed by this preparation. -Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, the Account-local explicit public-production JOIN writer and durable audit outbox/producer retry path, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Logging & Admin receipt persistence/readback is separate #2848 work and is not included in this Account core. The Account `POST /auth/bootstrap/join` route exists locally, but its receiving method returns `AUTH_UNAVAILABLE` before bootstrap/scope, target, entitlement, or membership reads or mutation; the Gateway guard still blocks external exposure. See [canonical billing and retention receiving](#canonical-billing-and-retention-receiving) for current status and retained obligations. Game Session text JOIN dispatch remains with #2898 and direct text-client end-to-end proof is unclaimed. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. JOIN's durable `PENDING`/unknown-database-outcome recovery seam remains unresolved under the Overseer decision and is owned by #2848; PostgreSQL runtime proof is not claimed. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. +Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. The Account-local explicit public-production JOIN writer and durable audit outbox/producer retry components remain prepared source behind the held receiving boundary. Logging & Admin receipt persistence/readback is separate #2848 work and is not included in this Account core. The Account `POST /auth/bootstrap/join` route exists locally, but its receiving method returns `AUTH_UNAVAILABLE` before bootstrap/scope, target, entitlement, or membership reads or mutation, without invoking those prepared components; the Gateway guard still blocks external exposure. See [canonical billing and retention receiving](#canonical-billing-and-retention-receiving) for current status and retained obligations. Game Session text JOIN dispatch remains with #2898 and direct text-client end-to-end proof is unclaimed. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. JOIN's durable `PENDING`/unknown-database-outcome recovery seam remains unresolved under the Overseer decision and is owned by #2848; PostgreSQL runtime proof is not claimed. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. Official-hosted creator-content acceptance remains an unregistered target workflow. Source-only persistence now includes Creator Party and hosted-terms/environment-binding evidence plus V98 disclosure handoff and source-evidence tables; these relations do not supply external environment observation, authenticated publication, a legal authority verifier, dispatch, a consumer, registry/runtime binding, creator UI, or downstream write-gate proof. The fixed server environment-evidence adapter exists but remains deliberately unregistered and supplies no genuine input delivery. Its target authority remains under [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md), outside player-admission and session authority. Future managed creator commerce remains outside player access and session authority; its canonical boundary is [ADR 0179](../../architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md); no marketplace or purchase-entitlement implementation is present. @@ -526,7 +526,7 @@ The local receiving preparation uses the dedicated Gateway RS256 non-JWT envelop [FirstPartyConnectContextService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java) joins that verified context to the current [canonical route owner read](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java). Logical UUID authority stays separate from owner-supplied private storage handles. Retention keeps the original compact envelope and resolved owner snapshot, re-verifies expiry and current owner evidence on reads, and rejects old partial selector fragments, corruption, or unavailable authority. Main's latest focused evidence reports 12 controlled-key envelope tests, 199 Game Session unit cases after two narrow fixes, 184 Account unit cases after the fixture mock-history correction, 15 Gateway unit cases, and six physical Redis cases. The local socket-ownership correction requests transport close after send failure and performs disconnect cleanup only when the close callback atomically removes the exact registered transport. Forty-seven focused ownership unit cases and affected static/format gates pass. A fresh PostgreSQL-backed WebSocket class run passes 19 of 20 cases after default-off route-reader wiring is repaired; its remaining fixture-room assertion is corrected and that case passes in a separate focused run. The original startup and assertion failures and earlier all-skipped result remain retained; no genuine first-party admission authority is claimed. See [Session Behavior](../../architecture/system-architecture-session-behavior.md#session-types-and-lifetimes). These partial results do not establish a complete consumer gate or packaged runtime. -Account connect-token issuance retains its existing bootstrap and scope authentication checks, then denies before cached-success replay, token minting, or session mutation while the canonical producer is unavailable. Gateway removes the legacy HMAC context mint and replay fallback; first-party cookie admission and public gameplay readiness remain unavailable. The separate trusted TCP Proxy listener path retains its existing boundary. First-party bare `LOGIN` and `PLAY` preserve the complete context and deny before legacy Account, Entity, or binding effects pending the genuine authority, lease, and finalization consumers. This entire source batch is local preparation; the `AA-2.1` capability remains partial and no new publication boundary or playable completion is claimed. +Account connect-token issuance returns `AUTH_UNAVAILABLE` before bootstrap/scope validation, cached-success replay, token minting, or session mutation while the canonical producer is unavailable. Gateway removes the legacy HMAC context mint and replay fallback; first-party cookie admission and public gameplay readiness remain unavailable. The separate trusted TCP Proxy listener path retains its existing boundary. First-party bare `LOGIN` and `PLAY` preserve the complete context and deny before legacy Account, Entity, or binding effects pending the genuine authority, lease, and finalization consumers. This entire source batch is local preparation; the `AA-2.1` capability remains partial and no new publication boundary or playable completion is claimed. ## Capability Status @@ -537,11 +537,11 @@ Account connect-token issuance retains its existing bootstrap and scope authenti | `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.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 returns `AUTH_UNAVAILABLE` before bootstrap/scope validation, 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` validates existing bootstrap and scope, then returns `AUTH_UNAVAILABLE` before 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.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, 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. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisMovementEffectIdempotencyService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [RedisMovementEffectIdempotencyServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java); [SessionContextSecretAndPresenceRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/SessionContextSecretAndPresenceRedisIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. The [local secret/presence containment](#session-secret-and-presence-containment) prevents new raw delegation-JWT persistence and projects legacy values without rehydration; physical retained-value cleanup remains open; scoped receiving proof is recorded at that owner. | -The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary without claiming explicit JOIN completion. Account bootstrap character discovery requires membership permitting gameplay admission without an Entity read; connect-token issuance returns `AUTH_UNAVAILABLE` before cached replay or membership, entitlement, grant, and routing-authority reads. Pre-membership world and realm discovery remains available. Current text `PLAY` implements the lifecycle/generation and admission checks covered by this receiving boundary. The canonical ordering contract is defined in [Authentication and authorization](../../architecture/system-architecture-authentication.md#play-current-and-target-failure-boundaries). Focused service proof covers Account-before-roster ordering, strict persisted actor selection, and the Game Session-to-Entity peer allowlist across 124 focused tests. Deployment/mTLS and fresh-image proof remain incomplete, so this targeted `PLAY` work does not complete AA-2.1, explicit JOIN, or `playableSmoke`. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject any `stateScope` other than exact `SHARED` or `ISOLATED`, so malformed authority cannot silently become shared-state admission. Account-owned explicit public-production JOIN writing and operation checks are implemented locally; first-party text JOIN dispatch, full caller-target/atomic authority, `allowNewGameplayBindings`, grant lifecycle/expiry, and lease-commit proof remain open as recorded above. +The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary without claiming explicit JOIN completion. Account bootstrap character discovery requires membership permitting gameplay admission without an Entity read; connect-token issuance returns `AUTH_UNAVAILABLE` before cached replay or membership, entitlement, grant, and routing-authority reads. Pre-membership world and realm discovery remains available. Current text `PLAY` implements the lifecycle/generation and admission checks covered by this receiving boundary. The canonical ordering contract is defined in [Authentication and authorization](../../architecture/system-architecture-authentication.md#play-current-and-target-failure-boundaries). Focused service proof covers Account-before-roster ordering, strict persisted actor selection, and the Game Session-to-Entity peer allowlist across 124 focused tests. Deployment/mTLS and fresh-image proof remain incomplete, so this targeted `PLAY` work does not complete AA-2.1, explicit JOIN, or `playableSmoke`. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject any `stateScope` other than exact `SHARED` or `ISOLATED`, so malformed authority cannot silently become shared-state admission. Account-owned explicit public-production JOIN writer and operation-check components remain prepared locally behind the held receiver; current `POST /auth/bootstrap/join` denies before invoking them. First-party text JOIN dispatch, full caller-target/atomic authority, `allowNewGameplayBindings`, grant lifecycle/expiry, and lease-commit proof remain open as recorded above. At receiving source `6c14229c32`, consolidated focused proof passes 572 cases across 15 unit, PostgreSQL-backed WebSocket, physical Redis and cross-service WebSocket/communication/Telnet suites, with zero failures, errors or skips, plus affected Checkstyle, formatting and canonical documentation checks. The gate includes current-parent menu/dispatch corrections; unchanged tasks may reuse qualified Gradle results. Account authority is controlled or mocked in transport fixtures, so these results do not prove full caller-target atomic authority, grant lifecycle/expiry, exact lease commit, genuine custody or public admission. Earlier focused counts overlap and are not additive. @@ -598,7 +598,7 @@ Previously signed numeric scopes are rejected when presented to the strict reade #### Account-owned response UUID projection -The response-only Account source projects canonical persisted Account UUIDs in every explicit JOIN outcome and in profile GET/UPDATE, gRPC JSON and Account-local export responses. Private scope/operation/member identities, immutable digests, receipts and side effects retain their existing representation. JOIN owner projection follows transaction completion; unavailable owner evidence returns `AUTH_UNAVAILABLE` without rewriting a retained result. Profile projection validates tenant/owner coherence and rereads the full Account because its repository embeds only a partial owner. The [Account API contract](../../architecture/microservices/account-service/api-contracts.md) owns the response semantics. +Current profile GET/UPDATE, gRPC JSON and Account-local export responses project canonical persisted Account UUIDs. Prepared explicit JOIN outcomes retain that UUID response shape, but the current JOIN receiving facade denies before producing them. Private scope/operation/member identities, immutable digests, receipts and side effects retain their existing representation. JOIN owner projection follows transaction completion; unavailable owner evidence returns `AUTH_UNAVAILABLE` without rewriting a retained result. Profile projection validates tenant/owner coherence and rereads the full Account because its repository embeds only a partial owner. The [Account API contract](../../architecture/microservices/account-service/api-contracts.md) owns the response semantics. Focused service/controller/gRPC cases and native PostgreSQL composition cover UUID responses, generated profile mapping, retained private rows, replay and owner readback refusal. R1189 qualifies the response projection; REST selector proof has its separate attribution. At that source, incoming direct-text context, ordinary JWT identity/shared forwarding and Account-to-Entity discovery remained separate gaps; the final ordinary receiving cohort subsequently qualifies those UUID boundaries. Canonical tenant-qualified profile routes/authorization, token registry qualification and gameplay activation remain separate gaps. No production Game Session text-JOIN caller is introduced, and the unavailable JOIN route remains absent from public OpenAPI. @@ -698,7 +698,7 @@ The canonical gRPC `GameSessionGrpcService.startSession` path preflights IP admi ### Entitlement read and JOIN failure classification -The shared local Account subscription reader rejects null, missing, ambiguous or nonpositive-version evidence and preserves bounded entitlement-unavailable classification for storage outages; mapping/configuration faults remain unexpected failures. JOIN leaves a potentially aborted SQL transaction before writing diagnostic evidence through its existing post-rollback path. A failed fresh authority read during terminal replay returns unavailable without changing the complete retained result. This does not implement a complete entitlement bundle, current-row history, positive connect-token issuance, unknown-outcome observation after lost authority, or production admission. The [Account runtime owner](../../architecture/microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority) and [API error catalog](../../architecture/microservices/account-service/api-contracts.md#login-error-codes) own those contracts. +The shared local Account subscription reader rejects null, missing, ambiguous or nonpositive-version evidence and preserves bounded entitlement-unavailable classification for storage outages; mapping/configuration faults remain unexpected failures. The prepared JOIN owner leaves a potentially aborted SQL transaction before writing diagnostic evidence through its existing post-rollback path; the current receiving method denies before invoking that owner. A failed fresh authority read during terminal replay returns unavailable without changing the complete retained result. This does not implement a complete entitlement bundle, current-row history, positive connect-token issuance, unknown-outcome observation after lost authority, or production admission. The [Account runtime owner](../../architecture/microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority) and [API error catalog](../../architecture/microservices/account-service/api-contracts.md#login-error-codes) own those contracts. R1424’s current Account correction passes 305 unit cases and nine actual PostgreSQL cases, including a real SQL abort followed by rollback and a successful fresh-transaction diagnostic write, with correct unavailable classification and unchanged terminal evidence. The CHARS-focused Game Session source separately passes 184 selected unit cases and two actual WebSocket cases. All selected executions have zero failures, errors or skips, and affected enabled main/unit/integration analysis and formatting pass. These separate gates cover 500 selected cases; this is not one full service-suite run. The prior 488-case aggregate remains attributed to its earlier classification source. The PostgreSQL cases retain original intent, scope and Account provenance, prove no membership/audit on refusal, and exercise same-original recovery and immutable terminal evidence. The Game Session cases qualify unavailable direct-text `CHARS`, no accepted command event, and consistent HELP/PLAY/localized guidance while preserving supported WORLDS/REALMS and the separate Account roster. These are controlled owner/transport fixtures, not genuine issuer/custody, full service-suite or successful public-admission proof. Fresh packaged-runtime proof remains pending for the combined receiving source. @@ -746,7 +746,7 @@ R1418 subsequently carries published #3365 parent `1d2b862ea5a176f9c7e08dd3a0d76 The initial review corrections qualify script-local certificate defaults beneath a symlinked checkout ancestor while continuing to refuse explicit caller paths through links and preserving retained certificate bytes, modes and foreign entries. The certificate contract now requires each intended repository refusal marker on stderr as well as unchanged state, so unrelated command failures cannot satisfy it. Four freshly executed currency adapter cases require one response and completion per call, exact fail-closed metrics when a registry exists, no-registry constructor behavior and no owner interaction. Affected test static analysis, full Java formatting, ShellCheck, capability tracking and documentation checks pass. These direct corrections add no currency capability, public browser handoff, production identity or JOIN recovery authority. -Current writer inspection also narrows the retained JOIN recovery gap: the public owner commits membership, transition audit and its terminal together after a separate durable intent. Unknown acknowledgement can leave either that intent without membership effects or a complete terminal; it does not establish the donor's manufactured positive-PENDING state. A lost committed result may remain unobservable after scope expiry, changed replay policy or lost caller binding. Same-original retry and this later outcome-observation limitation require distinct proof; the existing unknown-recovery and lawful-release holds remain. The proposed audit projection-version marker likewise has no implemented Logging receipt/projection producer here and must not be inferred from receiver IDs, payload replay or stamped test rows. No historical producer provenance, new receiver, recovery RPC or release authority is supplied. +Inspection of the prepared JOIN owner path narrows the retained recovery gap: when invoked, the public owner commits membership, transition audit and its terminal together after a separate durable intent. The current receiving method denies before reaching that owner. Unknown acknowledgement can leave either that intent without membership effects or a complete terminal; it does not establish the donor's manufactured positive-PENDING state. A lost committed result may remain unobservable after scope expiry, changed replay policy or lost caller binding. Same-original retry and this later outcome-observation limitation require distinct proof; the existing unknown-recovery and lawful-release holds remain. The proposed audit projection-version marker likewise has no implemented Logging receipt/projection producer here and must not be inferred from receiver IDs, payload replay or stamped test rows. No historical producer provenance, new receiver, recovery RPC or release authority is supplied. ### Fail-Closed Boundary Convergence @@ -786,7 +786,7 @@ The evidence records focused unit, controller, gRPC, WebSocket, cross-service, a The focused admission proofs cover fresh acceptance, same-IP replacement reservation transfer, rejection without destroying the old session, and the non-destructive operator path. Telnet proofs cover envelope parsing, event metadata, reconnect backoff, bounded connection-local ordered input buffering during edge rebind, buffer exhaustion, sensitive logging, and Telnet/WebSocket `LOOK` parity; they do not prove durable replay of client input or transport bytes. Game Session gRPC proofs cover `Ping`, `NotifyDisconnect`, session lifecycle/control-plane parsing, application-error payloads, and `grpc.app_error` classification. Earlier first-party fresh-token, bare-login, `PLAY` scope, replay/expiry/context, screen-buffer restore, and fresh-redraw proofs describe the superseded path; current first-party coverage is fail-closed and does not establish playable admission. -Account authority proof covers account-first tenantless bootstrap authentication and account-scoped session state, the local `JoinPublicProductionMembership` writer and its Account-owned audit/outbox boundary, Account-owned non-public realm grant denial, cross-tenant membership enforcement, and account-owned export/delete/recovery boundaries including active-subscription deletion guards. The strict ADR 0025 commit fence and connect-token membership-authority-generation reread remain incomplete; Game Session text `JOIN`/`Join & Play` dispatch remains #2898, while unknown-outcome recovery and Logging receipt receiver/readback remain #2848 work. Exact-final-head PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Canonical tenant-role, lifecycle-state, and authority-generation follow-through also remain partial or unproved. +Account authority proof covers account-first tenantless bootstrap authentication and account-scoped session state, the prepared local `JoinPublicProductionMembership` writer and its Account-owned audit/outbox components, Account-owned non-public realm grant denial, cross-tenant membership enforcement, and account-owned export/delete/recovery boundaries including active-subscription deletion guards. The current JOIN receiving method denies before invoking that prepared writer. The strict ADR 0025 commit fence and connect-token membership-authority-generation reread remain incomplete; Game Session text `JOIN`/`Join & Play` dispatch remains #2898, while unknown-outcome recovery and Logging receipt receiver/readback remain #2848 work. Exact-final-head PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Canonical tenant-role, lifecycle-state, and authority-generation follow-through also remain partial or unproved. The #3224 candidate adds an explicit held-admission image-smoke mode: it preserves the existing isolated backend `LOGIN` -> `PLAY` -> `LOOK` proof and checks that real Gateway and Telnet public paths fail closed while admission readiness is out of service. This is separate from successful public admission. The focused transport and image-environment contracts pass. Fresh source-built held-admission qualification on `3c71c8c24379af623ca66550a4f4acaadd0ffd81` passes from 2026-10-16 05:20:30 to 05:27:42 UTC: the run-owned Gateway public listener receives the first-party loopback request outside configured TCP-proxy trust and returns exact `CONNECT_REPLAY_PROTECTION_UNAVAILABLE`; Telnet returns `startup_unavailable` and closes; the direct backend completes `WORLDS`, `LOGIN`, `PLAY`, `LOOK` and `LOGOUT`. Canonical teardown completes and independent exact-project inspection finds no containers, networks or volumes. This proves the held mode and isolated backend flow; it does not prove Kubernetes Service endpoint withdrawal or independent TCP Proxy Service readiness. Host-published Gateway ingress and successful public admission also remain unproved. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeBillingPrerequisiteObserver.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeBillingPrerequisiteObserver.java index c75decfffe..142612ca4e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeBillingPrerequisiteObserver.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeBillingPrerequisiteObserver.java @@ -3,6 +3,7 @@ import com.stripe.exception.StripeException; import com.stripe.model.Customer; import com.stripe.model.PaymentMethod; +import com.stripe.net.RequestOptions; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; @@ -77,11 +78,17 @@ public StripeBillingPrerequisiteObserver( * not-found response) remains unresolved with its original cause; it never proves absence. */ public Result observe(ExpectedBinding expected) { + return observe(expected, RequestOptions.getDefault()); + } + + // The held hosting provisioner supplies its validated finite transport policy for both reads. + Result observe(ExpectedBinding expected, RequestOptions requestOptions) { Objects.requireNonNull(expected, "expected binding is required"); + Objects.requireNonNull(requestOptions, "request options are required"); Instant readStartedAt = clock.instant(); Customer customer; try { - customer = stripeClient.customers().retrieve(expected.providerCustomerId()); + customer = stripeClient.customers().retrieve(expected.providerCustomerId(), requestOptions); } catch (StripeException providerFailure) { return unresolved(expected, readStartedAt, clock.instant(), providerFailure); } @@ -101,7 +108,10 @@ public Result observe(ExpectedBinding expected) { PaymentMethod paymentMethod; try { - paymentMethod = stripeClient.paymentMethods().retrieve(expected.providerPaymentMethodId()); + paymentMethod = + stripeClient + .paymentMethods() + .retrieve(expected.providerPaymentMethodId(), requestOptions); } catch (StripeException providerFailure) { return unresolved(expected, readStartedAt, clock.instant(), providerFailure); } 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 index 0d3662965b..c6de43e0a2 100644 --- 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 @@ -23,6 +23,7 @@ public final class StripeHostingSubscriptionProvisioner { private final com.stripe.StripeClient stripe; private final Clock clock; + private final RequestOptions requestOptions; private final StripeHostingSubscriptionObserver observer; private final StripeBillingPrerequisiteObserver prerequisites; @@ -34,13 +35,18 @@ public StripeHostingSubscriptionProvisioner( com.stripe.StripeClient stripe, Clock clock, boolean expectedLivemode, - Duration observationConnectTimeout, - Duration observationReadTimeout) { + Duration connectTimeout, + Duration readTimeout) { this.stripe = Objects.requireNonNull(stripe); this.clock = Objects.requireNonNull(clock); - observer = - new StripeHostingSubscriptionObserver( - stripe, clock, observationConnectTimeout, observationReadTimeout); + 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); } @@ -63,7 +69,8 @@ public Result provision(ProviderDispatch dispatch) { creation.customerProvisioningRequestId(), dispatch.customerProviderIdempotencyId(), creation.providerCustomerId(), - dispatch.providerPaymentMethodId())); + dispatch.providerPaymentMethodId()), + requestOptions); if (!(prerequisite instanceof StripeBillingPrerequisiteObserver.ObservedBillingPrerequisites)) { return new Pending("PROVIDER_PREREQUISITES_UNRESOLVED", null); } @@ -92,7 +99,9 @@ public Result provision(ProviderDispatch dispatch) { StripeSearchResult matches = stripe .subscriptions() - .search(SubscriptionSearchParams.builder().setQuery(query).setLimit(2L).build()); + .search( + SubscriptionSearchParams.builder().setQuery(query).setLimit(2L).build(), + requestOptions); if (matches == null || matches.getData() == null || !Boolean.FALSE.equals(matches.getHasMore()) @@ -125,9 +134,9 @@ public Result provision(ProviderDispatch dispatch) { .build()) .putAllMetadata(metadata) .build(), - RequestOptions.builder() + requestOptions + .toBuilderFullCopy() .setIdempotencyKey(creation.subscriptionProvisioningRequestId().toString()) - .setMaxNetworkRetries(0) .build()); } else { candidate = matches.getData().getFirst(); 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 index d6630513c4..a64ef32f6d 100644 --- 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 @@ -79,11 +79,16 @@ void initialCreateUsesExactDurableBindingsAndKeyThenIndependentlyReadsProvider() RequestMethod.GET, RequestMethod.POST, RequestMethod.GET); - assertThat(transport.options.get(3).getIdempotencyKey()).isEqualTo(OPERATION.toString()); - assertThat(transport.options.get(3).getMaxNetworkRetries()).isZero(); - assertThat(transport.options.get(4).getConnectTimeout()).isEqualTo(250); - assertThat(transport.options.get(4).getReadTimeout()).isEqualTo(1000); - assertThat(transport.options.get(4).getMaxNetworkRetries()).isZero(); + 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", diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 52ef20b55e..691b47977e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -1347,24 +1347,6 @@ void getTenantMembershipForRuntimeRejectsMissingAccount() { () -> service.getTenantMembershipForRuntime(11L, 7L, "req-1")); } - @Test - void getTenantMembershipForRuntimeRejectsCrossTenantAccount() { - Account account = new Account(); - account.setId(11L); - setPersistedAuthenticationIdentity(account); - account.setUsername("demo"); - account.setEmail("demo@example.com"); - account.setPasswordHash(hash("password")); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - - var dto = service.getTenantMembershipForRuntime(11L, 7L, "req-1"); - - assertEquals(11L, dto.accountId()); - assertEquals(7L, dto.tenantId()); - assertTrue(!dto.membershipExists()); - assertTrue(!dto.gameplayAdmissionAllowed()); - } - @Test void getTenantEntitlementsForRuntimeFailsClosedBeforeReadingLegacyEvidence() { AuthenticationException exception = From 5439facb97b64a50092ae580329a0fb30007b19a Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 7 Nov 2026 15:07:41 +1300 Subject: [PATCH 10/23] Require exact owner refusals and exercised rollback proof Tighten stale-dispatch and Account-authority refusal assertions; require a committed lifecycle, one capture invocation and the controlled rollback cause. Use the canonical primary authentication error code and correct the fixture constructor label. Record the held deletion owner's missing canonical billing classification without enabling deletion or reviving retained authority. Seven focused terminal-resolution units, integration compilation, enabled unit/integration/test-fixture analysis, formatting and documentation pass. Physical PostgreSQL execution and canonical positive PLAY remain CI/owning runtime qualification obligations; no smoke or authority bypass is added. --- .../player-access-and-session.md | 2 ++ ...iptionDispatchPostgresIntegrationTest.java | 4 +++- ...titlementOwnerPostgresIntegrationTest.java | 24 ++++++++++++------- ...ionCompositionPostgresIntegrationTest.java | 3 ++- ...criptionTerminalResolutionServiceTest.java | 6 +++-- .../AccountControlUiOwnerSourcesFixture.java | 2 +- 6 files changed, 28 insertions(+), 13 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index f347069c22..7382b22fba 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -12,6 +12,8 @@ Account initial/current/final creation owners, explicit initial billing-owner co 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 provisioning and cancellation components keep actual Account actor/authentication and owner-local atomic receipt/fence/event checks; cancellation prepares one allowed safe outcome. Coupled 356 physical proof now passes through genuine certified ACCOUNT issuance/current actor, fresh primary OTP authentication and the guarded cancellation commit. Its five PostgreSQL/AOF-replica cases 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. +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. + Paid first-invoice confirmation remains an unfinished Account checkout obligation. Stripe `default_incomplete` creation and subscription polling do not confirm a required first payment; controlled active-subscription inputs are not live paid-checkout proof. Complete confirmation through 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. 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. 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 index db486b40c4..266839459d 100644 --- 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 @@ -33,6 +33,7 @@ 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; @@ -209,7 +210,8 @@ void recoveredUndispatchedAttemptMayOwnFirstDispatchButReplayAndExpiredReadbackC assertThat(prepareAndRead(f, second).initialCallAllowed()).isFalse(); f.clock().advance(Duration.ofSeconds(10)); assertThatThrownBy(() -> f.tx().execute(s -> f.owner().readProviderDispatch(prepared))) - .isInstanceOf(RuntimeException.class); + .isInstanceOf(FenceRejectedException.class) + .hasMessage("Exact live provisioning claim readback rejected"); } @Test 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 index e587f60ecc..db8088530b 100644 --- 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 @@ -7,6 +7,7 @@ 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; @@ -150,20 +151,24 @@ void captureRunsInsideFinalWritableTransactionAndFailureRollsBackCapturedSql() { var f = c.fixture(); var claim = f.service().claimProvisioning(f.creation().requestId(), 1, UUID.randomUUID()).claim(); - f.service() - .reconcile( - UUID.randomUUID(), - f.creation().requestId(), - claim.subscriptionRowVersion(), - f.providerId(), - claim.attemptId()); + 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( @@ -172,7 +177,10 @@ void captureRunsInsideFinalWritableTransactionAndFailureRollsBackCapturedSql() { f.dsl().execute("CREATE TABLE " + marker + " (id bigint)"); throw new IllegalStateException("controlled capture rollback"); })) - .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE") + .hasCauseInstanceOf(IllegalStateException.class) + .hasRootCauseMessage("controlled capture rollback"); + assertThat(captures).hasValue(1); assertThat(f.dsl().fetchOne("SELECT to_regclass(?)::text", marker).get(0, String.class)) .isNull(); } 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 index 45c1b8d33a..ac2bc07df9 100644 --- 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 @@ -239,7 +239,8 @@ void realAccountAuthorityAdvanceDuringSdkReadRejectsBeforeMutationAndKeepsOtp() return issued.sources().accounts.save(account); })); assertThatThrownBy(() -> resolve(failed, issued.account().getEmail(), OTP)) - .isInstanceOf(RuntimeException.class); + .isExactlyInstanceOf(IllegalStateException.class) + .hasMessage("Exact current authenticated initial creator required"); var authorityAfter = issued .sources() diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionServiceTest.java index bf51ec80e1..21d89cd499 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionServiceTest.java @@ -22,6 +22,7 @@ import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import java.util.function.Supplier; +import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver.ExpectedBinding; import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver.ObservedSubscription; @@ -202,7 +203,7 @@ void deniedPrimaryAuthenticationCommitsFailureAccountingBeforeGenericErrorReturn assertThat(failure).isInstanceOf(AuthenticationException.class); AuthenticationException error = (AuthenticationException) failure; - assertThat(error.getCode()).isEqualTo("INVALID_CREDENTIALS"); + assertThat(error.getCode()).isEqualTo(AuthenticationErrorCodes.INVALID_CREDENTIALS); assertThat(error).hasMessage("Account reauthentication failed"); assertThat(error.getCause()).isNull(); assertThat(error.toString()).doesNotContain(EMAIL, SECRET); @@ -441,7 +442,8 @@ public void afterCommit() { } }); throw new AuthenticationException( - "INVALID_CREDENTIALS", "Rejected credential was " + SECRET); + AuthenticationErrorCodes.INVALID_CREDENTIALS, + "Rejected credential was " + SECRET); }) .when(primaryAuthentication) .authenticateControlUiPrimaryIdentity(EMAIL, SECRET); diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java index 3f2a920a59..4d33bbc4bc 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java @@ -393,7 +393,7 @@ final class AccountControlUiOwnerSourcesFixture { null, // Email delivery is not used by primary authentication. null, // Mail properties are not used by primary authentication. null, // Token properties are not used by primary authentication. - null, // Entity Management client is not used by primary authentication. + null, // JWT auth properties are not used by primary authentication. null, // JWT utility is not used by primary authentication. null, // Session service is not used by primary authentication. manager); From 44625d3cd72f77b54179132b459130ab3f9266f7 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 7 Nov 2026 15:22:43 +1300 Subject: [PATCH 11/23] Clarify historical reader proof and guarded owner-update refusal Label superseded R1424 entitlement classifications as historical, preserving the current unavailable receiver. Name the unaudited owner UPDATE test for its actual database guard and assert its exact retained PENDING request, inflight reservation and absent receipt rather than claiming reconcile ran. Integration compilation, enabled integration analysis, formatting and docs pass. Physical PostgreSQL execution remains CI-owned. The accepted High required-PLAY regression remains UNFIXED pending a coherent canonical runtime replacement or qualified existing-carrier reconstruction; neither this proof repair nor documentation closes that runtime obligation. --- .../player-access-and-session.md | 4 +-- ...ptionLifecyclePostgresIntegrationTest.java | 26 +++++++++++++++++-- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 7382b22fba..8b92bde533 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -700,9 +700,9 @@ The canonical gRPC `GameSessionGrpcService.startSession` path preflights IP admi ### Entitlement read and JOIN failure classification -The shared local Account subscription reader rejects null, missing, ambiguous or nonpositive-version evidence and preserves bounded entitlement-unavailable classification for storage outages; mapping/configuration faults remain unexpected failures. The prepared JOIN owner leaves a potentially aborted SQL transaction before writing diagnostic evidence through its existing post-rollback path; the current receiving method denies before invoking that owner. A failed fresh authority read during terminal replay returns unavailable without changing the complete retained result. This does not implement a complete entitlement bundle, current-row history, positive connect-token issuance, unknown-outcome observation after lost authority, or production admission. The [Account runtime owner](../../architecture/microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority) and [API error catalog](../../architecture/microservices/account-service/api-contracts.md#login-error-codes) own those contracts. +R1424 historically proved that the shared local Account subscription reader rejected null, missing, ambiguous or nonpositive-version evidence and preserved bounded entitlement-unavailable classification for storage outages; mapping/configuration faults remained unexpected failures. It also proved that the prepared JOIN owner leaves a potentially aborted SQL transaction before writing diagnostic evidence through its existing post-rollback path, and that a failed fresh authority read during terminal replay returns unavailable without changing the complete retained result. The current JOIN receiving method denies before invoking that owner, and the current numeric runtime entitlement endpoint returns `ENTITLEMENT_UNAVAILABLE` before any subscription read. This historical proof does not implement a complete entitlement bundle, current-row history, positive connect-token issuance, unknown-outcome observation after lost authority, or production admission. The [Account runtime owner](../../architecture/microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority) and [API error catalog](../../architecture/microservices/account-service/api-contracts.md#login-error-codes) own those contracts. -R1424’s current Account correction passes 305 unit cases and nine actual PostgreSQL cases, including a real SQL abort followed by rollback and a successful fresh-transaction diagnostic write, with correct unavailable classification and unchanged terminal evidence. The CHARS-focused Game Session source separately passes 184 selected unit cases and two actual WebSocket cases. All selected executions have zero failures, errors or skips, and affected enabled main/unit/integration analysis and formatting pass. These separate gates cover 500 selected cases; this is not one full service-suite run. The prior 488-case aggregate remains attributed to its earlier classification source. The PostgreSQL cases retain original intent, scope and Account provenance, prove no membership/audit on refusal, and exercise same-original recovery and immutable terminal evidence. The Game Session cases qualify unavailable direct-text `CHARS`, no accepted command event, and consistent HELP/PLAY/localized guidance while preserving supported WORLDS/REALMS and the separate Account roster. These are controlled owner/transport fixtures, not genuine issuer/custody, full service-suite or successful public-admission proof. Fresh packaged-runtime proof remains pending for the combined receiving source. +R1424’s historical Account correction passed 305 unit cases and nine actual PostgreSQL cases, including a real SQL abort followed by rollback and a successful fresh-transaction diagnostic write, with correct unavailable classification and unchanged terminal evidence. The CHARS-focused Game Session source separately passes 184 selected unit cases and two actual WebSocket cases. All selected executions have zero failures, errors or skips, and affected enabled main/unit/integration analysis and formatting pass. These separate gates cover 500 selected cases; this is not one full service-suite run. The prior 488-case aggregate remains attributed to its earlier classification source. The PostgreSQL cases retain original intent, scope and Account provenance, prove no membership/audit on refusal, and exercise same-original recovery and immutable terminal evidence. The Game Session cases qualify unavailable direct-text `CHARS`, no accepted command event, and consistent HELP/PLAY/localized guidance while preserving supported WORLDS/REALMS and the separate Account roster. These are controlled owner/transport fixtures, not genuine issuer/custody, full service-suite or successful public-admission proof. Fresh packaged-runtime proof remains pending for the combined receiving source. ### Session Lifecycle and Logout 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 index 36580afe4d..d22db0d47d 100644 --- 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 @@ -578,7 +578,7 @@ void walletDisplayAdvanceDuringSdkReadPreservesBindingAndStaleRowOwnerInputsReje } @Test - void unauditedOwnerChangeDuringActualSdkReadIsRefusedBeforeAnyReceipt() { + void databaseGuardRejectsUnauditedOwnerUpdateDuringSdkTransport() { Context c = context("1030"); Fixture f = fixture(c); var claim = claim(f); @@ -594,12 +594,13 @@ void unauditedOwnerChangeDuringActualSdkReadIsRefusedBeforeAnyReceipt() { "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( - UUID.randomUUID(), + reconciliationRequest, f.creation().requestId(), 2, f.providerId(), @@ -607,6 +608,27 @@ void unauditedOwnerChangeDuringActualSdkReadIsRefusedBeforeAnyReceipt() { 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, From 97f4a6a4f2694e0bec40e2d90831f88674149904 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 7 Nov 2026 16:32:33 +1300 Subject: [PATCH 12/23] Separate Account source foundation from unfinished canonical PLAY cutover Preserve the supported develop runtime while carrying reviewed transport, owner-source and proof components. Keep canonical schema retirement and live PLAY replacement in the draft successor. Retain all review obligations and existing grants. --- .../account-service/api-contracts.md | 30 +- .../account-service/runtime-and-data.md | 18 +- .../game-session-service/api-contracts.md | 4 +- .../player-access-and-session.md | 66 +- .../player_admission_entitlement_read.proto | 35 + .../v1/account_bootstrap_roster_read.proto | 40 + services/account-service/build.gradle.kts | 15 +- .../AccountBootstrapRosterReadClient.java | 198 + .../accountservice/data/TestDataSeeder.java | 24 + .../dto/CanonicalJoinScopeV2.java | 5 + ...etainedSubscriptionEvidenceRepository.java | 41 - .../repository/SubscriptionRepository.java | 158 + ...ayerAdmissionEntitlementWorkloadGuard.java | 76 + .../AccountCanonicalConnectScopeReader.java | 269 + ...ccountPlayerAdmissionEntitlementOwner.java | 623 ++ ...PlayerAdmissionEntitlementGrpcService.java | 120 + .../service/impl/AccountServiceImpl.java | 1508 ++++- ..._non_authorizing_subscription_evidence.sql | 44 - ...bscription_intent_and_provider_history.sql | 494 -- ...sting_subscription_provisioning_claims.sql | 561 -- ...g_subscription_first_provider_dispatch.sql | 82 - ...sting_subscription_terminal_resolution.sql | 202 - .../AccountApplicationIntegrationTest.java | 921 ++- ...rUuidEntityCompositionIntegrationTest.java | 614 ++ ...horityProducerPostgresIntegrationTest.java | 7 +- ...ntAuthorityCurrentnessIntegrationTest.java | 196 +- ...rceEvidencePersistenceIntegrationTest.java | 3 + ...CurrentSourcesPostgresIntegrationTest.java | 100 +- ...iptionDispatchPostgresIntegrationTest.java | 818 --- ...ptionLifecyclePostgresIntegrationTest.java | 1940 ------ ...mittedLoginCompositionIntegrationTest.java | 344 + .../AccountRepositoryIntegrationTest.java | 106 +- ...urceOwnerGuardPostgresIntegrationTest.java | 7 +- ...sionProtectionPostgresIntegrationTest.java | 8 +- ...criptionIntentPostgresIntegrationTest.java | 1751 ----- ...ourceSelectionPostgresIntegrationTest.java | 351 - ...nonicalHostingSubscriptionTestFixture.java | 502 -- ...iptionEvidencePostgresIntegrationTest.java | 233 - ...titlementOwnerPostgresIntegrationTest.java | 718 ++ ...titlementOwnerPostgresIntegrationTest.java | 330 - ...AuthenticationPostgresIntegrationTest.java | 7 +- ...ameplayDelegationRedisIntegrationTest.java | 12 +- ...entialVerifierPostgresIntegrationTest.java | 6 +- ...ionCompositionPostgresIntegrationTest.java | 538 -- ...authenticationPostgresIntegrationTest.java | 7 +- ...ationAdmissionPostgresIntegrationTest.java | 7 +- ...tionCompletionPostgresIntegrationTest.java | 7 +- ...ionSourceOrderPostgresIntegrationTest.java | 7 +- ...ountBootstrapRosterReadClientMtlsTest.java | 316 + .../data/TestDataSeederTest.java | 104 +- .../dto/CanonicalJoinScopeV2Test.java | 9 + ...AdmissionEntitlementWorkloadGuardTest.java | 117 + ...ccountCanonicalConnectScopeReaderTest.java | 490 ++ ...ntPlayerAdmissionEntitlementOwnerTest.java | 941 +++ ...AccountPublicBootstrapWorldsOwnerTest.java | 29 +- ...erAdmissionEntitlementGrpcServiceTest.java | 47 + .../service/impl/AccountServiceImplTest.java | 5758 +++++++++++++++-- .../LegacySubscriptionContainmentTest.java | 175 - ...GameplayPrimaryCredentialVerifierTest.java | 7 +- .../AccountControlUiOriginalOrderFixture.java | 99 +- .../AccountControlUiOwnerSourcesFixture.java | 80 +- ...ountPlayerAdmissionSharedOwnerFixture.java | 523 ++ ...imePlayerAdmissionEntitlementEvidence.java | 588 ++ ...layerAdmissionEntitlementEvidenceTest.java | 298 + ...mePlayerAdmissionEntitlementGrpcCodec.java | 161 + ...ameplayAdmissionDecisionReadGrpcCodec.java | 5 +- ...layAdmissionDecisionReadGrpcCodecTest.java | 21 +- ...ayerAdmissionEntitlementGrpcCodecTest.java | 279 + ...AccountBootstrapRosterActorProjection.java | 13 + ...AccountBootstrapRosterPeerInterceptor.java | 71 + .../AccountBootstrapRosterReadContract.java | 79 + ...AccountBootstrapRosterReadGrpcService.java | 76 + .../AccountBootstrapRosterReadService.java | 95 + .../repository/CharacterRepository.java | 89 +- ...calGameplayRosterOwnerEvidenceAdapter.java | 23 +- ...trapRosterPostgresMtlsIntegrationTest.java | 488 ++ ...untBootstrapRosterPeerInterceptorTest.java | 108 + ...AccountBootstrapRosterReadServiceTest.java | 219 + .../AccountBootstrapRosterFixture.java | 272 + .../game-session-service/build.gradle.kts | 4 + ...countPlayerAdmissionEntitlementClient.java | 393 ++ ...eplayAdmissionDecisionReadGrpcService.java | 14 +- ...dmissionActualOwnerCompositionFixture.java | 51 + ...meplayLoginPhysicalCompositionFixture.java | 410 ++ ...yerAdmissionEntitlementClientMtlsTest.java | 783 +++ ...yAdmissionDecisionReadGrpcServiceTest.java | 41 +- ...ationOwnerCompositionCrossServiceTest.java | 115 +- 87 files changed, 18312 insertions(+), 9232 deletions(-) create mode 100644 protos/account/v1/player_admission_entitlement_read.proto create mode 100644 protos/entity-management/v1/account_bootstrap_roster_read.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClient.java delete mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/RetainedSubscriptionEvidenceRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/SubscriptionRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountPlayerAdmissionEntitlementWorkloadGuard.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReader.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java delete mode 100644 services/account-service/src/main/resources/db/migration/V1028__retain_non_authorizing_subscription_evidence.sql delete mode 100644 services/account-service/src/main/resources/db/migration/V1029__canonical_subscription_intent_and_provider_history.sql delete mode 100644 services/account-service/src/main/resources/db/migration/V1030__hosting_subscription_provisioning_claims.sql delete mode 100644 services/account-service/src/main/resources/db/migration/V1032__hosting_subscription_first_provider_dispatch.sql delete mode 100644 services/account-service/src/main/resources/db/migration/V1036__hosting_subscription_terminal_resolution.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java delete mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java delete mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecyclePostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java delete mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentPostgresIntegrationTest.java delete mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionPostgresIntegrationTest.java delete mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java delete mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/RetainedSubscriptionEvidencePostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java delete mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerPostgresIntegrationTest.java delete mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionCompositionPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClientMtlsTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountPlayerAdmissionEntitlementWorkloadGuardTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReaderTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java delete mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/LegacySubscriptionContainmentTest.java create mode 100644 services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodec.java create mode 100644 services/common-security/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodecTest.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterActorProjection.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPeerInterceptor.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadContract.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadGrpcService.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadService.java create mode 100644 services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPostgresMtlsIntegrationTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPeerInterceptorTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadServiceTest.java create mode 100644 services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterFixture.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClient.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalPublishedAdmissionActualOwnerCompositionFixture.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginPhysicalCompositionFixture.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index f210cf3217..bd0a587ab9 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -125,9 +125,11 @@ Fresh-enrollment certification is internal Account owner work, not a public regi ## Implementation Status -The UUID billing foundation archives numeric subscription rows as immutable, non-authorizing retained evidence and supplies canonical intent, provisioning, lifecycle and cancellation-recovery storage. It also prepares the distinct `TENANT_OPERATION` source and protected transport; these owners remain manually composed and unregistered. Detailed receiving proof and unfinished authority boundaries belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). +The public bootstrap WORLDS source is prepared as an unregistered Account owner and is not yet wired into the existing `ListBootstrapWorlds` facade. Its current schema-backed source is the canonical Account DEMO entitlement; paid-hosting discovery remains unavailable until the subscription schema and retained facade consumers migrate together. Current source and proof status are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#public-bootstrap-worlds-source-preparation). -The existing public WORLDS, REALMS, CHARS, browser/direct JOIN, direct scope and connect-token facades currently return `AUTH_UNAVAILABLE` before legacy discovery or subscription reads. The complete canonical UUID public facade and positive compositions remain in the preserved receiving successor. Ordinary authentication/player-bootstrap identity remains available. Retained numeric rows never authorize current billing or admission. +Additional unregistered source prepares separate World Management `TENANT_OPERATION` and Game Session [player-admission entitlement reads](#private-player-admission-entitlement-read), held hosting provisioning and terminal-resolution owners, a signed canonical V2 scope reader, and an Account client for Entity-owned persisted bootstrap-roster discovery. These sources do not replace the existing public discovery/JOIN facade or runtime entitlement RPC, register a receiver, or enable player admission. The scope reader verifies an existing selector rather than authenticating its caller; the roster read supplies transient persisted discovery rather than a selection, actor allocation, session, or admission result. Exact source boundaries and pending proof are recorded in [local source-foundation preparation](../../../project-management/implementation-tracking/player-access-and-session.md#local-source-foundation-preparation). + +The opaque `bootstrap-connect-scope` artifact uses canonical non-nil Account UUID subject/claim equality. Both browser discovery and the existing direct-text Account producer obtain that identity from Account persistence; the dedicated reader resolves it back to Account-local storage before existing binding checks. Numeric scopes have no compatibility parser: clients obtain fresh scope evidence through bounded rediscovery, while retained rows/receipts are not rewritten and existing retained-replay guards remain. Caller authentication, public-join policy and the held connect-token issuer are unchanged. Detailed receiving proof belongs to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#bootstrap-connect-scope-uuid-artifact). The prepared selected gameplay-rule intake authorization, source-reservation/recovery, read and terminal-settlement owners are standalone and unregistered. Their typed transports add no available API or caller authority. Before enabling any standalone intake receiver (authorization, source read, HELD read, or settlement), its inbound message limit must accommodate the applicable 24 MiB codec bound: authorization and HELD read use `GameLogicIntakeAuthorizationGrpcCodec.MAX_WIRE_BYTES`; source read uses `GameLogicIntakeSourceReadProtoCodec.MAX_WIRE_BYTES`; settlement uses `AccountGameLogicIntakeSettlementEvidence.MAX_WIRE_BYTES`. The authorization receiver also carries the unchanged protected creator credential in binary metadata, so its inbound metadata limit must accommodate `AccountGameLogicIntakeAuthorizationCredentials.MAX_METADATA_BYTES`, which includes base64 wire encoding of the existing 16 KiB credential maximum plus metadata overhead. Binding a service configures neither limit. These are required receiver configurations, not claims about current deployment. The [Account prerequisite tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-gameplay-rule-intake-authorization-prerequisite) records qualification and receiving pipeline gaps. @@ -139,7 +141,7 @@ Account UUID generation currently has three established provenances: `ACCOUNT_RE This Account source-currentness and first-JOIN persistence prerequisite builds on the authority-storage and retention-safety stage. V40 adds owner-proven fresh issuer/Account source baselines and complete transactional source-event hooks; the owner-local first-JOIN producer/coordinator composes immutable membership, event, audit, and terminal operation evidence. These primitives do not authenticate callers, supply the cross-service target-through-commit gate, add a public route, or wire current LOGIN/public JOIN/Game Session text JOIN. Validation of the reconciled source-currentness stage remains pending; inherited storage proof is not proof of these additions. #2898 and #2848 retain their runtime and recovery gaps. -Current explicit JOIN status: Account's `JoinPublicProductionMembership` receiving method returns `AUTH_UNAVAILABLE` before bootstrap/scope, target, entitlement, or membership reads or mutation. The Gateway route remains blocked by its guard and absent from `publicOpenAPI`. The held boundary, preserved positive obligations, and proof history are in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving); target JOIN authority and commit requirements remain in [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md). +Current explicit JOIN status: the local `/auth/bootstrap/join` controller and operation are implemented, but the exact Gateway path is blocked by its route guard and the route is absent from `publicOpenAPI`. Local policy-digest revalidation does not prove that the exact target remains valid through Account commit; the strict ADR 0025 commit gate remains incomplete. The canonical owner is [Runtime & Data](./runtime-and-data.md#membership-and-entitlement-authority), with the target contract in [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md). `ResolveRuntimeAccountIdentity` is implemented as an authenticated Account-owner provenance read. The isolated producer extraction passes 31 focused unit tests, Account integration-source compilation, and formatting/documentation checks. These are handler, codec, and interceptor-wiring proofs, not PostgreSQL execution or a live mTLS handshake. The exact RPC is listed in `public-methods` in both base and production Account configuration to bypass bearer-token validation for this workload-only method; the gRPC listener still requires mTLS and the handler authorizes only the exact same-namespace Game Session and Entity Management workload identities. This result establishes neither Account UUID authentication nor membership, grants, actor ownership, namespace selection, or gameplay admission. @@ -149,7 +151,7 @@ Account has unregistered individual Creator Party, hosted-terms catalog, and ind `CommitTenantCapacityAdmission` is target-only. Its canonical request contract requires the stable identity, expected complete applicable `authorityTuple`, separate expected `entitlementVersion`, exact expected billing stream/checkpoint evidence, capacity delta, and versioned `mutationDigest`, but no proto RPC, durable authority/usage ledger, caller integration, or reservation-finalization path is implemented. The target replay rule is exact identity-and-payload replay with any changed tuple, entitlement, checkpoint, delta, or digest producing an idempotency conflict; implementation and focused proof remain future capability work rather than a nonfunctional service seam. -The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` implementation is Account/profile-local, with identity projections governed by [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity). This is partial data, not the canonical target portable-data export lifecycle, which is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route and policy remain implementation drift pending direct convergence on tenant-qualified routes. The legacy profile selector and authorization consequences are recorded under [REST APIs](#rest-apis); membership-authority-generation validation remains unimplemented. Public registration follows the response identity contract below and writes that same public identity in its platform audit outbox row; it creates only global Account state and does not create a profile or tenant membership. Current `JoinPublicProductionMembership` receiving returns `AUTH_UNAVAILABLE` before bootstrap/scope, target, entitlement, or membership reads or mutation; the Gateway route is blocked. Current status, preserved positive component obligations, and proof history are in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Target JOIN operation, digest, retry, and commit semantics remain owned by [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md) and the linked [Authentication contract](../../system-architecture-authentication.md). The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Current `/auth/connect-token` issuance returns `AUTH_UNAVAILABLE` before bootstrap or scope validation, replay or admission-authority reads, token minting, or replay/session mutation; cached-success replay and current membership, entitlement, grant, and pointer checks do not execute on this path. Current text `PLAY` validates the emitted `membershipLifecycleState` and independent `membershipAuthorityGeneration` and requires coherent `ACTIVE` admitting membership. Missing or `INACTIVE` public-production membership yields `JOIN_REQUIRED` only when fresh enrollment policy permits repair; an existing active but non-admitting response is not a join fallback. The implemented consumer limits remain in [Account runtime status](./runtime-and-data.md#implementation-status); these checks do not establish the complete caller-target and atomic-freshness contract. Current non-public or non-visible target handling remains split across existing discovery, membership, and grant surfaces; the complete grant/entitlement admission predicate at connect-token issuance remains target-only. The obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware. The browser connect-token body and OpenAPI response are defined as metadata-only; any issued raw token is carried only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. The `player-bootstrap` credential/result profile uses the persisted Account UUID in its result `accountId` and matching JWT subject/Account claim; its Account-owned reader rejects noncanonical, numeric or mismatched identity before resolving the private storage row. The final ordinary receiving composition also carries UUID ordinary login results/credentials, UUID shared intake and forwarding, UUID internal selectors and UUID Account references in downstream consumers; tenant identifiers remain numeric. Full token-profile/registry qualification remains held. Derived `bootstrap-connect-scope` artifacts use the persisted Account UUID in their signed subject/Account claim, through the shared browser/direct-text producer and dedicated Account reader. Profile self-binding and REST caller identity use UUID `SessionContext`; private Account SQL rows remain numeric. The legacy GameInstance owner/StartSession boundary remains separately numeric and unqualified. The bounded response and REST selector identity contract is defined below. Scoped-role population and tenant-switching proof remain target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. +The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` implementation is Account/profile-local, with identity projections governed by [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity). This is partial data, not the canonical target portable-data export lifecycle, which is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route and policy remain implementation drift pending direct convergence on tenant-qualified routes. The legacy profile selector and authorization consequences are recorded under [REST APIs](#rest-apis); membership-authority-generation validation remains unimplemented. Public registration follows the response identity contract below and writes that same public identity in its platform audit outbox row; it creates only global Account state and does not create a profile or tenant membership. Explicit public-production `JOIN` / `Join & Play` is implemented locally through `JoinPublicProductionMembership`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then evaluates current public-join entitlement. Only an authoritative `AVAILABLE` evaluation creates the versioned policy-bound operation digest and stores the exact `allowPublicJoin` and `entitlementVersion`; an unavailable attempt records its failure and availability and leaves the operation `PENDING` without invented policy evidence. A matching retry can re-evaluate that pending operation, and the membership commit gate revalidates the same digest and policy evidence. The operation, membership transition, and tenant audit outbox evidence are committed together. Focused local PostgreSQL retry/rollback proof is recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#account-email-verification-and-deferred-currency-containment); original-outcome observation after retry authority expires and direct-text end-to-end proof remain open. The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Current `/auth/connect-token` issuance returns `AUTH_UNAVAILABLE` after bootstrap and scope validation, before replay or admission-authority reads, token minting, or replay/session mutation; cached-success replay and current membership, entitlement, grant, and pointer checks do not execute on this path. Current text `PLAY` validates the emitted `membershipLifecycleState` and independent `membershipAuthorityGeneration` and requires coherent `ACTIVE` admitting membership. Missing or `INACTIVE` public-production membership yields `JOIN_REQUIRED` only when fresh enrollment policy permits repair; an existing active but non-admitting response is not a join fallback. The implemented consumer limits remain in [Account runtime status](./runtime-and-data.md#implementation-status); these checks do not establish the complete caller-target and atomic-freshness contract. Current non-public or non-visible target handling remains split across existing discovery, membership, and grant surfaces; the complete grant/entitlement admission predicate at connect-token issuance remains target-only. The obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware. The browser connect-token body and OpenAPI response are defined as metadata-only; any issued raw token is carried only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. The `player-bootstrap` credential/result profile uses the persisted Account UUID in its result `accountId` and matching JWT subject/Account claim; its Account-owned reader rejects noncanonical, numeric or mismatched identity before resolving the private storage row. The final ordinary receiving composition also carries UUID ordinary login results/credentials, UUID shared intake and forwarding, UUID internal selectors and UUID Account references in downstream consumers; tenant identifiers remain numeric. Full token-profile/registry qualification remains held. Derived `bootstrap-connect-scope` artifacts use the persisted Account UUID in their signed subject/Account claim, through the shared browser/direct-text producer and dedicated Account reader. Profile self-binding and REST caller identity use UUID `SessionContext`; private Account SQL rows remain numeric. The legacy GameInstance owner/StartSession boundary remains separately numeric and unqualified. The bounded response and REST selector identity contract is defined below. Scoped-role population and tenant-switching proof remain target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. ### Account UUID Response and REST Selector Identity @@ -195,7 +197,7 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - `CreateAccount` – registers a global Account identity and returns its canonical UUID as REST `AccountDto.id` and gRPC `CreateAccountResponse.account_id`; its platform audit outbox payload carries the same UUID. It does not select a tenant or create membership/profile state. - `SendNotification` – deliver account notifications asynchronously. - `Authenticate` – verifies one account-selected ordinary credential mode, either `PASSWORD` or verified-email `EMAIL_OTP`, using a required, typed `CredentialSourceContext` and, only for the approved Game Session-to-Account control path, issues the receiver-specific private `game-session-account-delegation` JWT with exact audience `account-service`. Gameplay credential and email-code authentication are global Account-identity operations: their current wire requests reserve the former `tenant_id` fields, and Account neither selects nor requires membership before returning identity. The pre-v1 wire convergence also reserves the former `username` field number and places `email` on a new field number, so mixed old/new Account and Game Session versions fail closed instead of reinterpreting identifiers; the two services must be deployed as one compatibility cohort for uninterrupted gameplay login. The target registry-backed flow stores one `session:auth:token:` record; current gameplay issuance uses the legacy account-scoped session key and defers tenant membership/grant/entitlement to `JOIN`/`PLAY`. Generic `Service JWT` and `aud=internal` profiles are forbidden; workload-only authorization uses mTLS. The context contains a server-derived canonical client address and transport class; Account rejects absent or untrusted context in player-facing environments, and public callers cannot assert it. -- `JoinPublicProductionMembership` – prepared internal Account interface for explicit public-production membership creation/restoration; the current receiving facade returns `AUTH_UNAVAILABLE` pending its complete canonical consumer. It accepts the Account-issued `connectScopeId`, operation `requestId`, and authenticated caller context; it revalidates the exact stored target and fresh `allowPublicJoin` entitlement evidence, binds the versioned digest to that caller/scope/policy snapshot, and commits membership/version, durable operation outcome, and tenant audit outbox evidence together. The digest's canonical grammar remains owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). A `PENDING` operation after an unknown database commit outcome still requires recovery/reconciliation implementation and exact-final-head PostgreSQL proof; no implicit membership writer or production end-to-end completion is claimed. +- `JoinPublicProductionMembership` – implemented local internal Account RPC for explicit public-production membership creation/restoration. It accepts the Account-issued `connectScopeId`, operation `requestId`, and authenticated caller context; it revalidates the exact stored target and fresh `allowPublicJoin` entitlement evidence, binds a v1 digest to that caller/scope/policy snapshot, and commits membership/version, durable operation outcome, and tenant audit outbox evidence together. The digest's canonical grammar remains owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). A `PENDING` operation after an unknown database commit outcome still requires recovery/reconciliation implementation and exact-final-head PostgreSQL proof; no implicit membership writer or production end-to-end completion is claimed. - `ResolveEffectiveSecurityPolicy` – **Target-state internal Account contract.** Resolve the effective policy for the exact account, optional tenant-scoped action, and action class from the versioned platform baseline, deployment policy, and applicable tenant policy using the tightening precedence in ADR 0045. Return the contributing policy versions, resolved values, and opaque `effectivePolicyVersion`/digest from one Account-owned resolution. Callers must not merge inputs or use cached/default policy; missing, invalid, contradictory, stale, or unavailable resolution fails the sensitive action closed. No other service is a policy authority. - `ApplyAccountSafetyRestriction` / `GetAccountSafetyRestrictions` – target Account-owned owner-command and safe projection contracts for `account_security_lock` and `platform_access_ban`. The command carries one exact category, global account scope, source case/security-event identity, a distinct `ownerEnforcementRequestId`, owner-enforcement digest, and owner authorization evidence; `controlPlaneRequestId` remains correlation-only and never carries or aliases the owner identity. Account validates and atomically commits its monotonic revision, account authority-generation effects, and idempotent result. The current proto/transport mapping does not yet expose the distinct owner request field; that is implementation drift, not proof that the target command is implemented. These contracts do not create a moderation appeal case, and current proto/implementation/proof do not yet provide the complete lifecycle. - `RefreshGameplayServiceToken` – Account-local RPC for the token refresh/replacement operation defined in [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md). Account validates the declared receiver binding and current authority, while Game Session supplies the binding-refresh installation/reconciliation consequence; the current proto and implementation do not yet prove the target registry-backed operation. @@ -221,10 +223,10 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - `IssuePlayerBootstrapToken` – authenticate a first-party player account and issue the short-lived `player-bootstrap` token profile used only for gameplay bootstrap. - `ListBootstrapWorlds` – list caller-visible worlds for first-party gameplay bootstrap. - `ListBootstrapRealms` – list caller-visible realms for a selected world during first-party gameplay bootstrap. -- `IssueDirectTextConnectScope` – prepared internal Account API; the current receiving method returns `AUTH_UNAVAILABLE` before caller/scope, target, entitlement, or scope-persistence work. Game Session text `REALMS` dispatch remains pending under #2898. Current held status, preserved source obligations, and proof history are in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving); the target scope and transport contract remains owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). +- `IssueDirectTextConnectScope` – implemented local internal Account RPC for issuing a direct-text connect scope. Game Session text `REALMS` dispatch to this RPC remains pending under #2898. The request carries typed `PlayerExecutionContext` scope data plus the server-resolved target. The certificate-derived Game Session mTLS workload identity authenticates the caller; Account validates the context against that trusted caller and Account-owned records separately from the short-lived scope, and returns an opaque `connectScopeId` with its expiry. After routing and entitlement validation, Account samples its own immutable `evaluatedAt` and binds it into the issued scope snapshot; this timestamp is not supplied by or inherited from the retained routing snapshot. Game Session retains the returned timestamp rather than deriving one from its clock or the expiry. Missing, ambiguous, or unavailable entitlement records fail as `ENTITLEMENT_UNAVAILABLE`, distinct from reachable missing or invalid routing evidence (`ADMISSION_POINTER_UNAVAILABLE`), a changed exact routing pair (`CONNECT_SCOPE_MISMATCH`), or unavailable routing authority (`AUTH_UNAVAILABLE`). An authoritative entitlement that denies gameplay returns `TENANT_BILLING_BLOCKED`. This RPC is distinct from `ListBootstrapRealms`, which is first-party discovery, and `JoinPublicProductionMembership`, which is the membership mutation. Fresh Account membership checks remain required separately at applicable admission gates. The canonical scope and transport requirements remain owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative); this local status does not claim direct text-client end-to-end proof. - `ListBootstrapCharacters` – list caller-visible characters for the selected opaque server-issued `connectScopeId` target during first-party gameplay bootstrap. The exact realm snapshot resolves and carries `playableStateScope` to the character-query boundary; neither clients nor Account derive a physical storage key, and the route world/realm must match the resolved scope. - Bootstrap discovery and join use the canonical realm catalog and admission-pointer contract in [Multi-Tenancy](../../system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract). The existing canonical resolver for the exact-snapshot `stateScope` to `playableStateScope` projection is owned there. REST bootstrap character discovery/creation and direct-text `CHARS`/creation are transport-local producers of that same server-derived projection; neither path accepts a caller-selected value, derives a storage key, or carries the projection through `JOIN` or connect-token issuance. Missing or mismatched proof that the REST and direct-text producers apply the same resolver is implementation drift, not a second resolver contract. Character-query input remains owned by the [Entity Management API contract](../entity-management-service/api-contracts.md#grpc). - +- `JoinPublicProductionMembership` – implemented local internal Account API for explicit public-production `JOIN`; the canonical membership lifecycle and freshness contract are owned by [Authentication](../../system-architecture-authentication.md) and its local persistence/transaction consequences by [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). It accepts the server-issued scope and request identity, and does not expose the removed implicit membership writer. Durable recovery/reconciliation for an operation left `PENDING` after an unknown database commit outcome, exact-final-head PostgreSQL runtime proof, direct text-client end-to-end proof, and membership-generation snapshot proof remain open. - `GetCallerTenantMembership` – caller-bound membership read for billing-safe mutation checks; freshness and sequence semantics follow [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). - `GetTenantMembershipForAccount` – cross-tenant membership lookup for billing/reporting workflows (`billingAdmin`/`platformAdmin` only). - `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` – internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. **Current implementation:** the proto and Account producer emit lifecycle state and `membershipAuthorityGeneration` alongside the independent `membershipVersion`, but Game Session does not enforce those fields. **Local unregistered preparation:** `AccountCanonicalRuntimeMembershipSnapshotRepository` and its explicit transaction service assemble the existing shared content carrier from canonical Account and fresh-tenant provenance, current owner generations/fence, role and membership-pair records, and exact committed source events/checkpoints in one owner transaction. Current tenant cutoff fields bind exactly to the verified current tenant source; unequal historical tenant generations fail closed without an Account-owned reconciliation result. This kernel neither authenticates a caller nor grants gameplay or entitlement authority, and the runtime RPC is not wired to it. **Target gap:** the authenticated runtime producer and consumers must carry and enforce the complete fresh snapshot at their admission boundaries. @@ -245,6 +247,14 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - `AddCurrency` – deferred virtual-currency substrate; unavailable as a supported v1 monetization API and not entitlement authority. - `SpendCurrency` – deferred virtual-currency substrate; unavailable as a supported v1 monetization API and not entitlement authority. +### Private player-admission entitlement read + +`AccountPlayerAdmissionEntitlementReadService/ReadPlayerAdmissionEntitlement` is a distinct private `PLAYER_ADMISSION` evidence read defined by the [purpose-specific protobuf](../../../../protos/account/v1/player_admission_entitlement_read.proto). Only the exact same-namespace Game Session workload may call it over mTLS; method authorization precedes request decoding, and ambient bearer or caller-supplied workload context cannot replace transport identity. The request carries schema version 1, the complete retained canonical target selector, Account-issued connect scope and explicit initial `game-session-account-delegation` credential. Repeated transport members each require exactly one value, and unknown fields fail closed. The credential is disclosed only to the verified Account peer on this method and must never be logged or persisted as request evidence. + +Account verifies the credential subject and current committed issuance, retained scope, current membership including explicit absence, and Account-selected paid-or-DEMO source. Callers cannot select a source family or convert missing paid authority into DEMO. The response echoes only the closed selectors and carries exact canonical `PLAYER_ADMISSION` evidence, never the credential. The [closed codec](../../../../services/common-security/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodec.java) owns wire bounds, the call deadline and exact response comparisons; the [evidence codec](../../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java) owns the canonical content. `scopeDigest` preserves the retained V2 `sha256:`-prefixed digest, distinct from raw-hex token/registry hashes. Unavailable, changed or expired authority produces no positive or empty-success evidence. + +This read supports only public-production `SHARED`/`PRESEEDED_ONLY` targets. Broader WORLDS discovery does not widen that restriction. It supplies point-in-time evidence, not membership repair, actor selection, capacity commitment, a World hold through Account commit or later admission, or gameplay admission. The receiver and Game Session client remain manually composed and unregistered; genuine scope/LOGIN custody, runtime integration and proof limits belong to the [player-admission source tracker](../../../project-management/implementation-tracking/player-access-and-session.md#player-admission-entitlement-source-preparation). + ### Runtime account identity owner read `RuntimeAccountIdentityService/ResolveRuntimeAccountIdentity` reads Account's already-persisted canonical UUID and provenance for Account's own row. The protobuf in [`runtime_account_identity_service.proto`](../../../../protos/account/v1/runtime_account_identity_service.proto) is the wire authority; Account does not derive an identity from another owner's key or row. @@ -380,8 +390,8 @@ Implemented Account-valued REST selectors and response fields use canonical Acco | `PUT` | `/tenants/{tenantId}/profiles/{accountId}` | **Canonical target, `tenant_regular`.** `accountId` is the canonical lowercase non-nil Account UUID. Account live membership authority supplies current membership lifecycle, `membershipAuthorityGeneration`, and independent `membershipVersion`; caller subject and scoped role checks apply. The legacy `/profiles/{accountId}` route remains implementation drift and has no `platformAdmin` override. | | `GET` | `/tenants/{tenantId}/memberships/me` | Authoritative caller-bound membership and roles for billing-safe mutation guards | | `GET` | `/tenants/{tenantId}/memberships/{accountId}` | Cross-tenant membership lookup for billing/reporting roles (`billingAdmin`/`platformAdmin`) | -| `POST` | `/auth/connect-token` | **Target behavior, not current compatibility behavior:** issue a short-lived gameplay connect token for one discovery-selected realm target using caller-bound player-bootstrap identity after one fresh atomic caller-bound runtime membership snapshot, including lifecycle state, independent membership version, and membership authority generation, plus the applicable grant, entitlement, and admission-pointer validation. The complete first-party sequence and private/playtest grant-and-entitlement predicate are owned by [ADR 0021](../../decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md#first-party-browser-flow); this local row records only the Account issuance consequence. Account must reread that exact membership on every issuance, including the first issuance after explicit join, at the issuance commit gate and compare both the independent membership version and opaque authority generation before issuing; stale or cached bootstrap/discovery membership evidence cannot substitute. For a selected public-production target, `allowPublicJoin` gates the required join/repair only when membership is missing or `INACTIVE`: a closed joining policy returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, and `JOIN_REQUIRED` is returned only when that policy permits joining and fresh target evidence passes. An existing `ACTIVE` member is not denied issuance solely because `allowPublicJoin=false`; fresh gameplay entitlement and every other applicable membership, routing, grant, and binding check still apply. An exact duplicate whose compact receipt remains after response-envelope recovery expiry returns typed `RESPONSE_RECOVERY_EXPIRED` and requires a fresh authorized request with a new `requestId`; a changed digest remains `IDEMPOTENCY_CONFLICT`. **Current implementation:** Account returns `AUTH_UNAVAILABLE` before bootstrap or connect-scope validation, cached-success replay, membership/entitlement/target reads, minting, or replay/session mutation; the held boundary and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). `ConnectTokenResponse` retains a dormant `jti` field; no current successful response or cookie delivery is reachable. **Target delivery:** HTTP response delivery uses only the protected `Set-Cookie` field: the response body and custom response headers never expose the raw token or provide a header fallback. First-party browser/mobile-browser clients and first-party native-mobile or other first-party non-browser clients using a cookie jar remain cookie-only. A separately registered and proven route for explicitly classified public/non-first-party native-mobile and other non-browser clients may later return the token once for protected secure storage and permit only the dedicated handshake header; that route and header are target-only/unavailable now and are not a browser endpoint or a cookie fallback. | -| `POST` | `/auth/bootstrap/join` | **Target JOIN behavior; current receiver unavailable.** The current Account receiving method returns `AUTH_UNAVAILABLE` before bootstrap/scope, target, entitlement, or membership reads or mutation; the Gateway path remains blocked by its explicit route guard. Current status, preserved obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). The target operation uses the exact caller-bound `connectScopeId` and `requestId`, first persisting a policy-independent request-intent digest and `PENDING` operation, then reading entitlement authority. Only an `AVAILABLE` authoritative result produces the versioned policy-bound request digest and stored `allowPublicJoin` / `entitlementVersion` evidence. An unavailable authority attempt records its failure and availability while keeping the operation `PENDING`, without a fabricated policy result, entitlement version, or final request digest; a matching retry can re-evaluate it. For a retained `PENDING` operation, an expired scope fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. Account revalidates the exact policy digest at the membership commit gate. The request accepts no caller-selected `playableStateScope`, storage key, or independently supplied runtime target. A changed scope, intent, or available policy returns the applicable deterministic error, including `CONNECT_SCOPE_MISMATCH` or `IDEMPOTENCY_CONFLICT`, without silently retargeting the join; an `ACTIVE` retry remains event-free. Exact-final-head PostgreSQL proof and membership-generation snapshot proof remain open. Game Session text JOIN dispatch remains with #2898; recovery/reconciliation after an unknown commit outcome and Logging receipt receiver/readback remain #2848. Direct text-client proof remains open; the canonical JOIN contract remains with [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). | +| `POST` | `/auth/connect-token` | **Target behavior, not current compatibility behavior:** issue a short-lived gameplay connect token for one discovery-selected realm target using caller-bound player-bootstrap identity after one fresh atomic caller-bound runtime membership snapshot, including lifecycle state, independent membership version, and membership authority generation, plus the applicable grant, entitlement, and admission-pointer validation. The complete first-party sequence and private/playtest grant-and-entitlement predicate are owned by [ADR 0021](../../decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md#first-party-browser-flow); this local row records only the Account issuance consequence. Account must reread that exact membership on every issuance, including the first issuance after explicit join, at the issuance commit gate and compare both the independent membership version and opaque authority generation before issuing; stale or cached bootstrap/discovery membership evidence cannot substitute. For a selected public-production target, `allowPublicJoin` gates the required join/repair only when membership is missing or `INACTIVE`: a closed joining policy returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, and `JOIN_REQUIRED` is returned only when that policy permits joining and fresh target evidence passes. An existing `ACTIVE` member is not denied issuance solely because `allowPublicJoin=false`; fresh gameplay entitlement and every other applicable membership, routing, grant, and binding check still apply. An exact duplicate whose compact receipt remains after response-envelope recovery expiry returns typed `RESPONSE_RECOVERY_EXPIRED` and requires a fresh authorized request with a new `requestId`; a changed digest remains `IDEMPOTENCY_CONFLICT`. **Current implementation:** after bootstrap and connect-scope authentication, the endpoint returns `AUTH_UNAVAILABLE` before cached-success replay, membership/entitlement/target reads, minting, or replay/session mutation while the canonical producer is unavailable. `ConnectTokenResponse` retains a dormant `jti` field; no current successful response or cookie delivery is reachable. **Target delivery:** HTTP response delivery uses only the protected `Set-Cookie` field: the response body and custom response headers never expose the raw token or provide a header fallback. First-party browser/mobile-browser clients and first-party native-mobile or other first-party non-browser clients using a cookie jar remain cookie-only. A separately registered and proven route for explicitly classified public/non-first-party native-mobile and other non-browser clients may later return the token once for protected secure storage and permit only the dedicated handshake header; that route and header are target-only/unavailable now and are not a browser endpoint or a cookie fallback. | +| `POST` | `/auth/bootstrap/join` | **Local Account controller and operation; complete production proof incomplete.** The local `JoinPublicProductionMembership` operation implements explicit caller-bound JOIN using the exact `connectScopeId` and `requestId`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then reads entitlement authority. Only an `AVAILABLE` authoritative result produces the versioned policy-bound request digest and stored `allowPublicJoin` / `entitlementVersion` evidence. An unavailable authority attempt records its failure and availability while keeping the operation `PENDING`, without a fabricated policy result, entitlement version, or final request digest; a matching retry can re-evaluate it. For a retained `PENDING` operation, an expired scope fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. Account revalidates the exact policy digest at the membership commit gate. The request accepts no caller-selected `playableStateScope`, storage key, or independently supplied runtime target. A changed scope, intent, or available policy returns the applicable deterministic error, including `CONNECT_SCOPE_MISMATCH` or `IDEMPOTENCY_CONFLICT`, without silently retargeting the join; an `ACTIVE` retry remains event-free. The Account route exists locally, but its exact public Gateway path is currently denied by the explicit route guard; this is an exposure restriction, not target-only controller status. Exact-final-head PostgreSQL proof and membership-generation snapshot proof remain open. Game Session text JOIN dispatch remains with #2898; recovery/reconciliation after an unknown commit outcome and Logging receipt receiver/readback remain #2848. Direct text-client proof remains open; the canonical JOIN contract remains with [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). | | `DELETE` | `/tenants/{tenantId}/memberships/me` | Leave a joined game using caller-bound membership authority; removes future membership-based discovery/admission while retained character, purchase, audit, and legal data follow their owning policies | | `GET` | `/internal/runtime/tenants/{tenantId}/entitlements` | Internal runtime/admission entitlement snapshot for gameplay-affecting services | | `GET` | `/tenants/{tenantId}/entitlements/me` | Caller-bound tenant-admin entitlement view for billing-safe UX | @@ -430,7 +440,7 @@ Every tenant-targeted request identifies its tenant in the route or request cont | --- | --- | --- | --- | | Public auth/bootstrap | `/auth/login`, `/auth/request-password-reset`, `/auth/complete-password-reset`, `/auth/request-email-verification`, `/auth/verify-email`, `/auth/recover-username`, `/.well-known/jwks.json` | No pre-existing user JWT; endpoint-specific validation and abuse controls | Intended for initial auth/bootstrap flows. The public `POST /auth/verify-email` is configured, but the verification email's `GET /auth/verify-email` link has no controller mapping and no browser handoff to POST. See [Runtime and Data](./runtime-and-data.md#email-and-notification-design). | | Player bootstrap issuance | `/auth/player-bootstrap` | First-party player account authentication bootstrap | **Target state:** issues the `player-bootstrap` token profile only after atomically creating its one active `session:auth:token:` registry record; registry failure fails issuance before exposure. It must not return a `control-ui` JWT or perform tenant-scoped admission checks. It may share Account's credential verification, abuse controls, and account-state checks with `/auth/login`, but the endpoint, audience, claims, lifetime, and allowed surfaces remain distinct. **Current implementation:** uses the legacy `session:auth:account::` Account session key rather than the ADR 0035 registry shape. | -| Player bootstrap | `/auth/bootstrap/worlds`, `/auth/bootstrap/worlds/{world}/realms`, `/auth/bootstrap/join`, `/auth/bootstrap/worlds/{world}/realms/{realm}/characters`, `/auth/connect-token` | Target first-party flow: short-lived, memory-only `player-bootstrap` token in `Authorization: Bearer ...` | Current `/auth/player-bootstrap` issuance authenticates the account before tenant selection and records account-scoped bootstrap session state. The Account world/realm/character discovery, direct-scope, JOIN, and connect-token receiving methods currently return `AUTH_UNAVAILABLE` before bootstrap/scope or legacy authority reads; the numeric runtime entitlement receiver returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. The held boundary and preserved obligations/proof are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). In the target flow, world and realm discovery may show a public production target before membership exists; character discovery requires the caller's current membership to exist and permit gameplay admission, while `/auth/bootstrap/join` is the explicit first-party open-enrollment writer. Character discovery consumes the opaque server-issued `connectScopeId`, verifies the route matches it, and revalidates its tenant/runtime target. Current `POST /auth/connect-token` returns `AUTH_UNAVAILABLE` before bootstrap/scope validation, membership/entitlement/admission-pointer or cached-result reads, or token minting. The target character-creation route is not currently routable or implemented: it requires that exact `connectScopeId`, derives `playableStateScope` from the realm catalog/pointer snapshot, and delegates the scoped write to Entity Management `CreateCharacter`; it does not persist character state or accept a caller-selected scope. Later character and connect-token surfaces must require live membership plus applicable grant, entitlement, and pointer checks. `POST /auth/connect-token` must obtain the exact current caller-bound runtime membership snapshot at its issuance commit gate, including lifecycle state, independent membership version, and opaque authority generation; cached or bootstrap evidence cannot substitute even when its generation appears current. Target success delivery uses only the protected `Firemud-Connect-Token` `Set-Cookie` field; the HTTP response body and custom response-header fields are metadata-only. First-party browser/mobile-browser and first-party native-mobile or other first-party non-browser cookie-jar clients remain cookie-only. A separately registered route for explicitly classified public/non-first-party native-mobile and other non-browser clients returns the token once for protected secure storage and permits only the dedicated handshake header; it is not a browser endpoint or a cookie fallback. PostgreSQL exact-final-head, recovery/reconciliation, direct text end-to-end, and membership-generation proof remain open. | +| Player bootstrap | `/auth/bootstrap/worlds`, `/auth/bootstrap/worlds/{world}/realms`, `/auth/bootstrap/join`, `/auth/bootstrap/worlds/{world}/realms/{realm}/characters`, `/auth/connect-token` | Target first-party flow: short-lived, memory-only `player-bootstrap` token in `Authorization: Bearer ...` | The implemented bootstrap derives caller identity before tenant selection, then resolves tenant scope through realm discovery. World and realm discovery may show a public production target before membership exists; character discovery now requires the caller's current membership to exist and permit gameplay admission, and `/auth/bootstrap/join` has a local Account controller/operation for the explicit first-party open-enrollment writer. Character discovery consumes the opaque server-issued `connectScopeId`, verifies the route matches it, and revalidates its tenant/runtime target. Current `POST /auth/connect-token` validates bootstrap identity and scope binding, then returns `AUTH_UNAVAILABLE` before membership, entitlement, admission-pointer, or cached-result reads and token minting. The target character-creation route is not currently routable or implemented: it requires that exact `connectScopeId`, derives `playableStateScope` from the realm catalog/pointer snapshot, and delegates the scoped write to Entity Management `CreateCharacter`; it does not persist character state or accept a caller-selected scope. Later character and connect-token surfaces must require live membership plus applicable grant, entitlement, and pointer checks. `POST /auth/connect-token` must obtain the exact current caller-bound runtime membership snapshot at its issuance commit gate, including lifecycle state, independent membership version, and opaque authority generation; cached or bootstrap evidence cannot substitute even when its generation appears current. Target success delivery uses only the protected `Firemud-Connect-Token` `Set-Cookie` field; the HTTP response body and custom response-header fields are metadata-only. First-party browser/mobile-browser and first-party native-mobile or other first-party non-browser cookie-jar clients remain cookie-only. A separately registered route for explicitly classified public/non-first-party native-mobile and other non-browser clients returns the token once for protected secure storage and permits only the dedicated handshake header; it is not a browser endpoint or a cookie fallback. PostgreSQL exact-final-head, recovery/reconciliation, direct text end-to-end, and membership-generation proof remain open. | | Authenticated account control-plane APIs | Current legacy `/accounts/{accountId}/export`; target `/auth/logout`, `/auth/logout-all`, `/tenants/{tenantId}/profiles/{accountId}`, active-account `/accounts/{accountId}/exports/**`, `/accounts/{accountId}`, `/tenants/{tenantId}/memberships/me`, `/tenants/{tenantId}/memberships/{accountId}` | Exact ordinary account subject through the declared `control-ui` JWT route class | This is the target authentication class only while the account remains eligible for ordinary authority. The current singular legacy export is classified here as an ordinary authenticated account-subject route; the target export lifecycle uses the authenticated account subject while active. The REST inventory identifies which routes are currently implemented and which remain target-only. | | Tenant-admin billing-safe export | `/tenant-admin/tenants/{tenantId}/export` | Exact `control-ui` caller with live `tenantAdmin` membership bound to the `{tenantId}` route segment | `billing_safe_tenant` classification. The route has a tenant binding but no `accountId` subject selector, requires live membership and membership-generation evidence, and remains target-only/not currently routable. | diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 76a3c3ace1..29dbc4cdc1 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,6 +8,10 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ## Implementation Status +The local source-foundation preparation retains the existing numeric subscription schema, runtime reader, public facade and demo seeder. It does not install the V1028-and-later subscription UUID transition, archive numeric subscription rows, retire their reader, or replace the facade with denial stubs. This retained runtime is implementation drift under the canonical [membership and entitlement authority](#membership-and-entitlement-authority), not a second target authority. Schema retirement and a functioning canonical UUID admission replacement remain one downstream receiving boundary; this preparation adds no numeric bridge or dual-authority path. The [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#local-source-foundation-preparation) owns source and proof status. + +The manually composed hosting provisioning and terminal-resolution sources require the downstream canonical subscription schema and cannot establish paid lifecycle or entitlement operation against the retained numeric schema. Separate `TENANT_OPERATION` and `PLAYER_ADMISSION` sources/transports, the V2 scope reader, and Account-to-Entity bootstrap-roster client remain unregistered and non-admitting. The player-admission owner performs JWT/registry, provider and protected target reads outside SQL, then rereads current Account issuance, membership, exact retained scope and selected billing source in a final writable `SERIALIZABLE` transaction; failed commit releases no evidence. Its DEMO proof sources use the existing schema, while paid execution requires canonical subscription storage and genuine provider receipts. Existing JOIN transactions are also explicitly writable and `SERIALIZABLE`; neither local guarantee supplies distributed target protection or completes the canonical JOIN commit gate. The [private player-admission API](./api-contracts.md#private-player-admission-entitlement-read) owns the protocol, [Subscription Management](./subscription-management.md) owns billing lifecycle, and the [tracker](../../../project-management/implementation-tracking/player-access-and-session.md#player-admission-entitlement-source-preparation) owns source/proof limits. + Both existing `bootstrap-connect-scope` producer paths mint the exact persisted Account UUID. Scope validation compares canonical UUID subject/Account claims before owner readback; malformed identity remains `CONNECT_SCOPE_INVALID`, while unavailable owner evidence is `AUTH_UNAVAILABLE`. Retained scope/JOIN rows and digests continue to use private Account row keys without a schema rewrite. This scope-artifact transition itself adds no Game Session text dispatch; the separately qualified ordinary receiving cohort now carries UUID Account identity through the direct-text caller context and Account-to-Entity references. Proof and retained-scope rediscovery limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#bootstrap-connect-scope-uuid-artifact) and [ordinary UUID receiving](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving). JOIN keeps numeric owner keys inside its retained scope, operation, membership and digest records. A private in-process outcome is projected through full Account owner readback only after the JOIN transaction returns, so response identity failure cannot undo a committed receipt or replace its original outcome. Profile repositories embed only partial Account rows; GET/UPDATE response projection rereads the full owner and supplies its verified UUID to the generated mapper. Both existing export paths verify their already-loaded Account once and reuse that UUID while retaining each profile owner, tenant and mapped-output check. The response identity contract is owned by [Account API contracts](./api-contracts.md); implementation and proof limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#account-owned-response-uuid-projection). @@ -66,11 +70,11 @@ Account implements bounded owner-local cleanup of expired password-reset, email- Account also performs a bounded sweep of public connect-scope evidence after its configured scope expiry. It deletes only rows with a valid parsed expiry at or before the captured UTC time and no `account_join_operations` reference of any status; malformed expiry rows remain untouched without blocking valid rows. V27 adds a restrictive foreign key from each JOIN operation to its exact scope row, fencing concurrent intent insertion against deletion. The sweep does not expire JOIN operation receipts or change account-deletion retention. -The current public registration path creates only a global Account row and a platform-scoped audit outbox record; it does not create a tenant membership or profile, and a legacy caller-supplied `tenantId` does not establish tenant authority. The current `JoinPublicProductionMembership` receiving method returns `AUTH_UNAVAILABLE` before bootstrap/scope, target, entitlement, or membership reads or mutations. The held receiving boundary, preserved positive implementation obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving); unknown-outcome recovery remains open under #2848, with no background reconciler claimed. `ACTIVE` membership is idempotent, while only missing or inactive membership transitions to `ACTIVE`. PostgreSQL repository proof covers independent intent insertion and atomic policy-binding/membership/outbox/outcome persistence, while the service unit proof covers the separate transaction commit/rollback boundary; focused native PostgreSQL and HTTP execution is recorded with its source-specific limits in the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md). No direct text-client end-to-end proof is claimed. Legacy Account migrations still assign tenant defaults/backfills and retain prior memberships as unverified, non-admitting evidence. This remains a retained-data deployment blocker: before any affected deployment, Account must record either a verified no-data boundary or an explicit retained-row disposition/mapping, including exact readback and admission-isolation evidence. No recovery is implied for already-applied irreversible migrations, and this status does not choose a tenant-identity migration design. +The current public registration path creates only a global Account row and a platform-scoped audit outbox record; it does not create a tenant membership or profile, and a legacy caller-supplied `tenantId` does not establish tenant authority. Explicit `JoinPublicProductionMembership` is the only public-production membership writer. It first commits a policy-independent `PENDING` intent containing the global request ID, verified caller binding, exact retained connect-scope evidence, and a version-1 intent digest. Only after authoritative entitlement evaluation succeeds does a separate Account transaction bind `allowPublicJoin`, the positive `entitlementVersion`, and the version-1 policy digest; that transaction revalidates the exact policy at the membership commit gate and atomically commits any membership transition, tenant-scoped audit outbox event, and terminal operation outcome. If entitlement authority is unavailable, the row remains `PENDING` with a typed last-attempt failure and availability but null policy values and null policy digest; an exact request retry may reconcile it after authority recovers. For a retained `PENDING` operation, an expired or malformed scope now fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. Definitive pre-policy failures retain the intent digest and a durable terminal outcome rather than fabricating policy evidence. A definitive mismatch between the freshly evaluated policy digest and an already-bound digest fails terminally as `IDEMPOTENCY_CONFLICT`, retaining the original request digest, policy version, and policy result without membership or transition audit/outbox mutation; this applies both on a retry and at the immediate commit-gate reread. Unavailable or unsafe authority and uncertain commit outcomes remain `PENDING`. A post-transaction readback applies the terminal retry checks when a terminal row is present; otherwise Account returns retryable `AUTH_UNAVAILABLE` and the caller must retry the same request ID. No background PENDING-operation reconciler is claimed; recovery/reconciliation after an unknown database commit outcome remains open. An exact retry of a terminal JOIN replays its stored result only after the retained scope is still unexpired and current target/entitlement authority is available and matches the stored policy digest; expiry, unavailable authority, or changed policy fails closed without rewriting the terminal operation or membership. `ACTIVE` membership is idempotent, while only missing or inactive membership transitions to `ACTIVE`. PostgreSQL repository proof covers independent intent insertion and atomic policy-binding/membership/outbox/outcome persistence, while the service unit proof covers the separate transaction commit/rollback boundary; focused native PostgreSQL and HTTP execution is recorded with its source-specific limits in the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md). No direct text-client end-to-end proof is claimed. Legacy Account migrations still assign tenant defaults/backfills and retain prior memberships as unverified, non-admitting evidence. This remains a retained-data deployment blocker: before any affected deployment, Account must record either a verified no-data boundary or an explicit retained-row disposition/mapping, including exact readback and admission-isolation evidence. No recovery is implied for already-applied irreversible migrations, and this status does not choose a tenant-identity migration design. Account has source-only persistence for individual Creator Party identity, hosted-terms acceptance/environment-binding evidence, and (from V98) disclosure handoffs with immutable captured source evidence. The V98 database guards constrain handoff identity, result transitions, and source-evidence insertion. A passive Account source-fence seam now excludes unsettled World participation from applicable source mutation/abort settlement and hosted-terms disclosure preparation/dispatch admission; `HostedTermsDisclosureHandoff` and its repository use the existing V98 journal. The unregistered historical World-participation reader resolves retained participation coordinates from the complete unchanged original tuple, verifies the retained capture and source-child vector, and can read after lease expiry or immutable terminal settlement; it uses existing rows and introduces no migration or table. It does not establish currentness, renew or admit authorization, or classify an Account expiry or failed response as World `ABORTED`; only the World owner can produce that terminal outcome with its original commit/fence evidence. The handoff retains opaque authority evidence as supplied and does not authenticate it. No verifier, dispatcher, transport, registry/runtime binding, creator UI, or Game Design evidence binding is registered. Reserve, claim, and publication paths that require the hosted-terms workflow remain unavailable. The acceptance/currentness authority remains target-only under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md), with changed-terms continuity under [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md); local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner workflow is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled. -The live `GetTenantMembershipForRuntime` producer emits `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`; `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent from the proto and producer. Current text `PLAY` consumes the emitted lifecycle and independent authority generation alongside version and admission evidence; this does not establish the complete atomic-freshness contract. Account-first bootstrap and credential-bearing gameplay `Authenticate` authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current Account public bootstrap discovery, direct-scope, JOIN, and connect-token receiving methods return `AUTH_UNAVAILABLE` before bootstrap/scope or legacy authority reads; the numeric runtime entitlement receiver returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. The held boundary, preserved positive obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Current text `PLAY` evaluates fresh entitlement before membership/grant and later actor/binding checks; public `JOIN_REQUIRED` is limited to coherent missing or `INACTIVE` membership when enrollment permits repair. An active but non-admitting response is not a join fallback. Complete caller-target/atomic authority and the remaining AA-2.1 / Unit 1B boundaries remain open. These flows do not create or restore membership. The Account-owned public-production JOIN writer remains a prepared persistence component with atomic membership, operation-outcome, and audit-outbox evidence; the current receiving facade returns `AUTH_UNAVAILABLE` before reaching it. Its HTTP exposure remains blocked by the Gateway route guard; Game Session text `JOIN`/`Join & Play` dispatch remains with #2898, while durable recovery after an unknown database commit and Logging receipt receiver/readback remain with #2848. Focused PostgreSQL/component proof and its limits are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#validation-and-proof); those controlled fixtures do not establish genuine deployed receiving custody or complete public admission. See [Account API Contracts](./api-contracts.md) for the public and internal API boundary and [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the canonical direct-text scope and JOIN contract. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The numeric runtime entitlement endpoint returns retryable `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and canonical snapshot fields/freshness remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Earlier focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof is limited to the prior cardinality guard and retry boundary; it does not establish current positive entitlement production. `CommitTenantCapacityAdmission` has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. +The live `GetTenantMembershipForRuntime` producer emits `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`; `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent from the proto and producer. Current text `PLAY` consumes the emitted lifecycle and independent authority generation alongside version and admission evidence; this does not establish the complete atomic-freshness contract. Account-first bootstrap and credential-bearing gameplay `Authenticate` authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Character discovery requires membership after applicable target and entitlement checks; on an eligible public-production target missing or `INACTIVE` membership returns non-actionable `JOIN_REQUIRED` when `allowPublicJoin` permits entry and `PUBLIC_PRODUCTION_ADMISSION_DENIED` otherwise, while other present non-admitting membership is denied as `CONNECT_TOKEN_REJECTED`. Current `POST /auth/connect-token` validates bootstrap identity and the retained connect scope, then returns `AUTH_UNAVAILABLE` before membership, entitlement, admission-pointer, cached-result, or token-issuance work; it does not currently return an issuance `JOIN_REQUIRED` or `CONNECT_TOKEN_REJECTED` result. Current text `PLAY` evaluates fresh entitlement before membership/grant and later actor/binding checks; public `JOIN_REQUIRED` is limited to coherent missing or `INACTIVE` membership when enrollment permits repair. An active but non-admitting response is not a join fallback. Complete caller-target/atomic authority and the remaining AA-2.1 / Unit 1B boundaries remain open. These flows do not create or restore membership. The Account-owned public-production `JOIN` writer is implemented locally with a v1 policy-bound digest and atomic membership, operation-outcome, and audit-outbox evidence. Its HTTP exposure remains blocked by the Gateway route guard; Game Session text `JOIN`/`Join & Play` dispatch remains with #2898, while durable recovery after an unknown database commit and Logging receipt receiver/readback remain with #2848. Focused PostgreSQL/component proof and its limits are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#validation-and-proof); those controlled fixtures do not establish genuine deployed receiving custody or complete public admission. See [Account API Contracts](./api-contracts.md) for the public and internal API boundary and [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the canonical direct-text scope and JOIN contract. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The entitlement producer returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field) when a tenant has zero or multiple subscription rows; only one explicit row is projected through current status mapping. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and canonical snapshot fields/freshness remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof covers only that cardinality guard and retry boundary. `CommitTenantCapacityAdmission` has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. The current `application.yml` and `application-prod.yml` retain `GetTenantMembershipForRuntime`, `GetRealmAccessGrantForRuntime`, `GetTenantEntitlementsForRuntime`, and `ListPresenceVisibilityPolicies` in the gRPC bearer-validation bypass list. Their handlers independently require certificate-derived workload identity in the exact configured namespace: Game Session for membership and realm-grant reads, Game Session or World Management for entitlement reads, and Social & Groups for presence-policy reads. Handler and configured-interceptor tests cover permitted peers without bearer credentials and refusal of unauthorized or wrong-namespace peers. This workload-only bypass does not make the methods unauthenticated public APIs. Complete typed caller-context and tenant-binding qualification, membership/currentness consumption, and the remaining canonical admission and registry contracts remain separate gaps under the [Account API contract](./api-contracts.md); these workload checks alone do not establish readiness. @@ -78,7 +82,7 @@ The target realm-grant mutation boundary remains the Account API's tenant-admin Recovery/verification foundations are live. Password-reset completion now uses an owner-locked atomic token claim/consume, Account update, canonical event and operation receipt, and current-source readback; an unresolved prior source intent fences token/password mutation and returns retryable `AUTH_UNAVAILABLE` until an exact retry can establish its outcome. `AccountAuthoritySourceEventReadback` accepts only the supported closed-operation event shapes with their exact immutable operation receipts; generic Account authority events without that receipt remain unreadable as current source evidence and fail closed as `AUTH_UNAVAILABLE`. This does not establish complete LOGIN/currentness closure. Reset-driven revocation and the broader recovery/session/logout family remain incomplete. Exact retry, concurrent reuse, and physical PostgreSQL proof for this cut remain pending under the [Account API recovery boundary](./api-contracts.md#rest-apis) and [authentication security contract](../../system-architecture-authentication.md). -Current Account public bootstrap, `IssueDirectTextConnectScope`, `JoinPublicProductionMembership`, and connect-token receiving methods return `AUTH_UNAVAILABLE` before bootstrap/scope or legacy authority reads; 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 recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Game Session text `REALMS`/`JOIN` dispatch remains unimplemented under #2898; unknown JOIN outcome recovery and Logging receipt receiver/readback remain #2848, and direct text-client end-to-end proof remains open. The target scope and transport contract remains in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). +Account locally implements `IssueDirectTextConnectScope` for an authenticated caller and the exact Game Session-resolved public-production target from `REALMS`, validating its retained target snapshot and caller binding. Game Session does not yet wire this RPC into text `REALMS` or retain the returned scope in transport context. Account also implements the `JoinPublicProductionMembership` RPC/operation and local HTTP JOIN route, including retained-target and caller-binding validation; Game Session text `JOIN`/`Join & Play` dispatch remains unimplemented under #2898. These local Account capabilities do not yet form an end-to-end direct-text `REALMS`-to-`JOIN` flow. Account request retries can resume a committed policy-independent intent across entitlement outages; after an uncertain second-transaction outcome, Account reads back and returns a terminal result if committed, otherwise asks the caller to retry that request ID. No background recovery worker or direct text-client end-to-end proof is claimed. The canonical scope and transport contract remains in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). The target capacity retry contract uses stable outer `(tenantId, requestId, admissionId)`, fresh per-attempt `admissionAttemptId`, current `capacityRearmFence`, exact complete entitlement evidence, bounded `capacityDelta`, and a versioned `mutationDigest` over that attempt identity, fence, and complete payload. Exact retries replay the stored result. A new attempt requires an Account-owned atomic CAS over the same outer tuple, terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` plus durable no-commit evidence, current fence, and prior digest; the CAS advances the fence without creating a second reservation. Changed fields without a matching rearm return `IDEMPOTENCY_CONFLICT`; stale or losing fences return `FENCE_REJECTED` only with durable no-accept/no-runtime-mutation proof. This remains target-only and follows the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). @@ -201,7 +205,7 @@ The `player-bootstrap` token profile is distinct from both `control-ui` and priv - Audience is `player-bootstrap`. - It is issued only by `POST /auth/player-bootstrap` / `IssuePlayerBootstrapToken`. - `POST /auth/player-bootstrap` is the canonical first-party browser/mobile player-login endpoint. It authenticates player credentials directly under the same password, OTP, brute-force defense, and account-lock policy used for gameplay login rather than deriving bootstrap from a pre-existing admin/creator session. -- It establishes account identity for first-party gameplay bootstrap only. Target behavior is that public-game membership is created only by explicit `/auth/bootstrap/join`; character discovery, character creation, and `POST /auth/connect-token` later require that membership and recheck applicable grants, entitlements, and the discovery-selected runtime target. World and realm discovery remain available before membership. On an eligible public-production target, character discovery returns non-actionable `JOIN_REQUIRED` for missing or `INACTIVE` membership when `allowPublicJoin` permits entry and `PUBLIC_PRODUCTION_ADMISSION_DENIED` otherwise; other present non-admitting membership is denied as `CONNECT_TOKEN_REJECTED`. Current text `PLAY` consumes the emitted membership lifecycle and independent authority generation alongside existence, admission, version, and evaluation-time evidence; it checks fresh entitlement before membership/grant and later actor/binding checks. Its implemented checks follow the [canonical PLAY outcome matrix](../../system-architecture-authentication.md#play-current-and-target-failure-boundaries). This implemented field validation is not the complete atomic freshness contract. Current connect-token issuance returns `AUTH_UNAVAILABLE` before bootstrap/scope validation, membership, entitlement, target-authority, or cached-result processing. None of these paths creates or restores membership. Account's owner-local public-production JOIN v2 remains a prepared persistence component, but the current receiving facade returns `AUTH_UNAVAILABLE` before reaching it. First-party text `JOIN`/`Join & Play` dispatch and durable recovery after an unknown database commit outcome remain open. Non-public or non-visible targets remain subject to their realm-access and grant checks rather than using public onboarding semantics. +- It establishes account identity for first-party gameplay bootstrap only. Target behavior is that public-game membership is created only by explicit `/auth/bootstrap/join`; character discovery, character creation, and `POST /auth/connect-token` later require that membership and recheck applicable grants, entitlements, and the discovery-selected runtime target. World and realm discovery remain available before membership. On an eligible public-production target, character discovery returns non-actionable `JOIN_REQUIRED` for missing or `INACTIVE` membership when `allowPublicJoin` permits entry and `PUBLIC_PRODUCTION_ADMISSION_DENIED` otherwise; other present non-admitting membership is denied as `CONNECT_TOKEN_REJECTED`. Current text `PLAY` consumes the emitted membership lifecycle and independent authority generation alongside existence, admission, version, and evaluation-time evidence; it checks fresh entitlement before membership/grant and later actor/binding checks. Its implemented checks follow the [canonical PLAY outcome matrix](../../system-architecture-authentication.md#play-current-and-target-failure-boundaries). This implemented field validation is not the complete atomic freshness contract. Current connect-token issuance validates bootstrap identity and scope, then returns `AUTH_UNAVAILABLE` before membership, entitlement, target-authority, or cached-result processing. None of these paths creates or restores membership. The Account-owned public-production `JOIN` writer is implemented locally; first-party text `JOIN`/`Join & Play` dispatch and durable recovery after an unknown database commit outcome remain open. Non-public or non-visible targets remain subject to their realm-access and grant checks rather than using public onboarding semantics. - It is stored in memory only by first-party gameplay UIs and is accepted only on gameplay-bootstrap surfaces such as bootstrap discovery and `POST /auth/connect-token`. - For first-party `/ws/game/**`, subsequent gameplay `LOGIN` must complete from the bootstrap/connect context already established for that socket; browser clients must not be required to replay account credentials after bootstrap. - If the token is lost because the page/app process is restarted, the client must restart bootstrap from `POST /auth/player-bootstrap`; the current architecture does not define a hidden silent-bootstrap refresh mechanism. @@ -316,7 +320,7 @@ Entitlement producer contract: - `provisioningStatus` is `pending`, `provisioning`, or null; while non-null, `subscriptionStatus` is null and all new gameplay/admission/instance-start flags are false. `tenantAuthorityGeneration` is opaque and may be compared only for exact equality, never ordered or used as an event identity. - The focused producer proof must show that every entitlement response is one Account-authenticated bundle from the same authoritative committed evaluation, that `tenantAuthorityGeneration` is the Account-committed fence rather than a value reconstructed from a later projection read, and that no caller reconstructs or separately sources bundle identities, tuple members, cutoff evidence, or checkpoints. -The current numeric runtime entitlement endpoint refuses with `ENTITLEMENT_UNAVAILABLE` before historical subscription reads. Canonical UUID billing and the distinct unregistered `TENANT_OPERATION` source are prepared separately; the complete public `PLAYER_ADMISSION` consumer remains in its receiving successor. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving) owns receiving proof and gaps. +Current implementation remains a narrower local subscription read: unusable row sets and versions fail closed, and classified storage failures are kept distinct from programming faults. JOIN diagnostic persistence uses its existing post-rollback path, while terminal retry refusal preserves the original receipt. This supplies neither the complete bundle above nor positive connect-token issuance. Current proof and remaining boundaries belong to the [entitlement read tracker](../../../project-management/implementation-tracking/player-access-and-session.md#entitlement-read-and-join-failure-classification). ### Playtest Grant Persistence and Authority Consequences @@ -353,9 +357,9 @@ Existing `AccountRealmAccessGrant` persistence and registered internal grant rea ### Runtime Implementation Status and Drift -- Account's owner-local JOIN v2 model remains a prepared persistence component with a closed canonical scope, stable intent digest, and policy-bound request digest. The current `JoinPublicProductionMembership` receiving facade returns `AUTH_UNAVAILABLE` before bootstrap/scope, target, or entitlement reads or membership mutation; canonical status, preserved obligations, and proof history are in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Game Session text JOIN dispatch (#2898), unknown-outcome recovery (#2848), PostgreSQL execution, and direct text-client proof remain outstanding. +- Account's owner-local JOIN v2 model adds a closed canonical scope, stable intent digest, and policy-bound request digest to the existing persistence foundation. It does not change the current JoinPublicProductionMembership RPC or confer target authority by digest alone. Account login/public JOIN wiring, Game Session text JOIN dispatch (#2898), unknown-outcome recovery (#2848), PostgreSQL execution, and direct text-client proof remain outstanding. -- Account-first bootstrap now authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current Account public bootstrap discovery, direct-scope, JOIN, and connect-token receiving methods return `AUTH_UNAVAILABLE` before bootstrap/scope or legacy authority reads; the numeric runtime entitlement receiver returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. The held boundary and preserved source obligations/proof are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Current text `PLAY` implements lifecycle/generation validation and entitlement-first ordering under the [canonical PLAY outcome matrix](../../system-architecture-authentication.md#play-current-and-target-failure-boundaries); complete caller-target and atomic authority proof remains open. The current Account JOIN receiving method returns `AUTH_UNAVAILABLE` before bootstrap/scope, target, entitlement, or membership reads or mutation; the public Gateway route remains blocked by its explicit guard. See [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving) for the held boundary and preserved component obligations/proof. Game Session text `JOIN`/`Join & Play` dispatch remains with #2898; recovery after unknown JOIN commit outcomes and Logging receipt receiver/readback remain #2848. PostgreSQL exact-final-head proof and direct text-client end-to-end proof remain incomplete. The target connect-token membership-authority-generation reread remains unenforced and is a prerequisite for any future connect-token producer. The current non-public character-discovery mapping returns `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay; connect-token issuance instead returns `AUTH_UNAVAILABLE` before membership processing. Text `PLAY` implements the private membership and grant checks covered by the canonical outcome matrix linked above; complete caller-target, grant-lifecycle/expiry, and atomic freshness proof remains open. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling are also incomplete. +- Account-first bootstrap now authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current Account connect-token issuance validates bootstrap identity and connect-scope binding, then returns `AUTH_UNAVAILABLE` before membership, entitlement, admission-pointer, cached-success, or token-minting work. Character discovery checks local membership existence/admission after fresh entitlement and target checks. On an eligible public-production target, missing or `INACTIVE` membership returns `JOIN_REQUIRED` when `allowPublicJoin` permits entry and `PUBLIC_PRODUCTION_ADMISSION_DENIED` otherwise; other present non-admitting membership is denied as `CONNECT_TOKEN_REJECTED`. Current text `PLAY` implements lifecycle/generation validation and entitlement-first ordering under the [canonical PLAY outcome matrix](../../system-architecture-authentication.md#play-current-and-target-failure-boundaries); complete caller-target and atomic authority proof remains open. The Account-owned explicit public-production JOIN writer and operation controller, including the local `POST /auth/bootstrap/join` REST route, exist locally; its public Gateway exposure remains blocked by the explicit route guard pending production proof. Game Session text `JOIN`/`Join & Play` dispatch remains with #2898; recovery after unknown JOIN commit outcomes and Logging receipt receiver/readback remain #2848. PostgreSQL exact-final-head proof and direct text-client end-to-end proof remain incomplete. The target connect-token membership-authority-generation reread remains unenforced and is a prerequisite for any future connect-token producer. The current non-public character-discovery mapping returns `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay; connect-token issuance instead returns `AUTH_UNAVAILABLE` before membership processing. Text `PLAY` implements the private membership and grant checks covered by the canonical outcome matrix linked above; complete caller-target, grant-lifecycle/expiry, and atomic freshness proof remains open. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling are also incomplete. The current JOIN implementation re-reads Game Session routing/catalog/pointer evidence but does not ensure that the exact target remains valid through the Account commit. The strict ADR 0025 commit gate is incomplete; detailed implementation and proof status is tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#capability-status). diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 489962950c..2880fa5364 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -16,6 +16,8 @@ The local [canonical NEW admission lease contract](../../system-architecture-ses The initial-LOGIN PostgreSQL journal and exact original-attempt cleanup owner are unregistered source preparation, with no new Game Session endpoint or legacy LOGIN handler composition. Their unregistered Account client authenticates the exact same-namespace Account mTLS peer and validates the explicit initial delegation profile, signature, original request/context, token hash, claim/projection equality and bounded nonsecret evidence. Its one transient invocation permits at most one transport reload/retry under the unchanged deadline. It also uses the original-request retirement contract. The result retains compact private-token bytes only in process; validation supplies neither current registry authority nor live context installation. Journal snapshots and typed closure fixtures supply no authenticated caller custody or physical Redis closure; the separate Redis adapter remains outside runtime composition. See the [canonical coordination contract](../../system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination) and [implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). +The manually composed `AccountPlayerAdmissionEntitlementClient` consumes the distinct [Account player-admission entitlement purpose](../account-service/api-contracts.md#private-player-admission-entitlement-read). It accepts either a verified first-party connect context or an Account-issued canonical direct-text lobby scope inside its current LOGIN-custody callback. The direct-text read retains the exact original attempt, observed transport, target and Account-issued expiry; historical scope decoding does not authenticate custody. Both inputs share bounded peer-qualified transport, before/after currentness checks and exact response/LOGIN bindings. This source installs no custody, registers no handler and supplies no World hold or admission decision; current proof and unfinished runtime composition belong to the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving). + The source-first owner stage consumes the closed Game Design creation/source receipt, four immutable launch snapshots and policy seal through the trusted fixed capability parser. `RunOwnedCanonicalLaunchPreparationOwner` exposes canonical fresh-association, catalog and `STARTING` creation with independent owner readback only through an explicit preparation call; it has no scheduler. The published `RunOwnedInitialAdmissionFixtureCoordinator` bootstrap and existing `GameInstanceServiceImpl` behavior remain until coherent canonical adoption, so this source-first path is not evidence that the current scheduled runtime allocates that canonical launch. Game Design source keys and Game Session's allocated private tenant/runtime keys remain separate. The published numeric fixture path has not been removed by this source-only split. This explicit canonical path establishes no canonical World materialization/activation, canonical first-`OPEN`, or canonical admission result. `GameSessionControlPlaneService.GetRunOwnedFixtureLaunchAssociation` is a fixed, default-off source read of that exact `STARTING` allocation. It authenticates the same-namespace World workload and retained recipient certificate before decoding caller selectors, then requires the original operation and policy-seal digest. It returns the exact owner-allocated identities and retained policy request/seal, not World lifecycle, first `OPEN`, Account membership or player authority. The transport bypasses bearer validation only for this method; its exact workload checks remain mandatory. The canonical evidence shape is owned by [Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence), with producer consequences in [Game Design API contracts](../game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt) and candidate proof in the [runtime tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#canonical-fixture-launch-owner-stage). @@ -64,7 +66,7 @@ Multi-Tenancy owns the realm catalog, the canonical durable `{tenantId, realmId} ### Public-production bootstrap target collection read -The manually composed, unregistered `CanonicalGameplayAdmissionDecisionReadService.ListVisiblePublicProductionAdmissionTargets` is an Account-purpose point-in-time source read. It accepts only the exact same-namespace Account workload over mTLS, without propagated player context or an ambient SQL transaction. The closed request and response are defined by [`canonical_gameplay_admission_decision_read.proto`](../../../../protos/game-session/v1/canonical_gameplay_admission_decision_read.proto). The source is the complete current canonical visible public-production target collection from `CanonicalPlayerRouteReadService`, restricted to `SHARED` targets with `PRESEEDED_ONLY`; each returned target retains the canonical target and committed owner proof needed by Account for pre-scope discovery. The [canonical realm-catalog contract](../../system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract) requires exactly one visible, player-addressable `publicProduction=true` realm per tenant. This collection therefore contains at most one target per canonical tenant and tenant slug; duplicate tenant authority is invalid and refuses the complete collection rather than selecting or grouping a fallback. Other realms returned by realm-listing APIs do not create additional public-production targets. Valid `PLAYER_CREATED` targets are excluded from both discovery reads only after validating their authority and collection uniqueness; malformed or duplicate authority still refuses the complete collection. +The manually composed, unregistered `CanonicalGameplayAdmissionDecisionReadService.ListVisiblePublicProductionAdmissionTargets` is an Account-purpose point-in-time source read. It accepts only the exact same-namespace Account workload over mTLS, without propagated player context or an ambient SQL transaction. The closed request and response are defined by [`canonical_gameplay_admission_decision_read.proto`](../../../../protos/game-session/v1/canonical_gameplay_admission_decision_read.proto). The source is the complete current canonical visible public-production target collection from `CanonicalPlayerRouteReadService`, restricted to `SHARED` targets with either canonical `PRESEEDED_ONLY` or `PLAYER_CREATED` creation policy; each returned target retains the canonical target and committed owner proof needed by Account for pre-scope discovery. The [canonical realm-catalog contract](../../system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract) requires exactly one visible, player-addressable `publicProduction=true` realm per tenant. This collection therefore contains at most one target per canonical tenant and tenant slug; duplicate tenant identities/slugs or realm identities refuse the complete collection rather than selecting or grouping a fallback. Other realms returned by realm-listing APIs do not create additional public-production targets. Malformed or duplicate authority, including `PLAYER_CREATED` authority, unknown policies, isolated/private targets and incomplete evidence refuse the whole collection. This complete discovery collection does not relax policy-specific target selection, roster or admission methods. Game Session validates the complete first collection, independently rereads the complete collection, and returns it only if an order-independent comparison finds the exact target values and membership unchanged. An authenticated empty collection is valid. Missing or unavailable authority, malformed or ambiguous targets, changed sources, and an oversized response do not become an empty or partial success. The request is bounded to 16 KiB, each target to 64 KiB, and the complete response to 4 MiB; there is no pagination or truncation, and the Account client uses a five-second deadline. This read supplies neither a fresh World lifecycle read or hold nor caller authorization, scope issuance, membership, JOIN, or gameplay admission. Account owns entitlement filtering and result semantics; target selection and subsequent strict source reads remain separate. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 8b92bde533..7f291b0114 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,21 +8,27 @@ This is a non-normative implementation tracker for player access and session. Ca Account initial/current/final creation owners, explicit initial billing-owner consent, private Game Design create/close receivers, and original-bound dispatch/recovery are locally composed and unregistered. Focused receiving proof passes, while physical cross-owner qualification, protected Redis/source custody and public/default registration remain incomplete; proof limits are recorded below. -### Canonical billing and retention receiving +### Local source-foundation preparation -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 provisioning and cancellation components keep actual Account actor/authentication and owner-local atomic receipt/fence/event checks; cancellation prepares one allowed safe outcome. Coupled 356 physical proof now passes through genuine certified ACCOUNT issuance/current actor, fresh primary OTP authentication and the guarded cancellation commit. Its five PostgreSQL/AOF-replica cases 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 local reconstruction based on `6b86f46f3fd0a76729b27f99b1e573bbac649838` carries selected source from #3389, #3390 and #3403 without their subscription-schema retirement or canonical public-facade cutover. The existing numeric subscription schema, reader, public facade and demo seeder remain unchanged. The only retained [`AccountServiceImpl`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java) change makes its independent JOIN transactions explicitly writable and `SERIALIZABLE`; this is local transaction hardening, not completion of the canonical distributed commit gate. Existing runtime behavior remains implementation drift rather than the target contract. -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. +The #3389 source includes the private [`TENANT_OPERATION` proto](../../../protos/account/v1/tenant_operation_entitlement_read.proto), [strict common evidence codec](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementGrpcCodec.java), [Account source owner](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwner.java), [workload guard](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantOperationEntitlementWorkloadGuard.java), [gRPC receiver](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantOperationEntitlementGrpcService.java), and [World client](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClient.java). They prepare an explicit paid-or-DEMO eligibility read for the exact same-namespace World workload without source fallback, capacity commitment or player admission. They remain manually composed and unregistered; the paid branch still depends on the missing canonical subscription schema. The [controlled mTLS transport test source](../../../services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClientMtlsTest.java) uses a controlled Account source owner and does not establish physical paid entitlement authority. -Paid first-invoice confirmation remains an unfinished Account checkout obligation. Stripe `default_incomplete` creation and subscription polling do not confirm a required first payment; controlled active-subscription inputs are not live paid-checkout proof. Complete confirmation through 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. +Held hosting sources include 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), [lifecycle repository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java), and [same-owner terminal-resolution composition](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionService.java), with their focused unit sources. Retained dispatch/readback and fresh Account primary-authentication guards do not enable `CreateSubscription`, a provider worker, cancellation recovery, or a production billing route. Their required canonical intent, provisioning, lifecycle, dispatch and terminal-resolution storage is not installed in this candidate; the dependent physical billing/retention proofs are not carried as candidate qualification. -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 #3390 source adds the unregistered [Entity bootstrap-roster proto](../../../protos/entity-management/v1/account_bootstrap_roster_read.proto), [Entity persisted reader](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadService.java), [Account client](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClient.java), and [signed V2 scope reader](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReader.java). Discovery is bounded to independently current public-production `SHARED`/`PRESEEDED_ONLY` targets and actual persisted eligible actors, including their stored level and valid empty rosters; it creates no selection, actor, retained roster, session or admission authority. Target reads surrounding Entity SQL detect source movement but supply no distributed hold. The scope reader compares the signed selector with retained Account evidence and requires an externally authenticated Account identity. Neither reader is consumed by the existing public facade. [`CanonicalJoinScopeV2`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CanonicalJoinScopeV2.java) also redacts its bearer scope in `toString()`. -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. +Focused unit and controlled physical proof sources are retained, including the [Entity PostgreSQL/mTLS roster tests](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPostgresMtlsIntegrationTest.java), [Account roster-client mTLS tests](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClientMtlsTest.java), and [V2 scope-reader units](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReaderTest.java). The expanded candidate passes 523 selected cases: 403 Account, eight Entity, 73 Game Session, fourteen Common Platform Core, 21 Common Security and four World client mTLS cases, with no failures, errors or skips. The first expanded run passed 524 cases plus affected integration/cross-service source compilation in 13m16s; removing the previously adjudicated duplicate membership test preserved its richer proof, and the final Account rerun plus affected enabled Checkstyle, SpotBugs, formatting and documentation checks passed in 9m26s. These local units and controlled transports do not establish physical PostgreSQL or source-built runtime Smoke; fresh exact-comparison CI and positive Smoke remain required before this earlier boundary is ready. -The existing public WORLDS/REALMS/CHARS, browser/direct JOIN, direct scope and connect-token facade paths temporarily return AUTH_UNAVAILABLE before legacy authority reads; the numeric runtime entitlement endpoint returns ENTITLEMENT_UNAVAILABLE. Complete canonical V2/JOIN/CHARS implementation and all positive compositions remain preserved in the separate public receiving source. This temporary boundary does not complete that work or permit dropping its positive obligations. Ordinary Account authentication, UUID player-bootstrap issuance, profile and retention/deletion protections remain in scope for receiving qualification. Private/ISOLATED/PLAYER_CREATED/AUTO positives, protected target currentness through commit, genuine installation delivery and private FRESH/CLOSED aggregation remain unfinished; registration/issuer/custody/activation holds remain. +The V1028-and-later subscription UUID transition, immutable retained archive, numeric-authority retirement, production denial stubs, canonical public facade and live `PLAYER_ADMISSION` integration are outside this preparation. Schema retirement and a functioning canonical UUID admission replacement must arrive together at one downstream receiving boundary, preserving retained-data safety without a new numeric bridge or dual authority. No entitlement-receiver registration, production custody, canonical player admission, activation or physical proof success is claimed, and the capability ratings below remain unchanged. -Foundation draft #3389 at `fec647a5` fails its fresh source-built runtime at PLAY with `ENTITLEMENT_UNAVAILABLE`; authenticated teardown completes with no remaining project resources. The denied legacy numeric endpoint is intentional, but a qualified canonical runtime replacement is still required. Remote Validation also exposed a UUID/text readback assertion and an enabled-ALWAYS trigger expectation. Its obsolete numeric-subscription HTTP-to-Entity CHARS fixture belongs to the complete canonical public successor, where both replacement positive compositions pass; the foundation does not claim that positive boundary. These failures remain recorded, with current-head CI and runtime qualification outstanding. +### Player-admission entitlement source preparation + +The local candidate now retains the [Account player-admission owner](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java), [exact workload guard](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountPlayerAdmissionEntitlementWorkloadGuard.java), [receiver](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java), and [Game Session client](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClient.java), with closed protocol/codec and unit/mTLS proof sources. The [Account API contract](../../architecture/microservices/account-service/api-contracts.md#private-player-admission-entitlement-read) owns the wire and caller restrictions. These are manually composed, unregistered components; the default `PLAY` chain still uses the existing numeric entitlement call. No live LOGIN private-result custody, first-party/direct-text scope receiving chain, final admission or `PLAY` wiring is supplied. Policy-aware WORLDS discovery does not widen this read beyond public-production `SHARED`/`PRESEEDED_ONLY` targets. + +Three Account physical proof sources are present: the [current-source PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java), [entitlement-owner PostgreSQL/mTLS suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java), and [committed-LOGIN composition](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java). They prepare DEMO, absent/joined membership, exact scope and committed LOGIN checks on the existing schema; shared owner/context fixture and resource integration must preserve the existing constructors and numeric runtime dependencies. The owner suite controls caller/current issuance and protected Game Session/World inputs; the committed-LOGIN case replaces Account caller doubles with actual committed issuance and recovery while retaining controlled signing, initial delivery and protected targets. None establishes paid billing composition. The four-file World/shared positive composition cohort remains downstream because it requires the canonical UUID direct-text scope DTOs and producer; genuine LOGIN/World positive composition remains an explicit receiving obligation, not dropped scope. + +Historical #3390 proof324 (22 owner and five shared cases), proof335 (three Account PostgreSQL cases) and proof352 (34 client mTLS cases) remain donor-source results. Earlier locally skipped physical aggregates remain skipped; none of these results qualifies this expanded reconstruction. Fresh selected unit/mTLS, affected source compilation and enabled static checks are recorded in the foundation proof above; physical execution remains outstanding here. Production mTLS/custody and Redis qualification, complete authenticated target provenance, a World hold through later commitment, paid schema/provider composition, runtime registration and functional admission remain open; point-in-time evidence is not a capacity or admission decision. ### Lifecycle-bound private realm-grant source preparation @@ -34,9 +40,9 @@ Bounded source/storage proof passes: 24 shared codec/mutation unit cases and 10 Paid discovery activation requires a composed durable webhook-driven or periodic lifecycle-reconciliation producer that commits a new Account receipt for each verified provider renewal period. The local `reconcile` entry point is implemented, but no such automatic producer is registered or qualified here. A renewal changes provider period facts and expires the prior positive bound; the current read intentionally refuses rather than extending or reinterpreting that immutable receipt. Until the new receipt is committed, a visible paid tenant can therefore make the complete WORLDS collection return `ENTITLEMENT_UNAVAILABLE`. The provider-reconciliation and registration prerequisite remains open under [Subscription Management](../../architecture/microservices/account-service/subscription-management.md#runtime-entitlement-contract) and [Stripe Integration](../../architecture/microservices/account-service/stripe-integration.md#subscriptions-and-hosting-plans); component read proof does not qualify paid discovery activation. -The current-read source also supports a freshly confirmed terminal negative projection for the existing `CANCELED` marker after its retained observation deadline, under [Subscription Management](../../architecture/microservices/account-service/subscription-management.md#runtime-entitlement-contract). Original receipt/source bytes and fresh exact provider facts remain required. Proof396 passes 46 front policy/repository/service and Game Session discovery cases with enabled affected analysis, formatting and documentation checks. Proof397 passes 20 discovery/entitlement units and 27 physical lifecycle/terminal cases, including delayed provider-confirmed and effective-cancellation negative reads, stale/changed provider refusal and unchanged receipt/authority rows including xmin. The bounded shared-cause check covers every implemented hosting status and both paid/DEMO discovery branches: proof399 passes 37 physical lifecycle, terminal-recovery and DEMO cases, including delayed suspended reads and real grace/period cutoffs; proof400 passes four tenant-operation owner cases with a fresh SDK evaluation after the original observation window and stable committed snapshot identity. All have zero failures, errors or skips and enabled affected checks. TENANT_OPERATION remains an as-of, non-admitting source observation; this does not add currentness protection, capacity authority or default registration. +The current-read source also supports a freshly confirmed terminal negative projection for the existing `CANCELED` marker after its retained observation deadline, under [Subscription Management](../../architecture/microservices/account-service/subscription-management.md#runtime-entitlement-contract). Original receipt/source bytes and fresh exact provider facts remain required; this source change needs delayed provider/effective-cancellation physical qualification at the canonical schema receiver before claiming discovery recovery. -The local hosting lifecycle policy and receipt producer separate the committed provider/policy fact bound from each fresh SDK read's observation deadline under [Subscription Management](../../architecture/microservices/account-service/subscription-management.md#runtime-entitlement-contract). Receipt bytes and SQL readback retain the same committed bound; current read results still expire at their own observation deadline without a new lifecycle event. Proof392 passes all 26 selected physical cases: 21 lifecycle cases and five genuine terminal-recovery compositions, with no failures, errors or skips, plus enabled integration analysis, formatting and documentation checks. The delayed active/trialing reads use new real SDK observations after the original observation window, retain the original receipt and authority rows including xmin, and append no events; stale reads, changed facts, actual period and recovery boundaries still refuse. Proof390 separately passes 32 front policy/repository/service and Game Session published-read cases with enabled affected analysis and documentation checks. Proof389 failed compilation and proof391 failed a public-versus-private error-message assertion; both are retained and corrected. The front carrier does not contain the V1028–V1032 schema foundation and takes this physical qualification from the canonical receiver. Existing receipts remain immutable, and current paid discovery/runtime support is not inferred from these source changes. +The local hosting lifecycle policy and receipt producer separate the committed provider/policy fact bound from each fresh SDK read's observation deadline under [Subscription Management](../../architecture/microservices/account-service/subscription-management.md#runtime-entitlement-contract). Receipt bytes and SQL readback retain the same committed bound; current read results still expire at their own observation deadline without a new lifecycle event. This correction requires focused delayed-read PostgreSQL qualification in the canonical subscription receiver; this source slice does not contain its V1028–V1032 schema foundation. Existing receipts remain immutable, and current paid discovery/runtime support is not inferred from these source changes. [`AccountPublicBootstrapWorldsOwner`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwner.java) composes [`AccountPlayerBootstrapCallerVerifier`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerBootstrapCallerVerifier.java), [`CanonicalGameplayAdmissionDecisionReadClient`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClient.java), and [`AccountPublicBootstrapEntitlementOwner`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwner.java). The caller is checked before source work and revalidated before return. Account requests the complete public target collection twice, evaluates current entitlement once per canonical tenant, rejects collection changes and duplicate or ambiguous target identities, and checks each observation deadline before returning. It emits only `gameplayAvailable` targets, ordered by world slug; `allowPublicJoin` does not filter discovery. Any required source failure, changed source, or expired evaluation fails the whole call without a partial list. @@ -46,11 +52,11 @@ Paid-provider observation remains an activation blocker owned by Account billing The current SDK transport uses socket timeouts while consuming the complete response; the [current-read fence](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java) carries no retained policy budget, and the discovery owner has no provider-latency/429 instrumentation or fleet-wide provider-rate qualification. Before paid facade registration, the owners must complete the linked deadline, retained-policy, load and telemetry gates and their physical proof in the canonical subscription receiver. That receiver's missing V1028–V1032 schema and the unregistered runtime composition leave the complete boundary unqualified here. No cache or registration is supplied. This handoff preserves an open implementation obligation; it does not classify the socket-timeout change as a completed activation fix. -The source owner refuses ambient Account SQL and requires a workload-only `SessionContext` for its Game Session call; it rejects authenticated caller and internal-service contexts. Facade integration must satisfy that guard without clearing or bypassing caller security context, and is not established by this unregistered composition. The Game Session read is the exact same-namespace Account mTLS source and returns only the complete visible public-production `SHARED`/`PRESEEDED_ONLY` target collection. Its owning contract is [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md#public-production-bootstrap-target-collection-read). Neither owner supplies a fresh World lifecycle read or hold, and this source does not issue a scope, perform JOIN, or admit gameplay. +The source owner refuses ambient Account SQL and requires a workload-only `SessionContext` for its Game Session call; it rejects authenticated caller and internal-service contexts. Facade integration must satisfy that guard without clearing or bypassing caller security context, and is not established by this unregistered composition. The Game Session read is the exact same-namespace Account mTLS source and now prepares the complete visible public-production `SHARED` collection for both `PRESEEDED_ONLY` and `PLAYER_CREATED`. It preserves complete canonical identity/namespace checks, committed owner/no-abort evidence, tenant UUID/slug and realm uniqueness, bounded closed frames and two complete reads with whole-set equality. Strict target selection, roster and admission remain `PRESEEDED_ONLY`. The owning contract is [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md#public-production-bootstrap-target-collection-read); the expanded collection passes the selected closed-codec, owner and receiver tests recorded above. Neither owner supplies a fresh World lifecycle read or hold, and this source does not issue a scope, perform JOIN, or admit gameplay. -Current component proof is bounded by the [Account discovery-owner tests](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java), [entitlement-owner tests](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwnerTest.java), [Account target-client tests](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClientTest.java), [Game Session collection-read tests](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java), and [workload-guard tests](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayAdmissionDecisionReadWorkloadGuardTest.java). The latest affected regression run passed 76 selected Account and Game Session cases without failures, errors or skips, plus enabled affected static analysis, formatting and documentation checks. It covers concurrent requests across separate owners, unchanged target projection and sanitized dependency failures. Retained physical proof passed all 10 [Account DEMO discovery and scope PostgreSQL cases](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java), including deterministic filtering, source-head drift, expiry refusal and immutable rows. Earlier broader unit, loopback-mTLS and final-admission composition runs overlap this coverage and are not additive or a current whole-system qualification. The PostgreSQL discovery tests use controlled Game Session responses; client mTLS tests use a controlled Game Session server, and final-admission composition uses a controlled World capture. These proofs do not establish the complete authenticated cross-owner source chain, deployment custody, paid discovery activation or production capacity. +Earlier component proof is bounded by the [Account discovery-owner tests](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java), [entitlement-owner tests](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwnerTest.java), [Account target-client tests](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClientTest.java), [Game Session collection-read tests](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java), and [workload-guard tests](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayAdmissionDecisionReadWorkloadGuardTest.java). The prior affected regression run passed 76 selected Account and Game Session cases without failures, errors or skips, plus enabled affected static analysis, formatting and documentation checks. It covers concurrent requests across separate owners, unchanged target projection and sanitized dependency failures, not the local mixed-policy addition. Retained physical proof passed all 10 [Account DEMO discovery and scope PostgreSQL cases](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java), including deterministic filtering, source-head drift, expiry refusal and immutable rows. Earlier broader unit, loopback-mTLS and final-admission composition runs overlap this coverage and are not additive or a current whole-system qualification. The PostgreSQL discovery tests use controlled Game Session responses; client mTLS tests use a controlled Game Session server, and final-admission composition uses a controlled World capture. These proofs do not establish the complete authenticated cross-owner source chain, deployment custody, paid discovery activation or production capacity. -The existing public facade is temporarily unavailable during the [canonical billing receiving](#canonical-billing-and-retention-receiving) split. Its complete canonical consumer and positive proof remain preserved in [#3390](https://github.com/benhook1013/FireMUD/pull/3390); neither retained numeric billing history nor the separately prepared scope owner supplies a fallback. The unregistered hosting observer, intent, lifecycle and plan implementations and focused proof are present here with their canonical UUID schema; their source inventory is recorded in `AA-1.4` below. No default registration or successful public admission is implied. +The existing [`AccountServiceImpl.listBootstrapWorlds`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java) and its positive tests remain on the legacy path in this source slice. The local [`AccountCanonicalPublicRealmScopeOwner`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java) separately issues and retains signed canonical UUID V2 public selector scopes; its focused and pre-V1028 PostgreSQL proof remains component-only. That scope owner and the newly retained [V2 reader](#local-source-foundation-preparation) are not consumed by the existing facade. Unregistered hosting observer, intent, lifecycle, provisioning and plan implementations and focused units are present; they do not establish paid discovery against this source slice’s legacy schema. Subscription schema retirement and functioning canonical UUID facade/admission consumers remain one downstream receiving boundary, including the V1028 retained archive, V1029 canonical table and dependent lifecycle/dispatch/terminal-resolution storage. No numeric fallback or second subscription table is introduced. Private `REALMS`, registered browser/direct scope consumption, live [player-admission entitlement integration](#player-admission-entitlement-source-preparation), JOIN consumer migration, default registration and gameplay admission remain gaps. The local [`AccountCanonicalPublicRealmScopeOwner`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java) adds an actual public selector-scope producer over the same complete target and current Account source owners. It preserves genuine membership absence without enrolling a pair, returns current ACTIVE/INACTIVE facts without treating closed enrollment as loss of public visibility, and persists signed canonical UUID V2 scope preimages through the existing Account scope repository. Focused signing and orchestration cases use real local signing and bootstrap verification with controlled source and transaction inputs. The retained pre-V1028 PostgreSQL scope cases preserve exact signed UUID/V2 hash, digest and provenance bytes without membership, pair, JOIN or event writes, refuse a real DEMO source-head change, and roll back a real PostgreSQL insert refusal. No facade/default registration, private lifecycle completion, JOIN or admission is established. Current-head CI remains required after source changes. @@ -494,7 +500,7 @@ Account's persisted UUID now backs registration REST/gRPC output and the Account Internal Account-carrier typing is prepared in Game Session, while current producers, JWT claims/parsers, and numeric-only collaborators remain unchanged. This does not activate canonical Account UUID authentication or Entity roster/entry behavior and does not backfill historical command UUIDs; canonical identity/namespace targets remain [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md), [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), and [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). Focused unit proof covers fail-closed first-party retained-context lookup, unreadable presence lookup without index pruning, and bounded pre-mutation rejection of unreadable or wrong-type presence values for removal, AFK/activity updates, and registration. `RedisSessionContextService` mutation reads still expose raw `SerializationException`; mocked tests show unreadable session-alias reads abort before writes/deletes, but mixed-binary behavior, same-session-ID reauthentication/recovery, live Redis/runtime, and fresh-image proof remain unproved. #2898 is not fixed by this preparation. -Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. The Account-local explicit public-production JOIN writer and durable audit outbox/producer retry components remain prepared source behind the held receiving boundary. Logging & Admin receipt persistence/readback is separate #2848 work and is not included in this Account core. The Account `POST /auth/bootstrap/join` route exists locally, but its receiving method returns `AUTH_UNAVAILABLE` before bootstrap/scope, target, entitlement, or membership reads or mutation, without invoking those prepared components; the Gateway guard still blocks external exposure. See [canonical billing and retention receiving](#canonical-billing-and-retention-receiving) for current status and retained obligations. Game Session text JOIN dispatch remains with #2898 and direct text-client end-to-end proof is unclaimed. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. JOIN's durable `PENDING`/unknown-database-outcome recovery seam remains unresolved under the Overseer decision and is owned by #2848; PostgreSQL runtime proof is not claimed. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. +Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, the Account-local explicit public-production JOIN writer and durable audit outbox/producer retry path, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Logging & Admin receipt persistence/readback is separate #2848 work and is not included in this Account core. The Account `POST /auth/bootstrap/join` controller/operation exists locally, while the current Gateway guard still blocks external exposure; Game Session text JOIN dispatch remains with #2898 and direct text-client end-to-end proof is unclaimed. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. JOIN's durable `PENDING`/unknown-database-outcome recovery seam remains unresolved under the Overseer decision and is owned by #2848; PostgreSQL runtime proof is not claimed. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. Official-hosted creator-content acceptance remains an unregistered target workflow. Source-only persistence now includes Creator Party and hosted-terms/environment-binding evidence plus V98 disclosure handoff and source-evidence tables; these relations do not supply external environment observation, authenticated publication, a legal authority verifier, dispatch, a consumer, registry/runtime binding, creator UI, or downstream write-gate proof. The fixed server environment-evidence adapter exists but remains deliberately unregistered and supplies no genuine input delivery. Its target authority remains under [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md), outside player-admission and session authority. Future managed creator commerce remains outside player access and session authority; its canonical boundary is [ADR 0179](../../architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md); no marketplace or purchase-entitlement implementation is present. @@ -528,22 +534,22 @@ The local receiving preparation uses the dedicated Gateway RS256 non-JWT envelop [FirstPartyConnectContextService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java) joins that verified context to the current [canonical route owner read](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java). Logical UUID authority stays separate from owner-supplied private storage handles. Retention keeps the original compact envelope and resolved owner snapshot, re-verifies expiry and current owner evidence on reads, and rejects old partial selector fragments, corruption, or unavailable authority. Main's latest focused evidence reports 12 controlled-key envelope tests, 199 Game Session unit cases after two narrow fixes, 184 Account unit cases after the fixture mock-history correction, 15 Gateway unit cases, and six physical Redis cases. The local socket-ownership correction requests transport close after send failure and performs disconnect cleanup only when the close callback atomically removes the exact registered transport. Forty-seven focused ownership unit cases and affected static/format gates pass. A fresh PostgreSQL-backed WebSocket class run passes 19 of 20 cases after default-off route-reader wiring is repaired; its remaining fixture-room assertion is corrected and that case passes in a separate focused run. The original startup and assertion failures and earlier all-skipped result remain retained; no genuine first-party admission authority is claimed. See [Session Behavior](../../architecture/system-architecture-session-behavior.md#session-types-and-lifetimes). These partial results do not establish a complete consumer gate or packaged runtime. -Account connect-token issuance returns `AUTH_UNAVAILABLE` before bootstrap/scope validation, cached-success replay, token minting, or session mutation while the canonical producer is unavailable. Gateway removes the legacy HMAC context mint and replay fallback; first-party cookie admission and public gameplay readiness remain unavailable. The separate trusted TCP Proxy listener path retains its existing boundary. First-party bare `LOGIN` and `PLAY` preserve the complete context and deny before legacy Account, Entity, or binding effects pending the genuine authority, lease, and finalization consumers. This entire source batch is local preparation; the `AA-2.1` capability remains partial and no new publication boundary or playable completion is claimed. +Account connect-token issuance retains its existing bootstrap and scope authentication checks, then denies before cached-success replay, token minting, or session mutation while the canonical producer is unavailable. Gateway removes the legacy HMAC context mint and replay fallback; first-party cookie admission and public gameplay readiness remain unavailable. The separate trusted TCP Proxy listener path retains its existing boundary. First-party bare `LOGIN` and `PLAY` preserve the complete context and deny before legacy Account, Entity, or binding effects pending the genuine authority, lease, and finalization consumers. This entire source batch is local preparation; the `AA-2.1` capability remains partial and no new publication boundary or playable completion is claimed. ## Capability Status | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [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; tenant IDs remain numeric and 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. Current public bootstrap discovery, direct-scope, JOIN, and connect-token receiving methods return `AUTH_UNAVAILABLE` before bootstrap/scope or legacy authority reads; 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 current held 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.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. Current connect-token issuance returns `AUTH_UNAVAILABLE` before replay-cache or fresh pointer/visibility/membership reads while the canonical producer is unavailable; target current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `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.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 returns `AUTH_UNAVAILABLE` before bootstrap/scope validation, 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, 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-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); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml); [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. Their canonical UUID schema prerequisites V1028/V1029 and existing facade convergence are carried by [#3389](https://github.com/benhook1013/FireMUD/pull/3389) and [#3390](https://github.com/benhook1013/FireMUD/pull/3390). This source carrier still retains the legacy numeric schema; `CreateSubscription` still fails closed before mutation. Subscription lifecycle processing, reconciliation, entitlement/availability enforcement, caller-stable creation identity, active-subscription deletion guards, per-subscription binding, 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 local reader refuses null, missing, ambiguous or nonpositive-version subscription evidence. Classified storage outages preserve `ENTITLEMENT_UNAVAILABLE`; JOIN diagnostic persistence follows rollback, and terminal-outage reads preserve the complete original receipt. The focused current-source qualification is recorded below. Legacy gRPC still carries unavailable outcomes in its error field, an explicit transport-classification gap. Current connect-token issuance returns `AUTH_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. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [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` validates existing bootstrap and scope, then returns `AUTH_UNAVAILABLE` before 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. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisMovementEffectIdempotencyService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [RedisMovementEffectIdempotencyServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java); [SessionContextSecretAndPresenceRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/SessionContextSecretAndPresenceRedisIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. The [local secret/presence containment](#session-secret-and-presence-containment) prevents new raw delegation-JWT persistence and projects legacy values without rehydration; physical retained-value cleanup remains open; scoped receiving proof is recorded at that owner. | -The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary without claiming explicit JOIN completion. Account bootstrap character discovery requires membership permitting gameplay admission without an Entity read; connect-token issuance returns `AUTH_UNAVAILABLE` before cached replay or membership, entitlement, grant, and routing-authority reads. Pre-membership world and realm discovery remains available. Current text `PLAY` implements the lifecycle/generation and admission checks covered by this receiving boundary. The canonical ordering contract is defined in [Authentication and authorization](../../architecture/system-architecture-authentication.md#play-current-and-target-failure-boundaries). Focused service proof covers Account-before-roster ordering, strict persisted actor selection, and the Game Session-to-Entity peer allowlist across 124 focused tests. Deployment/mTLS and fresh-image proof remain incomplete, so this targeted `PLAY` work does not complete AA-2.1, explicit JOIN, or `playableSmoke`. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject any `stateScope` other than exact `SHARED` or `ISOLATED`, so malformed authority cannot silently become shared-state admission. Account-owned explicit public-production JOIN writer and operation-check components remain prepared locally behind the held receiver; current `POST /auth/bootstrap/join` denies before invoking them. First-party text JOIN dispatch, full caller-target/atomic authority, `allowNewGameplayBindings`, grant lifecycle/expiry, and lease-commit proof remain open as recorded above. +The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary without claiming explicit JOIN completion. Account bootstrap character discovery requires membership permitting gameplay admission without an Entity read; connect-token issuance returns `AUTH_UNAVAILABLE` before cached replay or membership, entitlement, grant, and routing-authority reads. Pre-membership world and realm discovery remains available. Current text `PLAY` implements the lifecycle/generation and admission checks covered by this receiving boundary. The canonical ordering contract is defined in [Authentication and authorization](../../architecture/system-architecture-authentication.md#play-current-and-target-failure-boundaries). Focused service proof covers Account-before-roster ordering, strict persisted actor selection, and the Game Session-to-Entity peer allowlist across 124 focused tests. Deployment/mTLS and fresh-image proof remain incomplete, so this targeted `PLAY` work does not complete AA-2.1, explicit JOIN, or `playableSmoke`. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject any `stateScope` other than exact `SHARED` or `ISOLATED`, so malformed authority cannot silently become shared-state admission. Account-owned explicit public-production JOIN writing and operation checks are implemented locally; first-party text JOIN dispatch, full caller-target/atomic authority, `allowNewGameplayBindings`, grant lifecycle/expiry, and lease-commit proof remain open as recorded above. At receiving source `6c14229c32`, consolidated focused proof passes 572 cases across 15 unit, PostgreSQL-backed WebSocket, physical Redis and cross-service WebSocket/communication/Telnet suites, with zero failures, errors or skips, plus affected Checkstyle, formatting and canonical documentation checks. The gate includes current-parent menu/dispatch corrections; unchanged tasks may reuse qualified Gradle results. Account authority is controlled or mocked in transport fixtures, so these results do not prove full caller-target atomic authority, grant lifecycle/expiry, exact lease commit, genuine custody or public admission. Earlier focused counts overlap and are not additive. @@ -566,9 +572,9 @@ Reconnect prompt-setting precedence remains owned by [Input, Output, and Present Platform accounts are global identities. Tenant membership, tenant-scoped authorization, purchased/runtime entitlements, and non-public realm grants are distinct Account-owned authorities. The canonical tenant roles are `player`, `designer`, `tenantAdmin`, and `moderator`; global elevated roles such as `god`/platform admin are handled separately. Runtime consumers reuse Account and Common Security authority rather than deriving local equivalents. -`POST /auth/player-bootstrap` authenticates the account before tenant selection, accepts the account's configured password or verified-email OTP mode, and records only account-scoped bootstrap session state. The target non-public discovery flow requires both an admitting Account membership and the separately stored Account-owned realm grant; ordinary credential `PLAY` evaluates the same authorities independently. Current Account bootstrap discovery and connect-token receiving methods return `AUTH_UNAVAILABLE` before bootstrap/scope or legacy authority reads, cached-success replay, or token issuance. See [canonical billing and retention receiving](#canonical-billing-and-retention-receiving) for the held boundary and preserved obligations. The earlier cache-hit and fresh-issuance behavior is historical and does not establish current gameplay authority. A canonical producer must still validate the applicable non-public grant and current Account/runtime authority before it can issue context. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md). +`POST /auth/player-bootstrap` authenticates the account before tenant selection, accepts the account's configured password or verified-email OTP mode, and records only account-scoped bootstrap session state. Current non-public discovery requires both an admitting Account membership and the separately stored Account-owned realm grant; ordinary credential `PLAY` evaluates the same authorities independently. The current `/auth/connect-token` validates bootstrap and connect scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, membership/entitlement/runtime reads, token minting, or replay/session mutation. The earlier cache-hit and fresh-issuance behavior is historical and does not establish current gameplay authority. A canonical producer must still validate the applicable non-public grant and current Account/runtime authority before it can issue context. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md). -The obsolete implicit public-production membership-writer RPC/client/service seam has been removed. Current `/auth/connect-token` fails closed before replay or issuance and does not create membership. Prepared Account JOIN persistence components and the local `POST /auth/bootstrap/join` route remain, but the current `JoinPublicProductionMembership` receiving method returns `AUTH_UNAVAILABLE` before bootstrap/scope, target, entitlement, or membership reads or mutation. The current Gateway guard still blocks external exposure; the held boundary and preserved positive obligations are recorded in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving). Game Session text `JOIN` dispatch remains with #2898, so first-party text `Join & Play` is unavailable in this stage. The writer's `PENDING`/unknown-database-outcome recovery seam remains open under #2848, as does direct text-client proof, so ADR 0025 is not complete. The membership-authority-generation reread remains a requirement for any future connect-token producer under [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). +The obsolete implicit public-production membership-writer RPC/client/service seam has been removed. Current `/auth/connect-token` fails closed before replay or issuance and does not create membership. The canonical `JoinPublicProductionMembership` Account writer and `POST /auth/bootstrap/join` controller/operation are implemented locally, including a policy-bound v1 digest and membership/audit outbox transaction; the current Gateway guard still blocks external exposure. Game Session text `JOIN` dispatch remains with #2898, so first-party text `Join & Play` is unavailable in this stage. The writer's `PENDING`/unknown-database-outcome recovery seam remains open under #2848, as does direct text-client proof, so ADR 0025 is not complete. The membership-authority-generation reread remains a requirement for any future connect-token producer under [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). Account export, deletion, recovery, password reset, username reminder, email verification, and profile operations are account-scoped. Public reset, reminder, and verification initiation resolve normalized email and return neutral success for unknown accounts without creating tokens or deliveries; public verification no longer accepts a numeric account selector. The broader trusted-source and distributed abuse controls remain absent. The target `ExportTenantData` contract is the separate tenant-admin route for a tenant-wide export of tenant-owned records and minimum stable subject references; it has no account subject selector and does not redefine full account export or deletion. The current Account Service route remains account-targeted implementation drift until that contract is implemented. Account deletion observes active subscription/billing preconditions without collapsing global account ownership into tenant ownership. @@ -600,7 +606,7 @@ Previously signed numeric scopes are rejected when presented to the strict reade #### Account-owned response UUID projection -Current profile GET/UPDATE, gRPC JSON and Account-local export responses project canonical persisted Account UUIDs. Prepared explicit JOIN outcomes retain that UUID response shape, but the current JOIN receiving facade denies before producing them. Private scope/operation/member identities, immutable digests, receipts and side effects retain their existing representation. JOIN owner projection follows transaction completion; unavailable owner evidence returns `AUTH_UNAVAILABLE` without rewriting a retained result. Profile projection validates tenant/owner coherence and rereads the full Account because its repository embeds only a partial owner. The [Account API contract](../../architecture/microservices/account-service/api-contracts.md) owns the response semantics. +The response-only Account source projects canonical persisted Account UUIDs in every explicit JOIN outcome and in profile GET/UPDATE, gRPC JSON and Account-local export responses. Private scope/operation/member identities, immutable digests, receipts and side effects retain their existing representation. JOIN owner projection follows transaction completion; unavailable owner evidence returns `AUTH_UNAVAILABLE` without rewriting a retained result. Profile projection validates tenant/owner coherence and rereads the full Account because its repository embeds only a partial owner. The [Account API contract](../../architecture/microservices/account-service/api-contracts.md) owns the response semantics. Focused service/controller/gRPC cases and native PostgreSQL composition cover UUID responses, generated profile mapping, retained private rows, replay and owner readback refusal. R1189 qualifies the response projection; REST selector proof has its separate attribution. At that source, incoming direct-text context, ordinary JWT identity/shared forwarding and Account-to-Entity discovery remained separate gaps; the final ordinary receiving cohort subsequently qualifies those UUID boundaries. Canonical tenant-qualified profile routes/authorization, token registry qualification and gameplay activation remain separate gaps. No production Game Session text-JOIN caller is introduced, and the unavailable JOIN route remains absent from public OpenAPI. @@ -700,9 +706,9 @@ The canonical gRPC `GameSessionGrpcService.startSession` path preflights IP admi ### Entitlement read and JOIN failure classification -R1424 historically proved that the shared local Account subscription reader rejected null, missing, ambiguous or nonpositive-version evidence and preserved bounded entitlement-unavailable classification for storage outages; mapping/configuration faults remained unexpected failures. It also proved that the prepared JOIN owner leaves a potentially aborted SQL transaction before writing diagnostic evidence through its existing post-rollback path, and that a failed fresh authority read during terminal replay returns unavailable without changing the complete retained result. The current JOIN receiving method denies before invoking that owner, and the current numeric runtime entitlement endpoint returns `ENTITLEMENT_UNAVAILABLE` before any subscription read. This historical proof does not implement a complete entitlement bundle, current-row history, positive connect-token issuance, unknown-outcome observation after lost authority, or production admission. The [Account runtime owner](../../architecture/microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority) and [API error catalog](../../architecture/microservices/account-service/api-contracts.md#login-error-codes) own those contracts. +The shared local Account subscription reader rejects null, missing, ambiguous or nonpositive-version evidence and preserves bounded entitlement-unavailable classification for storage outages; mapping/configuration faults remain unexpected failures. JOIN leaves a potentially aborted SQL transaction before writing diagnostic evidence through its existing post-rollback path. A failed fresh authority read during terminal replay returns unavailable without changing the complete retained result. This does not implement a complete entitlement bundle, current-row history, positive connect-token issuance, unknown-outcome observation after lost authority, or production admission. The [Account runtime owner](../../architecture/microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority) and [API error catalog](../../architecture/microservices/account-service/api-contracts.md#login-error-codes) own those contracts. -R1424’s historical Account correction passed 305 unit cases and nine actual PostgreSQL cases, including a real SQL abort followed by rollback and a successful fresh-transaction diagnostic write, with correct unavailable classification and unchanged terminal evidence. The CHARS-focused Game Session source separately passes 184 selected unit cases and two actual WebSocket cases. All selected executions have zero failures, errors or skips, and affected enabled main/unit/integration analysis and formatting pass. These separate gates cover 500 selected cases; this is not one full service-suite run. The prior 488-case aggregate remains attributed to its earlier classification source. The PostgreSQL cases retain original intent, scope and Account provenance, prove no membership/audit on refusal, and exercise same-original recovery and immutable terminal evidence. The Game Session cases qualify unavailable direct-text `CHARS`, no accepted command event, and consistent HELP/PLAY/localized guidance while preserving supported WORLDS/REALMS and the separate Account roster. These are controlled owner/transport fixtures, not genuine issuer/custody, full service-suite or successful public-admission proof. Fresh packaged-runtime proof remains pending for the combined receiving source. +R1424’s current Account correction passes 305 unit cases and nine actual PostgreSQL cases, including a real SQL abort followed by rollback and a successful fresh-transaction diagnostic write, with correct unavailable classification and unchanged terminal evidence. The CHARS-focused Game Session source separately passes 184 selected unit cases and two actual WebSocket cases. All selected executions have zero failures, errors or skips, and affected enabled main/unit/integration analysis and formatting pass. These separate gates cover 500 selected cases; this is not one full service-suite run. The prior 488-case aggregate remains attributed to its earlier classification source. The PostgreSQL cases retain original intent, scope and Account provenance, prove no membership/audit on refusal, and exercise same-original recovery and immutable terminal evidence. The Game Session cases qualify unavailable direct-text `CHARS`, no accepted command event, and consistent HELP/PLAY/localized guidance while preserving supported WORLDS/REALMS and the separate Account roster. These are controlled owner/transport fixtures, not genuine issuer/custody, full service-suite or successful public-admission proof. Fresh packaged-runtime proof remains pending for the combined receiving source. ### Session Lifecycle and Logout @@ -748,7 +754,7 @@ R1418 subsequently carries published #3365 parent `1d2b862ea5a176f9c7e08dd3a0d76 The initial review corrections qualify script-local certificate defaults beneath a symlinked checkout ancestor while continuing to refuse explicit caller paths through links and preserving retained certificate bytes, modes and foreign entries. The certificate contract now requires each intended repository refusal marker on stderr as well as unchanged state, so unrelated command failures cannot satisfy it. Four freshly executed currency adapter cases require one response and completion per call, exact fail-closed metrics when a registry exists, no-registry constructor behavior and no owner interaction. Affected test static analysis, full Java formatting, ShellCheck, capability tracking and documentation checks pass. These direct corrections add no currency capability, public browser handoff, production identity or JOIN recovery authority. -Inspection of the prepared JOIN owner path narrows the retained recovery gap: when invoked, the public owner commits membership, transition audit and its terminal together after a separate durable intent. The current receiving method denies before reaching that owner. Unknown acknowledgement can leave either that intent without membership effects or a complete terminal; it does not establish the donor's manufactured positive-PENDING state. A lost committed result may remain unobservable after scope expiry, changed replay policy or lost caller binding. Same-original retry and this later outcome-observation limitation require distinct proof; the existing unknown-recovery and lawful-release holds remain. The proposed audit projection-version marker likewise has no implemented Logging receipt/projection producer here and must not be inferred from receiver IDs, payload replay or stamped test rows. No historical producer provenance, new receiver, recovery RPC or release authority is supplied. +Current writer inspection also narrows the retained JOIN recovery gap: the public owner commits membership, transition audit and its terminal together after a separate durable intent. Unknown acknowledgement can leave either that intent without membership effects or a complete terminal; it does not establish the donor's manufactured positive-PENDING state. A lost committed result may remain unobservable after scope expiry, changed replay policy or lost caller binding. Same-original retry and this later outcome-observation limitation require distinct proof; the existing unknown-recovery and lawful-release holds remain. The proposed audit projection-version marker likewise has no implemented Logging receipt/projection producer here and must not be inferred from receiver IDs, payload replay or stamped test rows. No historical producer provenance, new receiver, recovery RPC or release authority is supplied. ### Fail-Closed Boundary Convergence @@ -764,7 +770,7 @@ The current numeric-reader guardrail is: numeric identifiers still used by an im This includes positive readers for account, tenant, session, game-instance, character, version, item/container, payment, report, formation, and control-plane identities across the participating services; current-account claims that are present but malformed count as authenticated caller context and therefore fail tenant access rather than silently becoming anonymous; and current presence projects only `PLAYER` until an independent gameplay-grant carrier exists. JWT global/scoped role claims and cached elevation supply no gameplay authority; broader admission, grant-issuance, and capability qualification remains tracked in [EA-2.3](./player-experience-commands-and-communication.md#communication-social-and-presence). Automation schedule due-point identities reject fractional JSON numbers as `invalid_built_in_payload` before handler, pin, quota, or durable-queue work. Runtime-version, work-item, tenant, and gameplay routing readers reject malformed/non-positive values before lookups or mutation. Entity replay-backed mutations validate expiry, required text, optional container identity, and positive quantity before replay execution so a replay hit cannot hide malformed request shape. -Replay boundaries validate both read and write sides. The legacy Account connect-token cached-success path is no longer called: `/auth/connect-token` returns `AUTH_UNAVAILABLE` before bootstrap/scope validation, any replay read, token mint, or replay/session mutation. See [canonical billing and retention receiving](#canonical-billing-and-retention-receiving) for current status and preserved obligations. Public-production membership replays require valid success/created flags, nonblank required text, and payload identity matching cache-key inputs; otherwise the replay is treated as unavailable rather than as authoritative success. Prepared upgrade and remote-control-plane replays likewise compare request/execution payloads before reuse. Shared control-plane response readers reject malformed or non-positive returned ids instead of projecting them into apparently valid DTOs. +Replay boundaries validate both read and write sides. The legacy Account connect-token cached-success path is no longer called: `/auth/connect-token` denies after bootstrap/scope validation before any replay read, token mint, or replay/session mutation. Public-production membership replays require valid success/created flags, nonblank required text, and payload identity matching cache-key inputs; otherwise the replay is treated as unavailable rather than as authoritative success. Prepared upgrade and remote-control-plane replays likewise compare request/execution payloads before reuse. Shared control-plane response readers reject malformed or non-positive returned ids instead of projecting them into apparently valid DTOs. Equivalent HTTP, WebSocket, and gRPC failures use stable boundary semantics. The [gRPC owner contract](../../architecture/system-architecture-grpc.md#outcome-and-transport-classification) uses typed result unions for successfully produced expected domain outcomes and canonical non-OK status with bounded details when a domain result cannot be produced. Current Game Session/peer handlers still return many response-level `ErrorDetail` payloads, while transport failures cover infrastructure and some pre-domain cases; exact per-RPC migration and proof remain gaps. Shared REST exception handling continues to produce `ApiResponse` envelopes and field-specific `INVALID_ARGUMENT` responses instead of framework-default JSON. These seams log application warnings, meter `grpc.app_error` where applicable, and preserve span/error-code classification. @@ -776,6 +782,8 @@ R1419 passes 70 fresh selected cases (49 Logging units, fifteen application/Post ## Validation and Proof +The [local source-foundation preparation](#local-source-foundation-preparation) records fresh selected unit/mTLS, affected source compilation and enabled static/format proof for the reconstructed source. Historical #3389, #3390 and #3403 results retain their original comparisons. Physical PostgreSQL qualification and fresh positive runtime Smoke remain receiving obligations; the independently supported parent runtime is preserved, not requalified by source-only checks. + The prepared region owner has a scope-local liveness limit when `beginInitialTimeline` commits `INITIALIZING` but the Redis initialization call never executes. The retained phase, initialization operation and source do not grant a second creation permission; absent keys cannot distinguish that cut from metadata loss, so repeated owner retries refuse without a lease or runtime owner installation. No shipped in-place automatic recovery, dedicated alert or operator repair is claimed. The operator recovery boundary is recorded by [Game Session operations](../../architecture/microservices/game-session-service/operations.md#initial-region-timeline-recovery-boundary). Source-added focused regression `CanonicalGameplayRegionLeaseOwnerIntegrationTest.initializingBeforeRedisExecutionRetainsEvidenceAndRefusesRepeatedOwnerRetry` uses actual PostgreSQL preparation/begin APIs, an actual Redis absence probe and repeated actual owner retries at that precise pre-Redis cut. It asserts the retained SQL row image and absent lease/metadata before and after refusals, and no reacquired creation permit or installed runtime owner. World, provisional binding and stable-incarnation inputs are controlled fixtures; the cut is modeled by discarding the original permit before calling Redis, not by killing a process or fabricating SQL. R890 freshly passed all five native region-owner cases, including this cut, and the inherited protected-admission concurrency case; its aggregate still failed Entity test SpotBugs. The extracted Entity producer's R890/R891/R893 history is recorded separately below. This is bounded refusal proof and does not establish recovery or production activation. @@ -788,7 +796,7 @@ The evidence records focused unit, controller, gRPC, WebSocket, cross-service, a The focused admission proofs cover fresh acceptance, same-IP replacement reservation transfer, rejection without destroying the old session, and the non-destructive operator path. Telnet proofs cover envelope parsing, event metadata, reconnect backoff, bounded connection-local ordered input buffering during edge rebind, buffer exhaustion, sensitive logging, and Telnet/WebSocket `LOOK` parity; they do not prove durable replay of client input or transport bytes. Game Session gRPC proofs cover `Ping`, `NotifyDisconnect`, session lifecycle/control-plane parsing, application-error payloads, and `grpc.app_error` classification. Earlier first-party fresh-token, bare-login, `PLAY` scope, replay/expiry/context, screen-buffer restore, and fresh-redraw proofs describe the superseded path; current first-party coverage is fail-closed and does not establish playable admission. -Account authority proof covers account-first tenantless bootstrap authentication and account-scoped session state, the prepared local `JoinPublicProductionMembership` writer and its Account-owned audit/outbox components, Account-owned non-public realm grant denial, cross-tenant membership enforcement, and account-owned export/delete/recovery boundaries including active-subscription deletion guards. The current JOIN receiving method denies before invoking that prepared writer. The strict ADR 0025 commit fence and connect-token membership-authority-generation reread remain incomplete; Game Session text `JOIN`/`Join & Play` dispatch remains #2898, while unknown-outcome recovery and Logging receipt receiver/readback remain #2848 work. Exact-final-head PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Canonical tenant-role, lifecycle-state, and authority-generation follow-through also remain partial or unproved. +Account authority proof covers account-first tenantless bootstrap authentication and account-scoped session state, the local `JoinPublicProductionMembership` writer and its Account-owned audit/outbox boundary, Account-owned non-public realm grant denial, cross-tenant membership enforcement, and account-owned export/delete/recovery boundaries including active-subscription deletion guards. The strict ADR 0025 commit fence and connect-token membership-authority-generation reread remain incomplete; Game Session text `JOIN`/`Join & Play` dispatch remains #2898, while unknown-outcome recovery and Logging receipt receiver/readback remain #2848 work. Exact-final-head PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Canonical tenant-role, lifecycle-state, and authority-generation follow-through also remain partial or unproved. The #3224 candidate adds an explicit held-admission image-smoke mode: it preserves the existing isolated backend `LOGIN` -> `PLAY` -> `LOOK` proof and checks that real Gateway and Telnet public paths fail closed while admission readiness is out of service. This is separate from successful public admission. The focused transport and image-environment contracts pass. Fresh source-built held-admission qualification on `3c71c8c24379af623ca66550a4f4acaadd0ffd81` passes from 2026-10-16 05:20:30 to 05:27:42 UTC: the run-owned Gateway public listener receives the first-party loopback request outside configured TCP-proxy trust and returns exact `CONNECT_REPLAY_PROTECTION_UNAVAILABLE`; Telnet returns `startup_unavailable` and closes; the direct backend completes `WORLDS`, `LOGIN`, `PLAY`, `LOOK` and `LOGOUT`. Canonical teardown completes and independent exact-project inspection finds no containers, networks or volumes. This proves the held mode and isolated backend flow; it does not prove Kubernetes Service endpoint withdrawal or independent TCP Proxy Service readiness. Host-published Gateway ingress and successful public admission also remain unproved. @@ -865,7 +873,7 @@ No competing target state is currently recorded. Future design discussion is req | Owner | Current responsibility | Primary contract boundary | | --- | --- | --- | -| Account Service | Global accounts, credentials/challenges, memberships, canonical tenant roles, entitlements, non-public realm grants, account lifecycle, and explicit public-production JOIN; canonical gameplay connect-token receiving currently fails closed before bootstrap/scope validation; current status and proof history are recorded in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving) | Account REST/gRPC APIs, including `/auth/bootstrap/join` and the local JOIN RPC; `/auth/connect-token` currently returns `AUTH_UNAVAILABLE` before cached-success replay, minting, or replay/session mutation; public Gateway exposure remains blocked, leave remains target-only, and Game Session text JOIN dispatch remains #2898 | +| Account Service | Global accounts, credentials/challenges, memberships, canonical tenant roles, entitlements, non-public realm grants, account lifecycle, and explicit public-production JOIN; canonical gameplay connect-token production currently fails closed after bootstrap/scope validation | Account REST/gRPC APIs, including `/auth/bootstrap/join` and the local JOIN RPC; `/auth/connect-token` currently returns `AUTH_UNAVAILABLE` before cached-success replay, minting, or replay/session mutation; public Gateway exposure remains blocked, leave remains target-only, and Game Session text JOIN dispatch remains #2898 | | Common Security | **Current:** JWT/signed-token claims, current-account and tenant access, control-plane privilege claims, legacy session attestation, current service-identity handling, and downstream caller authorization. **Target:** certificate-derived mTLS workload identity and method allowlists authorize services, while typed `PlayerExecutionContext` carries player scope | `JwtClaims`, `SessionClaims`, session-context helpers, target `PlayerExecutionContext`, certificate-derived mTLS caller identity, caller allowlists, and shared authorization checks; legacy attestation/service-identity code is implementation debt, not target player authority | | TCP Proxy | Telnet transport, hidden bootstrap envelope, bounded connection-local ordered input buffering during edge rebind, disconnect notification, and Telnet close taxonomy | Telnet bridge; `TelnetRoutingBundle`; Game Session `NotifyDisconnect` | | Spring Cloud Gateway | Trusted TCP Proxy handshake validation, stable edge socket/session id, upstream gameplay bridge and rebind; public first-party cookie admission and shared pod readiness currently fail closed pending canonical producer/replay/key qualification. The combined readiness hold withdraws both Gateway Service endpoint families; independent route-level Service readiness remains a pre-rollout gap. | `/ws/game/**`; `TrustedTcpProxyIdentity`; current first-party cookie denial and deployment qualification in [Gateway readiness](../../architecture/microservices/spring-cloud-gateway/README.md#readiness-and-liveness) | diff --git a/protos/account/v1/player_admission_entitlement_read.proto b/protos/account/v1/player_admission_entitlement_read.proto new file mode 100644 index 0000000000..ee5d174bb6 --- /dev/null +++ b/protos/account/v1/player_admission_entitlement_read.proto @@ -0,0 +1,35 @@ +syntax = "proto3"; + +package account.v1; + +import "game-session/v1/canonical_gameplay_admission_decision_read.proto"; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Manually composed Account read for exact same-namespace Game Session over workload mTLS. +// This point-in-time PLAYER_ADMISSION value supplies neither capacity nor a later World hold. +service AccountPlayerAdmissionEntitlementReadService { + rpc ReadPlayerAdmissionEntitlement(ReadPlayerAdmissionEntitlementRequest) + returns (ReadPlayerAdmissionEntitlementResponse); +} + +// Comparison selectors only. Account verifies the credential subject and retained scope, and +// selects the current paid/demo source itself. Repeated members each require exactly one value. +message PlayerAdmissionEntitlementReadSelectors { + repeated uint32 schema_version = 1; + repeated game_session.v1.ResolvePublishedRealmAdmissionTargetRequest target = 2; + repeated string connect_scope_id = 3; +} + +// Credential travels only on this exact trusted mTLS method and must never be logged or persisted. +message ReadPlayerAdmissionEntitlementRequest { + repeated PlayerAdmissionEntitlementReadSelectors selectors = 1; + repeated string initial_login_jwt = 2; +} + +// Echo only selectors, never the presented credential. Evidence is exact bounded RFC 8785 UTF-8. +message ReadPlayerAdmissionEntitlementResponse { + repeated PlayerAdmissionEntitlementReadSelectors request = 1; + repeated bytes canonical_evidence = 2; +} diff --git a/protos/entity-management/v1/account_bootstrap_roster_read.proto b/protos/entity-management/v1/account_bootstrap_roster_read.proto new file mode 100644 index 0000000000..9e1a9dacbd --- /dev/null +++ b/protos/entity-management/v1/account_bootstrap_roster_read.proto @@ -0,0 +1,40 @@ +syntax = "proto3"; + +package entity_management.v1; + +import "entity-management/v1/entity_management_service.proto"; + +option java_package = "net.firedevops.firemud.entitymanagement.v1"; +option java_multiple_files = true; + +// Manually composed and unregistered non-admitting Account discovery. This transient +// projection creates no original selection, roster snapshot, retention or session. +service AccountBootstrapRosterReadService { + // Exact same-workload-namespace Account mTLS is required before request decoding. + // Only independently current public-production SHARED PRESEEDED_ONLY targets are + // supported. A valid empty persisted roster succeeds; unsupported, stale and + // unavailable sources never become an empty success. Failures use non-OK status. + rpc ReadAccountBootstrapRoster(AccountBootstrapRosterReadRequest) + returns (AccountBootstrapRosterReadResponse); +} + +message AccountBootstrapRosterReadRequest { + string request_uuid = 1; + string canonical_account_uuid = 2; + string target_namespace = 3; + CanonicalGameplayRosterTarget expected_target = 4; +} + +message AccountBootstrapRosterReadResponse { + // Complete exact request echo, including every source digest and target counter. + AccountBootstrapRosterReadRequest request = 1; + // At most 100 persisted eligible actors, ordered by canonical UUID text. + repeated AccountBootstrapRosterActor actors = 2; +} + +message AccountBootstrapRosterActor { + string character_uuid = 1; + string display_name = 2; + // Existing Entity-owned persisted level from the same eligible actor row, including real zero. + optional int32 level = 3; +} diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index 8eb626f23b..51865174cf 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -180,7 +180,7 @@ tasks.named("integrationTest") { classpath = classpath.filter { it !in socialArtifacts } + files(extractSocialIntegrationTestClasses) } -// Owner proof exports classes and its required registry script without Account application or +// Owner proof exports classes and required registry/projection resources without Account application or // Flyway resources, so a receiving service retains its own configuration and migration ownership. val accountOriginalOrderProofJar by tasks.registering(Jar::class) { archiveClassifier.set("original-order-proof") @@ -189,6 +189,19 @@ val accountOriginalOrderProofJar by tasks.registering(Jar::class) { from(sourceSets["testFixtures"].output.classesDirs) from("src/main/resources") { include("redis/lua/account-control-ui-registry-cas.lua") + include("redis/lua/account-game-session-delegation-pending-register.lua") + include("redis/lua/account-game-session-delegation-activate-committed.lua") + include("redis/lua/account-game-session-delegation-authority-project.lua") + include("redis/lua/account-initial-gameplay-login-dispose.lua") + include("redis/account_generation_projection_cas.lua") + include("redis/scripts/account-game-session-delegation-pending-register.json") + include("redis/scripts/account-game-session-delegation-activate-committed.json") + include("redis/scripts/account-game-session-delegation-authority-project-issuer.json") + include("redis/scripts/account-initial-gameplay-login-dispose.json") + include("redis/scripts/account-generation-projection-cas.json") + include("redis/scripts/account-selected-tenant-generation-projection.json") + include("redis/scripts/account-selected-membership-generation-projection.json") + include("META-INF/services/net.firedevops.firemud.common.redis.contracts.RedisScriptContribution") } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClient.java new file mode 100644 index 0000000000..605fa05d04 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClient.java @@ -0,0 +1,198 @@ +package net.firedevops.firemud.accountservice.client; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +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.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadRequest; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; + +/** + * Manually composed Entity persisted discovery read. No session, selection or admission is minted. + */ +public final class AccountBootstrapRosterReadClient + extends AbstractReloadingBlockingGrpcClient< + AccountBootstrapRosterReadServiceGrpc.AccountBootstrapRosterReadServiceBlockingStub> { + public static final int MAX_REQUEST_BYTES = 4096; + public static final int MAX_RESPONSE_BYTES = 64 * 1024; + public static final int MAX_ACTORS = 100; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private final String namespace; + + public AccountBootstrapRosterReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + String namespace) { + super( + endpoints, + requireFileBackedMtls(tls, "Account bootstrap Entity discovery"), + channels, + AccountBootstrapRosterReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.namespace = namespace; + } + + public void init() throws IOException { + requireNoAmbientSql("Bootstrap Entity discovery initialization refuses ambient SQL"); + initOnce( + "Bootstrap Entity discovery client is closed", + "Bootstrap Entity discovery client is not initialized"); + } + + /** + * Reads an exact independently resolved target; scope/caller authentication remains with Account. + */ + public List read(UUID requestId, UUID accountId, PublishedRealmEvidence published) { + requireNoAmbientSql("Bootstrap Entity discovery refuses ambient SQL"); + // This stub has no GrpcClientAuth/customizer: local browser SessionContext is preserved, + // and only the Account workload certificate authenticates this purpose-specific read. + requireUuid(requestId); + requireUuid(accountId); + Objects.requireNonNull(published); + if (!accountId.equals(published.selector().canonicalAccountUuid()) + || !namespace.equals(published.selector().targetNamespace())) { + throw new IllegalArgumentException("Bootstrap Entity discovery caller/namespace mismatch"); + } + AccountBootstrapRosterReadRequest request = + AccountBootstrapRosterReadRequest.newBuilder() + .setRequestUuid(requestId.toString()) + .setCanonicalAccountUuid(accountId.toString()) + .setTargetNamespace(namespace) + .setExpectedTarget(expectedTarget(published)) + .build(); + if (request.getSerializedSize() > MAX_REQUEST_BYTES) { + throw new IllegalArgumentException("Bootstrap Entity request exceeds its bound"); + } + var response = + requireInitializedStub("Bootstrap Entity discovery client is not initialized") + .withDeadlineAfter(5L, TimeUnit.SECONDS) + .withMaxInboundMessageSize(MAX_RESPONSE_BYTES) + .readAccountBootstrapRoster(request); + if (!response.getUnknownFields().asMap().isEmpty() + || response.getSerializedSize() > MAX_RESPONSE_BYTES + || !response.hasRequest() + || !request.equals(response.getRequest()) + || response.getActorsCount() > MAX_ACTORS) { + throw new IllegalStateException( + "Entity bootstrap discovery response is malformed or mismatched"); + } + List actors = new ArrayList<>(response.getActorsCount()); + String previous = null; + for (var actor : response.getActorsList()) { + UUID id = parseUuid(actor.getCharacterUuid()); + if (!actor.getUnknownFields().asMap().isEmpty() + || !actor.hasLevel() + || (previous != null && previous.compareTo(actor.getCharacterUuid()) >= 0)) { + throw new IllegalStateException( + "Entity bootstrap discovery actors are duplicated or unordered"); + } + actors.add(new Actor(id, actor.getDisplayName(), actor.getLevel())); + previous = actor.getCharacterUuid(); + } + return List.copyOf(actors); + } + + private CanonicalGameplayRosterTarget expectedTarget(PublishedRealmEvidence published) { + var target = published.currentTarget(); + var source = published.sourceEvidence(); + var policy = source.selectedPolicyEvidence(); + var policySet = source.publishedPolicySetEvidence(); + policySet.requireValidDigest(); + policy.requireValidDigest(policySet); + if (!namespace.equals(target.targetNamespace()) + || !"SHARED".equals(target.playableStateScope()) + || !"PRESEEDED_ONLY".equals(target.characterCreationPolicy())) { + throw new IllegalArgumentException( + "Bootstrap Entity discovery supports public SHARED PRESEEDED_ONLY targets"); + } + return CanonicalGameplayRosterTarget.newBuilder() + .setTenantUuid(target.canonicalTenantId().toString()) + .setRealmUuid(target.realmId().toString()) + .setWorldSlug(target.worldSlug()) + .setRealmSlug(target.realmSlug()) + .setGameInstanceUuid(target.canonicalGameInstanceId().toString()) + .setCatalogRevision(target.catalogRevision()) + .setPointerVersion(target.pointerVersion()) + .setActiveWorldEpoch(target.activeWorldEpoch()) + .setCanonicalVersionUuid(target.canonicalVersionId().toString()) + .setPublishedPolicyDigest(rawDigest(policy.policyDigest())) + .setPublishedReleaseBundleRef(policySet.publishedReleaseBundleRef()) + .setAdmissionPointerSnapshotDigest(target.admissionPointerSnapshotDigest()) + .setPublishedOwnerProofDigest(rawDigest(target.ownerProofDigest())) + .setPlayableStateNamespaceUuid(target.playableStateNamespaceId().toString()) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .setEntryPolicy( + CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY) + .build(); + } + + private static String rawDigest(String prefixed) { + if (prefixed == null || !prefixed.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Canonical published source digest is malformed"); + } + return prefixed.substring(7); + } + + private static UUID parseUuid(String value) { + UUID id = UUID.fromString(value); + requireUuid(id); + if (!id.toString().equals(value)) + throw new IllegalStateException("Canonical actor UUID required"); + return id; + } + + private static void requireUuid(UUID value) { + if (value == null || NIL_UUID.equals(value)) + throw new IllegalArgumentException("Canonical non-nil UUID required"); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getEntityManagementService(); + } + + @Override + protected String defaultTarget() { + return "entity-management-service:6565"; + } + + @Override + protected AccountBootstrapRosterReadServiceGrpc.AccountBootstrapRosterReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String peer = "spiffe://firemud/ns/" + namespace + "/sa/entity-management-service"; + return AccountBootstrapRosterReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(peer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer)); + } + + public record Actor(UUID characterId, String displayName, int level) { + public Actor { + requireUuid(characterId); + if (level < 0 + || displayName == null + || displayName.isBlank() + || !displayName.equals(displayName.trim()) + || displayName.codePointCount(0, displayName.length()) > 100 + || displayName.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("Canonical actor display name required"); + } + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java index de5bde5a35..ac571813e3 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java @@ -2,15 +2,19 @@ import de.mkammerer.argon2.Argon2; import de.mkammerer.argon2.Argon2Factory; +import java.time.LocalDateTime; +import java.util.List; import java.util.Objects; import java.util.Optional; import lombok.RequiredArgsConstructor; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; +import net.firedevops.firemud.accountservice.entity.Subscription; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.ProfileRepository; +import net.firedevops.firemud.accountservice.repository.SubscriptionRepository; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -30,10 +34,12 @@ public class TestDataSeeder implements ApplicationRunner { private static final String DEMO_USERNAME = "demo"; private static final String DEMO_EMAIL = "demo@example.com"; private static final String DEMO_PASSWORD = "swordfish"; + private static final String DEMO_SUBSCRIPTION_PLAN_ID = "local-smoke"; private final AccountRepository accountRepository; private final AccountTenantMembershipRepository accountTenantMembershipRepository; private final ProfileRepository profileRepository; + private final SubscriptionRepository subscriptionRepository; @Override @Transactional @@ -92,6 +98,24 @@ public void run(ApplicationArguments args) { profile.setPresenceVisibilityPolicy(ProfilePresenceVisibilityPolicy.FRIENDS_ONLY); profileRepository.save(profile); } + + List subscriptions = subscriptionRepository.findByTenantId(DEMO_TENANT_ID); + if (subscriptions.isEmpty()) { + Subscription subscription = new Subscription(); + subscription.setAccount(account); + subscription.setPlanId(DEMO_SUBSCRIPTION_PLAN_ID); + subscription.setStatus("active"); + subscription.setStartedAt(LocalDateTime.now()); + subscription.setTenantId(DEMO_TENANT_ID); + subscriptionRepository.save(subscription); + } else if (subscriptions.size() > 1) { + throw new IllegalStateException( + "Cannot seed demo tenant entitlement: tenant " + + DEMO_TENANT_ID + + " has ambiguous subscription authority (" + + subscriptions.size() + + " rows)"); + } } private static boolean isQuarantinedDemoMembership( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CanonicalJoinScopeV2.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CanonicalJoinScopeV2.java index 7c779d3e43..433ace8057 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CanonicalJoinScopeV2.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CanonicalJoinScopeV2.java @@ -60,6 +60,11 @@ public record CanonicalJoinScopeV2( connectScopeExpiresAt = requireUtcRfc3339("connectScopeExpiresAt", connectScopeExpiresAt); } + @Override + public String toString() { + return "CanonicalJoinScopeV2[connectScopeId=]"; + } + private static UUID requireNonNilUuid(String field, UUID value) { if (value == null || NIL_UUID.equals(value)) { throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/RetainedSubscriptionEvidenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/RetainedSubscriptionEvidenceRepository.java deleted file mode 100644 index 5aa35ca5b9..0000000000 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/RetainedSubscriptionEvidenceRepository.java +++ /dev/null @@ -1,41 +0,0 @@ -package net.firedevops.firemud.accountservice.repository; - -import static net.firedevops.firemud.accountservice.jooq.Tables.ACCOUNT_RETAINED_SUBSCRIPTION_EVIDENCE; - -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import java.util.List; -import net.firedevops.firemud.accountservice.entity.RetainedSubscriptionEvidence; -import org.jooq.DSLContext; -import org.springframework.stereotype.Repository; - -/** Historical evidence for Account retention/deletion checks only; no current-tenant selector. */ -@Repository -@SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "Injected DSLContext is an internal Spring collaborator.") -public class RetainedSubscriptionEvidenceRepository { - private final DSLContext dsl; - - public RetainedSubscriptionEvidenceRepository(DSLContext dsl) { - this.dsl = dsl; - } - - public List findHistoryByAccountId(Long accountId) { - var evidence = ACCOUNT_RETAINED_SUBSCRIPTION_EVIDENCE; - return dsl.selectFrom(evidence) - .where(evidence.ACCOUNT_ID.eq(accountId)) - .orderBy(evidence.ID.asc()) - .fetch( - row -> - new RetainedSubscriptionEvidence( - row.get(evidence.ID), - row.get(evidence.ACCOUNT_ID), - row.get(evidence.PLAN_ID), - row.get(evidence.STATUS), - row.get(evidence.STARTED_AT), - row.get(evidence.ENDED_AT), - row.get(evidence.TENANT_ID), - row.get(evidence.ENTITLEMENT_VERSION), - row.get(evidence.TENANT_AUTHORITY_GENERATION))); - } -} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/SubscriptionRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/SubscriptionRepository.java new file mode 100644 index 0000000000..483e041c33 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/SubscriptionRepository.java @@ -0,0 +1,158 @@ +package net.firedevops.firemud.accountservice.repository; + +import static net.firedevops.firemud.accountservice.jooq.Tables.ACCOUNTS; +import static net.firedevops.firemud.accountservice.jooq.Tables.SUBSCRIPTION; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.Subscription; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; + +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class SubscriptionRepository { + private final DSLContext dsl; + + public SubscriptionRepository(DSLContext dsl) { + this.dsl = dsl; + } + + public List findByTenantId(Long tenantId) { + return baseSelect() + .where(SUBSCRIPTION.TENANT_ID.eq(tenantId)) + .orderBy(SUBSCRIPTION.ID.asc()) + .fetch(this::toEntity); + } + + /** Shares the row lock with subscription writers through the JOIN commit boundary. */ + public List findByTenantIdForUpdate(Long tenantId) { + return baseSelect() + .where(SUBSCRIPTION.TENANT_ID.eq(tenantId)) + .orderBy(SUBSCRIPTION.ID.asc()) + .forUpdate() + .of(SUBSCRIPTION) + .fetch(this::toEntity); + } + + public List findByAccountId(Long accountId) { + return baseSelect() + .where(SUBSCRIPTION.ACCOUNT_ID.eq(accountId)) + .orderBy(SUBSCRIPTION.ID.asc()) + .fetch(this::toEntity); + } + + public Subscription save(Subscription entity) { + Long accountId = entity.getAccount() == null ? null : entity.getAccount().getId(); + if (entity.getId() == null) { + var inserted = + dsl.insertInto(SUBSCRIPTION) + .set(SUBSCRIPTION.ACCOUNT_ID, accountId) + .set(SUBSCRIPTION.PLAN_ID, entity.getPlanId()) + .set(SUBSCRIPTION.STATUS, entity.getStatus()) + .set(SUBSCRIPTION.STARTED_AT, entity.getStartedAt()) + .set(SUBSCRIPTION.ENDED_AT, entity.getEndedAt()) + .set(SUBSCRIPTION.TENANT_ID, entity.getTenantId()) + .set(SUBSCRIPTION.ENTITLEMENT_VERSION, 1L) + .set(SUBSCRIPTION.TENANT_AUTHORITY_GENERATION, UUID.randomUUID()) + .returningResult( + SUBSCRIPTION.ID, + SUBSCRIPTION.ENTITLEMENT_VERSION, + SUBSCRIPTION.TENANT_AUTHORITY_GENERATION) + .fetchOne(); + if (inserted == null) { + throw new IllegalStateException("Subscription insert did not return its authority state"); + } + entity.setId(inserted.get(SUBSCRIPTION.ID)); + entity.setEntitlementVersion(1L); + entity.setTenantAuthorityGeneration(inserted.get(SUBSCRIPTION.TENANT_AUTHORITY_GENERATION)); + return entity; + } + var updated = + dsl.update(SUBSCRIPTION) + .set(SUBSCRIPTION.ACCOUNT_ID, accountId) + .set(SUBSCRIPTION.PLAN_ID, entity.getPlanId()) + .set(SUBSCRIPTION.STATUS, entity.getStatus()) + .set(SUBSCRIPTION.STARTED_AT, entity.getStartedAt()) + .set(SUBSCRIPTION.ENDED_AT, entity.getEndedAt()) + .set(SUBSCRIPTION.TENANT_ID, entity.getTenantId()) + .where( + SUBSCRIPTION + .ID + .eq(entity.getId()) + .and(SUBSCRIPTION.ENTITLEMENT_VERSION.eq(entity.getEntitlementVersion())) + .and( + entity.getTenantAuthorityGeneration() == null + ? SUBSCRIPTION.TENANT_AUTHORITY_GENERATION.isNull() + : SUBSCRIPTION.TENANT_AUTHORITY_GENERATION.eq( + entity.getTenantAuthorityGeneration()))) + .returningResult( + SUBSCRIPTION.ENTITLEMENT_VERSION, SUBSCRIPTION.TENANT_AUTHORITY_GENERATION) + .fetchOne(); + if (updated == null) { + throw JooqAccountRepositorySupport.staleWrite("subscription", entity.getId()); + } + entity.setEntitlementVersion(updated.get(SUBSCRIPTION.ENTITLEMENT_VERSION)); + entity.setTenantAuthorityGeneration(updated.get(SUBSCRIPTION.TENANT_AUTHORITY_GENERATION)); + return entity; + } + + public void deleteByAccountId(Long accountId, Long tenantId) { + dsl.deleteFrom(SUBSCRIPTION) + .where(SUBSCRIPTION.ACCOUNT_ID.eq(accountId).and(SUBSCRIPTION.TENANT_ID.eq(tenantId))) + .execute(); + } + + public void deleteByAccountId(Long accountId) { + dsl.deleteFrom(SUBSCRIPTION).where(SUBSCRIPTION.ACCOUNT_ID.eq(accountId)).execute(); + } + + private org.jooq.SelectOnConditionStep baseSelect() { + return dsl.select( + SUBSCRIPTION.ID, + SUBSCRIPTION.ACCOUNT_ID, + SUBSCRIPTION.PLAN_ID, + SUBSCRIPTION.STATUS, + SUBSCRIPTION.STARTED_AT, + SUBSCRIPTION.ENDED_AT, + SUBSCRIPTION.TENANT_ID, + SUBSCRIPTION.ENTITLEMENT_VERSION, + SUBSCRIPTION.TENANT_AUTHORITY_GENERATION, + ACCOUNTS.ID, + ACCOUNTS.USERNAME, + ACCOUNTS.EMAIL, + ACCOUNTS.PASSWORD_HASH, + ACCOUNTS.ROLE, + ACCOUNTS.EMAIL_VERIFIED, + ACCOUNTS.LOGIN_AUTH_MODES) + .from(SUBSCRIPTION) + .join(ACCOUNTS) + .on(SUBSCRIPTION.ACCOUNT_ID.eq(ACCOUNTS.ID)); + } + + private Subscription toEntity(Record record) { + Subscription entity = new Subscription(); + entity.setId(record.get(SUBSCRIPTION.ID)); + entity.setAccount( + JooqAccountRepositorySupport.partialAccount( + record.get(ACCOUNTS.ID), + record.get(ACCOUNTS.USERNAME), + record.get(ACCOUNTS.EMAIL), + record.get(ACCOUNTS.PASSWORD_HASH), + record.get(ACCOUNTS.ROLE), + record.get(ACCOUNTS.EMAIL_VERIFIED), + record.get(ACCOUNTS.LOGIN_AUTH_MODES))); + entity.setPlanId(record.get(SUBSCRIPTION.PLAN_ID)); + entity.setStatus(record.get(SUBSCRIPTION.STATUS)); + entity.setStartedAt(record.get(SUBSCRIPTION.STARTED_AT)); + entity.setEndedAt(record.get(SUBSCRIPTION.ENDED_AT)); + entity.setTenantId(record.get(SUBSCRIPTION.TENANT_ID)); + entity.setEntitlementVersion(record.get(SUBSCRIPTION.ENTITLEMENT_VERSION)); + entity.setTenantAuthorityGeneration(record.get(SUBSCRIPTION.TENANT_AUTHORITY_GENERATION)); + return entity; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountPlayerAdmissionEntitlementWorkloadGuard.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountPlayerAdmissionEntitlementWorkloadGuard.java new file mode 100644 index 0000000000..d4839ed5e5 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountPlayerAdmissionEntitlementWorkloadGuard.java @@ -0,0 +1,76 @@ +package net.firedevops.firemud.accountservice.security; + +import io.grpc.Context; +import io.grpc.Contexts; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.Status; +import net.firedevops.firemud.account.v1.AccountPlayerAdmissionEntitlementReadServiceGrpc; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; + +/** + * Exact method/Game Session gate deriving its private assertion from transport TLS, never caller + * context. + */ +public final class AccountPlayerAdmissionEntitlementWorkloadGuard implements ServerInterceptor { + private final Context.Key authenticatedCaller = + Context.key("player-admission-game-session-peer"); + private final String expectedWorkload; + + public AccountPlayerAdmissionEntitlementWorkloadGuard(String namespace) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + expectedWorkload = "spiffe://firemud/ns/" + namespace + "/sa/game-session-service"; + } + + /** Only this guard's TLS interception can supply the private method-authorized assertion. */ + public String requireAuthenticatedGameSessionCaller() { + if (!expectedWorkload.equals(authenticatedCaller.get()) || hasSessionContext()) { + throw Status.UNAUTHENTICATED + .withDescription("Protected Game Session workload call required") + .asRuntimeException(); + } + return expectedWorkload; + } + + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + var peer = + GrpcPeerIdentity.fromSslSession(call.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION)); + if (peer.isEmpty()) return deny(call, Status.UNAUTHENTICATED); + if (!expectedWorkload.equals(peer.orElseThrow().uri()) + || hasSessionContext() + || !AccountPlayerAdmissionEntitlementReadServiceGrpc + .getReadPlayerAdmissionEntitlementMethod() + .getFullMethodName() + .equals(call.getMethodDescriptor().getFullMethodName())) { + return deny(call, Status.PERMISSION_DENIED); + } + return Contexts.interceptCall( + Context.current().withValue(authenticatedCaller, peer.orElseThrow().uri()), + call, + headers, + next); + } + + private static boolean hasSessionContext() { + return SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService() + || SessionContext.getServiceName() != null + || SessionContext.getServiceInstanceId() != null; + } + + private static ServerCall.Listener deny( + ServerCall call, Status status) { + call.close( + status.withDescription("Exact protected Game Session entitlement method required"), + new Metadata()); + return new ServerCall.Listener<>() {}; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReader.java new file mode 100644 index 0000000000..7c46b60d73 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReader.java @@ -0,0 +1,269 @@ +package net.firedevops.firemud.accountservice.service; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.JwtException; +import java.time.Clock; +import java.time.DateTimeException; +import java.time.Instant; +import java.util.Date; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository.CanonicalConnectScopeEvidence; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.common.security.JwtClaims; +import net.firedevops.firemud.common.security.JwtUtil; +import org.jooq.exception.DataAccessException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered reader for an exact signed V2 public-production connect scope and its Account row. + * + *

The expected Account UUID is comparison data supplied by an outer authenticating owner; this + * reader does not authenticate a caller or create a caller context. It returns only the persisted + * V2 selector. Neither constructing nor reading the selector grants membership, JOIN, or gameplay + * authority. + */ +public final class AccountCanonicalConnectScopeReader { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String AUDIENCE = "bootstrap-connect-scope"; + private static final String INVALID_MESSAGE = "Canonical connect scope is invalid"; + private static final String UNAVAILABLE_MESSAGE = "Account authority is unavailable"; + + private final JwtUtil jwt; + private final AccountConnectScopeRepository scopes; + private final TransactionTemplate transaction; + private final Clock clock; + + public AccountCanonicalConnectScopeReader( + JwtUtil jwt, + AccountConnectScopeRepository scopes, + PlatformTransactionManager transactions, + Clock clock) { + this.jwt = Objects.requireNonNull(jwt, "JWT verifier is required"); + this.scopes = Objects.requireNonNull(scopes, "Account scope repository is required"); + this.clock = Objects.requireNonNull(clock, "Account clock is required"); + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + transaction.setReadOnly(false); + transaction.setTimeout(5); + } + + /** Reads the persisted scope only when it exactly matches this signed bearer and Account UUID. */ + public CanonicalJoinScopeV2 read(UUID expectedAccountId, String presentedScope) { + requireNoAmbientTransaction(); + if (expectedAccountId == null || NIL_UUID.equals(expectedAccountId)) throw invalid(null); + + final CanonicalJoinScopeV2 signed; + try { + signed = verifySignedScope(expectedAccountId, presentedScope); + } catch (AuthenticationException failure) { + throw failure; + } catch (RuntimeException failure) { + throw unavailable(failure); + } + String tokenHash = AccountJoinDigest.tokenHash(presentedScope); + final CanonicalJoinScopeV2 retained; + try { + retained = + Objects.requireNonNull( + transaction.execute(status -> readRetained(expectedAccountId, tokenHash, signed)), + "Account scope transaction returned no result"); + } catch (AuthenticationException failure) { + throw failure; + } catch (RuntimeException failure) { + throw unavailable(failure); + } + + requireCurrentScopeTime(signed); + if (!signed.equals(retained)) throw invalid(null); + return retained; + } + + private CanonicalJoinScopeV2 verifySignedScope(UUID expectedAccountId, String token) { + if (token == null || token.isBlank() || !token.equals(token.trim())) throw invalid(null); + + final Claims claims; + try { + claims = jwt.parseToken(token).getPayload(); + } catch (JwtException | IllegalArgumentException failure) { + throw invalid(null); + } catch (RuntimeException failure) { + throw unavailable(failure); + } + + try { + // JJWT normalizes the signed aud string to a set. Require this one exact audience rather + // than relying on a string cast or accepting the first value of a multi-audience token. + if (!Set.of(AUDIENCE).equals(claims.getAudience())) throw invalid(null); + String subject = JwtClaims.requireCanonicalAccountUuid(claims.getSubject(), "sub"); + String accountText = + JwtClaims.requireCanonicalAccountUuid(claims.get("accountId"), "accountId"); + if (!subject.equals(accountText) || !expectedAccountId.toString().equals(accountText)) { + throw invalid(null); + } + requireNonNilUuid(claims.get("jti"), "jti"); + if (!"PUBLIC_PRODUCTION".equals(requireString(claims.get("targetClass"), "targetClass"))) { + throw invalid(null); + } + if (requireIntegralLong(claims.get("scopeDigestVersion"), "scopeDigestVersion") != 2L) { + throw invalid(null); + } + + UUID tenantId = requireNonNilUuid(claims.get("tenantId"), "tenantId"); + UUID realmId = requireNonNilUuid(claims.get("realmId"), "realmId"); + UUID namespaceId = + requireNonNilUuid(claims.get("playableStateNamespaceId"), "playableStateNamespaceId"); + UUID gameInstanceId = requireNonNilUuid(claims.get("gameInstanceId"), "gameInstanceId"); + long catalogRevision = requireIntegralLong(claims.get("catalogRevision"), "catalogRevision"); + long pointerVersion = requireIntegralLong(claims.get("pointerVersion"), "pointerVersion"); + Instant evaluatedAt = requireCanonicalInstant(claims.get("evaluatedAt"), "evaluatedAt"); + Instant expiresAt = + requireCanonicalInstant(claims.get("connectScopeExpiresAt"), "connectScopeExpiresAt"); + Date issuedAt = claims.getIssuedAt(); + Date jwtExpiresAt = claims.getExpiration(); + if (issuedAt == null + || jwtExpiresAt == null + || !issuedAt.toInstant().isAfter(Instant.EPOCH) + || !issuedAt.toInstant().isBefore(jwtExpiresAt.toInstant()) + || !expiresAt.equals(jwtExpiresAt.toInstant()) + || !expiresAt.isAfter(evaluatedAt)) { + throw invalid(null); + } + + CanonicalJoinScopeV2 scope = + new CanonicalJoinScopeV2( + token, + expectedAccountId, + tenantId, + realmId, + requireString(claims.get("tenantSlug"), "tenantSlug"), + requireString(claims.get("worldSlug"), "worldSlug"), + requireString(claims.get("realmSlug"), "realmSlug"), + namespaceId, + requireString(claims.get("playableStateScope"), "playableStateScope"), + gameInstanceId, + catalogRevision, + pointerVersion, + evaluatedAt.toString(), + expiresAt.toString()); + requireCurrentScopeTime(scope); + return scope; + } catch (AuthenticationException failure) { + throw failure; + } catch (JwtException + | DateTimeException + | IllegalArgumentException + | ArithmeticException failure) { + throw invalid(failure); + } + } + + private CanonicalJoinScopeV2 readRetained( + UUID expectedAccountId, String tokenHash, CanonicalJoinScopeV2 signed) { + try { + CanonicalJoinScopeV2 retained = + scopes.findCanonical(signed.connectScopeId()).orElseThrow(() -> invalid(null)); + CanonicalConnectScopeEvidence evidence = + scopes.findCanonicalEvidenceByTokenHash(tokenHash).orElseThrow(() -> invalid(null)); + String digest = AccountJoinDigest.scopeV2(signed); + if (!expectedAccountId.equals(retained.accountId()) + || !signed.equals(retained) + || !tokenHash.equals(evidence.scopeTokenHash()) + || evidence.privateAccountId() <= 0L + || !"PUBLIC_PRODUCTION".equals(evidence.targetClass()) + || evidence.scopeDigestVersion() != 2 + || !digest.equals(evidence.scopeDigest()) + || evidence.tenantProvenance() == null + || !evidence.accountUuid().equals(signed.accountId()) + || !evidence.tenantUuid().equals(signed.tenantId()) + || !evidence.realmId().equals(signed.realmId()) + || !evidence.tenantSlug().equals(signed.tenantSlug()) + || !evidence.worldSlug().equals(signed.worldSlug()) + || !evidence.realmSlug().equals(signed.realmSlug()) + || !evidence.playableStateNamespaceUuid().equals(signed.playableStateNamespaceId()) + || !evidence.playableStateScope().equals(signed.playableStateScope()) + || !evidence.gameInstanceUuid().equals(signed.gameInstanceId()) + || evidence.catalogRevision() != signed.catalogRevision() + || evidence.pointerVersion() != signed.pointerVersion() + || !evidence.evaluatedAt().equals(signed.evaluatedAt()) + || !evidence.connectScopeExpiresAt().equals(signed.connectScopeExpiresAt())) { + throw invalid(null); + } + return retained; + } catch (AuthenticationException failure) { + throw failure; + } catch (DataAccessException | org.springframework.dao.DataAccessException failure) { + throw failure; + } catch (RuntimeException failure) { + throw invalid(failure); + } + } + + private void requireCurrentScopeTime(CanonicalJoinScopeV2 scope) { + Instant now = clock.instant(); + Instant evaluatedAt = Instant.parse(scope.evaluatedAt()); + Instant expiresAt = Instant.parse(scope.connectScopeExpiresAt()); + if (now.isBefore(evaluatedAt) || !now.isBefore(expiresAt)) throw invalid(null); + } + + private static String requireString(Object value, String field) { + if (!(value instanceof String text) || text.isEmpty() || !text.equals(text.trim())) { + throw new IllegalArgumentException("Malformed claim: " + field); + } + return text; + } + + private static UUID requireNonNilUuid(Object value, String field) { + String text = requireString(value, field); + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) || NIL_UUID.equals(parsed)) { + throw new IllegalArgumentException("Malformed claim: " + field); + } + return parsed; + } + + private static long requireIntegralLong(Object value, String field) { + final long result; + if (value instanceof Integer integer) result = integer.longValue(); + else if (value instanceof Long longValue) result = longValue; + else if (value instanceof Short shortValue) result = shortValue.longValue(); + else if (value instanceof Byte byteValue) result = byteValue.longValue(); + else throw new IllegalArgumentException("Malformed numeric claim: " + field); + if (result <= 0L) throw new IllegalArgumentException("Invalid numeric claim: " + field); + return result; + } + + private static Instant requireCanonicalInstant(Object value, String field) { + String text = requireString(value, field); + Instant parsed = Instant.parse(text); + if (!parsed.toString().equals(text)) { + throw new IllegalArgumentException("Non-canonical instant claim: " + field); + } + return parsed; + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Canonical connect-scope read requires no ambient Account transaction"); + } + } + + private static AuthenticationException invalid(Throwable ignored) { + // Do not retain the bearer or parser diagnostics that may include attacker-controlled text. + return new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_MESSAGE); + } + + private static AuthenticationException unavailable(Throwable cause) { + return new AuthenticationException("AUTH_UNAVAILABLE", UNAVAILABLE_MESSAGE, cause); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java new file mode 100644 index 0000000000..fc705d2d1b --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java @@ -0,0 +1,623 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.time.Clock; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository.CanonicalConnectScopeEvidence; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionCurrentReceipt; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceSelection; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier.VerifiedCaller; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.SessionContext; +import org.jooq.DSLContext; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered Account owner for PUBLIC_PRODUCTION SHARED PRESEEDED player entitlement evidence. + * JWT/registry, Stripe and protected Game Session/World reads run outside SQL. A final + * Account-first writable SERIALIZABLE transaction rereads caller issuance, membership (including + * explicit absence), exact persisted scope and paid/demo currentness before constructing the + * canonical value. No value escapes a failed commit. All repositories and the DSL must share the + * transaction manager. + * + *

The protected target is a point-in-time source read, not a World lock through this transaction + * or later mutation. This grants no capacity or admission. Request workload remains a trusted + * method-authorized transport assertion; parsing it does not authenticate it. No bean, public RPC, + * issuer or activation is supplied. Private/playtest and PLAYER_CREATED are unsupported. + */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected collaborators are private Account owner-source components.") +public final class AccountPlayerAdmissionEntitlementOwner { + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private final DSLContext dsl; + private final AccountRepository accounts; + private final AccountGameplayAdmissionCallerVerifier callers; + private final AccountGameplayDelegationIssuanceRepository issuances; + private final AccountCanonicalRuntimeMembershipSnapshotRepository memberships; + private final AccountConnectScopeRepository scopes; + private final AccountHostingSubscriptionLifecycleRepository hosting; + private final StripeHostingSubscriptionObserver observer; + private final AccountDemoTenantEntitlementRepository demos; + private final AccountTenantAuthorityEventRepository sources; + private final CanonicalGameplayAdmissionDecisionReadClient targets; + private final String namespace; + private final TransactionTemplate transaction; + private final Clock clock; + private final String expectedWorkload; + + public AccountPlayerAdmissionEntitlementOwner( + DSLContext dsl, + AccountRepository accounts, + AccountGameplayAdmissionCallerVerifier callers, + AccountGameplayDelegationIssuanceRepository issuances, + AccountCanonicalRuntimeMembershipSnapshotRepository memberships, + AccountConnectScopeRepository scopes, + AccountHostingSubscriptionLifecycleRepository hosting, + StripeHostingSubscriptionObserver observer, + AccountDemoTenantEntitlementRepository demos, + AccountTenantAuthorityEventRepository sources, + CanonicalGameplayAdmissionDecisionReadClient targets, + PlatformTransactionManager transactions, + Clock clock, + String workloadNamespace) { + this.dsl = Objects.requireNonNull(dsl); + this.accounts = Objects.requireNonNull(accounts); + this.callers = Objects.requireNonNull(callers); + this.issuances = Objects.requireNonNull(issuances); + this.memberships = Objects.requireNonNull(memberships); + this.scopes = Objects.requireNonNull(scopes); + this.hosting = Objects.requireNonNull(hosting); + this.observer = Objects.requireNonNull(observer); + this.demos = Objects.requireNonNull(demos); + this.sources = Objects.requireNonNull(sources); + this.targets = Objects.requireNonNull(targets); + this.namespace = workloadNamespace; + this.clock = Objects.requireNonNull(clock); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Session workload namespace is required"); + } + expectedWorkload = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"; + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + transaction.setReadOnly(false); + } + + /** Selects the sole current Account-owned billing source; callers cannot select a family. */ + public RuntimePlayerAdmissionEntitlementEvidence evaluate( + Request request, String presentedInitialLoginJwt) { + VerifiedCaller caller = verifyCaller(request, presentedInitialLoginJwt); + Prepared prepared = + inSourceTransaction( + () -> { + CurrentPlayer player = readCurrentPlayer(request, caller); + return new Prepared(player, sources.readCurrentSourceSelection(request.tenantId())); + }); + requireCurrentTimes(prepared.player(), now()); + RuntimePlayerAdmissionEntitlementEvidence evidence = + switch (prepared.selection().kind()) { + case PAID_HOSTING -> capturePaidSources(request, caller, prepared); + case NON_PAID_DEMO -> captureDemoSources(request, caller, prepared); + }; + evidence.requireCurrentAt(now()); + return evidence; + } + + private RuntimePlayerAdmissionEntitlementEvidence capturePaidSources( + Request request, VerifiedCaller caller, Prepared prepared) { + var fence = inSourceTransaction(() -> hosting.prepareCurrentRead(request.tenantId())); + requireNoAmbientTransaction(); + var observation = observer.observe(fence.binding()); + PublishedRealmEvidence target = readProtectedTarget(request, prepared.player().scope()); + return inSourceTransaction( + () -> { + CurrentPlayer player = readCurrentPlayer(request, caller); + if (!prepared.player().scope().equals(player.scope())) throw unavailable(); + requireSameHead(request, prepared.selection()); + var receipt = hosting.readCurrent(fence, observation); + Instant evaluatedAt = now(); + requireFreshReceipt(request, receipt, evaluatedAt); + var event = receipt.tenantAuthorityEvent(); + if (!prepared.selection().matches(event)) throw unavailable(); + requireTenantSource( + player.snapshot(), + event.tenantId(), + event.tenantAuthorityGeneration(), + receipt.tenantBillingSequence(), + event.outboxStreamKey(), + event.outboxSequence(), + event.eventId(), + event.eventDigest()); + if (!receipt.billingEventId().equals(event.tenantBillingEventId()) + || !receipt.billingEventDigest().equals(event.tenantBillingEventDigest()) + || receipt.tenantBillingSequence() != event.tenantBillingSequence()) { + throw unavailable(); + } + requireCurrentTimes(player, evaluatedAt); + var quote = receipt.current().planQuote(); + return capture( + request, + player, + target, + facts( + "PAID_HOSTING", + receipt.subscriptionStatus().storageValue(), + receipt.gameplayAvailable(), + receipt.allowPublicJoin(), + receipt.allowNewGameplayBindings(), + receipt.allowNewInstanceStarts(), + quote.maxActiveSessions(), + quote.maxConcurrentGameInstances(), + quote.maxStorageBytes(), + receipt.entitlementVersion(), + receipt.tenantBillingSequence(), + event.tenantAuthorityGeneration()), + RuntimePlayerAdmissionEntitlementEvidence.digest( + Map.of( + "receiptRequestId", receipt.receiptRequestId().toString(), + "subscriptionId", receipt.current().subscriptionId().toString(), + "subscriptionRowVersion", Long.toString(receipt.current().rowVersion()), + "billingEventId", receipt.billingEventId().toString(), + "billingEventDigest", receipt.billingEventDigest(), + "tenantAuthorityEventDigest", event.eventDigest())), + evaluatedAt, + receipt.validUntil()); + }); + } + + private RuntimePlayerAdmissionEntitlementEvidence captureDemoSources( + Request request, VerifiedCaller caller, Prepared prepared) { + PublishedRealmEvidence target = readProtectedTarget(request, prepared.player().scope()); + return inSourceTransaction( + () -> { + CurrentPlayer player = readCurrentPlayer(request, caller); + if (!prepared.player().scope().equals(player.scope())) throw unavailable(); + requireSameHead(request, prepared.selection()); + DemoTenantEntitlementSnapshot demo = demos.readCurrent(request.tenantId()); + var head = prepared.selection().checkpoint(); + if (!demo.tenantAuthorityEventId().equals(head.eventId()) + || !demo.tenantAuthorityEventDigest().equals(head.eventDigest()) + || !demo.canonicalTenantId().equals(head.tenantId()) + || demo.tenantAuthorityGeneration() != head.tenantAuthorityGeneration() + || !demo.tenantAuthorityOutboxStreamKey().equals(head.outboxStreamKey()) + || demo.tenantAuthorityOutboxSequence() != head.outboxSequence() + || demo.tenantBillingSequence() != head.tenantBillingSequence() + || !demo.eventId().equals(head.tenantBillingEventId()) + || !demo.eventDigest().equals(head.tenantBillingEventDigest()) + || demo.tenantAuthoritySourceVersion() != head.tenantAuthoritySourceVersion()) { + throw unavailable(); + } + requireTenantSource( + player.snapshot(), + demo.canonicalTenantId(), + demo.tenantAuthorityGeneration(), + demo.tenantBillingSequence(), + demo.tenantAuthorityOutboxStreamKey(), + demo.tenantAuthorityOutboxSequence(), + demo.tenantAuthorityEventId(), + demo.tenantAuthorityEventDigest()); + Instant capturedAt = now(); + requireCurrentTimes(player, capturedAt); + return capture( + request, + player, + target, + facts( + "NON_PAID_DEMO", + null, + demo.gameplayAvailable(), + demo.allowPublicJoin(), + demo.allowNewGameplayBindings(), + demo.allowNewInstanceStarts(), + demo.quotas().maxActiveSessions(), + demo.quotas().maxConcurrentGameInstances(), + demo.quotas().maxStorageBytes(), + demo.entitlementVersion(), + demo.tenantBillingSequence(), + demo.tenantAuthorityGeneration()), + demo.snapshotIdentity(), + capturedAt, + null); + }); + } + + private VerifiedCaller verifyCaller(Request request, String token) { + Objects.requireNonNull(request, "Player entitlement request is required"); + requireNoAmbientTransaction(); + if (!expectedWorkload.equals(request.authenticatedCallerWorkload()) + || !namespace.equals(request.target().targetNamespace()) + || SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService() + || SessionContext.getServiceName() != null + || SessionContext.getServiceInstanceId() != null) throw unavailable(); + VerifiedCaller caller = callers.verifyPresentedCompactToken(token); + if (!expectedWorkload.equals(caller.identity().callerWorkload()) + || !request.target().accountId().equals(caller.identity().accountId())) throw unavailable(); + return caller; + } + + private CurrentPlayer readCurrentPlayer(Request request, VerifiedCaller caller) { + UUID accountId = caller.identity().accountId(); + var account = + accounts + .findByAccountUuidForUpdate(accountId) + .orElseThrow(AccountPlayerAdmissionEntitlementOwner::unavailable); + if (!accountId.equals(account.getAccountUuid())) throw unavailable(); + CommittedCandidateVerificationData current = + issuances + .readCurrentCommittedCandidateByJti(caller.identity().tokenJti()) + .orElseThrow(AccountPlayerAdmissionEntitlementOwner::unavailable); + if (!CommittedCandidateVerificationData.hasSameOwnerEvidence( + caller.currentCandidate(), current)) { + throw unavailable(); + } + Snapshot snapshot = memberships.readCurrent(accountId, request.tenantId()); + RuntimeMembershipAuthorityEvidenceValidator.validate(snapshot); + var authority = current.authoritySnapshot(); + var tuple = snapshot.authorityTuple(); + var expectedCutoff = + authority + .accountSecurityCutoff() + .map( + cutoff -> + Map.of( + "accountAuthorityGeneration", + cutoff.accountAuthorityGeneration(), + "outboxStreamKey", + cutoff.outboxStreamKey(), + "outboxSequence", + cutoff.outboxSequence())); + var actualCutoff = + tuple + .accountSecurityCutoff() + .map( + cutoff -> + Map.of( + "accountAuthorityGeneration", + cutoff.accountAuthorityGeneration(), + "outboxStreamKey", + cutoff.outboxStreamKey(), + "outboxSequence", + cutoff.outboxSequence())); + if (!ISSUER.equals(snapshot.issuerId()) + || !accountId.toString().equals(snapshot.accountId()) + || !request.tenantId().toString().equals(snapshot.tenantId()) + || !accountId.equals(authority.accountId()) + || !Long.toString(authority.issuerGeneration()).equals(tuple.issuerAuthGeneration()) + || !Long.toString(authority.accountGeneration()).equals(tuple.accountAuthorityGeneration()) + || !Long.toString(authority.issuanceFence()).equals(snapshot.issuanceFence()) + || !expectedCutoff.equals(actualCutoff) + || !tuple.privateRealmGrantVersions().isEmpty()) { + throw unavailable(); + } + var verifiedScope = + scopes + .findCanonical(request.connectScopeId()) + .orElseThrow(AccountPlayerAdmissionEntitlementOwner::unavailable); + CanonicalConnectScopeEvidence scope = + scopes + .findCanonicalEvidenceByTokenHash(AccountJoinDigest.tokenHash(request.connectScopeId())) + .orElseThrow(AccountPlayerAdmissionEntitlementOwner::unavailable); + if (!"PUBLIC_PRODUCTION".equals(scope.targetClass()) + || scope.tenantProvenance().kind() != TenantProvenanceKind.FRESH_GAME_DESIGN + || scope.tenantProvenance().legacyTenantId() != null + || !accountId.equals(scope.accountUuid()) + || !request.tenantId().equals(scope.tenantUuid()) + || !AccountJoinDigest.scopeV2(verifiedScope).equals(scope.scopeDigest()) + || !Objects.equals(account.getId(), scope.privateAccountId())) { + throw unavailable(); + } + if (!request.target().equals(selector(request, scope))) throw unavailable(); + return new CurrentPlayer(snapshot, scope, current); + } + + private static void requireTenantSource( + Snapshot snapshot, + UUID tenantId, + long generation, + long billingSequence, + String stream, + long sequence, + UUID eventId, + String eventDigest) { + String tenant = snapshot.tenantId(); + TenantBillingCutoff cutoff = + new TenantBillingCutoff( + Long.toString(generation), + Long.toString(billingSequence), + stream, + Long.toString(sequence)); + if (!tenant.equals(tenantId.toString()) + || !TenantAuthorityEventV1Codec.streamKey(tenantId).equals(stream) + || !snapshot + .authorityTuple() + .tenantAuthorityGeneration() + .equals(Map.of(tenant, Long.toString(generation))) + || !snapshot + .authorityTuple() + .tenantBillingCutoff() + .filter(Map.of(tenant, cutoff)::equals) + .isPresent() + || snapshot.sourceEvidence().stream() + .noneMatch( + source -> + stream.equals(source.outboxStreamKey()) + && Long.toString(sequence).equals(source.outboxSequence()) + && eventId.toString().equals(source.eventId()) + && eventDigest.equals(source.eventDigest()))) { + throw unavailable(); + } + } + + private static void requireFreshReceipt( + Request request, AccountHostingSubscriptionCurrentReceipt receipt, Instant now) { + if (!request.tenantId().equals(receipt.current().tenantId()) + || receipt.evaluatedAt() == null + || receipt.validUntil() == null + || now.isBefore(receipt.evaluatedAt()) + || !now.isBefore(receipt.validUntil())) { + throw unavailable(); + } + } + + private static void requireCurrentTimes(CurrentPlayer player, Instant evaluatedAt) { + CanonicalConnectScopeEvidence scope = player.scope(); + var identity = player.issuance().identity(); + if (evaluatedAt.isBefore(Instant.parse(scope.evaluatedAt())) + || !evaluatedAt.isBefore(Instant.parse(scope.connectScopeExpiresAt())) + || evaluatedAt.getEpochSecond() < identity.notBeforeEpochSecond() + || evaluatedAt.getEpochSecond() >= identity.expiresAtEpochSecond()) { + throw unavailable(); + } + } + + private T inSourceTransaction(Supplier action) { + requireNoAmbientTransaction(); + return Objects.requireNonNull( + transaction.execute( + status -> { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + throw unavailable(); + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() + != Connection.TRANSACTION_SERIALIZABLE) { + throw unavailable(); + } + }); + return Objects.requireNonNull(action.get()); + })); + } + + private Instant now() { + return clock.instant().truncatedTo(ChronoUnit.MICROS); + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) throw unavailable(); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException( + "ENTITLEMENT_UNAVAILABLE: current player source evidence is unavailable"); + } + + private void requireSameHead(Request request, SourceSelection selected) { + SourceSelection current = sources.readCurrentSourceSelection(request.tenantId()); + if (selected.kind() != current.kind() || !selected.matches(current.checkpoint())) + throw unavailable(); + } + + /** Trusted method-authorized workload assertion; construction does not authenticate a peer. */ + public record Request( + RetainedTargetSelector target, String connectScopeId, String authenticatedCallerWorkload) { + public Request { + Objects.requireNonNull(target, "Exact resolved target selectors are required"); + if (connectScopeId == null || connectScopeId.isBlank() || connectScopeId.length() > 16384) + throw new IllegalArgumentException("Bounded opaque connect scope is required"); + GrpcPeerIdentity.parseUri(authenticatedCallerWorkload) + .filter( + peer -> + peer.uri().equals(authenticatedCallerWorkload) + && "game-session-service".equals(peer.service())) + .orElseThrow( + () -> new IllegalArgumentException("Exact Game Session workload is required")); + } + + public UUID tenantId() { + return target.tenantId(); + } + + public UUID requestId() { + return target.readRequestId(); + } + + @Override + public String toString() { + return "PlayerAdmissionEntitlementRequest[redacted]"; + } + } + + private static RetainedTargetSelector selector( + Request request, CanonicalConnectScopeEvidence scope) { + return new RetainedTargetSelector( + request.requestId(), + scope.accountUuid(), + request.target().targetNamespace(), + scope.tenantUuid(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmId(), + scope.realmSlug(), + scope.playableStateNamespaceUuid(), + scope.playableStateScope(), + scope.gameInstanceUuid(), + scope.catalogRevision(), + scope.pointerVersion()); + } + + private PublishedRealmEvidence readProtectedTarget( + Request request, CanonicalConnectScopeEvidence scope) { + requireNoAmbientTransaction(); + var selector = selector(request, scope); + var resolved = Objects.requireNonNull(targets.resolvePublishedRealmAdmissionTarget(selector)); + if (!selector.equals(resolved.selector())) throw unavailable(); + CanonicalGameplayAdmissionDecisionReadGrpcCodec.requireRetainedTargetMatches( + selector, resolved.currentTarget()); + var result = + Objects.requireNonNull(targets.readPublishedRealmAdmissionOwner(resolved.strictSelector())); + if (!resolved.strictSelector().equals(result.selector()) + || !resolved.currentTarget().equals(result.currentTarget())) throw unavailable(); + return result; + } + + private static RuntimePlayerAdmissionEntitlementEvidence capture( + Request request, + CurrentPlayer player, + PublishedRealmEvidence target, + Map facts, + String entitlementSourceDigest, + Instant time, + Instant paidReceiptValidUntil) { + var scope = player.scope(); + var current = target.currentTarget(); + Map binding = new LinkedHashMap<>(); + binding.put("targetClass", "PUBLIC_PRODUCTION"); + binding.put("characterCreationPolicy", "PRESEEDED_ONLY"); + binding.put("targetNamespace", current.targetNamespace()); + binding.put("tenantId", scope.tenantUuid().toString()); + binding.put("tenantSlug", scope.tenantSlug()); + binding.put("worldSlug", scope.worldSlug()); + binding.put("realmId", scope.realmId().toString()); + binding.put("realmSlug", scope.realmSlug()); + binding.put("playableStateNamespaceId", scope.playableStateNamespaceUuid().toString()); + binding.put("playableStateScope", scope.playableStateScope()); + binding.put("gameInstanceId", scope.gameInstanceUuid().toString()); + binding.put("canonicalVersionId", current.canonicalVersionId().toString()); + binding.put("catalogRevision", Long.toString(scope.catalogRevision())); + binding.put("pointerVersion", Long.toString(scope.pointerVersion())); + binding.put("activeWorldEpoch", Long.toString(current.activeWorldEpoch())); + binding.put("evaluatedAt", scope.evaluatedAt()); + binding.put("connectScopeExpiresAt", scope.connectScopeExpiresAt()); + var caller = player.issuance(); + var world = target.worldLifecycleEvidence(); + Map sources = new LinkedHashMap<>(); + sources.put("callerTokenJti", caller.identity().tokenJti().toString()); + sources.put( + "callerTokenExpiresAt", + Instant.ofEpochSecond(caller.identity().expiresAtEpochSecond()).toString()); + sources.put( + "paidReceiptValidUntil", + paidReceiptValidUntil == null ? null : paidReceiptValidUntil.toString()); + sources.put("callerTokenSha256", caller.tokenSha256()); + sources.put("callerRegistryRecordSha256", caller.canonicalRegistryRecordSha256()); + sources.put("callerCommitProofSha256", caller.commitProofSha256()); + sources.put("callerContextId", caller.identity().callerContextId().toString()); + sources.put("callerOperationId", caller.identity().operationId().toString()); + sources.put("scopeDigest", scope.scopeDigest()); + sources.put("entitlementSourceDigest", entitlementSourceDigest); + sources.put( + "admissionPointerSnapshotDigest", target.sourceEvidence().admissionPointerSnapshotDigest()); + sources.put( + "gameSessionOwnerProofDigest", + target.sourceEvidence().gameSessionOwnerProof().proofDigest()); + sources.put( + "publishedPolicySetDigest", + target.sourceEvidence().publishedPolicySetEvidence().policySetDigest()); + sources.put( + "worldLifecycleDigest", + RuntimePlayerAdmissionEntitlementEvidence.digestBytes(world.canonicalBytes())); + sources.put("worldCaptureId", world.captureId().toString()); + sources.put("worldRowVersion", Long.toString(world.rowVersion())); + return RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( + request.requestId(), + request.authenticatedCallerWorkload(), + request.connectScopeId(), + player.snapshot(), + binding, + facts, + sources, + time); + } + + private static Map facts( + String kind, + String status, + boolean gameplay, + boolean join, + boolean bindings, + boolean starts, + long sessions, + long instances, + long storage, + long version, + long sequence, + long generation) { + Map result = new LinkedHashMap<>(); + result.put("sourceKind", kind); + result.put("subscriptionStatus", status); + result.put("provisioningStatus", null); + result.put("gameplayAvailable", gameplay); + result.put("allowPublicJoin", join); + result.put("allowNewGameplayBindings", bindings); + result.put("allowNewInstanceStarts", starts); + result.put( + "quotas", + Map.of( + "maxActiveSessions", + Long.toString(sessions), + "maxConcurrentGameInstances", + Long.toString(instances), + "maxStorageBytes", + Long.toString(storage))); + result.put("entitlementVersion", Long.toString(version)); + result.put("tenantBillingSequence", Long.toString(sequence)); + result.put("tenantAuthorityGeneration", Long.toString(generation)); + return result; + } + + private record Prepared(CurrentPlayer player, SourceSelection selection) {} + + private record CurrentPlayer( + Snapshot snapshot, + CanonicalConnectScopeEvidence scope, + CommittedCandidateVerificationData issuance) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java new file mode 100644 index 0000000000..2ddf42719a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java @@ -0,0 +1,120 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.TlsServerCredentials; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.Objects; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.TrustManagerFactory; +import net.firedevops.firemud.account.v1.AccountPlayerAdmissionEntitlementReadServiceGrpc; +import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementRequest; +import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementResponse; +import net.firedevops.firemud.accountservice.security.AccountPlayerAdmissionEntitlementWorkloadGuard; +import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementGrpcCodec; +import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; +import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered Account owner receiver. No component annotation, capacity commit, World hold or + * gameplay admission. + */ +public final class AccountPlayerAdmissionEntitlementGrpcService + extends AccountPlayerAdmissionEntitlementReadServiceGrpc + .AccountPlayerAdmissionEntitlementReadServiceImplBase { + private final AccountPlayerAdmissionEntitlementOwner owner; + private final String namespace; + private final AccountPlayerAdmissionEntitlementWorkloadGuard guard; + + public AccountPlayerAdmissionEntitlementGrpcService( + AccountPlayerAdmissionEntitlementOwner owner, String namespace) { + this.owner = Objects.requireNonNull(owner); + this.guard = new AccountPlayerAdmissionEntitlementWorkloadGuard(namespace); + this.namespace = namespace; + } + + /** + * Explicit private composition, requiring real client certificates. Returns an unstarted server. + */ + public Server createUnregisteredServer( + String address, KeyManagerFactory keys, TrustManagerFactory trust) { + var factory = + new BoundedGrpcServerFactory( + Objects.requireNonNull(address), + List.of(), + Objects.requireNonNull(keys), + Objects.requireNonNull(trust), + TlsServerCredentials.ClientAuth.REQUIRE, + GrpcRequestBytePolicy.ordinary(), + RuntimePlayerAdmissionEntitlementGrpcCodec.MAX_REQUEST_WIRE_BYTES); + factory.addService(ServerInterceptors.interceptForward(this, guard)); + return factory.createServer(); + } + + @Override + public void readPlayerAdmissionEntitlement( + ReadPlayerAdmissionEntitlementRequest wire, + StreamObserver observer) { + Objects.requireNonNull(observer); + final String authenticatedCaller; + try { + authenticatedCaller = guard.requireAuthenticatedGameSessionCaller(); + } catch (StatusRuntimeException denied) { + fail(observer, denied.getStatus()); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + fail(observer, Status.FAILED_PRECONDITION); + return; + } + final RuntimePlayerAdmissionEntitlementGrpcCodec.PresentedRequest presented; + if (wire == null) { + fail(observer, Status.INVALID_ARGUMENT); + return; + } + try { + presented = RuntimePlayerAdmissionEntitlementGrpcCodec.parseRequest(wire); + } catch (IllegalArgumentException invalid) { + fail(observer, Status.INVALID_ARGUMENT); + return; + } + var request = presented.request(); + if (!namespace.equals(request.target().targetNamespace())) { + fail(observer, Status.PERMISSION_DENIED); + return; + } + final ReadPlayerAdmissionEntitlementResponse response; + try { + var sourceRequest = + new AccountPlayerAdmissionEntitlementOwner.Request( + request.target(), request.connectScopeId(), authenticatedCaller); + var evidence = owner.evaluate(sourceRequest, presented.initialLoginJwt()); + response = RuntimePlayerAdmissionEntitlementGrpcCodec.toResponse(request, evidence); + } catch (RuntimeException unavailableSource) { + // No positive evidence, alternate source, or exception details escape an unavailable + // evaluation. + fail(observer, Status.UNAVAILABLE); + return; + } + try { + observer.onNext(response); + } catch (RuntimeException callbackFailure) { + fail(observer, Status.INTERNAL); + return; + } + observer.onCompleted(); + } + + private static void fail(StreamObserver observer, Status status) { + observer.onError( + Status.fromCode(status.getCode()) + .withDescription("Player-admission entitlement evidence is unavailable") + .asRuntimeException()); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 756f83b446..a8fba53811 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -13,6 +13,7 @@ import java.security.SecureRandom; import java.time.Instant; import java.time.LocalDateTime; +import java.util.Comparator; import java.util.HashMap; import java.util.HexFormat; import java.util.LinkedHashMap; @@ -23,10 +24,13 @@ import java.util.UUID; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.accountservice.AccountUuidText; +import net.firedevops.firemud.accountservice.client.EntityManagementClient; +import net.firedevops.firemud.accountservice.client.GameSessionClient; import net.firedevops.firemud.accountservice.config.AccountTokenProperties; import net.firedevops.firemud.accountservice.config.MailProperties; import net.firedevops.firemud.accountservice.dto.AccountDataExportDto; import net.firedevops.firemud.accountservice.dto.AccountDto; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.AccountLoginAuthModesDto; import net.firedevops.firemud.accountservice.dto.BootstrapCharacterDto; import net.firedevops.firemud.accountservice.dto.BootstrapRealmDto; @@ -51,6 +55,7 @@ import net.firedevops.firemud.accountservice.dto.UpdateAccountLoginAuthModesRequest; import net.firedevops.firemud.accountservice.dto.UpdateProfileRequest; import net.firedevops.firemud.accountservice.dto.UsernameRecoveryRequest; +import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; import net.firedevops.firemud.accountservice.dto.VerifyEmailRequest; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge; @@ -63,7 +68,6 @@ import net.firedevops.firemud.accountservice.entity.EmailVerificationToken; import net.firedevops.firemud.accountservice.entity.Profile; import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; -import net.firedevops.firemud.accountservice.entity.RetainedSubscriptionEvidence; import net.firedevops.firemud.accountservice.mapper.AccountMapper; import net.firedevops.firemud.accountservice.mapper.ProfileMapper; import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; @@ -75,8 +79,10 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.EventEvidence; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.JoinOperation; import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.PasswordResetReceipt; @@ -89,7 +95,7 @@ import net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository; import net.firedevops.firemud.accountservice.repository.PaymentTransactionRepository; import net.firedevops.firemud.accountservice.repository.ProfileRepository; -import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.SubscriptionRepository; import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository.Intent; @@ -107,6 +113,7 @@ import net.firedevops.firemud.common.security.JwtAuthProperties; import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import org.jooq.exception.IntegrityConstraintViolationException; import org.slf4j.Logger; import org.springframework.dao.DataAccessException; @@ -115,11 +122,14 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; +import org.springframework.util.StringUtils; import org.springframework.web.server.ResponseStatusException; +import tools.jackson.databind.json.JsonMapper; @Service public class AccountServiceImpl implements AccountService { @@ -139,6 +149,7 @@ public class AccountServiceImpl implements AccountService { private static final int EMAIL_LOGIN_OTP_MAX_ATTEMPTS = 5; private static final UUID NIL_ACCOUNT_UUID = new UUID(0L, 0L); private static final SecureRandom EMAIL_LOGIN_OTP_RANDOM = new SecureRandom(); + private static final JsonMapper AUDIT_JSON = JsonMapper.builder().build(); private String gameplayDecoyPasswordVerifier; @@ -150,6 +161,7 @@ public class AccountServiceImpl implements AccountService { private final AccountAuthoritySourceEventReadback accountAuthoritySourceEventReadback; private final AccountPasswordResetDraftSourceChangeRepository passwordResetDraftSourceChanges; private final AccountAuditOutboxRepository accountAuditOutboxRepository; + private final AccountConnectScopeRepository accountConnectScopeRepository; private final AccountJoinOperationRepository accountJoinOperationRepository; private final AccountEmailLoginChallengeRepository accountEmailLoginChallengeRepository; private final AccountRealmAccessGrantRepository accountRealmAccessGrantRepository; @@ -158,7 +170,7 @@ public class AccountServiceImpl implements AccountService { private final ProfileRepository profileRepository; private final ProfileMapper profileMapper; private final PaymentTransactionRepository paymentTransactionRepository; - private final RetainedSubscriptionEvidenceRepository retainedSubscriptionEvidenceRepository; + private final SubscriptionRepository subscriptionRepository; private final ExternalAccountRepository externalAccountRepository; private final PasswordResetTokenRepository passwordResetTokenRepository; private final EmailVerificationTokenRepository emailVerificationTokenRepository; @@ -167,6 +179,8 @@ public class AccountServiceImpl implements AccountService { private final MailProperties mailProperties; private final AccountTokenProperties tokenProperties; private final JwtAuthProperties jwtAuthProperties; + private final GameSessionClient gameSessionClient; + private final EntityManagementClient entityManagementClient; private final JwtUtil jwtUtil; private final net.firedevops.firemud.accountservice.service.session.SessionService sessionService; private final TransactionTemplate joinTransactionTemplate; @@ -185,6 +199,7 @@ public AccountServiceImpl( AccountSecurityStateOperationRepository securityStateOperationRepository, AccountPasswordResetDraftSourceChangeRepository passwordResetDraftSourceChanges, AccountAuditOutboxRepository accountAuditOutboxRepository, + AccountConnectScopeRepository accountConnectScopeRepository, AccountJoinOperationRepository accountJoinOperationRepository, AccountEmailLoginChallengeRepository accountEmailLoginChallengeRepository, AccountRealmAccessGrantRepository accountRealmAccessGrantRepository, @@ -193,7 +208,7 @@ public AccountServiceImpl( ProfileRepository profileRepository, ProfileMapper profileMapper, PaymentTransactionRepository paymentTransactionRepository, - RetainedSubscriptionEvidenceRepository retainedSubscriptionEvidenceRepository, + SubscriptionRepository subscriptionRepository, ExternalAccountRepository externalAccountRepository, PasswordResetTokenRepository passwordResetTokenRepository, EmailVerificationTokenRepository emailVerificationTokenRepository, @@ -202,6 +217,8 @@ public AccountServiceImpl( MailProperties mailProperties, AccountTokenProperties tokenProperties, JwtAuthProperties jwtAuthProperties, + GameSessionClient gameSessionClient, + EntityManagementClient entityManagementClient, JwtUtil jwtUtil, net.firedevops.firemud.accountservice.service.session.SessionService sessionService, PlatformTransactionManager transactionManager) { @@ -218,6 +235,7 @@ public AccountServiceImpl( securityStateOperationRepository); this.passwordResetDraftSourceChanges = passwordResetDraftSourceChanges; this.accountAuditOutboxRepository = accountAuditOutboxRepository; + this.accountConnectScopeRepository = accountConnectScopeRepository; this.accountJoinOperationRepository = accountJoinOperationRepository; this.accountEmailLoginChallengeRepository = accountEmailLoginChallengeRepository; this.accountRealmAccessGrantRepository = accountRealmAccessGrantRepository; @@ -226,7 +244,7 @@ public AccountServiceImpl( this.profileRepository = profileRepository; this.profileMapper = profileMapper; this.paymentTransactionRepository = paymentTransactionRepository; - this.retainedSubscriptionEvidenceRepository = retainedSubscriptionEvidenceRepository; + this.subscriptionRepository = subscriptionRepository; this.externalAccountRepository = externalAccountRepository; this.passwordResetTokenRepository = passwordResetTokenRepository; this.emailVerificationTokenRepository = emailVerificationTokenRepository; @@ -235,6 +253,8 @@ public AccountServiceImpl( this.mailProperties = mailProperties; this.tokenProperties = tokenProperties; this.jwtAuthProperties = jwtAuthProperties; + this.gameSessionClient = gameSessionClient; + this.entityManagementClient = entityManagementClient; this.jwtUtil = jwtUtil; this.sessionService = sessionService; this.joinTransactionTemplate = new TransactionTemplate(transactionManager); @@ -419,53 +439,543 @@ public PlayerBootstrapResult issuePlayerBootstrap(String accountIdentifier, Stri Instant.ofEpochMilli(expiresAt).toString()); } - // Numeric retained billing history cannot authorize public discovery or admission. - // The complete canonical public facade is integrated in the receiving successor. @Override + @Transactional(readOnly = true) @Timed(value = "account.bootstrap_worlds") public List listBootstrapWorlds(String bootstrapToken) { - throw publicBootstrapUnavailable(); + BootstrapContext bootstrapContext = requireBootstrapContext(bootstrapToken); + Map discoveryEntitlementMemo = new HashMap<>(); + return gameSessionClient.listGameplayWorlds().stream() + .filter( + world -> + hasAdmissibleRealm( + bootstrapContext, world.getWorldSlug(), discoveryEntitlementMemo)) + .map(world -> new BootstrapWorldDto(world.getWorldSlug(), world.getDisplayName())) + .toList(); } @Override + @Transactional(propagation = Propagation.NOT_SUPPORTED) @Timed(value = "account.bootstrap_realms") public List listBootstrapRealms(String bootstrapToken, String worldSlug) { - throw publicBootstrapUnavailable(); + BootstrapContext bootstrapContext = requireBootstrapContext(bootstrapToken); + Map discoveryEntitlementMemo = new HashMap<>(); + Instant evaluatedAt = Instant.now(); + Instant expiresAt = evaluatedAt.plusMillis(tokenProperties.getConnectScopeExpirationMs()); + final List admissibleRealms; + try { + admissibleRealms = + listAdmissibleRuntimeRealmTargets(bootstrapContext, worldSlug, discoveryEntitlementMemo); + } catch (AuthenticationException ex) { + throw ex; + } catch (RuntimeException ex) { + throw admissionPointerUnavailable(ex); + } + return admissibleRealms.stream() + .map( + discovered -> { + RuntimeRealmTarget current = + requireRealmTarget( + discovered.tenantId(), discovered.worldSlug(), discovered.realmSlug()); + if (!sameRuntimeRealmAuthority(discovered, current)) { + throw admissionPointerUnavailable( + new IllegalStateException( + "Public realm authority changed during bootstrap discovery")); + } + return current; + }) + .map( + realm -> + new BootstrapRealmDto( + realm.worldSlug(), + realm.realmSlug(), + realm.realmId().toString(), + realm.displayName(), + realm.tenantId(), + realm.gameInstanceId(), + realm.pointerVersion(), + realm.catalogRevision(), + realm.playableStateNamespaceId(), + toPlayableStateScope(realm).name(), + realm.requiresCharacterSelection(), + realm.stateScope(), + realm.characterCreationPolicy(), + evaluatedAt.toString(), + expiresAt.toString(), + mintAndRetainConnectScope(bootstrapContext, realm, evaluatedAt, expiresAt))) + .toList(); } @Override + @Transactional(readOnly = true) @Timed(value = "account.bootstrap_characters") public List listBootstrapCharacters( String bootstrapToken, String worldSlug, String realmSlug, String connectScopeId) { - throw publicBootstrapUnavailable(); + BootstrapContext bootstrapContext = requireBootstrapContext(bootstrapToken); + ConnectScopeContext scopeContext = requireConnectScopeContext(connectScopeId); + validateConnectScopeAgainstBootstrap(bootstrapContext, scopeContext); + validateConnectScopeRoute(scopeContext, worldSlug, realmSlug); + RuntimeRealmTarget realm = + requireCurrentAdmissibleConnectScopeTarget(bootstrapContext, scopeContext); + UUID accountUuid = bootstrapContext.accountUuid(); + if (accountUuid == null || NIL_ACCOUNT_UUID.equals(accountUuid)) { + throw new IllegalStateException("Bootstrap Account UUID is unavailable"); + } + return entityManagementClient + .listCharactersByAccount( + realm.tenantId(), accountUuid, realm.gameInstanceId(), toPlayableStateScope(realm)) + .stream() + .sorted(Comparator.comparing(net.firedevops.firemud.entitymanagement.v1.Character::getName)) + .map( + character -> + new BootstrapCharacterDto( + character.getId(), + character.getName(), + character.getLevel(), + realm.stateScope(), + realm.characterCreationPolicy())) + .toList(); } @Override @Timed(value = "account.public_production_join") public JoinPublicProductionResult joinPublicProduction( String bootstrapToken, JoinPublicProductionRequest request) { - throw publicBootstrapUnavailable(); + BootstrapContext caller = requireBootstrapContext(bootstrapToken); + Claims callerClaims = + requireSignedTokenClaims( + bootstrapToken, + "player-bootstrap", + "CONNECT_CONTEXT_INVALID", + "Missing bootstrap token", + "Invalid bootstrap token"); + String callerBinding; + try { + callerBinding = JwtClaims.requireText(callerClaims.get("jti"), "jti"); + } catch (IllegalArgumentException ex) { + throw new AuthenticationException( + "CONNECT_CONTEXT_INVALID", "Bootstrap caller binding is missing", ex); + } + requireAuthenticationEligible(requireAccount(caller.accountId())); + return projectJoinOutcome( + joinPublicProductionForTrustedCaller(caller.accountId(), callerBinding, null, request)); } @Override + @Transactional(propagation = Propagation.NOT_SUPPORTED) @Timed(value = "account.direct_text_connect_scope") public DirectTextJoinScope issueDirectTextConnectScope( DirectTextCallerContext caller, DirectTextJoinTarget target) { - throw publicBootstrapUnavailable(); + if (caller == null + || target == null + || caller.accountId() <= 0L + || !StringUtils.hasText(caller.requestId()) + || caller.tenantId() != target.tenantId() + || !caller.realmId().equals(target.realmId()) + || caller.gameInstanceId() != target.gameInstanceId() + || !caller.playableStateNamespaceId().equals(target.playableStateNamespaceId()) + || !caller.playableStateScope().equals(target.playableStateScope())) { + throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); + } + Account account = requireAccount(caller.accountId()); + requireAuthenticationEligible(account); + RuntimeRealmTarget current = + requireRealmTarget(target.tenantId(), target.worldSlug(), target.realmSlug()); + if (!isPublicProductionRealm(current)) { + throw new AuthenticationException( + "REALM_UNAVAILABLE", "Selected public realm is unavailable"); + } + if (!current.realmId().equals(target.realmId()) + || !current.playableStateNamespaceId().equals(target.playableStateNamespaceId()) + || !current.stateScope().equals(target.playableStateScope()) + || current.gameInstanceId() != target.gameInstanceId() + || current.catalogRevision() != target.catalogRevision() + || current.pointerVersion() != target.pointerVersion()) { + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); + } + RuntimeEntitlementsDto entitlements = + getTenantEntitlementsForRuntime(current.tenantId(), caller.requestId()); + if (!entitlements.gameplayAvailable()) { + throw new AuthenticationException( + "TENANT_BILLING_BLOCKED", "Gameplay is not available for this tenant"); + } + Instant evaluatedAt = Instant.now(); + Instant expiresAt = evaluatedAt.plusMillis(tokenProperties.getConnectScopeExpirationMs()); + requireAuthenticationAccountUuid(account); + String scopeId = + mintAndRetainConnectScope( + new BootstrapContext(caller.accountId(), account.getAccountUuid()), + current, + evaluatedAt, + expiresAt); + return new DirectTextJoinScope(scopeId, expiresAt.toString(), evaluatedAt.toString()); } @Override @Timed(value = "account.public_production_join_internal") public JoinPublicProductionResult joinPublicProductionFromGameSession( DirectTextCallerContext caller, JoinPublicProductionRequest request) { - throw publicBootstrapUnavailable(); + if (caller == null + || caller.accountId() <= 0L + || !StringUtils.hasText(caller.sessionId()) + || request == null + || !caller.requestId().equals(request.requestId())) { + throw new AuthenticationException( + "CONNECT_CONTEXT_INVALID", "JOIN caller context is missing"); + } + requireAuthenticationEligible(requireAccount(caller.accountId())); + return projectJoinOutcome( + joinPublicProductionForTrustedCaller( + caller.accountId(), caller.sessionId(), caller, request)); } - private AuthenticationException publicBootstrapUnavailable() { - return new AuthenticationException( - "AUTH_UNAVAILABLE", "Canonical public gameplay authority is unavailable"); + private JoinOutcome joinPublicProductionForTrustedCaller( + long accountId, + String callerBinding, + DirectTextCallerContext directTextCaller, + JoinPublicProductionRequest request) { + if (request == null + || !StringUtils.hasText(request.connectScopeId()) + || !StringUtils.hasText(request.requestId())) { + throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); + } + if (request.requestId().length() > JoinPublicProductionRequest.MAX_REQUEST_ID_LENGTH) { + throw new AuthenticationException( + "INVALID_ARGUMENT", "JOIN requestId exceeds the maximum length"); + } + String requestId = request.requestId(); + String scopeTokenHash = AccountJoinDigest.tokenHash(request.connectScopeId()); + Optional existing = accountJoinOperationRepository.find(requestId); + VerifiedJoinScope retained; + if (existing.isPresent()) { + JoinOperation operation = existing.orElseThrow(); + if (operation.accountId() != accountId + || !operation.callerBinding().equals(callerBinding) + || !operation.scopeTokenHash().equals(scopeTokenHash)) { + throw new AuthenticationException( + "IDEMPOTENCY_CONFLICT", "JOIN request ID was reused with different input"); + } + retained = retainedJoinScope(request.connectScopeId()); + validateDirectTextJoinScope(directTextCaller, retained); + requireMatchingJoinIntent(operation, requestId, callerBinding, retained); + } else { + ConnectScopeContext signedScope = requireConnectScopeContext(request.connectScopeId()); + retained = retainedJoinScope(request.connectScopeId()); + validateDirectTextJoinScope(directTextCaller, retained); + validateSignedJoinScope(signedScope, retained, accountId); + String intentDigest = AccountJoinDigest.intent(requestId, retained, callerBinding); + try { + joinTransactionTemplate.execute( + transactionStatus -> + accountJoinOperationRepository.insertIntent( + requestId, retained, callerBinding, intentDigest)); + } catch (RuntimeException ex) { + Optional claimReadback = safeFindJoinOperation(requestId); + if (claimReadback.isEmpty()) { + if (connectScopeEvidenceIsMissing(request.connectScopeId())) { + throw new AuthenticationException( + "CONNECT_SCOPE_INVALID", "JOIN scope evidence is unavailable", ex); + } + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "JOIN request claim is uncertain; retry the same request", ex); + } + requireMatchingJoinIntent(claimReadback.orElseThrow(), requestId, callerBinding, retained); + } + JoinOperation claimed = + accountJoinOperationRepository + .find(requestId) + .orElseThrow( + () -> + new AuthenticationException( + "AUTH_UNAVAILABLE", "JOIN request claim is not yet readable")); + requireMatchingJoinIntent(claimed, requestId, callerBinding, retained); + } + + try { + JoinAttemptOutcome outcome = + joinTransactionTemplate.execute( + transactionStatus -> + executeJoinAttempt(accountId, callerBinding, requestId, retained)); + if (outcome.terminalOperation() != null) { + return replayTerminalJoinSafely(outcome.terminalOperation(), callerBinding, retained); + } + return outcome.result(); + } catch (AuthenticationException ex) { + if ("IDEMPOTENCY_CONFLICT".equals(ex.getCode())) { + throw ex; + } + recordJoinAttemptFailureAfterRollback(requestId, ex.getCode()); + return pendingJoinFailure(retained, ex.getCode()); + } catch (RuntimeException ex) { + Optional outcomeReadback = safeFindJoinOperation(requestId); + if (outcomeReadback.isPresent()) { + JoinOperation operation = outcomeReadback.orElseThrow(); + requireMatchingJoinIntent(operation, requestId, callerBinding, retained); + if (!"PENDING".equals(operation.status())) { + return replayTerminalJoinSafely(operation, callerBinding, retained); + } + recordJoinAttemptFailureAfterRollback(requestId, "AUTH_UNAVAILABLE"); + } + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "JOIN outcome is uncertain; retry the same request", ex); + } + } + + private JoinAttemptOutcome executeJoinAttempt( + long accountId, String callerBinding, String requestId, VerifiedJoinScope scope) { + accountJoinOperationRepository.lockAccount(accountId); + JoinOperation operation = + accountJoinOperationRepository + .findForUpdate(requestId) + .orElseThrow(() -> new IllegalStateException("JOIN request claim disappeared")); + requireMatchingJoinIntent(operation, requestId, callerBinding, scope); + + if (!"PENDING".equals(operation.status())) { + return JoinAttemptOutcome.terminal(operation); + } + return JoinAttemptOutcome.result( + executePendingJoinAttempt(accountId, callerBinding, requestId, scope, operation)); + } + + private JoinOutcome executePendingJoinAttempt( + long accountId, + String callerBinding, + String requestId, + VerifiedJoinScope scope, + JoinOperation operation) { + if (isConnectScopeExpired(scope)) { + return failedJoin(requestId, scope, "CONNECT_SCOPE_INVALID"); + } + + JoinEvaluation evaluation = evaluateJoin(scope, false); + if (evaluation.failureCode() != null) { + if (isRetryableJoinAuthorityFailure(evaluation)) { + accountJoinOperationRepository.recordAttemptFailure( + requestId, evaluation.authorityAvailability(), evaluation.failureCode()); + return pendingJoinFailure(scope, evaluation.failureCode()); + } + return failedJoin(requestId, scope, evaluation.failureCode()); + } + if (!"AVAILABLE".equals(evaluation.authorityAvailability()) + || evaluation.allowPublicJoin() == null + || evaluation.entitlementVersion() == null) { + accountJoinOperationRepository.recordAttemptFailure( + requestId, evaluation.authorityAvailability(), "ENTITLEMENT_UNAVAILABLE"); + return pendingJoinFailure(scope, "ENTITLEMENT_UNAVAILABLE"); + } + String requestDigest = + AccountJoinDigest.request( + scope, callerBinding, evaluation.allowPublicJoin(), evaluation.entitlementVersion()); + if (operation.requestDigest() != null + && (!Integer.valueOf(1).equals(operation.requestDigestVersion()) + || !operation.requestDigest().equals(requestDigest))) { + return failedJoin(requestId, scope, "IDEMPOTENCY_CONFLICT"); + } + if (operation.requestDigest() == null) { + accountJoinOperationRepository.bindPolicyEvidence( + requestId, requestDigest, evaluation.entitlementVersion(), evaluation.allowPublicJoin()); + } + if (!evaluation.gameplayAvailable()) { + return failedJoin(requestId, scope, "TENANT_BILLING_BLOCKED"); + } + if (!evaluation.allowPublicJoin()) { + return failedJoin(requestId, scope, "PUBLIC_PRODUCTION_ADMISSION_DENIED"); + } + + JoinEvaluation commitEvaluation = evaluateJoin(scope, true); + if (commitEvaluation.failureCode() != null) { + if (isRetryableJoinAuthorityFailure(commitEvaluation)) { + accountJoinOperationRepository.recordAttemptFailure( + requestId, commitEvaluation.authorityAvailability(), commitEvaluation.failureCode()); + return pendingJoinFailure(scope, commitEvaluation.failureCode()); + } + return failedJoin(requestId, scope, commitEvaluation.failureCode()); + } + if (!"AVAILABLE".equals(commitEvaluation.authorityAvailability())) { + accountJoinOperationRepository.recordAttemptFailure( + requestId, commitEvaluation.authorityAvailability(), "ENTITLEMENT_UNAVAILABLE"); + return pendingJoinFailure(scope, "ENTITLEMENT_UNAVAILABLE"); + } + String commitDigest = + AccountJoinDigest.request( + scope, + callerBinding, + commitEvaluation.allowPublicJoin(), + commitEvaluation.entitlementVersion()); + if (!requestDigest.equals(commitDigest)) { + return failedJoin(requestId, scope, "IDEMPOTENCY_CONFLICT"); + } + if (!commitEvaluation.gameplayAvailable()) { + return failedJoin(requestId, scope, "TENANT_BILLING_BLOCKED"); + } + if (!commitEvaluation.allowPublicJoin()) { + return failedJoin(requestId, scope, "PUBLIC_PRODUCTION_ADMISSION_DENIED"); + } + AccountTenantMembership membership = + accountTenantMembershipRepository + .findByAccountIdAndTenantId(accountId, scope.tenantId()) + .orElse(null); + boolean transitioned = false; + if (membership == null) { + membership = new AccountTenantMembership(); + membership.setAccount(requireAccount(accountId)); + membership.setTenantId(scope.tenantId()); + membership.setMembershipVersion(1L); + membership.setMembershipAuthorityGeneration(1L); + membership.setLifecycleState("ACTIVE"); + membership.setGameplayAdmissionAllowed(true); + membership.setAuthorityProvenance("EXPLICIT_JOIN"); + accountTenantMembershipRepository.save(membership); + transitioned = true; + } else if ("INACTIVE".equals(membership.getLifecycleState())) { + accountJoinOperationRepository.recordCallerBoundAuthorityInvalidation(requestId); + membership.setLifecycleState("ACTIVE"); + membership.setGameplayAdmissionAllowed(true); + membership.setMembershipVersion(membership.getMembershipVersion() + 1L); + membership.setMembershipAuthorityGeneration( + membership.getMembershipAuthorityGeneration() + 1L); + membership.setAuthorityProvenance("EXPLICIT_JOIN"); + accountTenantMembershipRepository.save(membership); + transitioned = true; + } else if (!"ACTIVE".equals(membership.getLifecycleState()) + || !membership.isGameplayAdmissionAllowed()) { + return failedJoin(requestId, scope, "MEMBERSHIP_RECONCILIATION_REQUIRED"); + } + if (transitioned) { + String payload = + AUDIT_JSON.writeValueAsString( + new JoinAuditPayload( + accountId, + scope.tenantId(), + scope.worldSlug(), + scope.realmSlug(), + membership.getMembershipVersion(), + requestId)); + UUID auditEventId = + UUID.nameUUIDFromBytes( + ("account-join-audit/v1:" + requestId).getBytes(StandardCharsets.UTF_8)); + accountAuditOutboxRepository.append( + auditEventId, "tenant", scope.tenantId(), "ACCOUNT_JOINED_PUBLIC_PRODUCTION", payload); + } + accountJoinOperationRepository.finish( + requestId, + "COMMITTED", + transitioned ? "JOINED" : "ALREADY_ACTIVE", + membership.getId(), + membership.getMembershipVersion(), + membership.getMembershipAuthorityGeneration()); + return new JoinOutcome( + true, + transitioned ? "JOINED" : "ALREADY_ACTIVE", + accountId, + scope.tenantId(), + membership.getId(), + membership.getMembershipVersion(), + membership.getMembershipAuthorityGeneration(), + false); + } + + private JoinOutcome failedJoin(String requestId, VerifiedJoinScope scope, String outcomeCode) { + accountJoinOperationRepository.finish(requestId, "FAILED", outcomeCode, null, null, null); + return new JoinOutcome( + false, outcomeCode, scope.accountId(), scope.tenantId(), 0L, 0L, 0L, false); + } + + private JoinOutcome pendingJoinFailure(VerifiedJoinScope scope, String outcomeCode) { + return joinRetryFailure(scope, outcomeCode); + } + + private JoinOutcome replayTerminalJoin( + JoinOperation operation, String callerBinding, VerifiedJoinScope scope) { + if (isConnectScopeExpired(scope)) { + return joinRetryFailure(scope, "CONNECT_SCOPE_INVALID"); + } + + boolean replayUnboundFailure = + "FAILED".equals(operation.status()) && operation.requestDigest() == null; + + JoinEvaluation evaluation; + try { + evaluation = evaluateJoin(scope); + } catch (AuthenticationException ex) { + return joinRetryFailure( + scope, isStorageBackedEntitlementFailure(ex) ? ex.getCode() : "AUTH_UNAVAILABLE"); + } catch (RuntimeException ex) { + return joinRetryFailure(scope, "AUTH_UNAVAILABLE"); + } + if (evaluation.failureCode() != null) { + if ("ENTITLEMENT_UNAVAILABLE".equals(evaluation.failureCode())) { + return joinRetryFailure(scope, evaluation.failureCode()); + } + if (isRetryableJoinAuthorityFailure(evaluation)) { + return joinRetryFailure(scope, "AUTH_UNAVAILABLE"); + } + return joinRetryFailure(scope, evaluation.failureCode()); + } + if (!"AVAILABLE".equals(evaluation.authorityAvailability()) + || evaluation.allowPublicJoin() == null + || evaluation.entitlementVersion() == null) { + return joinRetryFailure(scope, "AUTH_UNAVAILABLE"); + } + if (replayUnboundFailure) { + return resultFromJoinOperation(operation, true); + } + + String currentRequestDigest = + AccountJoinDigest.request( + scope, callerBinding, evaluation.allowPublicJoin(), evaluation.entitlementVersion()); + if (!Integer.valueOf(1).equals(operation.requestDigestVersion()) + || operation.requestDigest() == null + || operation.allowPublicJoin() == null + || !operation.allowPublicJoin().equals(evaluation.allowPublicJoin()) + || operation.entitlementVersion() == null + || !operation.entitlementVersion().equals(evaluation.entitlementVersion()) + || !operation.requestDigest().equals(currentRequestDigest) + || ("COMMITTED".equals(operation.status()) + && (!evaluation.gameplayAvailable() || !evaluation.allowPublicJoin()))) { + return joinRetryFailure(scope, "IDEMPOTENCY_CONFLICT"); + } + return resultFromJoinOperation(operation, true); + } + + private JoinOutcome replayTerminalJoinSafely( + JoinOperation operation, String callerBinding, VerifiedJoinScope scope) { + try { + return replayTerminalJoin(operation, callerBinding, scope); + } catch (RuntimeException policyCheckFailure) { + return joinRetryFailure(scope, "AUTH_UNAVAILABLE"); + } + } + + private JoinOutcome joinRetryFailure(VerifiedJoinScope scope, String outcomeCode) { + return new JoinOutcome( + false, outcomeCode, scope.accountId(), scope.tenantId(), 0L, 0L, 0L, false); } + /** Project only after the JOIN transaction has returned, preserving any committed receipt. */ + private JoinPublicProductionResult projectJoinOutcome(JoinOutcome outcome) { + return new JoinPublicProductionResult( + outcome.success(), + outcome.outcomeCode(), + responseAccountUuid(outcome.accountId()), + outcome.tenantId(), + outcome.membershipId(), + outcome.membershipVersion(), + outcome.membershipAuthorityGeneration(), + outcome.replayed()); + } + + /** Private Account row identities never escape through response projection. */ + private record JoinOutcome( + boolean success, + String outcomeCode, + long accountId, + long tenantId, + long membershipId, + long membershipVersion, + long membershipAuthorityGeneration, + boolean replayed) {} + private String responseAccountUuid(Long accountId) { try { return responseAccountUuid(requireAccount(accountId), accountId); @@ -487,18 +997,258 @@ private String responseAccountUuid(Account account, Long accountId) { } } + private boolean isConnectScopeExpired(VerifiedJoinScope scope) { + try { + return !Instant.parse(scope.connectScopeExpiresAt()).isAfter(Instant.now()); + } catch (RuntimeException ex) { + return true; + } + } + + private boolean isRetryableJoinAuthorityFailure(JoinEvaluation evaluation) { + return "UNAVAILABLE".equals(evaluation.authorityAvailability()) + || "ADMISSION_POINTER_UNAVAILABLE".equals(evaluation.failureCode()) + || "AUTH_UNAVAILABLE".equals(evaluation.failureCode()) + || "ENTITLEMENT_UNAVAILABLE".equals(evaluation.failureCode()); + } + + private VerifiedJoinScope retainedJoinScope(String connectScopeId) { + return accountConnectScopeRepository + .find(connectScopeId) + .orElseThrow( + () -> + new AuthenticationException( + "CONNECT_SCOPE_INVALID", "JOIN scope evidence is unavailable")); + } + + private boolean connectScopeEvidenceIsMissing(String connectScopeId) { + try { + return accountConnectScopeRepository.find(connectScopeId).isEmpty(); + } catch (RuntimeException ex) { + return false; + } + } + + private void validateSignedJoinScope( + ConnectScopeContext signedScope, VerifiedJoinScope retained, long accountId) { + if (retained.accountId() != accountId + || signedScope.accountId() != accountId + || signedScope.tenantId() != retained.tenantId() + || !signedScope.realmId().equals(retained.realmId()) + || !signedScope.playableStateNamespaceId().equals(retained.playableStateNamespaceId()) + || !signedScope.playableStateScope().equals(retained.playableStateScope()) + || signedScope.gameInstanceId() != retained.gameInstanceId() + || signedScope.catalogRevision() != retained.catalogRevision() + || signedScope.pointerVersion() != retained.pointerVersion() + || !signedScope.worldSlug().equals(retained.worldSlug()) + || !signedScope.realmSlug().equals(retained.realmSlug()) + || !signedScope.evaluatedAt().toString().equals(retained.evaluatedAt()) + || !signedScope + .connectScopeExpiresAt() + .toString() + .equals(retained.connectScopeExpiresAt())) { + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); + } + } + + private void requireMatchingJoinIntent( + JoinOperation operation, String requestId, String callerBinding, VerifiedJoinScope scope) { + String expectedIntentDigest = AccountJoinDigest.intent(requestId, scope, callerBinding); + if (operation.accountId() != scope.accountId() + || !operation.realmId().equals(scope.realmId()) + || !operation.callerBinding().equals(callerBinding) + || !operation.scopeTokenHash().equals(AccountJoinDigest.tokenHash(scope.connectScopeId())) + || !operation.connectScopeDigest().equals(scope.snapshotDigest()) + || operation.intentDigestVersion() != 1 + || !operation.intentDigest().equals(expectedIntentDigest)) { + throw new AuthenticationException( + "IDEMPOTENCY_CONFLICT", "JOIN request ID was reused with different input"); + } + } + + private JoinOutcome resultFromJoinOperation(JoinOperation operation, boolean replayed) { + return new JoinOutcome( + "COMMITTED".equals(operation.status()), + operation.outcome(), + operation.accountId(), + operation.tenantId(), + operation.membershipId() == null ? 0L : operation.membershipId(), + operation.membershipVersion() == null ? 0L : operation.membershipVersion(), + operation.membershipAuthorityGeneration() == null + ? 0L + : operation.membershipAuthorityGeneration(), + replayed); + } + + private Optional safeFindJoinOperation(String requestId) { + try { + return accountJoinOperationRepository.find(requestId); + } catch (RuntimeException ignored) { + return Optional.empty(); + } + } + + private void recordJoinAttemptFailureAfterRollback(String requestId, String failureCode) { + String availability = + "ENTITLEMENT_UNAVAILABLE".equals(failureCode) ? "UNAVAILABLE" : "NOT_EVALUATED"; + try { + joinTransactionTemplate.execute( + transactionStatus -> { + accountJoinOperationRepository + .findForUpdate(requestId) + .ifPresent( + operation -> { + if ("PENDING".equals(operation.status())) { + accountJoinOperationRepository.recordAttemptFailure( + requestId, availability, failureCode); + } + }); + return null; + }); + } catch (RuntimeException ignored) { + // The durable intent stays pending, and the caller retries the same request ID. + } + } + + private void validateDirectTextJoinScope( + DirectTextCallerContext caller, VerifiedJoinScope scope) { + if (caller != null + && (caller.accountId() != scope.accountId() + || caller.tenantId() != scope.tenantId() + || !caller.realmId().equals(scope.realmId()) + || caller.gameInstanceId() != scope.gameInstanceId() + || !caller.playableStateNamespaceId().equals(scope.playableStateNamespaceId()) + || !caller.playableStateScope().equals(scope.playableStateScope()))) { + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); + } + } + + private JoinEvaluation evaluateJoin(VerifiedJoinScope scope) { + return evaluateJoin(scope, true); + } + + private JoinEvaluation evaluateJoin(VerifiedJoinScope scope, boolean lockEntitlement) { + return evaluateJoin( + new ConnectScopeContext( + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + Instant.parse(scope.evaluatedAt()), + Instant.parse(scope.connectScopeExpiresAt())), + lockEntitlement); + } + + private JoinEvaluation evaluateJoin(ConnectScopeContext scope, boolean lockEntitlement) { + RuntimeRealmTarget target; + try { + target = requireCurrentConnectScopeTarget(scope); + } catch (AuthenticationException ex) { + if ("CONNECT_SCOPE_MISMATCH".equals(ex.getCode()) + || "ADMISSION_POINTER_UNAVAILABLE".equals(ex.getCode())) { + return new JoinEvaluation("NOT_EVALUATED", null, null, false, ex.getCode()); + } + throw ex; + } + if (!isPublicProductionRealm(target)) { + return new JoinEvaluation( + "NOT_EVALUATED", null, null, false, "PUBLIC_PRODUCTION_ADMISSION_DENIED"); + } + try { + RuntimeEntitlementsDto entitlement = joinEntitlement(scope.tenantId(), lockEntitlement); + return new JoinEvaluation( + "AVAILABLE", + entitlement.allowPublicJoin(), + entitlement.entitlementVersion(), + entitlement.gameplayAvailable(), + null); + } catch (AuthenticationException ex) { + if ("ENTITLEMENT_UNAVAILABLE".equals(ex.getCode())) { + if (isStorageBackedEntitlementFailure(ex)) { + // Leave a potentially aborted SQL transaction before recording the failed attempt. + throw ex; + } + return new JoinEvaluation("UNAVAILABLE", null, null, false, ex.getCode()); + } + throw ex; + } + } + + private boolean isStorageBackedEntitlementFailure(AuthenticationException failure) { + return "ENTITLEMENT_UNAVAILABLE".equals(failure.getCode()) + && (failure.getCause() instanceof org.jooq.exception.DataAccessException + || failure.getCause() instanceof DataAccessException); + } + + private record JoinEvaluation( + String authorityAvailability, + Boolean allowPublicJoin, + Long entitlementVersion, + boolean gameplayAvailable, + String failureCode) {} + + private record JoinAttemptOutcome(JoinOutcome result, JoinOperation terminalOperation) { + private static JoinAttemptOutcome result(JoinOutcome result) { + return new JoinAttemptOutcome(result, null); + } + + private static JoinAttemptOutcome terminal(JoinOperation operation) { + return new JoinAttemptOutcome(null, operation); + } + } + + private RuntimeEntitlementsDto joinEntitlement(long tenantId, boolean lockSubscription) { + return readTenantEntitlements(tenantId, lockSubscription); + } + private RuntimeEntitlementsDto readTenantEntitlements(long tenantId, boolean lockSubscription) { - // Retained numeric rows cannot supply canonical identity, provider provenance, current-row - // selection, or a committed billing checkpoint. Deny before any historical evidence read. - throw new AuthenticationException( - "ENTITLEMENT_UNAVAILABLE", - "Canonical tenant entitlement authority is unavailable; retry later"); + List rows; + try { + rows = + lockSubscription + ? subscriptionRepository.findByTenantIdForUpdate(tenantId) + : subscriptionRepository.findByTenantId(tenantId); + } catch (org.jooq.exception.MappingException | org.jooq.exception.ConfigurationException ex) { + throw ex; + } catch (org.jooq.exception.DataAccessException | DataAccessException ex) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", + "Tenant entitlement authority is unavailable; retry later", + ex); + } + if (rows == null || rows.size() != 1 || rows.getFirst() == null) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", "Tenant entitlement authority is missing or ambiguous"); + } + var subscription = rows.getFirst(); + if (subscription.getEntitlementVersion() <= 0L) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", "Entitlement version is missing"); + } + return new RuntimeEntitlementsDto( + tenantId, + isGameplayAvailableStatus(subscription.getStatus()), + isPublicJoinAllowedStatus(subscription.getStatus()), + subscription.getEntitlementVersion(), + subscription.getEntitlementVersion(), + Instant.now().toString()); } @Override + @Transactional(readOnly = true) @Timed(value = "account.connect_token") public ConnectTokenResult issueConnectToken(String bootstrapToken, ConnectTokenRequest request) { - throw publicBootstrapUnavailable(); + BootstrapContext bootstrapContext = requireBootstrapContext(bootstrapToken); + ConnectScopeContext scopeContext = requireConnectScopeContext(request.connectScopeId()); + validateConnectScopeAgainstBootstrap(bootstrapContext, scopeContext); + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Canonical gameplay connect-token authority is unavailable"); } @Override @@ -600,11 +1350,385 @@ public RuntimeEntitlementsDto getTenantEntitlementsForRuntime(Long tenantId, Str } private BootstrapContext requireBootstrapContext(String bootstrapToken) { - var caller = - new net.firedevops.firemud.accountservice.service.session - .AccountPlayerBootstrapCallerVerifier(jwtUtil, accountRepository, sessionService) - .requireCaller(bootstrapToken); - return new BootstrapContext(caller.accountId(), caller.accountUuid()); + Claims claims = + requireSignedTokenClaims( + bootstrapToken, + "player-bootstrap", + "CONNECT_CONTEXT_INVALID", + "Missing bootstrap token", + "Invalid bootstrap token"); + UUID subject = + claims.get("sub") instanceof String text ? AccountUuidText.parseOrNull(text) : null; + UUID accountUuid = + claims.get("accountId") instanceof String text ? AccountUuidText.parseOrNull(text) : null; + if (subject == null || accountUuid == null || !subject.equals(accountUuid)) { + throw new AuthenticationException("CONNECT_CONTEXT_INVALID", "Invalid bootstrap token"); + } + final Long accountId; + try { + accountId = resolveAccountStorageId(accountUuid); + } catch (IllegalArgumentException | IllegalStateException | DataAccessException ex) { + throw new AuthenticationException("AUTH_UNAVAILABLE", "Account authority is unavailable", ex); + } + if (!sessionService.isAccountSessionActive(accountId, bootstrapToken)) { + throw new AuthenticationException("CONNECT_CONTEXT_INVALID", "Bootstrap token expired"); + } + return new BootstrapContext(accountId, accountUuid); + } + + private RuntimeRealmTarget requireRealmTarget( + Long expectedTenantId, String worldSlug, String realmSlug) { + try { + List candidates = + listRuntimeRealmTargets(worldSlug, realmSlug).stream() + .filter(realm -> java.util.Objects.equals(worldSlug, realm.worldSlug())) + .filter(realm -> java.util.Objects.equals(realmSlug, realm.realmSlug())) + .filter(realm -> expectedTenantId == null || realm.tenantId() == expectedTenantId) + .toList(); + if (candidates.size() != 1) { + throw new IllegalStateException("Selected gameplay realm is absent or ambiguous"); + } + RuntimeRealmTarget candidate = candidates.getFirst(); + RuntimeRealmTarget realm = + readRuntimeRealmTarget( + gameSessionClient.getAdmissionPointer(candidate.tenantId(), worldSlug, realmSlug)); + if (realm.tenantId() != candidate.tenantId() + || !realm.realmId().equals(candidate.realmId()) + || !realm.playableStateNamespaceId().equals(candidate.playableStateNamespaceId()) + || !realm.stateScope().equals(candidate.stateScope()) + || realm.gameInstanceId() != candidate.gameInstanceId() + || realm.visible() != candidate.visible() + || realm.publicProductionRealm() != candidate.publicProductionRealm() + || realm.catalogRevision() != candidate.catalogRevision() + || realm.pointerVersion() != candidate.pointerVersion() + || !java.util.Objects.equals(worldSlug, realm.worldSlug()) + || !java.util.Objects.equals(realmSlug, realm.realmSlug())) { + throw new AuthenticationException( + "ADMISSION_POINTER_UNAVAILABLE", + "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry"); + } + return realm; + } catch (AuthenticationException ex) { + throw ex; + } catch (RuntimeException ex) { + throw admissionPointerUnavailable(ex); + } + } + + private boolean hasAdmissibleRealm( + BootstrapContext bootstrapContext, + String worldSlug, + Map discoveryEntitlementMemo) { + try { + return !listAdmissibleRuntimeRealmTargets( + bootstrapContext, worldSlug, discoveryEntitlementMemo) + .isEmpty(); + } catch (IllegalStateException ex) { + return false; + } + } + + private List listAdmissibleRuntimeRealmTargets( + BootstrapContext bootstrapContext, + String worldSlug, + Map discoveryEntitlementMemo) { + List realms = + gameSessionClient.listGameplayRealms(worldSlug); + if (realms == null) { + throw new IllegalStateException("Gameplay realm discovery returned no authority"); + } + List targets = + realms.stream() + .map(realm -> readReachableDiscoveryRealm(bootstrapContext, realm)) + .flatMap(Optional::stream) + .toList(); + validatePublicRealmCardinality(targets); + return targets.stream() + .filter( + realm -> isDiscoveryRealmAdmissible(bootstrapContext, realm, discoveryEntitlementMemo)) + .toList(); + } + + private List listRuntimeRealmTargets( + String worldSlug, String selectedRealmSlug) { + try { + List realms = + gameSessionClient.listGameplayRealms(worldSlug); + if (realms == null) { + throw new IllegalStateException("Gameplay realm discovery returned no authority"); + } + var realmStream = realms.stream(); + if (selectedRealmSlug != null) { + realmStream = + realmStream.filter( + realm -> + realm != null + && java.util.Objects.equals(selectedRealmSlug, realm.getRealmSlug())); + } + List targets = realmStream.map(this::readRuntimeRealmTarget).toList(); + validatePublicRealmCardinality(targets); + return targets; + } catch (AuthenticationException ex) { + throw ex; + } catch (RuntimeException ex) { + throw admissionPointerUnavailable(ex); + } + } + + private void validatePublicRealmCardinality(List realms) { + // The RPC is world-local: zero local public realms may be a valid private-only world when the + // tenant's public realm is in another world. Game Session owns the tenant-global zero check; + // Account can defensively reject only duplicate visible public targets returned here. + Map visiblePublicRealmCounts = + realms.stream() + .filter(this::isPublicProductionRealm) + .collect( + java.util.stream.Collectors.groupingBy( + RuntimeRealmTarget::tenantId, java.util.stream.Collectors.counting())); + if (realms.stream() + .map(RuntimeRealmTarget::tenantId) + .distinct() + .anyMatch(tenantId -> visiblePublicRealmCounts.getOrDefault(tenantId, 0L) > 1L)) { + throw admissionPointerUnavailable( + new IllegalStateException("Public production realm authority is ambiguous")); + } + } + + private Optional readReachableDiscoveryRealm( + BootstrapContext bootstrapContext, + net.firedevops.firemud.gamesession.v1.GameplayRealm realm) { + if (realm == null) { + throw admissionPointerUnavailable( + new IllegalArgumentException("Gameplay realm discovery returned a null realm")); + } + final RuntimeRealmTarget target; + try { + target = readRuntimeRealmTarget(realm); + } catch (IllegalArgumentException ex) { + if (isMalformedRealmReachable(bootstrapContext, realm)) { + throw admissionPointerUnavailable(ex); + } + return Optional.empty(); + } + return Optional.of(target); + } + + private boolean isMalformedRealmReachable( + BootstrapContext bootstrapContext, + net.firedevops.firemud.gamesession.v1.GameplayRealm realm) { + if (realm.getVisible() && realm.getPublicProductionRealm()) { + return true; + } + + final long tenantId; + try { + tenantId = requirePositiveLong(realm.getTenantId(), "tenantId"); + } catch (IllegalArgumentException ex) { + return false; + } + if (accountTenantMembershipRepository + .findByAccountIdAndTenantId(bootstrapContext.accountId(), tenantId) + .filter(AccountTenantMembership::isGameplayAdmissionAllowed) + .isEmpty()) { + return false; + } + if (!hasRealmAccessGrant( + bootstrapContext.accountId(), tenantId, realm.getWorldSlug(), realm.getRealmSlug())) { + return false; + } + return true; + } + + private AuthenticationException admissionPointerUnavailable(Throwable cause) { + return new AuthenticationException( + "ADMISSION_POINTER_UNAVAILABLE", + "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry", + cause); + } + + private boolean isDiscoveryRealmAdmissible( + BootstrapContext bootstrapContext, + RuntimeRealmTarget realm, + Map discoveryEntitlementMemo) { + if (!hasRealmAdmissionAccess(bootstrapContext, realm)) { + return false; + } + RuntimeEntitlementsDto entitlements = + discoveryEntitlementMemo.computeIfAbsent( + realm.tenantId(), + tenantId -> getTenantEntitlementsForRuntime(tenantId, "bootstrap-discovery")); + return entitlements.gameplayAvailable(); + } + + private boolean hasRealmAdmissionAccess( + BootstrapContext bootstrapContext, RuntimeRealmTarget realm) { + long tenantId = realm.tenantId(); + if (!isPublicProductionRealm(realm)) { + if (accountTenantMembershipRepository + .findByAccountIdAndTenantId(bootstrapContext.accountId(), tenantId) + .filter(AccountTenantMembership::isGameplayAdmissionAllowed) + .isEmpty()) { + return false; + } + if (!hasRealmAccessGrant( + bootstrapContext.accountId(), tenantId, realm.worldSlug(), realm.realmSlug())) { + return false; + } + } + return true; + } + + private boolean isPublicProductionRealm(RuntimeRealmTarget realm) { + return realm.visible() && realm.publicProductionRealm(); + } + + private boolean sameRuntimeRealmAuthority( + RuntimeRealmTarget expected, RuntimeRealmTarget actual) { + return expected.tenantId() == actual.tenantId() + && expected.realmId().equals(actual.realmId()) + && expected.playableStateNamespaceId().equals(actual.playableStateNamespaceId()) + && expected.gameInstanceId() == actual.gameInstanceId() + && expected.worldSlug().equals(actual.worldSlug()) + && expected.realmSlug().equals(actual.realmSlug()) + && expected.pointerVersion() == actual.pointerVersion() + && expected.catalogRevision() == actual.catalogRevision() + && expected.visible() == actual.visible() + && expected.publicProductionRealm() == actual.publicProductionRealm() + && expected.stateScope().equals(actual.stateScope()) + && expected.characterCreationPolicy().equals(actual.characterCreationPolicy()) + && expected.requiresCharacterSelection() == actual.requiresCharacterSelection(); + } + + private String mintConnectScopeId( + BootstrapContext bootstrapContext, + RuntimeRealmTarget realm, + Instant evaluatedAt, + Instant expiresAt) { + long expirationMs = Math.max(1L, expiresAt.toEpochMilli() - evaluatedAt.toEpochMilli()); + return mintToken( + bootstrapContext.accountUuid().toString(), + expirationMs, + Map.ofEntries( + Map.entry("aud", "bootstrap-connect-scope"), + Map.entry("accountId", bootstrapContext.accountUuid().toString()), + Map.entry("tenantId", realm.tenantId()), + Map.entry("realmId", realm.realmId().toString()), + Map.entry("worldSlug", realm.worldSlug()), + Map.entry("realmSlug", realm.realmSlug()), + Map.entry("playableStateNamespaceId", realm.playableStateNamespaceId()), + Map.entry("playableStateScope", realm.stateScope()), + Map.entry("gameInstanceId", realm.gameInstanceId()), + Map.entry("catalogRevision", realm.catalogRevision()), + Map.entry("pointerVersion", realm.pointerVersion()), + Map.entry("evaluatedAt", evaluatedAt.toString()), + Map.entry("connectScopeExpiresAt", expiresAt.toString()), + Map.entry( + "jti", + stableId( + "connect-scope", + bootstrapContext.accountId(), + Long.toString(realm.tenantId()), + realm.worldSlug(), + realm.realmSlug(), + realm.pointerVersion(), + evaluatedAt.toString())))); + } + + private String mintAndRetainConnectScope( + BootstrapContext caller, RuntimeRealmTarget realm, Instant evaluatedAt, Instant expiresAt) { + try { + if (!Long.valueOf(caller.accountId()).equals(resolveAccountStorageId(caller.accountUuid()))) { + throw new IllegalStateException("Scope Account UUID resolved to a different owner"); + } + } catch (IllegalArgumentException | IllegalStateException | DataAccessException ex) { + throw new AuthenticationException("AUTH_UNAVAILABLE", "Account authority is unavailable", ex); + } + String connectScopeId = mintConnectScopeId(caller, realm, evaluatedAt, expiresAt); + if (isPublicProductionRealm(realm)) { + VerifiedJoinScope pending = + new VerifiedJoinScope( + connectScopeId, + caller.accountId(), + realm.tenantId(), + realm.realmId(), + realm.worldSlug(), + realm.realmSlug(), + realm.playableStateNamespaceId(), + realm.stateScope(), + realm.gameInstanceId(), + realm.catalogRevision(), + realm.pointerVersion(), + evaluatedAt.toString(), + expiresAt.toString(), + ""); + accountConnectScopeRepository.insert( + new VerifiedJoinScope( + pending.connectScopeId(), + pending.accountId(), + pending.tenantId(), + pending.realmId(), + pending.worldSlug(), + pending.realmSlug(), + pending.playableStateNamespaceId(), + pending.playableStateScope(), + pending.gameInstanceId(), + pending.catalogRevision(), + pending.pointerVersion(), + pending.evaluatedAt(), + pending.connectScopeExpiresAt(), + AccountJoinDigest.scope(pending))); + } + return connectScopeId; + } + + private ConnectScopeContext requireConnectScopeContext(String connectScopeId) { + Claims claims = + requireSignedTokenClaims( + connectScopeId, + "bootstrap-connect-scope", + "CONNECT_SCOPE_INVALID", + INVALID_CONNECT_SCOPE_MESSAGE, + INVALID_CONNECT_SCOPE_MESSAGE); + try { + JwtClaims.SignedGameplayRoutingClaims routingClaims = + JwtClaims.requireSignedGameplayRoutingClaims( + claims, "signed token account subject mismatch"); + Instant connectScopeExpiresAt = parseInstant(claims.get("connectScopeExpiresAt")); + Instant evaluatedAt = parseInstant(claims.get("evaluatedAt")); + if (connectScopeExpiresAt == null) { + throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); + } + if (evaluatedAt == null) { + throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); + } + UUID realmId = requireCanonicalRealmId(claims.get("realmId")); + String namespace = + JwtClaims.requireText(claims.get("playableStateNamespaceId"), "playableStateNamespaceId"); + String scope = JwtClaims.requireText(claims.get("playableStateScope"), "playableStateScope"); + long catalogRevision = requirePositiveLong(claims.get("catalogRevision"), "catalogRevision"); + final Long accountId; + try { + accountId = resolveAccountStorageId(UUID.fromString(routingClaims.accountId())); + } catch (IllegalArgumentException | IllegalStateException | DataAccessException ex) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Account authority is unavailable", ex); + } + return new ConnectScopeContext( + accountId, + routingClaims.tenantId(), + realmId, + routingClaims.worldSlug(), + routingClaims.realmSlug(), + namespace, + scope, + routingClaims.gameInstanceId(), + catalogRevision, + routingClaims.pointerVersion(), + evaluatedAt, + connectScopeExpiresAt); + } catch (IllegalArgumentException ex) { + throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE, ex); + } } private Claims requireSignedTokenClaims( @@ -632,6 +1756,93 @@ private Claims requireSignedTokenClaims( } } + private void validateConnectScopeAgainstBootstrap( + BootstrapContext bootstrapContext, ConnectScopeContext scopeContext) { + if (scopeContext.accountId() != bootstrapContext.accountId()) { + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); + } + } + + private void validateConnectScopeRoute( + ConnectScopeContext scopeContext, String worldSlug, String realmSlug) { + if (!java.util.Objects.equals(scopeContext.worldSlug(), worldSlug) + || !java.util.Objects.equals(scopeContext.realmSlug(), realmSlug)) { + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); + } + } + + private RuntimeRealmTarget requireCurrentConnectScopeTarget(ConnectScopeContext scopeContext) { + RuntimeRealmTarget currentRealm = + requireRealmTarget( + scopeContext.tenantId(), scopeContext.worldSlug(), scopeContext.realmSlug()); + if (currentRealm.tenantId() != scopeContext.tenantId() + || !currentRealm.realmId().equals(scopeContext.realmId()) + || !currentRealm.playableStateNamespaceId().equals(scopeContext.playableStateNamespaceId()) + || !currentRealm.stateScope().equals(scopeContext.playableStateScope()) + || currentRealm.gameInstanceId() != scopeContext.gameInstanceId() + || currentRealm.catalogRevision() != scopeContext.catalogRevision() + || currentRealm.pointerVersion() != scopeContext.pointerVersion()) { + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); + } + return currentRealm; + } + + private RuntimeRealmTarget requireCurrentAdmissibleConnectScopeTarget( + BootstrapContext bootstrapContext, ConnectScopeContext scopeContext) { + RuntimeRealmTarget currentRealm = requireCurrentConnectScopeTarget(scopeContext); + RuntimeEntitlementsDto entitlements = + getTenantEntitlementsForRuntime(currentRealm.tenantId(), "bootstrap-characters"); + if (!entitlements.gameplayAvailable()) { + throw new AuthenticationException( + "TENANT_BILLING_BLOCKED", "Gameplay is not available for this tenant"); + } + + boolean publicProductionRealm = isPublicProductionRealm(currentRealm); + Optional maybeMembership = + accountTenantMembershipRepository.findByAccountIdAndTenantId( + bootstrapContext.accountId(), currentRealm.tenantId()); + if (maybeMembership.isPresent() + && "INACTIVE".equals(maybeMembership.orElseThrow().getLifecycleState()) + && publicProductionRealm) { + if (!entitlements.allowPublicJoin()) { + throw new AuthenticationException( + "PUBLIC_PRODUCTION_ADMISSION_DENIED", + "Public joining is not allowed for the selected game"); + } + throw new AuthenticationException("JOIN_REQUIRED", JOIN_REQUIRED_CHARACTERS_MESSAGE); + } + if (maybeMembership.isPresent() + && !maybeMembership.orElseThrow().isGameplayAdmissionAllowed()) { + throw new AuthenticationException( + "CONNECT_TOKEN_REJECTED", "Gameplay admission is not allowed for this account"); + } + if (maybeMembership.isEmpty()) { + if (!publicProductionRealm) { + throw new AuthenticationException( + "NON_PUBLIC_ENROLLMENT_REQUIRED", + "Existing game membership is required for this non-public realm"); + } + if (!entitlements.allowPublicJoin()) { + throw new AuthenticationException( + "PUBLIC_PRODUCTION_ADMISSION_DENIED", + "Public joining is not allowed for the selected game"); + } + throw new AuthenticationException("JOIN_REQUIRED", JOIN_REQUIRED_CHARACTERS_MESSAGE); + } + + if (!publicProductionRealm + && !hasRealmAccessGrant( + bootstrapContext.accountId(), + currentRealm.tenantId(), + currentRealm.worldSlug(), + currentRealm.realmSlug())) { + throw new AuthenticationException( + "ADMISSION_POINTER_UNAVAILABLE", + "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry"); + } + return currentRealm; + } + private Optional findAccountForAuthentication(String usernameOrEmail) { Optional emailMatch = accountRepository.findByEmail(EmailCanonicalization.normalize(usernameOrEmail)); @@ -1039,6 +2250,12 @@ private long requireAccountStorageId(Account account, UUID accountUuid) { return account.getId(); } + private boolean hasRealmAccessGrant( + Long accountId, Long tenantId, String worldSlug, String realmSlug) { + return accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( + accountId, tenantId, worldSlug, realmSlug); + } + private String mintToken(String subject, long expirationMs, Map claims) { return jwtUtil.generateToken(subject, expirationMs, claims); } @@ -1059,6 +2276,56 @@ private Map authenticationTokenClaims(String audience, Account a UUID.randomUUID().toString()); } + private Instant parseInstant(Object value) { + if (value == null) { + return null; + } + try { + return Instant.parse(value.toString()); + } catch (RuntimeException ex) { + return null; + } + } + + private String stableId(Object... components) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + for (Object component : components) { + digest.update(String.valueOf(component).getBytes(StandardCharsets.UTF_8)); + digest.update((byte) 0); + } + byte[] encoded = digest.digest(); + StringBuilder builder = new StringBuilder(encoded.length * 2); + for (byte value : encoded) { + builder.append(Character.forDigit((value >> 4) & 0xF, 16)); + builder.append(Character.forDigit(value & 0xF, 16)); + } + return builder.toString(); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("Missing SHA-256 implementation", ex); + } + } + + private boolean isGameplayAvailableStatus(String status) { + if (status == null) { + return false; + } + return switch (status.trim().toLowerCase(java.util.Locale.ROOT)) { + case "active", "trialing", "past_due", "grace" -> true; + default -> false; + }; + } + + private boolean isPublicJoinAllowedStatus(String status) { + if (status == null) { + return false; + } + return switch (status.trim().toLowerCase(java.util.Locale.ROOT)) { + case "active", "trialing", "past_due" -> true; + default -> false; + }; + } + @Override @Transactional(readOnly = true) @Timed(value = "account.get_profile") @@ -1209,9 +2476,9 @@ public void deleteAccount(Long accountId) { "ACCOUNT_DELETE_JOIN_RECEIPT_RETAINED", "Account JOIN receipts require retention and deletion reconciliation"); } - List subscriptions = - retainedSubscriptionEvidenceRepository.findHistoryByAccountId(accountId); - Optional blockingSubscription = + List subscriptions = + subscriptionRepository.findByAccountId(accountId); + Optional blockingSubscription = subscriptions.stream().filter(this::isNonterminalSubscription).findFirst(); if (blockingSubscription.isPresent()) { throw new AccountLifecycleException( @@ -1224,17 +2491,18 @@ public void deleteAccount(Long accountId) { + "deletion reconciliation are implemented"); } - private boolean isNonterminalSubscription(RetainedSubscriptionEvidence subscription) { + private boolean isNonterminalSubscription( + net.firedevops.firemud.accountservice.entity.Subscription subscription) { String status = - subscription.status() == null + subscription.getStatus() == null ? "" - : subscription.status().trim().toLowerCase(java.util.Locale.ROOT); + : subscription.getStatus().trim().toLowerCase(java.util.Locale.ROOT); boolean terminalStatus = switch (status) { case "canceled", "cancelled", "ended", "expired" -> true; default -> false; }; - return !terminalStatus || subscription.endedAt() == null; + return !terminalStatus || subscription.getEndedAt() == null; } @Override @@ -2130,4 +3398,176 @@ public void afterCommit() { } private record BootstrapContext(long accountId, UUID accountUuid) {} + + private record JoinAuditPayload( + long accountId, + long tenantId, + String worldSlug, + String realmSlug, + long membershipVersion, + String requestId) {} + + private RuntimeRealmTarget readRuntimeRealmTarget( + net.firedevops.firemud.gamesession.v1.GameplayRealm realm) { + return buildRuntimeRealmTarget( + realm.getTenantId(), + realm.getRealmId(), + realm.getPlayableStateNamespaceId(), + realm.getGameInstanceId(), + realm.getCatalogRevision(), + realm.getPointerVersion(), + realm.getWorldSlug(), + realm.getRealmSlug(), + realm.getVisible(), + realm.getPublicProductionRealm(), + realm.getStateScope(), + realm.getCharacterCreationPolicy(), + realm.getRequiresCharacterSelection(), + realm.getDisplayName()); + } + + private RuntimeRealmTarget readRuntimeRealmTarget( + net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer realm) { + return buildRuntimeRealmTarget( + realm.getTenantId(), + realm.getRealmId(), + realm.getPlayableStateNamespaceId(), + realm.getGameInstanceId(), + realm.getCatalogRevision(), + realm.getPointerVersion(), + realm.getWorldSlug(), + realm.getRealmSlug(), + realm.getVisible(), + realm.getPublicProductionRealm(), + realm.getStateScope(), + realm.getCharacterCreationPolicy(), + realm.getRequiresCharacterSelection(), + realm.getRealmDisplayName()); + } + + private RuntimeRealmTarget buildRuntimeRealmTarget( + String tenantIdText, + String realmIdText, + String playableStateNamespaceId, + String gameInstanceIdText, + long catalogRevision, + long pointerVersion, + String worldSlug, + String realmSlug, + boolean visible, + boolean publicProductionRealm, + String stateScope, + String characterCreationPolicy, + boolean requiresCharacterSelection, + String displayName) { + long tenantId = requirePositiveLong(tenantIdText, "tenantId"); + UUID realmId = requireCanonicalRealmId(realmIdText); + long gameInstanceId = requirePositiveLong(gameInstanceIdText, "gameInstanceId"); + String canonicalPlayableStateNamespaceId = + requireCanonicalPlayableStateNamespaceId(playableStateNamespaceId); + if (catalogRevision <= 0) { + throw new IllegalArgumentException("catalogRevision must be positive"); + } + if (pointerVersion <= 0) { + throw new IllegalArgumentException("pointerVersion must be positive"); + } + if (!StringUtils.hasText(worldSlug)) { + throw new IllegalArgumentException("worldSlug is required"); + } + if (!StringUtils.hasText(realmSlug)) { + throw new IllegalArgumentException("realmSlug is required"); + } + if (!"SHARED".equals(stateScope) && !"ISOLATED".equals(stateScope)) { + throw new IllegalArgumentException("stateScope must be SHARED or ISOLATED"); + } + return new RuntimeRealmTarget( + tenantId, + realmId, + canonicalPlayableStateNamespaceId, + gameInstanceId, + worldSlug, + realmSlug, + pointerVersion, + catalogRevision, + visible, + publicProductionRealm, + stateScope, + characterCreationPolicy, + requiresCharacterSelection, + displayName); + } + + private PlayableStateScope toPlayableStateScope(RuntimeRealmTarget realm) { + if ("SHARED".equals(realm.stateScope())) { + return PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED; + } + if ("ISOLATED".equals(realm.stateScope())) { + return PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED; + } + throw new IllegalArgumentException("stateScope must be SHARED or ISOLATED"); + } + + private long requirePositiveLong(Object value, String field) { + return JwtClaims.requireLong(value, field, false); + } + + private UUID requireCanonicalRealmId(Object value) { + if (!(value instanceof String text) || text.isBlank()) { + throw new IllegalArgumentException("realmId must be a canonical UUID"); + } + try { + UUID realmId = UUID.fromString(text); + if (!realmId.toString().equals(text)) { + throw new IllegalArgumentException("realmId must be a canonical UUID"); + } + return realmId; + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("realmId must be a canonical UUID", ex); + } + } + + private String requireCanonicalPlayableStateNamespaceId(String value) { + if (!StringUtils.hasText(value)) { + throw new IllegalArgumentException("playableStateNamespaceId is required"); + } + try { + UUID namespaceId = UUID.fromString(value); + if (!namespaceId.toString().equals(value)) { + throw new IllegalArgumentException("playableStateNamespaceId must be a canonical UUID"); + } + return value; + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("playableStateNamespaceId must be a canonical UUID", ex); + } + } + + private record ConnectScopeContext( + long accountId, + long tenantId, + UUID realmId, + String worldSlug, + String realmSlug, + String playableStateNamespaceId, + String playableStateScope, + long gameInstanceId, + long catalogRevision, + long pointerVersion, + Instant evaluatedAt, + Instant connectScopeExpiresAt) {} + + private record RuntimeRealmTarget( + long tenantId, + UUID realmId, + String playableStateNamespaceId, + long gameInstanceId, + String worldSlug, + String realmSlug, + long pointerVersion, + long catalogRevision, + boolean visible, + boolean publicProductionRealm, + String stateScope, + String characterCreationPolicy, + boolean requiresCharacterSelection, + String displayName) {} } diff --git a/services/account-service/src/main/resources/db/migration/V1028__retain_non_authorizing_subscription_evidence.sql b/services/account-service/src/main/resources/db/migration/V1028__retain_non_authorizing_subscription_evidence.sql deleted file mode 100644 index c5d5ff151d..0000000000 --- a/services/account-service/src/main/resources/db/migration/V1028__retain_non_authorizing_subscription_evidence.sql +++ /dev/null @@ -1,44 +0,0 @@ --- Preview-only containment: retain the original heap, not a copy/backfill. No UUID --- subscription, owner, provider mapping, winner or billing sequence is inferred. -/* [jooq ignore start] */ -LOCK TABLE subscription IN ACCESS EXCLUSIVE MODE; -/* [jooq ignore stop] */ - -ALTER TABLE subscription RENAME TO account_retained_subscription_evidence; --- PostgreSQL-generated object names are absent from the jOOQ/H2 schema simulator. -/* [jooq ignore start] */ -ALTER TABLE account_retained_subscription_evidence - RENAME CONSTRAINT subscription_pkey TO account_retained_subscription_evidence_pkey; -ALTER TABLE account_retained_subscription_evidence - RENAME CONSTRAINT subscription_account_id_fkey TO account_retained_subscription_evidence_account_fk; -ALTER TABLE account_retained_subscription_evidence - RENAME CONSTRAINT subscription_entitlement_version_positive TO account_retained_subscription_evidence_version_positive; -ALTER TABLE account_retained_subscription_evidence - RENAME CONSTRAINT subscription_tenant_authority_generation_non_nil TO account_retained_subscription_evidence_generation_non_nil; -ALTER INDEX idx_subscription_account_id RENAME TO idx_account_retained_subscription_evidence_account; -ALTER INDEX idx_subscription_tenant_id RENAME TO idx_account_retained_subscription_evidence_tenant; -ALTER SEQUENCE subscription_id_seq RENAME TO account_retained_subscription_evidence_id_seq; -/* [jooq ignore stop] */ - -/* [jooq ignore start] */ -DROP TRIGGER subscription_authority_generation_advance ON account_retained_subscription_evidence; --- RESTRICT is deliberate: an unexpected user of the obsolete function aborts --- this whole transactional migration, including the rename, without row changes. -DROP FUNCTION advance_subscription_authority_generation() RESTRICT; - -CREATE FUNCTION account_retained_subscription_evidence_refuse_mutation() RETURNS trigger AS $$ -BEGIN - RAISE EXCEPTION 'Retained subscription evidence is immutable and non-authorizing' - USING ERRCODE = '23514'; -END; -$$ LANGUAGE plpgsql; - -CREATE TRIGGER account_retained_subscription_evidence_immutable - BEFORE INSERT OR UPDATE OR DELETE OR TRUNCATE ON account_retained_subscription_evidence - FOR EACH STATEMENT EXECUTE FUNCTION account_retained_subscription_evidence_refuse_mutation(); -ALTER TABLE account_retained_subscription_evidence - ENABLE ALWAYS TRIGGER account_retained_subscription_evidence_immutable; -/* [jooq ignore stop] */ - -COMMENT ON TABLE account_retained_subscription_evidence IS - 'Immutable numeric historical evidence only. Not subscription, billing-owner, provider or production entitlement authority.'; diff --git a/services/account-service/src/main/resources/db/migration/V1029__canonical_subscription_intent_and_provider_history.sql b/services/account-service/src/main/resources/db/migration/V1029__canonical_subscription_intent_and_provider_history.sql deleted file mode 100644 index c2418e52a7..0000000000 --- a/services/account-service/src/main/resources/db/migration/V1029__canonical_subscription_intent_and_provider_history.sql +++ /dev/null @@ -1,494 +0,0 @@ --- One new, initially empty UUID owner. Numeric evidence remains untouched in the V1028 archive. --- No provider dispatch, verified lifecycle producer, transfer, entitlement or runtime grant. -CREATE TABLE subscription_create_operations ( - request_id UUID PRIMARY KEY CHECK (request_id <> '00000000-0000-0000-0000-000000000000'::UUID), - subscription_id UUID NOT NULL UNIQUE CHECK (subscription_id <> '00000000-0000-0000-0000-000000000000'::UUID), - tenant_id UUID NOT NULL REFERENCES account_tenant_billing_owners(tenant_uuid) ON DELETE RESTRICT, - account_uuid UUID NOT NULL REFERENCES accounts(account_uuid) ON DELETE RESTRICT, - owner_version BIGINT NOT NULL CHECK (owner_version > 0), - owner_generation UUID NOT NULL CHECK (owner_generation <> '00000000-0000-0000-0000-000000000000'::UUID), - actor_account_uuid UUID NOT NULL REFERENCES accounts(account_uuid) ON DELETE RESTRICT, - authorization_operation_id UUID NOT NULL CHECK (authorization_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID), - authorization_digest VARCHAR(71) NOT NULL CHECK (authorization_digest ~ '^sha256:[0-9a-f]{64}$'), - plan_code VARCHAR(255) NOT NULL CHECK (length(btrim(plan_code)) > 0 AND plan_code = btrim(plan_code)), - plan_quote_payload BYTEA NOT NULL CHECK (octet_length(plan_quote_payload) BETWEEN 1 AND 4096), - plan_quote_digest VARCHAR(71) NOT NULL CHECK (plan_quote_digest ~ '^sha256:[0-9a-f]{64}$') - CHECK (plan_quote_digest = 'sha256:' || encode(sha256(plan_quote_payload), 'hex')), - provider_price_id VARCHAR(255) NOT NULL CHECK (provider_price_id ~ '^price_[A-Za-z0-9]+$'), - provider_quantity BIGINT NOT NULL CHECK (provider_quantity > 0), - max_active_sessions BIGINT NOT NULL CHECK (max_active_sessions >= 0), - max_concurrent_game_instances BIGINT NOT NULL CHECK (max_concurrent_game_instances >= 0), - max_storage_bytes BIGINT NOT NULL CHECK (max_storage_bytes >= 0), - payment_instrument_id UUID NOT NULL REFERENCES payment_instrument(instrument_uuid) ON DELETE RESTRICT, - reserved_instrument_version BIGINT NOT NULL CHECK (reserved_instrument_version > 0), - customer_provisioning_request_id UUID NOT NULL REFERENCES billing_customer(customer_provisioning_request_id) ON DELETE RESTRICT, - provider_customer_id VARCHAR(255) NOT NULL, - subscription_provisioning_request_id UUID NOT NULL UNIQUE - CHECK (subscription_provisioning_request_id <> '00000000-0000-0000-0000-000000000000'::UUID), - cleanup_provider_identity UUID NOT NULL UNIQUE - CHECK (cleanup_provider_identity <> '00000000-0000-0000-0000-000000000000'::UUID), - request_payload BYTEA NOT NULL CHECK (octet_length(request_payload) BETWEEN 1 AND 1048576), - request_digest VARCHAR(71) NOT NULL CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$') - CHECK (request_digest = 'sha256:' || encode(sha256(request_payload), 'hex')), - replaced_subscription_id UUID, - replaced_row_version BIGINT CHECK (replaced_row_version > 0), - -- The immutable creation result is these columns, not a later mutable lifecycle snapshot. - result_status VARCHAR(16) NOT NULL DEFAULT 'pending' CHECK (result_status = 'pending'), - result_row_version BIGINT NOT NULL DEFAULT 1 CHECK (result_row_version = 1), - created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), - CHECK ((replaced_subscription_id IS NULL) = (replaced_row_version IS NULL)), - CHECK (request_id <> subscription_provisioning_request_id AND request_id <> cleanup_provider_identity - AND subscription_provisioning_request_id <> cleanup_provider_identity - AND customer_provisioning_request_id NOT IN (request_id, subscription_provisioning_request_id, cleanup_provider_identity)), - UNIQUE (request_id, subscription_id), - UNIQUE (request_id, plan_quote_digest), - UNIQUE (request_id, subscription_provisioning_request_id), - UNIQUE (request_id, cleanup_provider_identity), - UNIQUE (request_id, subscription_id, payment_instrument_id, reserved_instrument_version), - FOREIGN KEY (account_uuid, customer_provisioning_request_id, provider_customer_id) - REFERENCES billing_customer(account_uuid, customer_provisioning_request_id, provider_customer_id) ON DELETE RESTRICT -); - -CREATE TABLE subscription ( - subscription_id UUID PRIMARY KEY, - tenant_id UUID NOT NULL REFERENCES account_tenant_billing_owners(tenant_uuid) ON DELETE RESTRICT, - account_uuid UUID NOT NULL REFERENCES accounts(account_uuid) ON DELETE RESTRICT, - owner_version BIGINT NOT NULL CHECK (owner_version > 0), - owner_generation UUID NOT NULL, - plan_code VARCHAR(255) NOT NULL, - -- The exact current quote is retained by the immutable operation, not reconstructed from a - -- mutable plan catalog. This digest couples the current read to that original snapshot. - plan_quote_digest VARCHAR(71) NOT NULL, - payment_instrument_id UUID NOT NULL REFERENCES payment_instrument(instrument_uuid) ON DELETE RESTRICT, - reserved_instrument_version BIGINT NOT NULL CHECK (reserved_instrument_version > 0), - customer_provisioning_request_id UUID NOT NULL REFERENCES billing_customer(customer_provisioning_request_id) ON DELETE RESTRICT, - provider_customer_id VARCHAR(255) NOT NULL, - creation_request_id UUID NOT NULL UNIQUE, - row_version BIGINT NOT NULL CHECK (row_version > 0), - status VARCHAR(16) NOT NULL CHECK (status IN ('pending','provisioning','trialing','active','past_due','grace','suspended','canceled')), - provider_subscription_id VARCHAR(255) CHECK (provider_subscription_id ~ '^sub_[A-Za-z0-9]+$'), - terminal_resolution_id UUID, - superseded_at TIMESTAMPTZ, - superseded_by_request_id UUID UNIQUE, - created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), - CHECK (status NOT IN ('trialing','active','past_due','grace','suspended') OR provider_subscription_id IS NOT NULL), - -- Effective hosting cutoff and provider retirement are separate: a scheduled end may close - -- hosting before a provider-terminal read permits retiring the instrument reservation. - CHECK (terminal_resolution_id IS NULL OR status = 'canceled'), - CHECK ((superseded_at IS NULL) = (superseded_by_request_id IS NULL)), - CHECK (superseded_at IS NULL OR status = 'canceled'), - UNIQUE (creation_request_id, subscription_id), - FOREIGN KEY (creation_request_id, subscription_id) - REFERENCES subscription_create_operations(request_id, subscription_id) DEFERRABLE INITIALLY DEFERRED, - FOREIGN KEY (creation_request_id, plan_quote_digest) - REFERENCES subscription_create_operations(request_id, plan_quote_digest) ON DELETE RESTRICT, - FOREIGN KEY (superseded_by_request_id) REFERENCES subscription_create_operations(request_id) DEFERRABLE INITIALLY DEFERRED -); -ALTER TABLE subscription_create_operations ADD CONSTRAINT subscription_create_current_pair_fk - FOREIGN KEY (request_id, subscription_id) REFERENCES subscription(creation_request_id, subscription_id) - DEFERRABLE INITIALLY DEFERRED; -ALTER TABLE subscription_create_operations ADD CONSTRAINT subscription_create_replaced_fk - FOREIGN KEY (replaced_subscription_id) REFERENCES subscription(subscription_id) ON DELETE RESTRICT; - --- A shared key registry prevents even cross-role reuse between different subscription creates. -CREATE TABLE subscription_create_provider_identities ( - provider_identity UUID PRIMARY KEY, - request_id UUID NOT NULL REFERENCES subscription_create_operations(request_id) ON DELETE RESTRICT, - purpose VARCHAR(16) NOT NULL CHECK (purpose IN ('CREATE','CLEANUP')), - UNIQUE (request_id, purpose) -); - -CREATE TABLE subscription_instrument_reservations ( - request_id UUID PRIMARY KEY, - subscription_id UUID NOT NULL UNIQUE, - payment_instrument_id UUID NOT NULL, - instrument_version BIGINT NOT NULL CHECK (instrument_version > 0), - terminal_resolution_id UUID UNIQUE, - released_at TIMESTAMPTZ, - CHECK ((terminal_resolution_id IS NULL) = (released_at IS NULL)), - FOREIGN KEY (request_id, subscription_id, payment_instrument_id, instrument_version) - REFERENCES subscription_create_operations(request_id, subscription_id, payment_instrument_id, reserved_instrument_version) - ON DELETE RESTRICT, - UNIQUE (request_id, subscription_id) -); -CREATE INDEX idx_subscription_instrument_hold ON subscription_instrument_reservations(payment_instrument_id) - WHERE released_at IS NULL; - --- An immutable local work intent, NOT a dispatched item or lifecycle-event authority bridge. -CREATE TABLE subscription_create_outbox ( - request_id UUID PRIMARY KEY, - subscription_id UUID NOT NULL UNIQUE, - work_kind VARCHAR(40) NOT NULL CHECK (work_kind = 'SUBSCRIPTION_PROVISIONING_INTENT'), - created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), - FOREIGN KEY (request_id, subscription_id) REFERENCES subscription_create_operations(request_id, subscription_id) ON DELETE RESTRICT, - UNIQUE (request_id, subscription_id) -); -ALTER TABLE subscription_create_operations ADD CONSTRAINT subscription_create_reservation_pair_fk - FOREIGN KEY (request_id, subscription_id) REFERENCES subscription_instrument_reservations(request_id, subscription_id) - DEFERRABLE INITIALLY DEFERRED; -ALTER TABLE subscription_create_operations ADD CONSTRAINT subscription_create_outbox_pair_fk - FOREIGN KEY (request_id, subscription_id) REFERENCES subscription_create_outbox(request_id, subscription_id) - DEFERRABLE INITIALLY DEFERRED; - -CREATE TABLE subscription_provider_history ( - provider_subscription_id VARCHAR(255) PRIMARY KEY CHECK (provider_subscription_id ~ '^sub_[A-Za-z0-9]+$'), - subscription_id UUID NOT NULL REFERENCES subscription(subscription_id) ON DELETE RESTRICT, - operation_kind VARCHAR(32) NOT NULL CHECK (operation_kind = 'SUBSCRIPTION_PROVISIONING'), - request_id UUID NOT NULL, - provider_operation_id UUID NOT NULL, - -- Transfer roles/references require the genuine transfer owner, not an invented operation. - role VARCHAR(16) NOT NULL CHECK (role = 'canonical'), - effective_at TIMESTAMPTZ NOT NULL, - evidence_digest VARCHAR(71) NOT NULL CHECK (evidence_digest ~ '^sha256:[0-9a-f]{64}$'), - recorded_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), - UNIQUE (provider_subscription_id, subscription_id), - UNIQUE (request_id), - FOREIGN KEY (request_id, subscription_id) REFERENCES subscription_create_operations(request_id, subscription_id) ON DELETE RESTRICT, - FOREIGN KEY (request_id, provider_operation_id) - REFERENCES subscription_create_operations(request_id, subscription_provisioning_request_id) ON DELETE RESTRICT -); -ALTER TABLE subscription ADD CONSTRAINT subscription_confirmed_provider_history_fk - FOREIGN KEY (provider_subscription_id, subscription_id) - REFERENCES subscription_provider_history(provider_subscription_id, subscription_id) DEFERRABLE INITIALLY DEFERRED; - --- Separate immutable terminal evidence; inserting a history mapping cannot imply cancellation. --- No public writer exists until provider reconciliation and local cleanup are genuinely composed. -CREATE TABLE subscription_provider_terminal_resolutions ( - resolution_id UUID PRIMARY KEY CHECK (resolution_id <> '00000000-0000-0000-0000-000000000000'::UUID), - request_id UUID NOT NULL UNIQUE, - subscription_id UUID NOT NULL UNIQUE, - cleanup_provider_identity UUID NOT NULL, - provider_subscription_id VARCHAR(255), - outcome VARCHAR(24) NOT NULL CHECK (outcome IN ('PROVIDER_ABSENT','CANCELED')), - effective_at TIMESTAMPTZ NOT NULL, - evidence_digest VARCHAR(71) NOT NULL CHECK (evidence_digest ~ '^sha256:[0-9a-f]{64}$'), - recorded_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), - CHECK ((outcome = 'PROVIDER_ABSENT') = (provider_subscription_id IS NULL)), - UNIQUE (resolution_id, subscription_id), - FOREIGN KEY (request_id, subscription_id) REFERENCES subscription_create_operations(request_id, subscription_id) ON DELETE RESTRICT, - FOREIGN KEY (request_id, cleanup_provider_identity) - REFERENCES subscription_create_operations(request_id, cleanup_provider_identity) ON DELETE RESTRICT, - FOREIGN KEY (provider_subscription_id, subscription_id) - REFERENCES subscription_provider_history(provider_subscription_id, subscription_id) ON DELETE RESTRICT -); -ALTER TABLE subscription ADD CONSTRAINT subscription_terminal_resolution_fk - FOREIGN KEY (terminal_resolution_id, subscription_id) - REFERENCES subscription_provider_terminal_resolutions(resolution_id, subscription_id) DEFERRABLE INITIALLY DEFERRED; -ALTER TABLE subscription_instrument_reservations ADD CONSTRAINT subscription_reservation_resolution_fk - FOREIGN KEY (terminal_resolution_id, subscription_id) - REFERENCES subscription_provider_terminal_resolutions(resolution_id, subscription_id) DEFERRABLE INITIALLY DEFERRED; - -CREATE TABLE subscription_current_observations ( - subscription_id UUID NOT NULL REFERENCES subscription(subscription_id) ON DELETE RESTRICT, - row_version BIGINT NOT NULL CHECK (row_version > 0), - status VARCHAR(16) NOT NULL, - provider_subscription_id VARCHAR(255), - terminal_resolution_id UUID, - superseded_at TIMESTAMPTZ, - superseded_by_request_id UUID, - recorded_at TIMESTAMPTZ NOT NULL, - PRIMARY KEY (subscription_id, row_version) -); - --- [jooq ignore start] --- The canonical relation is new and empty. No old numeric row is a duplicate candidate/winner. --- Fence this new owner while checking the exact index candidates, not another schema catalog. -LOCK TABLE subscription IN ACCESS EXCLUSIVE MODE; -DO $$ -BEGIN - IF EXISTS (SELECT tenant_id FROM subscription WHERE superseded_at IS NULL GROUP BY tenant_id HAVING count(*) > 1) - OR EXISTS (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) THEN - RAISE EXCEPTION 'Canonical subscription candidates require explicit reconciliation'; - END IF; -END; -$$; --- [jooq ignore stop] -CREATE UNIQUE INDEX uq_subscription_active_tenant ON subscription(tenant_id) WHERE superseded_at IS NULL; -CREATE UNIQUE INDEX uq_subscription_active_provider ON subscription(provider_subscription_id) - WHERE superseded_at IS NULL AND provider_subscription_id IS NOT NULL; - --- [jooq ignore start] -CREATE FUNCTION account_subscription_no_mutation() RETURNS TRIGGER LANGUAGE plpgsql AS $$ -BEGIN - RAISE EXCEPTION 'Canonical subscription evidence is retained and immutable' USING ERRCODE = '23514'; -END; -$$; - -CREATE FUNCTION account_subscription_create_source_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ -DECLARE - wallet payment_instrument%ROWTYPE; - customer billing_customer%ROWTYPE; - owner account_tenant_billing_owners%ROWTYPE; - previous subscription%ROWTYPE; -BEGIN - -- Same lock order as V1027 repositories: Account -> customer -> instrument -> tenant owner. - PERFORM 1 FROM accounts WHERE account_uuid = NEW.account_uuid FOR UPDATE; - SELECT * INTO STRICT customer FROM billing_customer WHERE account_uuid = NEW.account_uuid FOR UPDATE; - SELECT * INTO STRICT wallet FROM payment_instrument WHERE instrument_uuid = NEW.payment_instrument_id FOR UPDATE; - SELECT * INTO STRICT owner FROM account_tenant_billing_owners WHERE tenant_uuid = NEW.tenant_id FOR UPDATE; - IF convert_from(NEW.plan_quote_payload, 'UTF8')::jsonb IS DISTINCT FROM jsonb_build_object( - 'schemaVersion', 'account-hosting-plan-quote/v1', 'planCode', NEW.plan_code, - 'providerPriceId', NEW.provider_price_id, 'providerQuantity', NEW.provider_quantity::text, - 'maxActiveSessions', NEW.max_active_sessions::text, - 'maxConcurrentGameInstances', NEW.max_concurrent_game_instances::text, - 'maxStorageBytes', NEW.max_storage_bytes::text) THEN - RAISE EXCEPTION 'Subscription hosting quote differs from its exact retained fields' USING ERRCODE = '23514'; - END IF; - IF (owner.owner_account_uuid, owner.owner_version, owner.owner_generation) - IS DISTINCT FROM (NEW.account_uuid, NEW.owner_version, NEW.owner_generation) - OR (wallet.account_uuid, wallet.row_version, wallet.customer_provisioning_request_id, wallet.provider_customer_id) - IS DISTINCT FROM (NEW.account_uuid, NEW.reserved_instrument_version, NEW.customer_provisioning_request_id, NEW.provider_customer_id) - OR wallet.state <> 'ATTACHABLE' OR customer.state <> 'CONFIRMED' - OR customer.provider_customer_id IS DISTINCT FROM NEW.provider_customer_id - OR customer.provider_idempotency_id IN (NEW.request_id, NEW.subscription_provisioning_request_id, NEW.cleanup_provider_identity) - OR convert_from(NEW.request_payload, 'UTF8')::jsonb IS DISTINCT FROM jsonb_build_object( - 'schemaVersion', 'account-subscription-create-request/v1', 'tenantId', NEW.tenant_id::text, - 'ownerAccountId', NEW.account_uuid::text, 'planCode', NEW.plan_code, - 'instrumentSelection', jsonb_build_object('kind', 'EXACT_SAVED_INSTRUMENT', 'paymentInstrumentId', NEW.payment_instrument_id::text)) THEN - RAISE EXCEPTION 'Subscription create owner, wallet or normalized request fence rejected' USING ERRCODE = '23514'; - END IF; - IF NEW.replaced_subscription_id IS NOT NULL THEN - SELECT * INTO STRICT previous FROM subscription WHERE subscription_id = NEW.replaced_subscription_id FOR UPDATE; - IF previous.tenant_id <> NEW.tenant_id OR previous.status <> 'canceled' - OR previous.terminal_resolution_id IS NULL - OR previous.row_version <> NEW.replaced_row_version + 1 - OR previous.superseded_by_request_id IS DISTINCT FROM NEW.request_id THEN - RAISE EXCEPTION 'Canceled subscription replacement fence rejected' USING ERRCODE = '23514'; - END IF; - ELSIF EXISTS (SELECT 1 FROM subscription WHERE tenant_id = NEW.tenant_id AND superseded_at IS NULL) THEN - RAISE EXCEPTION 'Tenant already has a current subscription' USING ERRCODE = '23514'; - END IF; - NEW.created_at := clock_timestamp(); - RETURN NEW; -END; -$$; - -CREATE FUNCTION account_subscription_record_provider_identities() RETURNS TRIGGER LANGUAGE plpgsql AS $$ -BEGIN - INSERT INTO subscription_create_provider_identities VALUES (NEW.subscription_provisioning_request_id, NEW.request_id, 'CREATE'); - INSERT INTO subscription_create_provider_identities VALUES (NEW.cleanup_provider_identity, NEW.request_id, 'CLEANUP'); - RETURN NEW; -END; -$$; -CREATE FUNCTION account_subscription_provider_identity_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ -BEGIN - IF NOT EXISTS (SELECT 1 FROM subscription_create_operations WHERE request_id = NEW.request_id - AND ((NEW.purpose = 'CREATE' AND subscription_provisioning_request_id = NEW.provider_identity) - OR (NEW.purpose = 'CLEANUP' AND cleanup_provider_identity = NEW.provider_identity))) THEN - RAISE EXCEPTION 'Subscription provider identity differs from its typed operation' USING ERRCODE = '23514'; - END IF; - RETURN NEW; -END; -$$; - -CREATE FUNCTION account_subscription_current_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ -DECLARE - intent subscription_create_operations%ROWTYPE; -BEGIN - IF TG_OP = 'DELETE' THEN - RAISE EXCEPTION 'Canonical subscription cannot be deleted' USING ERRCODE = '23514'; - ELSIF TG_OP = 'INSERT' THEN - SELECT * INTO STRICT intent FROM subscription_create_operations WHERE request_id = NEW.creation_request_id; - IF (NEW.subscription_id, NEW.tenant_id, NEW.account_uuid, NEW.owner_version, NEW.owner_generation, - NEW.plan_code, NEW.plan_quote_digest, NEW.payment_instrument_id, NEW.reserved_instrument_version, - NEW.customer_provisioning_request_id, NEW.provider_customer_id) - IS DISTINCT FROM (intent.subscription_id, intent.tenant_id, intent.account_uuid, intent.owner_version, - intent.owner_generation, intent.plan_code, intent.plan_quote_digest, intent.payment_instrument_id, intent.reserved_instrument_version, - intent.customer_provisioning_request_id, intent.provider_customer_id) - OR NEW.row_version <> 1 OR NEW.status <> 'pending' OR NEW.provider_subscription_id IS NOT NULL - OR NEW.terminal_resolution_id IS NOT NULL OR NEW.superseded_at IS NOT NULL THEN - RAISE EXCEPTION 'Subscription must begin as its exact pending intent' USING ERRCODE = '23514'; - END IF; - NEW.created_at := intent.created_at; - NEW.updated_at := NEW.created_at; - ELSE - -- No generic plan/instrument/owner rebind. Future typed update/transfer owners must extend - -- this guard with their real operation and authority evidence, never a compatibility path. - IF (NEW.subscription_id, NEW.tenant_id, NEW.account_uuid, NEW.owner_version, NEW.owner_generation, - NEW.plan_code, NEW.plan_quote_digest, NEW.payment_instrument_id, NEW.reserved_instrument_version, - NEW.customer_provisioning_request_id, NEW.provider_customer_id, NEW.creation_request_id, NEW.created_at) - IS DISTINCT FROM (OLD.subscription_id, OLD.tenant_id, OLD.account_uuid, OLD.owner_version, OLD.owner_generation, - OLD.plan_code, OLD.plan_quote_digest, OLD.payment_instrument_id, OLD.reserved_instrument_version, - OLD.customer_provisioning_request_id, OLD.provider_customer_id, OLD.creation_request_id, OLD.created_at) - OR OLD.superseded_at IS NOT NULL OR NEW.row_version <> OLD.row_version + 1 - OR (OLD.provider_subscription_id IS NOT NULL AND NEW.provider_subscription_id IS DISTINCT FROM OLD.provider_subscription_id) - OR (OLD.terminal_resolution_id IS NOT NULL AND NEW.terminal_resolution_id IS DISTINCT FROM OLD.terminal_resolution_id) - OR (OLD.status = 'canceled' AND NEW.status <> 'canceled') THEN - RAISE EXCEPTION 'Subscription identity, terminal state or row-version fence rejected' USING ERRCODE = '23514'; - END IF; - IF NEW.superseded_at IS NOT NULL THEN - IF OLD.status <> 'canceled' OR OLD.terminal_resolution_id IS NULL OR NEW.status <> OLD.status - OR NEW.provider_subscription_id IS DISTINCT FROM OLD.provider_subscription_id - OR NEW.terminal_resolution_id IS DISTINCT FROM OLD.terminal_resolution_id THEN - RAISE EXCEPTION 'Only terminal canceled current subscriptions may be superseded' USING ERRCODE = '23514'; - END IF; - NEW.superseded_at := clock_timestamp(); - END IF; - NEW.updated_at := clock_timestamp(); - END IF; - RETURN NEW; -END; -$$; - -CREATE FUNCTION account_subscription_record_observation() RETURNS TRIGGER LANGUAGE plpgsql AS $$ -BEGIN - INSERT INTO subscription_current_observations VALUES (NEW.subscription_id, NEW.row_version, NEW.status, - NEW.provider_subscription_id, NEW.terminal_resolution_id, NEW.superseded_at, NEW.superseded_by_request_id, NEW.updated_at); - RETURN NEW; -END; -$$; -CREATE FUNCTION account_subscription_observation_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ -DECLARE current_row subscription%ROWTYPE; -BEGIN - SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = NEW.subscription_id FOR UPDATE; - IF (NEW.row_version, NEW.status, NEW.provider_subscription_id, NEW.terminal_resolution_id, - NEW.superseded_at, NEW.superseded_by_request_id, NEW.recorded_at) IS DISTINCT FROM - (current_row.row_version, current_row.status, current_row.provider_subscription_id, current_row.terminal_resolution_id, - current_row.superseded_at, current_row.superseded_by_request_id, current_row.updated_at) THEN - RAISE EXCEPTION 'Subscription observation differs from its current owner' USING ERRCODE = '23514'; - END IF; - RETURN NEW; -END; -$$; - -CREATE FUNCTION account_subscription_reservation_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ -BEGIN - IF TG_OP = 'INSERT' THEN - IF NEW.terminal_resolution_id IS NOT NULL OR NEW.released_at IS NOT NULL THEN - RAISE EXCEPTION 'Subscription reservation must begin held' USING ERRCODE = '23514'; - END IF; - ELSIF TG_OP = 'DELETE' OR OLD.released_at IS NOT NULL - OR (NEW.request_id, NEW.subscription_id, NEW.payment_instrument_id, NEW.instrument_version) - IS DISTINCT FROM (OLD.request_id, OLD.subscription_id, OLD.payment_instrument_id, OLD.instrument_version) - OR NEW.terminal_resolution_id IS NULL OR NEW.released_at IS NULL THEN - RAISE EXCEPTION 'Subscription reservation identity or terminal release fence rejected' USING ERRCODE = '23514'; - END IF; - RETURN NEW; -END; -$$; - -CREATE FUNCTION account_subscription_final_pair_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ -DECLARE - current_row subscription%ROWTYPE; - hold subscription_instrument_reservations%ROWTYPE; - resolution subscription_provider_terminal_resolutions%ROWTYPE; - successor subscription_create_operations%ROWTYPE; - wallet payment_instrument%ROWTYPE; - owner account_tenant_billing_owners%ROWTYPE; -BEGIN - SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = NEW.subscription_id; - SELECT * INTO STRICT hold FROM subscription_instrument_reservations WHERE subscription_id = NEW.subscription_id; - IF current_row.row_version = 1 AND current_row.status = 'pending' THEN - SELECT * INTO STRICT wallet FROM payment_instrument WHERE instrument_uuid = current_row.payment_instrument_id; - SELECT * INTO STRICT owner FROM account_tenant_billing_owners WHERE tenant_uuid = current_row.tenant_id; - IF (owner.owner_account_uuid, owner.owner_version, owner.owner_generation) - IS DISTINCT FROM (current_row.account_uuid, current_row.owner_version, current_row.owner_generation) - OR (wallet.account_uuid, wallet.row_version, wallet.customer_provisioning_request_id, wallet.provider_customer_id, wallet.state) - IS DISTINCT FROM (current_row.account_uuid, current_row.reserved_instrument_version, - current_row.customer_provisioning_request_id, current_row.provider_customer_id, 'ATTACHABLE'::varchar) THEN - RAISE EXCEPTION 'Subscription commit owner/instrument fence rejected' USING ERRCODE = '23514'; - END IF; - END IF; - IF current_row.status = 'canceled' AND current_row.terminal_resolution_id IS NOT NULL THEN - SELECT * INTO STRICT resolution FROM subscription_provider_terminal_resolutions - WHERE resolution_id = current_row.terminal_resolution_id; - IF hold.terminal_resolution_id IS DISTINCT FROM current_row.terminal_resolution_id OR hold.released_at IS NULL - OR resolution.provider_subscription_id IS DISTINCT FROM current_row.provider_subscription_id THEN - RAISE EXCEPTION 'Subscription terminal result requires exact provider resolution and reservation release' USING ERRCODE = '23514'; - END IF; - ELSIF hold.released_at IS NOT NULL THEN - RAISE EXCEPTION 'Nonterminal subscription must retain its instrument reservation' USING ERRCODE = '23514'; - END IF; - IF current_row.superseded_at IS NOT NULL THEN - SELECT * INTO STRICT successor FROM subscription_create_operations WHERE request_id = current_row.superseded_by_request_id; - IF successor.replaced_subscription_id IS DISTINCT FROM current_row.subscription_id - OR successor.replaced_row_version <> current_row.row_version - 1 OR successor.tenant_id <> current_row.tenant_id THEN - RAISE EXCEPTION 'Subscription supersession requires the exact atomic replacement operation' USING ERRCODE = '23514'; - END IF; - END IF; - RETURN NULL; -END; -$$; -CREATE FUNCTION account_subscription_terminal_source_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ -DECLARE current_row subscription%ROWTYPE; -BEGIN - SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = NEW.subscription_id FOR UPDATE; - IF NEW.request_id IS DISTINCT FROM current_row.creation_request_id - OR (NEW.provider_subscription_id IS DISTINCT FROM current_row.provider_subscription_id - AND NOT (current_row.provider_subscription_id IS NULL AND NEW.provider_subscription_id IS NOT NULL - AND EXISTS (SELECT 1 FROM subscription_provider_history h - WHERE h.subscription_id = NEW.subscription_id AND h.provider_subscription_id = NEW.provider_subscription_id))) - OR (NEW.provider_subscription_id IS NULL AND EXISTS ( - SELECT 1 FROM subscription_provider_history WHERE subscription_id = NEW.subscription_id)) THEN - RAISE EXCEPTION 'Subscription terminal evidence differs from its exact provider mapping' USING ERRCODE = '23514'; - END IF; - RETURN NEW; -END; -$$; -CREATE FUNCTION account_subscription_provider_history_source_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ -DECLARE current_row subscription%ROWTYPE; -BEGIN - SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = NEW.subscription_id FOR UPDATE; - IF current_row.status = 'canceled' OR current_row.superseded_at IS NOT NULL - OR EXISTS (SELECT 1 FROM subscription_provider_terminal_resolutions WHERE subscription_id = NEW.subscription_id) THEN - RAISE EXCEPTION 'Terminal subscription cannot acquire a new provider mapping' USING ERRCODE = '23514'; - END IF; - RETURN NEW; -END; -$$; - -CREATE TRIGGER subscription_create_source_guard BEFORE INSERT ON subscription_create_operations - FOR EACH ROW EXECUTE FUNCTION account_subscription_create_source_guard(); -CREATE TRIGGER subscription_create_provider_keys AFTER INSERT ON subscription_create_operations - FOR EACH ROW EXECUTE FUNCTION account_subscription_record_provider_identities(); -CREATE TRIGGER subscription_provider_key_guard BEFORE INSERT ON subscription_create_provider_identities - FOR EACH ROW EXECUTE FUNCTION account_subscription_provider_identity_guard(); -CREATE TRIGGER subscription_current_guard BEFORE INSERT OR UPDATE OR DELETE ON subscription - FOR EACH ROW EXECUTE FUNCTION account_subscription_current_guard(); -CREATE TRIGGER subscription_current_history AFTER INSERT OR UPDATE ON subscription - FOR EACH ROW EXECUTE FUNCTION account_subscription_record_observation(); -CREATE TRIGGER subscription_observation_guard BEFORE INSERT ON subscription_current_observations - FOR EACH ROW EXECUTE FUNCTION account_subscription_observation_guard(); -CREATE TRIGGER subscription_terminal_source_guard BEFORE INSERT ON subscription_provider_terminal_resolutions - FOR EACH ROW EXECUTE FUNCTION account_subscription_terminal_source_guard(); -CREATE TRIGGER subscription_provider_history_source_guard BEFORE INSERT ON subscription_provider_history - FOR EACH ROW EXECUTE FUNCTION account_subscription_provider_history_source_guard(); -CREATE TRIGGER subscription_reservation_guard BEFORE INSERT OR UPDATE OR DELETE ON subscription_instrument_reservations - FOR EACH ROW EXECUTE FUNCTION account_subscription_reservation_guard(); -CREATE CONSTRAINT TRIGGER subscription_final_pair_guard AFTER INSERT OR UPDATE ON subscription - DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_final_pair_guard(); -CREATE CONSTRAINT TRIGGER subscription_reservation_final_pair_guard AFTER INSERT OR UPDATE ON subscription_instrument_reservations - DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_final_pair_guard(); - -CREATE TRIGGER subscription_create_immutable BEFORE UPDATE OR DELETE ON subscription_create_operations - FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); -CREATE TRIGGER subscription_create_no_truncate BEFORE TRUNCATE ON subscription_create_operations - FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); -CREATE TRIGGER subscription_provider_keys_immutable BEFORE UPDATE OR DELETE ON subscription_create_provider_identities - FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); -CREATE TRIGGER subscription_provider_keys_no_truncate BEFORE TRUNCATE ON subscription_create_provider_identities - FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); -CREATE TRIGGER subscription_no_truncate BEFORE TRUNCATE ON subscription - FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); -CREATE TRIGGER subscription_reservation_no_truncate BEFORE TRUNCATE ON subscription_instrument_reservations - FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); -CREATE TRIGGER subscription_outbox_immutable BEFORE UPDATE OR DELETE ON subscription_create_outbox - FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); -CREATE TRIGGER subscription_outbox_no_truncate BEFORE TRUNCATE ON subscription_create_outbox - FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); -CREATE TRIGGER subscription_provider_history_immutable BEFORE UPDATE OR DELETE ON subscription_provider_history - FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); -CREATE TRIGGER subscription_provider_history_no_truncate BEFORE TRUNCATE ON subscription_provider_history - FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); -CREATE TRIGGER subscription_terminal_immutable BEFORE UPDATE OR DELETE ON subscription_provider_terminal_resolutions - FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); -CREATE TRIGGER subscription_terminal_no_truncate BEFORE TRUNCATE ON subscription_provider_terminal_resolutions - FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); -CREATE TRIGGER subscription_observation_immutable BEFORE UPDATE OR DELETE ON subscription_current_observations - FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); -CREATE TRIGGER subscription_observation_no_truncate BEFORE TRUNCATE ON subscription_current_observations - FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); --- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1030__hosting_subscription_provisioning_claims.sql b/services/account-service/src/main/resources/db/migration/V1030__hosting_subscription_provisioning_claims.sql deleted file mode 100644 index 20fd82966c..0000000000 --- a/services/account-service/src/main/resources/db/migration/V1030__hosting_subscription_provisioning_claims.sql +++ /dev/null @@ -1,561 +0,0 @@ --- Local durable provisioning ownership only. No runtime reader, provider dispatch or entitlement --- receipt is enabled by these rows. Failure never proves provider absence or releases a hold. -CREATE TABLE subscription_provisioning_work ( - request_id UUID PRIMARY KEY, - subscription_id UUID NOT NULL UNIQUE, - phase VARCHAR(48) NOT NULL CHECK (phase IN ('RECONCILING','CLAIMED','CONFIRMED','BILLING_RECONCILIATION_TERMINAL_FAILURE')), - row_version BIGINT NOT NULL CHECK (row_version > 0), - attempt_count INTEGER NOT NULL CHECK (attempt_count >= 0), - max_attempts INTEGER NOT NULL CHECK (max_attempts > 0), - max_stalled_attempts INTEGER NOT NULL CHECK (max_stalled_attempts > 0), - lease_millis BIGINT NOT NULL CHECK (lease_millis > 0), - backoff_millis BIGINT NOT NULL CHECK (backoff_millis > 0), - deadline_at TIMESTAMPTZ NOT NULL, - retry_at TIMESTAMPTZ NOT NULL, - last_attempt_id UUID, - subscription_row_version BIGINT CHECK (subscription_row_version > 1), - lease_expires_at TIMESTAMPTZ, - failure_reason VARCHAR(64), - terminal_at TIMESTAMPTZ, - CHECK ((attempt_count = 0) = (last_attempt_id IS NULL)), - CHECK ((last_attempt_id IS NULL) = (subscription_row_version IS NULL)), - CHECK ((last_attempt_id IS NULL) = (lease_expires_at IS NULL)), - CHECK (phase <> 'CLAIMED' OR last_attempt_id IS NOT NULL), - CHECK ((phase = 'BILLING_RECONCILIATION_TERMINAL_FAILURE') = (terminal_at IS NOT NULL)), - CHECK (phase <> 'BILLING_RECONCILIATION_TERMINAL_FAILURE' OR failure_reason IS NOT NULL), - FOREIGN KEY (request_id, subscription_id) REFERENCES subscription_create_outbox(request_id, subscription_id) ON DELETE RESTRICT, - UNIQUE (request_id, subscription_id) -); - -CREATE TABLE subscription_provisioning_attempts ( - attempt_id UUID PRIMARY KEY CHECK (attempt_id <> '00000000-0000-0000-0000-000000000000'::UUID), - request_id UUID NOT NULL, - subscription_id UUID NOT NULL, - attempt_number INTEGER NOT NULL CHECK (attempt_number > 0), - expected_row_version BIGINT NOT NULL CHECK (expected_row_version > 0), - claimed_row_version BIGINT NOT NULL CHECK (claimed_row_version = expected_row_version + 1), - claimed_at TIMESTAMPTZ NOT NULL, - expires_at TIMESTAMPTZ NOT NULL CHECK (expires_at > claimed_at), - FOREIGN KEY (request_id, subscription_id) REFERENCES subscription_provisioning_work(request_id, subscription_id) ON DELETE RESTRICT, - UNIQUE (request_id, attempt_number), - UNIQUE (attempt_id, request_id, subscription_id, claimed_row_version) -); -ALTER TABLE subscription_provisioning_work ADD CONSTRAINT subscription_provisioning_last_attempt_fk - FOREIGN KEY (last_attempt_id, request_id, subscription_id, subscription_row_version) - REFERENCES subscription_provisioning_attempts(attempt_id, request_id, subscription_id, claimed_row_version) - DEFERRABLE INITIALLY DEFERRED; - -CREATE TABLE subscription_provisioning_operator_outbox ( - request_id UUID PRIMARY KEY, - subscription_id UUID NOT NULL UNIQUE, - reason VARCHAR(64) NOT NULL CHECK (reason IN ('ABSOLUTE_DEADLINE','ATTEMPT_BUDGET','STALLED_WITHOUT_COMMITTED_PROGRESS')), - recorded_at TIMESTAMPTZ NOT NULL, - FOREIGN KEY (request_id, subscription_id) REFERENCES subscription_provisioning_work(request_id, subscription_id) ON DELETE RESTRICT -); - --- [jooq ignore start] -CREATE FUNCTION account_subscription_provisioning_work_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ -BEGIN - IF TG_OP = 'DELETE' THEN - RAISE EXCEPTION 'Provisioning work is retained' USING ERRCODE = '23514'; - ELSIF TG_OP = 'INSERT' THEN - IF NEW.phase <> 'RECONCILING' OR NEW.attempt_count <> 0 OR NEW.row_version <> 1 - OR NEW.failure_reason IS NOT NULL OR NEW.terminal_at IS NOT NULL THEN - RAISE EXCEPTION 'Provisioning work must start unclaimed' USING ERRCODE = '23514'; - END IF; - ELSE - IF OLD.phase IN ('CONFIRMED','BILLING_RECONCILIATION_TERMINAL_FAILURE') - OR (NEW.request_id, NEW.subscription_id, NEW.max_attempts, NEW.max_stalled_attempts, - NEW.lease_millis, NEW.backoff_millis, NEW.deadline_at) - IS DISTINCT FROM (OLD.request_id, OLD.subscription_id, OLD.max_attempts, OLD.max_stalled_attempts, - OLD.lease_millis, OLD.backoff_millis, OLD.deadline_at) - OR NEW.row_version <> OLD.row_version + 1 THEN - RAISE EXCEPTION 'Provisioning identity, limits or terminal fence rejected' USING ERRCODE = '23514'; - END IF; - IF NEW.phase = 'CLAIMED' THEN - IF NEW.attempt_count <> OLD.attempt_count + 1 OR NEW.last_attempt_id IS NOT DISTINCT FROM OLD.last_attempt_id - OR NEW.attempt_count > NEW.max_attempts OR NEW.attempt_count > NEW.max_stalled_attempts THEN - RAISE EXCEPTION 'Provisioning claim count or attempt fence rejected' USING ERRCODE = '23514'; - END IF; - ELSIF (NEW.attempt_count, NEW.last_attempt_id, NEW.subscription_row_version, NEW.lease_expires_at) - IS DISTINCT FROM (OLD.attempt_count, OLD.last_attempt_id, OLD.subscription_row_version, OLD.lease_expires_at) THEN - RAISE EXCEPTION 'Provisioning settlement cannot replace its attempt' USING ERRCODE = '23514'; - END IF; - END IF; - RETURN NEW; -END; -$$; - -CREATE FUNCTION account_subscription_provisioning_consistency() RETURNS TRIGGER LANGUAGE plpgsql AS $$ -DECLARE - work subscription_provisioning_work%ROWTYPE; - attempt subscription_provisioning_attempts%ROWTYPE; - current_row subscription%ROWTYPE; - notice subscription_provisioning_operator_outbox%ROWTYPE; -BEGIN - SELECT * INTO STRICT work FROM subscription_provisioning_work WHERE request_id = NEW.request_id; - SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = work.subscription_id; - IF work.last_attempt_id IS NOT NULL THEN - SELECT * INTO STRICT attempt FROM subscription_provisioning_attempts WHERE attempt_id = work.last_attempt_id; - IF (attempt.request_id, attempt.subscription_id, attempt.attempt_number, attempt.claimed_row_version, attempt.expires_at) - IS DISTINCT FROM (work.request_id, work.subscription_id, work.attempt_count, work.subscription_row_version, work.lease_expires_at) - OR attempt.expires_at > work.deadline_at - OR (work.phase <> 'CONFIRMED' AND (current_row.status <> 'provisioning' OR current_row.row_version < attempt.claimed_row_version - OR current_row.superseded_at IS NOT NULL)) THEN - RAISE EXCEPTION 'Provisioning attempt lacks its exact current CAS' USING ERRCODE = '23514'; - END IF; - END IF; - IF work.phase = 'BILLING_RECONCILIATION_TERMINAL_FAILURE' THEN - SELECT * INTO STRICT notice FROM subscription_provisioning_operator_outbox WHERE request_id = work.request_id; - IF (notice.subscription_id, notice.reason, notice.recorded_at) - IS DISTINCT FROM (work.subscription_id, work.failure_reason, work.terminal_at) THEN - RAISE EXCEPTION 'Provisioning failure lacks its exact operator work item' USING ERRCODE = '23514'; - END IF; - ELSIF EXISTS (SELECT 1 FROM subscription_provisioning_operator_outbox WHERE request_id = work.request_id) THEN - RAISE EXCEPTION 'Operator resolution work requires terminal reconciliation failure' USING ERRCODE = '23514'; - END IF; - RETURN NULL; -END; -$$; - -CREATE FUNCTION account_subscription_provisioning_attempt_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ -DECLARE - work subscription_provisioning_work%ROWTYPE; - current_row subscription%ROWTYPE; -BEGIN - SELECT * INTO STRICT work FROM subscription_provisioning_work WHERE request_id = NEW.request_id FOR UPDATE; - SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = NEW.subscription_id; - IF work.phase = 'BILLING_RECONCILIATION_TERMINAL_FAILURE' - OR work.subscription_id <> NEW.subscription_id OR current_row.status <> 'provisioning' - OR current_row.provider_subscription_id IS NOT NULL OR current_row.superseded_at IS NOT NULL - OR current_row.row_version <> NEW.claimed_row_version - OR NEW.attempt_number <> work.attempt_count + 1 - OR NEW.attempt_number > work.max_attempts OR NEW.attempt_number > work.max_stalled_attempts - OR NEW.expected_row_version <> coalesce(work.subscription_row_version, 1) - OR NEW.claimed_at < current_row.created_at OR NEW.claimed_at < work.retry_at - OR NEW.claimed_at >= work.deadline_at OR NEW.expires_at > work.deadline_at - OR (work.phase = 'CLAIMED' AND NEW.claimed_at < work.lease_expires_at) - OR extract(epoch FROM (NEW.expires_at - NEW.claimed_at)) * 1000 > work.lease_millis THEN - RAISE EXCEPTION 'Provisioning attempt lacks its exact work and current-row fence' USING ERRCODE = '23514'; - END IF; - RETURN NEW; -END; -$$; - -CREATE TRIGGER subscription_provisioning_work_guard BEFORE INSERT OR UPDATE OR DELETE ON subscription_provisioning_work - FOR EACH ROW EXECUTE FUNCTION account_subscription_provisioning_work_guard(); -CREATE TRIGGER subscription_provisioning_attempt_guard BEFORE INSERT ON subscription_provisioning_attempts - FOR EACH ROW EXECUTE FUNCTION account_subscription_provisioning_attempt_guard(); -CREATE CONSTRAINT TRIGGER subscription_provisioning_work_consistency AFTER INSERT OR UPDATE ON subscription_provisioning_work - DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_provisioning_consistency(); -CREATE CONSTRAINT TRIGGER subscription_provisioning_attempt_consistency AFTER INSERT ON subscription_provisioning_attempts - DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_provisioning_consistency(); -CREATE CONSTRAINT TRIGGER subscription_provisioning_notice_consistency AFTER INSERT ON subscription_provisioning_operator_outbox - DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_provisioning_consistency(); -CREATE TRIGGER subscription_provisioning_work_no_truncate BEFORE TRUNCATE ON subscription_provisioning_work - FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); -CREATE TRIGGER subscription_provisioning_attempt_immutable BEFORE UPDATE OR DELETE ON subscription_provisioning_attempts - FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); -CREATE TRIGGER subscription_provisioning_attempt_no_truncate BEFORE TRUNCATE ON subscription_provisioning_attempts - FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); -CREATE TRIGGER subscription_provisioning_notice_immutable BEFORE UPDATE OR DELETE ON subscription_provisioning_operator_outbox - FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); -CREATE TRIGGER subscription_provisioning_notice_no_truncate BEFORE TRUNCATE ON subscription_provisioning_operator_outbox - FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); --- [jooq ignore stop] - --- Provider reads are outside SQL. One durable, row-version-bound reconciliation operation fences --- currentness before the SDK read starts. It is not a provider mutation or a reused create command. -CREATE TABLE subscription_lifecycle_operations ( - request_id UUID PRIMARY KEY CHECK (request_id <> '00000000-0000-0000-0000-000000000000'::UUID), - creation_request_id UUID NOT NULL, - subscription_id UUID NOT NULL, - tenant_id UUID NOT NULL, - expected_row_version BIGINT NOT NULL CHECK (expected_row_version > 0), - reserved_row_version BIGINT NOT NULL CHECK (reserved_row_version = expected_row_version + 1), - provider_subscription_id VARCHAR(255) NOT NULL CHECK (provider_subscription_id ~ '^sub_[A-Za-z0-9]+$'), - provisioning_attempt_id UUID REFERENCES subscription_provisioning_attempts(attempt_id) ON DELETE RESTRICT, - request_payload BYTEA NOT NULL, - request_digest VARCHAR(71) NOT NULL CHECK (request_digest = 'sha256:' || encode(sha256(request_payload), 'hex')), - state VARCHAR(48) NOT NULL CHECK (state IN ('PENDING','COMMITTED','BILLING_RECONCILIATION_TERMINAL_FAILURE')), - row_version BIGINT NOT NULL CHECK (row_version > 0), - attempt_count INTEGER NOT NULL DEFAULT 0 CHECK (attempt_count >= 0), - stalled_count INTEGER NOT NULL DEFAULT 0 CHECK (stalled_count >= 0), - max_attempts INTEGER NOT NULL CHECK (max_attempts > 0), - max_stalled_attempts INTEGER NOT NULL CHECK (max_stalled_attempts > 0), - lease_millis BIGINT NOT NULL CHECK (lease_millis > 0), - backoff_millis BIGINT NOT NULL CHECK (backoff_millis > 0), - observation_age_millis BIGINT NOT NULL CHECK (observation_age_millis > 0), - warning_millis BIGINT NOT NULL CHECK (warning_millis > 0), - grace_millis BIGINT NOT NULL CHECK (grace_millis > 0), - deadline_at TIMESTAMPTZ NOT NULL, - retry_at TIMESTAMPTZ NOT NULL, - last_attempt_id UUID, - last_facts_digest VARCHAR(71), - failure_reason VARCHAR(96), - created_at TIMESTAMPTZ NOT NULL, - created_transaction_id BIGINT NOT NULL DEFAULT txid_current(), - FOREIGN KEY (creation_request_id, subscription_id) REFERENCES subscription_create_operations(request_id, subscription_id) ON DELETE RESTRICT, - UNIQUE (request_id, subscription_id), - UNIQUE (request_id, tenant_id), - CHECK (octet_length(request_payload) BETWEEN 1 AND 32768) -); -CREATE UNIQUE INDEX subscription_lifecycle_one_inflight ON subscription_lifecycle_operations(subscription_id) - WHERE state IN ('PENDING','BILLING_RECONCILIATION_TERMINAL_FAILURE'); - -CREATE TABLE subscription_lifecycle_attempts ( - attempt_id UUID PRIMARY KEY, - request_id UUID NOT NULL REFERENCES subscription_lifecycle_operations(request_id) ON DELETE RESTRICT, - attempt_number INTEGER NOT NULL CHECK (attempt_number > 0), - started_at TIMESTAMPTZ NOT NULL, - expires_at TIMESTAMPTZ NOT NULL CHECK (expires_at > started_at), - UNIQUE (request_id, attempt_number), - UNIQUE (request_id, attempt_id) -); -ALTER TABLE subscription_lifecycle_operations ADD CONSTRAINT subscription_lifecycle_last_attempt_fk - FOREIGN KEY (request_id, last_attempt_id) REFERENCES subscription_lifecycle_attempts(request_id, attempt_id) - DEFERRABLE INITIALLY DEFERRED; - -CREATE TABLE subscription_lifecycle_observations ( - attempt_id UUID PRIMARY KEY, - request_id UUID NOT NULL, - payload BYTEA NOT NULL CHECK (octet_length(payload) BETWEEN 1 AND 32768), - evidence_digest VARCHAR(71) NOT NULL CHECK (evidence_digest = 'sha256:' || encode(sha256(payload), 'hex')), - facts_digest VARCHAR(71) NOT NULL CHECK (facts_digest ~ '^sha256:[0-9a-f]{64}$'), - raw_status VARCHAR(32), - period_start TIMESTAMPTZ, - period_end TIMESTAMPTZ, - read_started_at TIMESTAMPTZ NOT NULL, - observed_at TIMESTAMPTZ NOT NULL, - mapping_reason VARCHAR(64) NOT NULL, - recorded_transaction_id BIGINT NOT NULL DEFAULT txid_current(), - FOREIGN KEY (request_id, attempt_id) REFERENCES subscription_lifecycle_attempts(request_id, attempt_id) ON DELETE RESTRICT, - UNIQUE (request_id, attempt_id, evidence_digest) -); - -CREATE TABLE subscription_lifecycle_receipts ( - request_id UUID PRIMARY KEY, - subscription_id UUID NOT NULL, - tenant_id UUID NOT NULL, - request_digest VARCHAR(71) NOT NULL, - subscription_row_version BIGINT NOT NULL CHECK (subscription_row_version > 0), - status VARCHAR(16) NOT NULL CHECK (status IN ('trialing','active','past_due','grace','suspended','canceled')), - plan_quote_digest VARCHAR(71) NOT NULL, - provider_subscription_id VARCHAR(255) NOT NULL, - attempt_id UUID NOT NULL, - observation_digest VARCHAR(71) NOT NULL, - receipt_payload BYTEA NOT NULL CHECK (octet_length(receipt_payload) BETWEEN 1 AND 32768), - receipt_digest VARCHAR(71) NOT NULL CHECK (receipt_digest = 'sha256:' || encode(sha256(receipt_payload), 'hex')), - valid_until TIMESTAMPTZ NOT NULL, - cutoff_at TIMESTAMPTZ, - past_due_since TIMESTAMPTZ, - warning_millis BIGINT NOT NULL CHECK (warning_millis > 0), - grace_millis BIGINT NOT NULL CHECK (grace_millis > 0), - entitlement_version BIGINT NOT NULL CHECK (entitlement_version > 0), - billing_sequence BIGINT NOT NULL CHECK (billing_sequence > 0), - billing_event_id UUID NOT NULL, - billing_event_digest VARCHAR(71) NOT NULL, - authority_generation BIGINT NOT NULL CHECK (authority_generation > 1), - authority_source_version BIGINT NOT NULL CHECK (authority_source_version > 1), - authority_sequence BIGINT NOT NULL CHECK (authority_sequence > 0), - authority_event_id VARCHAR(512) NOT NULL, - authority_event_digest VARCHAR(71) NOT NULL, - committed_at TIMESTAMPTZ NOT NULL, - committed_transaction_id BIGINT NOT NULL DEFAULT txid_current(), - FOREIGN KEY (request_id, subscription_id) REFERENCES subscription_lifecycle_operations(request_id, subscription_id) ON DELETE RESTRICT, - FOREIGN KEY (request_id, attempt_id, observation_digest) REFERENCES subscription_lifecycle_observations(request_id, attempt_id, evidence_digest) ON DELETE RESTRICT, - FOREIGN KEY (tenant_id, billing_sequence, billing_event_id, billing_event_digest) - REFERENCES account_tenant_entitlement_outbox_events(tenant_uuid, tenant_billing_sequence, event_id, event_digest) ON DELETE RESTRICT, - UNIQUE (request_id, subscription_id), - UNIQUE (subscription_id, subscription_row_version) -); -CREATE TABLE subscription_lifecycle_operator_outbox ( - request_id UUID PRIMARY KEY REFERENCES subscription_lifecycle_operations(request_id) ON DELETE RESTRICT, - reason VARCHAR(96) NOT NULL, - recorded_at TIMESTAMPTZ NOT NULL -); -ALTER TABLE subscription ADD COLUMN lifecycle_inflight_request_id UUID, - ADD COLUMN current_receipt_request_id UUID; -ALTER TABLE subscription ADD CONSTRAINT subscription_lifecycle_inflight_fk - FOREIGN KEY (lifecycle_inflight_request_id, subscription_id) REFERENCES subscription_lifecycle_operations(request_id, subscription_id) - DEFERRABLE INITIALLY DEFERRED; -ALTER TABLE subscription ADD CONSTRAINT subscription_current_receipt_fk - FOREIGN KEY (current_receipt_request_id, subscription_id) REFERENCES subscription_lifecycle_receipts(request_id, subscription_id) - DEFERRABLE INITIALLY DEFERRED; - --- [jooq ignore start] -CREATE FUNCTION account_subscription_lifecycle_current_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ -BEGIN - IF TG_OP = 'INSERT' THEN - IF NEW.lifecycle_inflight_request_id IS NOT NULL OR NEW.current_receipt_request_id IS NOT NULL THEN - RAISE EXCEPTION 'Subscription cannot begin with lifecycle authority' USING ERRCODE = '23514'; - END IF; - ELSIF OLD.lifecycle_inflight_request_id IS NOT NULL THEN - IF NEW.lifecycle_inflight_request_id IS NULL THEN - IF NEW.current_receipt_request_id IS DISTINCT FROM OLD.lifecycle_inflight_request_id THEN - RAISE EXCEPTION 'Lifecycle fence may clear only into its exact receipt' USING ERRCODE = '23514'; - END IF; - ELSIF NEW.lifecycle_inflight_request_id IS DISTINCT FROM OLD.lifecycle_inflight_request_id - OR NEW.current_receipt_request_id IS DISTINCT FROM OLD.current_receipt_request_id THEN - RAISE EXCEPTION 'In-flight lifecycle ownership cannot be replaced' USING ERRCODE = '23514'; - END IF; - ELSE - IF NEW.current_receipt_request_id IS DISTINCT FROM OLD.current_receipt_request_id THEN - RAISE EXCEPTION 'Committed current receipt cannot be detached or replaced without a lifecycle fence' USING ERRCODE = '23514'; - END IF; - IF NEW.lifecycle_inflight_request_id IS NOT NULL - AND (NEW.status, NEW.provider_subscription_id, NEW.terminal_resolution_id) - IS DISTINCT FROM (OLD.status, OLD.provider_subscription_id, OLD.terminal_resolution_id) THEN - RAISE EXCEPTION 'Lifecycle preparation cannot pre-commit provider state' USING ERRCODE = '23514'; - END IF; - END IF; - RETURN NEW; -END; -$$; -CREATE TRIGGER subscription_lifecycle_current_guard BEFORE INSERT OR UPDATE ON subscription - FOR EACH ROW EXECUTE FUNCTION account_subscription_lifecycle_current_guard(); - -CREATE FUNCTION account_subscription_lifecycle_operation_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ -BEGIN - IF TG_OP = 'DELETE' THEN - RAISE EXCEPTION 'Lifecycle operation is retained' USING ERRCODE = '23514'; - ELSIF TG_OP = 'INSERT' THEN - IF NEW.state <> 'PENDING' OR NEW.row_version <> 1 OR NEW.attempt_count <> 0 OR NEW.last_attempt_id IS NOT NULL THEN - RAISE EXCEPTION 'Lifecycle operation must start pending' USING ERRCODE = '23514'; - END IF; - NEW.created_transaction_id := txid_current(); - ELSE - IF OLD.state <> 'PENDING' OR NEW.row_version <> OLD.row_version + 1 - OR (NEW.request_id, NEW.creation_request_id, NEW.subscription_id, NEW.tenant_id, NEW.expected_row_version, - NEW.reserved_row_version, NEW.provider_subscription_id, NEW.provisioning_attempt_id, NEW.request_payload, - NEW.request_digest, NEW.max_attempts, NEW.max_stalled_attempts, NEW.lease_millis, NEW.backoff_millis, - NEW.observation_age_millis, NEW.warning_millis, NEW.grace_millis, NEW.deadline_at, NEW.created_at, NEW.created_transaction_id) - IS DISTINCT FROM (OLD.request_id, OLD.creation_request_id, OLD.subscription_id, OLD.tenant_id, OLD.expected_row_version, - OLD.reserved_row_version, OLD.provider_subscription_id, OLD.provisioning_attempt_id, OLD.request_payload, - OLD.request_digest, OLD.max_attempts, OLD.max_stalled_attempts, OLD.lease_millis, OLD.backoff_millis, - OLD.observation_age_millis, OLD.warning_millis, OLD.grace_millis, OLD.deadline_at, OLD.created_at, OLD.created_transaction_id) - OR NEW.attempt_count NOT BETWEEN OLD.attempt_count AND OLD.attempt_count + 1 THEN - RAISE EXCEPTION 'Lifecycle immutable identity or transition CAS rejected' USING ERRCODE = '23514'; - END IF; - END IF; - RETURN NEW; -END; -$$; - -CREATE FUNCTION account_subscription_lifecycle_observation_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ -DECLARE attempt subscription_lifecycle_attempts%ROWTYPE; operation subscription_lifecycle_operations%ROWTYPE; -BEGIN - SELECT * INTO STRICT attempt FROM subscription_lifecycle_attempts WHERE attempt_id = NEW.attempt_id; - SELECT * INTO STRICT operation FROM subscription_lifecycle_operations WHERE request_id = NEW.request_id; - IF operation.state <> 'PENDING' OR operation.last_attempt_id IS DISTINCT FROM NEW.attempt_id - OR NEW.read_started_at < attempt.started_at OR NEW.observed_at < NEW.read_started_at - OR NEW.observed_at >= attempt.expires_at THEN - RAISE EXCEPTION 'SDK observation is not from the exact live read attempt' USING ERRCODE = '23514'; - END IF; - NEW.recorded_transaction_id := txid_current(); - RETURN NEW; -END; -$$; - -CREATE FUNCTION account_subscription_lifecycle_receipt_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ -DECLARE operation subscription_lifecycle_operations%ROWTYPE; observation subscription_lifecycle_observations%ROWTYPE; - current_row subscription%ROWTYPE; creation subscription_create_operations%ROWTYPE; payload JSONB; -BEGIN - SELECT * INTO STRICT operation FROM subscription_lifecycle_operations WHERE request_id = NEW.request_id; - SELECT * INTO STRICT observation FROM subscription_lifecycle_observations WHERE attempt_id = NEW.attempt_id; - SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = NEW.subscription_id; - SELECT * INTO STRICT creation FROM subscription_create_operations WHERE request_id = operation.creation_request_id; - payload := convert_from(NEW.receipt_payload, 'UTF8')::jsonb; - IF operation.state <> 'PENDING' OR current_row.lifecycle_inflight_request_id IS DISTINCT FROM NEW.request_id - OR current_row.row_version <> operation.reserved_row_version - OR NEW.subscription_row_version <> current_row.row_version + 1 - OR NEW.request_digest IS DISTINCT FROM operation.request_digest OR NEW.tenant_id <> operation.tenant_id - OR NEW.provider_subscription_id <> operation.provider_subscription_id - OR NEW.plan_quote_digest <> creation.plan_quote_digest - OR observation.recorded_transaction_id <> txid_current() - OR payload->>'requestId' IS DISTINCT FROM NEW.request_id::text - OR payload->>'subscriptionId' IS DISTINCT FROM NEW.subscription_id::text - OR payload->>'tenantId' IS DISTINCT FROM NEW.tenant_id::text - OR payload->>'subscriptionRowVersion' IS DISTINCT FROM NEW.subscription_row_version::text - OR payload->>'subscriptionStatus' IS DISTINCT FROM NEW.status - OR payload->>'planQuoteDigest' IS DISTINCT FROM NEW.plan_quote_digest - OR payload->>'planQuote' IS DISTINCT FROM convert_from(creation.plan_quote_payload, 'UTF8') - OR payload->>'billingOwnerAccountId' IS DISTINCT FROM creation.account_uuid::text - OR payload->>'billingOwnerVersion' IS DISTINCT FROM creation.owner_version::text - OR payload->>'billingOwnerGeneration' IS DISTINCT FROM creation.owner_generation::text - OR payload->>'paymentInstrumentId' IS DISTINCT FROM creation.payment_instrument_id::text - OR payload->>'reservedInstrumentVersion' IS DISTINCT FROM creation.reserved_instrument_version::text - OR payload->>'customerProvisioningRequestId' IS DISTINCT FROM creation.customer_provisioning_request_id::text - OR payload->>'providerCustomerId' IS DISTINCT FROM creation.provider_customer_id - OR payload->>'entitlementVersion' IS DISTINCT FROM NEW.entitlement_version::text - OR payload->>'observationDigest' IS DISTINCT FROM NEW.observation_digest - OR payload->>'providerSubscriptionId' IS DISTINCT FROM NEW.provider_subscription_id THEN - RAISE EXCEPTION 'Hosting receipt lacks its exact same-transaction provider/current CAS' USING ERRCODE = '23514'; - END IF; - NEW.committed_transaction_id := txid_current(); - RETURN NEW; -END; -$$; - -CREATE FUNCTION account_subscription_lifecycle_consistency() RETURNS TRIGGER LANGUAGE plpgsql AS $$ -DECLARE current_row subscription%ROWTYPE; operation subscription_lifecycle_operations%ROWTYPE; - receipt subscription_lifecycle_receipts%ROWTYPE; notice subscription_lifecycle_operator_outbox%ROWTYPE; - source_head account_tenant_authority_source_records%ROWTYPE; generation_row RECORD; -BEGIN - IF TG_TABLE_NAME = 'subscription' THEN - SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = NEW.subscription_id; - ELSE - SELECT * INTO STRICT operation FROM subscription_lifecycle_operations WHERE request_id = NEW.request_id; - SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = operation.subscription_id; - IF operation.state = 'COMMITTED' THEN - SELECT * INTO STRICT receipt FROM subscription_lifecycle_receipts WHERE request_id = operation.request_id; - IF EXISTS (SELECT 1 FROM subscription_lifecycle_operator_outbox WHERE request_id = operation.request_id) THEN - RAISE EXCEPTION 'Committed lifecycle cannot carry terminal-failure work' USING ERRCODE = '23514'; - END IF; - ELSIF operation.state = 'BILLING_RECONCILIATION_TERMINAL_FAILURE' THEN - SELECT * INTO STRICT notice FROM subscription_lifecycle_operator_outbox WHERE request_id = operation.request_id; - IF notice.reason IS DISTINCT FROM operation.failure_reason THEN - RAISE EXCEPTION 'Lifecycle failure lacks its exact operator work item' USING ERRCODE = '23514'; - END IF; - END IF; - END IF; - IF current_row.lifecycle_inflight_request_id IS NOT NULL THEN - SELECT * INTO STRICT operation FROM subscription_lifecycle_operations WHERE request_id = current_row.lifecycle_inflight_request_id; - IF operation.state = 'COMMITTED' OR current_row.row_version <> operation.reserved_row_version - OR current_row.tenant_id <> operation.tenant_id THEN - RAISE EXCEPTION 'In-flight lifecycle operation lacks its exact current fence' USING ERRCODE = '23514'; - END IF; - ELSIF current_row.current_receipt_request_id IS NOT NULL THEN - SELECT * INTO STRICT receipt FROM subscription_lifecycle_receipts WHERE request_id = current_row.current_receipt_request_id; - SELECT * INTO STRICT operation FROM subscription_lifecycle_operations WHERE request_id = receipt.request_id; - IF operation.state <> 'COMMITTED' OR current_row.status <> receipt.status - OR current_row.provider_subscription_id IS DISTINCT FROM receipt.provider_subscription_id - OR current_row.plan_quote_digest <> receipt.plan_quote_digest - OR (current_row.superseded_at IS NULL AND current_row.row_version <> receipt.subscription_row_version) THEN - RAISE EXCEPTION 'Hosting current row lacks its exact committed lifecycle receipt' USING ERRCODE = '23514'; - END IF; - IF current_row.superseded_at IS NULL THEN - SELECT * INTO STRICT source_head FROM account_tenant_authority_source_records WHERE tenant_uuid = current_row.tenant_id; - SELECT generation, source_version INTO STRICT generation_row FROM account_authority_generations - WHERE scope_kind = 'TENANT' AND tenant_uuid = current_row.tenant_id; - IF source_head.last_request_id IS DISTINCT FROM receipt.request_id - OR source_head.last_request_digest IS DISTINCT FROM receipt.request_digest - OR source_head.current_generation <> receipt.authority_generation - OR source_head.current_source_version <> receipt.authority_source_version - OR source_head.last_outbox_sequence <> receipt.authority_sequence - OR source_head.last_event_id IS DISTINCT FROM receipt.authority_event_id - OR source_head.last_event_digest IS DISTINCT FROM receipt.authority_event_digest - OR source_head.tenant_billing_sequence <> receipt.billing_sequence - OR source_head.tenant_billing_event_id IS DISTINCT FROM receipt.billing_event_id - OR source_head.tenant_billing_event_digest IS DISTINCT FROM receipt.billing_event_digest - OR generation_row.generation <> receipt.authority_generation OR generation_row.source_version <> receipt.authority_source_version THEN - RAISE EXCEPTION 'Hosting current receipt requires its atomic canonical source checkpoint' USING ERRCODE = '23514'; - END IF; - END IF; - END IF; - RETURN NULL; -END; -$$; - --- Extend only the canonical source's receipt branch. Original demo receipt semantics remain intact. -CREATE OR REPLACE FUNCTION account_tenant_authority_source_consistency() RETURNS TRIGGER LANGUAGE plpgsql AS $$ -DECLARE head RECORD; generation_row RECORD; stream_sequence BIGINT; operation_row RECORD; entitlement_row RECORD; - hosting subscription_lifecycle_receipts%ROWTYPE; current_row subscription%ROWTYPE; billing RECORD; -BEGIN - SELECT * INTO head FROM account_tenant_authority_source_records WHERE outbox_stream_key = NEW.outbox_stream_key; - SELECT generation, source_version INTO generation_row FROM account_authority_generations WHERE scope_kind = 'TENANT' AND tenant_uuid = NEW.tenant_uuid; - SELECT last_sequence INTO stream_sequence FROM account_authority_outbox_streams WHERE outbox_stream_key = NEW.outbox_stream_key; - IF head.outbox_stream_key IS NULL OR head.last_outbox_sequence <= 0 - OR head.current_generation IS DISTINCT FROM generation_row.generation - OR head.current_source_version IS DISTINCT FROM generation_row.source_version OR stream_sequence IS DISTINCT FROM head.last_outbox_sequence THEN - RAISE EXCEPTION 'Tenant authority source checkpoint is not the current Account generation' - USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_consistent'; - END IF; - SELECT * INTO hosting FROM subscription_lifecycle_receipts WHERE request_id = head.last_request_id; - IF FOUND THEN - SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = hosting.subscription_id; - SELECT * INTO STRICT operation_row FROM subscription_lifecycle_operations WHERE request_id = hosting.request_id; - SELECT * INTO STRICT billing FROM account_tenant_entitlement_outbox_events - WHERE tenant_uuid = hosting.tenant_id AND tenant_billing_sequence = hosting.billing_sequence; - IF operation_row.state <> 'COMMITTED' OR hosting.tenant_id <> NEW.tenant_uuid - OR current_row.superseded_at IS NOT NULL OR current_row.current_receipt_request_id IS DISTINCT FROM hosting.request_id - OR current_row.lifecycle_inflight_request_id IS NOT NULL OR current_row.row_version <> hosting.subscription_row_version - OR current_row.status <> hosting.status OR current_row.provider_subscription_id IS DISTINCT FROM hosting.provider_subscription_id - OR hosting.request_digest IS DISTINCT FROM head.last_request_digest - OR hosting.authority_generation <> head.current_generation OR hosting.authority_source_version <> head.current_source_version - OR hosting.authority_sequence <> head.last_outbox_sequence OR hosting.authority_event_id IS DISTINCT FROM head.last_event_id - OR hosting.authority_event_digest IS DISTINCT FROM head.last_event_digest - OR hosting.billing_sequence <> head.tenant_billing_sequence OR hosting.billing_event_id IS DISTINCT FROM head.tenant_billing_event_id - OR hosting.billing_event_digest IS DISTINCT FROM head.tenant_billing_event_digest - OR convert_from(billing.payload, 'UTF8')::jsonb->'receipt' IS DISTINCT FROM convert_from(hosting.receipt_payload, 'UTF8')::jsonb THEN - RAISE EXCEPTION 'Hosting tenant source lacks its exact current receipt and billing event' USING ERRCODE = '23514'; - END IF; - RETURN NULL; - END IF; - SELECT request_id, tenant_uuid, request_digest, status, tenant_billing_sequence, event_id, event_digest, - tenant_authority_outbox_stream_key, tenant_authority_outbox_sequence, tenant_authority_event_id, tenant_authority_event_digest - INTO operation_row FROM account_demo_tenant_entitlement_operations WHERE request_id = head.last_request_id; - SELECT * INTO entitlement_row FROM account_demo_tenant_entitlements WHERE tenant_uuid = NEW.tenant_uuid; - IF operation_row.status IS DISTINCT FROM 'COMMITTED' OR operation_row.tenant_uuid IS DISTINCT FROM NEW.tenant_uuid - OR operation_row.request_digest IS DISTINCT FROM head.last_request_digest - OR operation_row.tenant_billing_sequence IS DISTINCT FROM head.tenant_billing_sequence - OR operation_row.event_id IS DISTINCT FROM head.tenant_billing_event_id OR operation_row.event_digest IS DISTINCT FROM head.tenant_billing_event_digest - OR operation_row.tenant_authority_outbox_stream_key IS DISTINCT FROM head.outbox_stream_key - OR operation_row.tenant_authority_outbox_sequence IS DISTINCT FROM head.last_outbox_sequence - OR operation_row.tenant_authority_event_id IS DISTINCT FROM head.last_event_id OR operation_row.tenant_authority_event_digest IS DISTINCT FROM head.last_event_digest - OR entitlement_row.tenant_uuid IS DISTINCT FROM NEW.tenant_uuid - OR entitlement_row.tenant_authority_generation IS DISTINCT FROM head.current_generation OR entitlement_row.tenant_authority_source_version IS DISTINCT FROM head.current_source_version - OR entitlement_row.tenant_billing_sequence IS DISTINCT FROM head.tenant_billing_sequence - OR entitlement_row.event_id IS DISTINCT FROM head.tenant_billing_event_id OR entitlement_row.event_digest IS DISTINCT FROM head.tenant_billing_event_digest - OR entitlement_row.tenant_authority_outbox_stream_key IS DISTINCT FROM head.outbox_stream_key - OR entitlement_row.tenant_authority_outbox_sequence IS DISTINCT FROM head.last_outbox_sequence - OR entitlement_row.tenant_authority_event_id IS DISTINCT FROM head.last_event_id OR entitlement_row.tenant_authority_event_digest IS DISTINCT FROM head.last_event_digest THEN - RAISE EXCEPTION 'Tenant authority source lacks its exact current Account receipt and entitlement' - USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_receipt'; - END IF; - RETURN NULL; -END; -$$; - -CREATE TRIGGER subscription_lifecycle_operation_guard BEFORE INSERT OR UPDATE OR DELETE ON subscription_lifecycle_operations - FOR EACH ROW EXECUTE FUNCTION account_subscription_lifecycle_operation_guard(); -CREATE TRIGGER subscription_lifecycle_observation_guard BEFORE INSERT ON subscription_lifecycle_observations - FOR EACH ROW EXECUTE FUNCTION account_subscription_lifecycle_observation_guard(); -CREATE TRIGGER subscription_lifecycle_receipt_guard BEFORE INSERT ON subscription_lifecycle_receipts - FOR EACH ROW EXECUTE FUNCTION account_subscription_lifecycle_receipt_guard(); -CREATE CONSTRAINT TRIGGER subscription_lifecycle_current_consistency AFTER INSERT OR UPDATE ON subscription - DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_lifecycle_consistency(); -CREATE CONSTRAINT TRIGGER subscription_lifecycle_operation_consistency AFTER INSERT OR UPDATE ON subscription_lifecycle_operations - DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_lifecycle_consistency(); -CREATE CONSTRAINT TRIGGER subscription_lifecycle_receipt_consistency AFTER INSERT ON subscription_lifecycle_receipts - DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_lifecycle_consistency(); -CREATE CONSTRAINT TRIGGER subscription_lifecycle_notice_consistency AFTER INSERT ON subscription_lifecycle_operator_outbox - DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_lifecycle_consistency(); - -CREATE TRIGGER subscription_lifecycle_operation_no_truncate BEFORE TRUNCATE ON subscription_lifecycle_operations FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); -CREATE TRIGGER subscription_lifecycle_attempt_immutable BEFORE UPDATE OR DELETE ON subscription_lifecycle_attempts FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); -CREATE TRIGGER subscription_lifecycle_attempt_no_truncate BEFORE TRUNCATE ON subscription_lifecycle_attempts FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); -CREATE TRIGGER subscription_lifecycle_observation_immutable BEFORE UPDATE OR DELETE ON subscription_lifecycle_observations FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); -CREATE TRIGGER subscription_lifecycle_observation_no_truncate BEFORE TRUNCATE ON subscription_lifecycle_observations FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); -CREATE TRIGGER subscription_lifecycle_receipt_immutable BEFORE UPDATE OR DELETE ON subscription_lifecycle_receipts FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); -CREATE TRIGGER subscription_lifecycle_receipt_no_truncate BEFORE TRUNCATE ON subscription_lifecycle_receipts FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); -CREATE TRIGGER subscription_lifecycle_notice_immutable BEFORE UPDATE OR DELETE ON subscription_lifecycle_operator_outbox FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); -CREATE TRIGGER subscription_lifecycle_notice_no_truncate BEFORE TRUNCATE ON subscription_lifecycle_operator_outbox FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); - -CREATE FUNCTION account_subscription_provisioning_confirmed_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ -DECLARE work subscription_provisioning_work%ROWTYPE; -BEGIN - SELECT * INTO STRICT work FROM subscription_provisioning_work WHERE request_id = NEW.request_id; - IF work.phase = 'CONFIRMED' AND NOT EXISTS ( - SELECT 1 FROM subscription_lifecycle_operations operation - JOIN subscription_lifecycle_receipts receipt USING (request_id, subscription_id) - WHERE operation.creation_request_id = work.request_id AND operation.subscription_id = work.subscription_id - AND operation.provisioning_attempt_id = work.last_attempt_id AND operation.state = 'COMMITTED') THEN - RAISE EXCEPTION 'Provisioning confirmation lacks its exact lifecycle receipt' USING ERRCODE = '23514'; - END IF; - RETURN NULL; -END; -$$; -CREATE CONSTRAINT TRIGGER subscription_provisioning_confirmed_guard AFTER INSERT OR UPDATE ON subscription_provisioning_work - DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_provisioning_confirmed_guard(); --- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1032__hosting_subscription_first_provider_dispatch.sql b/services/account-service/src/main/resources/db/migration/V1032__hosting_subscription_first_provider_dispatch.sql deleted file mode 100644 index e3ec7519dd..0000000000 --- a/services/account-service/src/main/resources/db/migration/V1032__hosting_subscription_first_provider_dispatch.sql +++ /dev/null @@ -1,82 +0,0 @@ --- Separate remote dispatch from renewable worker attempts. Presence/replay is never permission. -CREATE TABLE subscription_provider_dispatch_claim ( - creation_request_id UUID PRIMARY KEY, - subscription_id UUID NOT NULL UNIQUE, - provider_operation_id UUID NOT NULL UNIQUE, - dispatch_id UUID NOT NULL UNIQUE CHECK (dispatch_id <> '00000000-0000-0000-0000-000000000000'::UUID), - classification VARCHAR(24) NOT NULL CHECK (classification IN ('FIRST_DISPATCH', 'PREEXISTING_UNKNOWN')), - first_attempt_id UUID, - first_claimed_row_version BIGINT, - recorded_at TIMESTAMPTZ NOT NULL, - CHECK ((first_attempt_id IS NULL) = (first_claimed_row_version IS NULL)), - CHECK (classification <> 'FIRST_DISPATCH' OR first_attempt_id IS NOT NULL), - FOREIGN KEY (creation_request_id, subscription_id) - REFERENCES subscription_create_operations(request_id, subscription_id) ON DELETE RESTRICT, - FOREIGN KEY (creation_request_id, provider_operation_id) - REFERENCES subscription_create_operations(request_id, subscription_provisioning_request_id) ON DELETE RESTRICT, - FOREIGN KEY (first_attempt_id, creation_request_id, subscription_id, first_claimed_row_version) - REFERENCES subscription_provisioning_attempts(attempt_id, request_id, subscription_id, claimed_row_version) ON DELETE RESTRICT -); - --- Existing attempt-1/work rows may already have unknown remote effects. Preserve their bytes and --- add only a non-authorizing guard. No dispatched/absent/canceled result is inferred. -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) -SELECT w.request_id, w.subscription_id, c.subscription_provisioning_request_id, - gen_random_uuid(), 'PREEXISTING_UNKNOWN', a.attempt_id, a.claimed_row_version, clock_timestamp() -FROM subscription_provisioning_work w -JOIN subscription_create_operations c ON c.request_id = w.request_id -LEFT JOIN subscription_provisioning_attempts a ON a.request_id = w.request_id AND a.attempt_number = 1; - --- [jooq ignore start] -CREATE FUNCTION account_subscription_provider_dispatch_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ -DECLARE - creation subscription_create_operations%ROWTYPE; - current_row subscription%ROWTYPE; - work subscription_provisioning_work%ROWTYPE; - attempt subscription_provisioning_attempts%ROWTYPE; - instrument payment_instrument%ROWTYPE; - customer billing_customer%ROWTYPE; -BEGIN - SELECT * INTO STRICT creation FROM subscription_create_operations WHERE request_id = NEW.creation_request_id; - PERFORM 1 FROM accounts WHERE account_uuid = creation.account_uuid FOR UPDATE; - SELECT * INTO STRICT instrument FROM payment_instrument WHERE instrument_uuid = creation.payment_instrument_id FOR UPDATE; - SELECT * INTO STRICT customer FROM billing_customer WHERE account_uuid = creation.account_uuid FOR UPDATE; - SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = creation.subscription_id FOR UPDATE; - SELECT * INTO STRICT work FROM subscription_provisioning_work WHERE request_id = creation.request_id FOR UPDATE; - SELECT * INTO STRICT attempt FROM subscription_provisioning_attempts WHERE attempt_id = NEW.first_attempt_id; - IF NEW.classification <> 'FIRST_DISPATCH' - OR NEW.subscription_id <> creation.subscription_id - OR NEW.provider_operation_id <> creation.subscription_provisioning_request_id - OR NEW.dispatch_id IN (creation.request_id, creation.subscription_provisioning_request_id, creation.cleanup_provider_identity) - OR NEW.first_claimed_row_version <> attempt.claimed_row_version - OR attempt.request_id <> creation.request_id OR attempt.subscription_id <> creation.subscription_id - OR work.phase <> 'CLAIMED' OR work.last_attempt_id <> attempt.attempt_id - OR work.attempt_count > work.max_attempts OR work.attempt_count > work.max_stalled_attempts - OR current_row.row_version <> attempt.claimed_row_version - OR current_row.status <> 'provisioning' OR current_row.provider_subscription_id IS NOT NULL - OR current_row.superseded_at IS NOT NULL OR current_row.lifecycle_inflight_request_id IS NOT NULL - OR instrument.account_uuid <> creation.account_uuid OR instrument.state <> 'ATTACHABLE' - OR instrument.row_version <> creation.reserved_instrument_version - OR instrument.customer_provisioning_request_id <> creation.customer_provisioning_request_id - OR instrument.provider_customer_id <> creation.provider_customer_id - OR customer.state <> 'CONFIRMED' OR customer.provider_customer_id <> creation.provider_customer_id - OR customer.customer_provisioning_request_id <> creation.customer_provisioning_request_id - OR NEW.recorded_at < attempt.claimed_at OR NEW.recorded_at >= attempt.expires_at - OR NEW.recorded_at >= work.deadline_at THEN - RAISE EXCEPTION 'Provider dispatch lacks exact live original provisioning fence' USING ERRCODE = '23514'; - END IF; - RETURN NEW; -END; -$$; -CREATE TRIGGER subscription_provider_dispatch_insert_guard - BEFORE INSERT ON subscription_provider_dispatch_claim - FOR EACH ROW EXECUTE FUNCTION account_subscription_provider_dispatch_guard(); -CREATE TRIGGER subscription_provider_dispatch_immutable - BEFORE UPDATE OR DELETE ON subscription_provider_dispatch_claim - FOR EACH ROW EXECUTE FUNCTION account_billing_prerequisite_no_erasure(); -CREATE TRIGGER subscription_provider_dispatch_no_truncate - BEFORE TRUNCATE ON subscription_provider_dispatch_claim - FOR EACH STATEMENT EXECUTE FUNCTION account_billing_prerequisite_no_erasure(); --- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1036__hosting_subscription_terminal_resolution.sql b/services/account-service/src/main/resources/db/migration/V1036__hosting_subscription_terminal_resolution.sql deleted file mode 100644 index 11bb675ceb..0000000000 --- a/services/account-service/src/main/resources/db/migration/V1036__hosting_subscription_terminal_resolution.sql +++ /dev/null @@ -1,202 +0,0 @@ --- Internal cancellation-only recovery. No actor authentication, provider absence, transfer, --- caller registration or operational permission is established by these stored comparison facts. -CREATE TABLE subscription_lifecycle_terminal_resolutions ( - resolution_request_id UUID PRIMARY KEY CHECK (resolution_request_id <> '00000000-0000-0000-0000-000000000000'::uuid), - failed_request_id UUID NOT NULL REFERENCES subscription_lifecycle_operations(request_id) ON DELETE RESTRICT, - creation_request_id UUID NOT NULL REFERENCES subscription_create_operations(request_id) ON DELETE RESTRICT, - subscription_id UUID NOT NULL REFERENCES subscription(subscription_id) ON DELETE RESTRICT, - tenant_id UUID NOT NULL, - expected_failed_version BIGINT NOT NULL CHECK (expected_failed_version > 0), - expected_subscription_version BIGINT NOT NULL CHECK (expected_subscription_version > 0 AND expected_subscription_version < 9223372036854775805), - actor_account_id UUID NOT NULL REFERENCES accounts(account_uuid) ON DELETE RESTRICT, - control_ui_issuance_operation_id UUID NOT NULL CHECK (control_ui_issuance_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid), - control_ui_token_hash VARCHAR(64) NOT NULL CHECK (control_ui_token_hash ~ '^[0-9a-f]{64}$'), - audit_event_id UUID NOT NULL UNIQUE REFERENCES account_audit_outbox(audit_event_id) ON DELETE RESTRICT, - audit_reason TEXT NOT NULL CHECK (octet_length(audit_reason) BETWEEN 1 AND 1000), - request_payload BYTEA NOT NULL CHECK (octet_length(request_payload) BETWEEN 1 AND 32768), - request_digest VARCHAR(71) NOT NULL CHECK (request_digest = 'sha256:' || encode(sha256(request_payload), 'hex')), - attempt_id UUID NOT NULL UNIQUE, - captured_at TIMESTAMPTZ NOT NULL, - expires_at TIMESTAMPTZ NOT NULL CHECK (expires_at > captured_at), - authenticated_at TIMESTAMPTZ NOT NULL, - authorization_outcome VARCHAR(32) NOT NULL DEFAULT 'PRIMARY_AUTHENTICATED' CHECK (authorization_outcome = 'PRIMARY_AUTHENTICATED'), - state VARCHAR(16) NOT NULL CHECK (state IN ('PREPARED', 'COMMITTED')), - result_row_version BIGINT, - receipt_digest VARCHAR(71), - committed_at TIMESTAMPTZ, - created_transaction_id BIGINT NOT NULL DEFAULT txid_current(), - CHECK (resolution_request_id <> failed_request_id), - CHECK (authenticated_at >= captured_at AND authenticated_at < expires_at), - CHECK ((state = 'PREPARED' AND result_row_version IS NULL AND receipt_digest IS NULL AND committed_at IS NULL) - OR (state = 'COMMITTED' AND result_row_version IS NOT NULL AND receipt_digest IS NOT NULL - AND result_row_version = expected_subscription_version + 2 - AND receipt_digest ~ '^sha256:[0-9a-f]{64}$' AND committed_at IS NOT NULL)), - UNIQUE (failed_request_id) -); - --- Failure history stays immutable. Its retained subscription fence still blocks normal prepare; --- only the journal-backed atomic cancellation transition may replace that fence. -DROP INDEX subscription_lifecycle_one_inflight; -CREATE UNIQUE INDEX subscription_lifecycle_one_inflight ON subscription_lifecycle_operations(subscription_id) - WHERE state = 'PENDING'; - --- [jooq ignore start] -ALTER TABLE subscription_lifecycle_terminal_resolutions - ADD CONSTRAINT subscription_terminal_resolution_reason_nfc CHECK (audit_reason IS NFC NORMALIZED); - -CREATE FUNCTION account_subscription_terminal_resolution_guard() RETURNS trigger LANGUAGE plpgsql AS $$ -DECLARE failed subscription_lifecycle_operations%ROWTYPE; current_row subscription%ROWTYPE; - audit account_audit_outbox%ROWTYPE; payload JSONB; field_count INTEGER; -BEGIN - IF TG_OP = 'DELETE' THEN - RAISE EXCEPTION 'Terminal lifecycle resolution is retained' USING ERRCODE = '23514'; - ELSIF TG_OP = 'UPDATE' THEN - IF OLD.state <> 'PREPARED' OR NEW.state <> 'COMMITTED' - OR (to_jsonb(NEW) - ARRAY['state','result_row_version','receipt_digest','committed_at']) - IS DISTINCT FROM (to_jsonb(OLD) - ARRAY['state','result_row_version','receipt_digest','committed_at']) - OR OLD.created_transaction_id <> txid_current() THEN - RAISE EXCEPTION 'Terminal lifecycle resolution is immutable outside its owner commit' USING ERRCODE = '23514'; - END IF; - RETURN NEW; - END IF; - SELECT * INTO STRICT failed FROM subscription_lifecycle_operations WHERE request_id = NEW.failed_request_id FOR UPDATE; - SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = NEW.subscription_id FOR UPDATE; - SELECT * INTO STRICT audit FROM account_audit_outbox WHERE audit_event_id = NEW.audit_event_id; - payload := convert_from(NEW.request_payload, 'UTF8')::jsonb; - SELECT count(*) INTO field_count FROM jsonb_object_keys(payload); - IF NEW.state <> 'PREPARED' OR failed.state <> 'BILLING_RECONCILIATION_TERMINAL_FAILURE' - OR failed.row_version <> NEW.expected_failed_version - OR failed.creation_request_id <> NEW.creation_request_id OR failed.subscription_id <> NEW.subscription_id - OR failed.tenant_id <> NEW.tenant_id OR current_row.tenant_id <> NEW.tenant_id - OR current_row.account_uuid <> NEW.actor_account_id OR current_row.creation_request_id <> NEW.creation_request_id - OR current_row.row_version <> NEW.expected_subscription_version OR current_row.superseded_at IS NOT NULL - OR current_row.lifecycle_inflight_request_id IS DISTINCT FROM NEW.failed_request_id - OR audit.scope <> 'tenant' OR audit.tenant_identity_version <> 2 OR audit.tenant_uuid IS DISTINCT FROM NEW.tenant_id - OR audit.producer_service <> 'account-service' OR audit.event_type <> 'HOSTING_SUBSCRIPTION_TERMINAL_RESOLVED' - OR audit.payload_digest <> NEW.request_digest OR audit.payload IS DISTINCT FROM convert_from(NEW.request_payload, 'UTF8') - OR field_count <> 14 OR payload->>'schemaVersion' IS DISTINCT FROM 'account-hosting-terminal-resolution/v1' - OR payload->>'outcome' IS DISTINCT FROM 'CANCELED' - OR payload->>'resolutionRequestId' IS DISTINCT FROM NEW.resolution_request_id::text - OR payload->>'failedRequestId' IS DISTINCT FROM NEW.failed_request_id::text - OR payload->>'creationRequestId' IS DISTINCT FROM NEW.creation_request_id::text - OR payload->>'subscriptionId' IS DISTINCT FROM NEW.subscription_id::text - OR payload->>'tenantId' IS DISTINCT FROM NEW.tenant_id::text - OR payload->>'expectedFailedOperationVersion' IS DISTINCT FROM NEW.expected_failed_version::text - OR payload->>'expectedSubscriptionVersion' IS DISTINCT FROM NEW.expected_subscription_version::text - OR payload->>'actorAccountId' IS DISTINCT FROM NEW.actor_account_id::text - OR payload->>'controlUiIssuanceOperationId' IS DISTINCT FROM NEW.control_ui_issuance_operation_id::text - OR payload->>'controlUiTokenHash' IS DISTINCT FROM NEW.control_ui_token_hash - OR payload->>'auditEventId' IS DISTINCT FROM NEW.audit_event_id::text - OR payload->>'auditReason' IS DISTINCT FROM NEW.audit_reason - OR btrim(NEW.audit_reason, E'\t\n\f\r ' || chr(11) || chr(133) || chr(160) || chr(5760) - || chr(8192) || chr(8193) || chr(8194) || chr(8195) || chr(8196) || chr(8197) - || chr(8198) || chr(8199) || chr(8200) || chr(8201) || chr(8202) || chr(8232) - || chr(8233) || chr(8239) || chr(8287) || chr(12288)) = '' THEN - RAISE EXCEPTION 'Terminal lifecycle resolution lacks its exact failed target and audit' USING ERRCODE = '23514'; - END IF; - NEW.created_transaction_id := txid_current(); - RETURN NEW; -END; -$$; -CREATE TRIGGER subscription_terminal_resolution_guard BEFORE INSERT OR UPDATE OR DELETE ON subscription_lifecycle_terminal_resolutions - FOR EACH ROW EXECUTE FUNCTION account_subscription_terminal_resolution_guard(); - -CREATE OR REPLACE FUNCTION account_subscription_lifecycle_current_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ -BEGIN - IF TG_OP = 'INSERT' THEN - IF NEW.lifecycle_inflight_request_id IS NOT NULL OR NEW.current_receipt_request_id IS NOT NULL THEN - RAISE EXCEPTION 'Subscription cannot begin with lifecycle authority' USING ERRCODE = '23514'; - END IF; - ELSIF OLD.lifecycle_inflight_request_id IS NOT NULL THEN - IF NEW.lifecycle_inflight_request_id IS NULL THEN - IF NEW.current_receipt_request_id IS DISTINCT FROM OLD.lifecycle_inflight_request_id THEN - RAISE EXCEPTION 'Lifecycle fence may clear only into its exact receipt' USING ERRCODE = '23514'; - END IF; - ELSIF NEW.lifecycle_inflight_request_id IS DISTINCT FROM OLD.lifecycle_inflight_request_id - OR NEW.current_receipt_request_id IS DISTINCT FROM OLD.current_receipt_request_id THEN - IF NEW.current_receipt_request_id IS DISTINCT FROM OLD.current_receipt_request_id - OR NOT EXISTS (SELECT 1 FROM subscription_lifecycle_terminal_resolutions resolution - JOIN subscription_lifecycle_operations operation ON operation.request_id = resolution.resolution_request_id - WHERE resolution.failed_request_id = OLD.lifecycle_inflight_request_id - AND resolution.resolution_request_id = NEW.lifecycle_inflight_request_id - AND resolution.subscription_id = OLD.subscription_id AND resolution.state = 'PREPARED' - AND resolution.expected_subscription_version = OLD.row_version - AND resolution.created_transaction_id = txid_current() - AND operation.state = 'PENDING' AND operation.request_digest = resolution.request_digest - AND operation.reserved_row_version = NEW.row_version - AND operation.creation_request_id = OLD.creation_request_id - AND operation.tenant_id = OLD.tenant_id) THEN - RAISE EXCEPTION 'In-flight lifecycle ownership cannot be replaced without exact resolution' USING ERRCODE = '23514'; - END IF; - END IF; - ELSE - IF NEW.current_receipt_request_id IS DISTINCT FROM OLD.current_receipt_request_id THEN - RAISE EXCEPTION 'Committed current receipt cannot be detached or replaced without a lifecycle fence' USING ERRCODE = '23514'; - END IF; - IF NEW.lifecycle_inflight_request_id IS NOT NULL - AND (NEW.status, NEW.provider_subscription_id, NEW.terminal_resolution_id) - IS DISTINCT FROM (OLD.status, OLD.provider_subscription_id, OLD.terminal_resolution_id) THEN - RAISE EXCEPTION 'Lifecycle preparation cannot pre-commit provider state' USING ERRCODE = '23514'; - END IF; - END IF; - RETURN NEW; -END; -$$; - -CREATE FUNCTION account_subscription_terminal_resolution_consistency() RETURNS trigger LANGUAGE plpgsql AS $$ -DECLARE resolution subscription_lifecycle_terminal_resolutions%ROWTYPE; operation subscription_lifecycle_operations%ROWTYPE; - receipt subscription_lifecycle_receipts%ROWTYPE; observation subscription_lifecycle_observations%ROWTYPE; - current_row subscription%ROWTYPE; failed subscription_lifecycle_operations%ROWTYPE; -BEGIN - SELECT * INTO STRICT resolution FROM subscription_lifecycle_terminal_resolutions WHERE resolution_request_id = NEW.resolution_request_id; - SELECT * INTO STRICT failed FROM subscription_lifecycle_operations WHERE request_id = resolution.failed_request_id; - SELECT * INTO STRICT operation FROM subscription_lifecycle_operations WHERE request_id = resolution.resolution_request_id; - SELECT * INTO STRICT receipt FROM subscription_lifecycle_receipts WHERE request_id = resolution.resolution_request_id; - SELECT * INTO STRICT observation FROM subscription_lifecycle_observations WHERE attempt_id = resolution.attempt_id; - SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = resolution.subscription_id; - IF resolution.state <> 'COMMITTED' OR resolution.created_transaction_id <> txid_current() - OR failed.state <> 'BILLING_RECONCILIATION_TERMINAL_FAILURE' OR failed.row_version <> resolution.expected_failed_version - OR operation.state <> 'COMMITTED' OR operation.request_digest <> resolution.request_digest - OR operation.request_payload <> resolution.request_payload OR operation.creation_request_id <> resolution.creation_request_id - OR receipt.status <> 'canceled' OR receipt.request_digest <> resolution.request_digest - OR receipt.subscription_id <> resolution.subscription_id OR receipt.tenant_id <> resolution.tenant_id - OR receipt.subscription_row_version <> resolution.result_row_version OR receipt.receipt_digest <> resolution.receipt_digest - OR receipt.attempt_id <> resolution.attempt_id OR receipt.committed_transaction_id <> txid_current() - OR observation.raw_status <> 'canceled' OR observation.recorded_transaction_id <> txid_current() - OR convert_from(observation.payload, 'UTF8')::jsonb->>'kind' IS DISTINCT FROM 'SDK_OBSERVED' - OR convert_from(observation.payload, 'UTF8')::jsonb->>'providerStatus' IS DISTINCT FROM 'canceled' - OR observation.read_started_at < resolution.captured_at OR observation.observed_at > resolution.authenticated_at - OR resolution.authenticated_at >= resolution.expires_at OR resolution.committed_at >= resolution.expires_at - OR current_row.current_receipt_request_id IS DISTINCT FROM resolution.resolution_request_id - OR current_row.lifecycle_inflight_request_id IS NOT NULL OR current_row.row_version <> resolution.result_row_version - OR current_row.status <> 'canceled' OR current_row.terminal_resolution_id IS NULL - OR NOT EXISTS (SELECT 1 FROM subscription_instrument_reservations reservation - WHERE reservation.request_id = resolution.creation_request_id AND reservation.subscription_id = resolution.subscription_id - AND reservation.terminal_resolution_id = current_row.terminal_resolution_id AND reservation.released_at IS NOT NULL) THEN - RAISE EXCEPTION 'Cancellation resolution lacks its atomic receipt, retained failure and terminal reservation' USING ERRCODE = '23514'; - END IF; - RETURN NULL; -END; -$$; -CREATE CONSTRAINT TRIGGER subscription_terminal_resolution_consistency AFTER INSERT OR UPDATE ON subscription_lifecycle_terminal_resolutions - DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_terminal_resolution_consistency(); -CREATE TRIGGER subscription_terminal_resolution_no_truncate BEFORE TRUNCATE ON subscription_lifecycle_terminal_resolutions - FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); - --- Replacing the partial index must not make unowned dangling PENDING rows committable. -CREATE FUNCTION account_subscription_pending_owner_consistency() RETURNS trigger LANGUAGE plpgsql AS $$ -DECLARE operation subscription_lifecycle_operations%ROWTYPE; current_row subscription%ROWTYPE; -BEGIN - SELECT * INTO STRICT operation FROM subscription_lifecycle_operations WHERE request_id = NEW.request_id; - IF operation.state = 'PENDING' THEN - SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = operation.subscription_id; - IF current_row.lifecycle_inflight_request_id IS DISTINCT FROM operation.request_id THEN - RAISE EXCEPTION 'Pending lifecycle requires its exact retained current fence' USING ERRCODE = '23514'; - END IF; - END IF; - RETURN NULL; -END; -$$; -CREATE CONSTRAINT TRIGGER subscription_pending_owner_consistency AFTER INSERT OR UPDATE ON subscription_lifecycle_operations - DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_subscription_pending_owner_consistency(); --- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java index 8a1838fbec..cb6e7bc04c 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java @@ -7,9 +7,10 @@ import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.Instant; import java.time.LocalDateTime; import java.util.List; -import java.util.Objects; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; @@ -19,15 +20,16 @@ import net.firedevops.firemud.accountservice.client.EntityManagementClient; import net.firedevops.firemud.accountservice.client.GameSessionClient; import net.firedevops.firemud.accountservice.client.LoggingAdminClient; -import net.firedevops.firemud.accountservice.dto.ConnectTokenRequest; import net.firedevops.firemud.accountservice.dto.CreateAccountRequest; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; import net.firedevops.firemud.accountservice.dto.VerifyEmailRequest; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException; import net.firedevops.firemud.accountservice.service.AccountService; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; -import net.firedevops.firemud.accountservice.service.session.SessionService; import net.firedevops.firemud.common.security.HttpAuthProperties; import net.firedevops.firemud.common.security.HttpAuthRoleRequirement; import net.firedevops.firemud.common.security.HttpJwtAuthInterceptor; @@ -91,7 +93,6 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private JwtUtil jwtUtil; @Autowired private DSLContext dsl; @Autowired private AccountService accountService; - @Autowired private SessionService realAccountSessions; @Autowired private HttpAuthProperties httpAuthProperties; @Autowired private ObjectProvider httpJwtAuthInterceptorProvider; @@ -102,6 +103,18 @@ static void configure(DynamicPropertyRegistry registry) { private net.firedevops.firemud.accountservice.repository.EmailVerificationTokenRepository emailVerificationTokenRepository; + @org.springframework.test.context.bean.override.mockito.MockitoSpyBean + private net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository + joinOperationRepository; + + @org.springframework.test.context.bean.override.mockito.MockitoSpyBean + private net.firedevops.firemud.accountservice.repository.SubscriptionRepository + subscriptionRepository; + + @Autowired + private net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository + connectScopeRepository; + @Autowired private org.springframework.transaction.PlatformTransactionManager transactionManager; @Autowired @@ -396,6 +409,655 @@ private List emailVerificationState(EmailVerificationFixture fixture) { private record EmailVerificationFixture(long accountId, String token) {} + @Test + void publicJoinLostCommitAcknowledgementAndReadbackReplayTheSameOriginalOnce() { + var fixture = publicJoinFixture(); + var readbackDropped = losePublicJoinTerminalResponse(fixture); + + assertPublicJoinUnavailable(fixture); + + assertThat(readbackDropped).isTrue(); + assertPublicJoinCommittedOnce(fixture); + var committed = publicJoinState(fixture); + var replay = publicJoin(fixture); + + assertThat(replay.success()).isTrue(); + assertThat(replay.replayed()).isTrue(); + assertThat(replay.outcomeCode()).isEqualTo("JOINED"); + assertThat(replay.accountId()).isEqualTo(fixture.accountUuid()); + assertPublicJoinCommittedOnce(fixture); + assertThat(publicJoinState(fixture)).isEqualTo(committed); + } + + @Test + void publicJoinFailureBeforeCommitRollsBackEffectsAndContinuesTheOriginalIntent() { + var fixture = publicJoinFixture(); + var failOnce = new AtomicBoolean(true); + org.mockito.Mockito.doAnswer( + invocation -> { + invocation.callRealMethod(); + if (failOnce.compareAndSet(true, false)) { + // The real terminal UPDATE ran, but its owner transaction has not committed. + throw new IllegalStateException("Injected failure before public JOIN commit"); + } + return null; + }) + .when(joinOperationRepository) + .finish( + org.mockito.ArgumentMatchers.eq(fixture.caller().requestId()), + org.mockito.ArgumentMatchers.eq("COMMITTED"), + org.mockito.ArgumentMatchers.eq("JOINED"), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any()); + + assertPublicJoinUnavailable(fixture); + + assertThat(failOnce).isFalse(); + var pending = + dsl.fetchOne( + "SELECT status, outcome, intent_digest, request_digest, membership_id " + + "FROM account_join_operations WHERE request_id = ?", + fixture.caller().requestId()); + assertThat(pending).isNotNull(); + assertThat(pending.get("status", String.class)).isEqualTo("PENDING"); + assertThat(pending.get("intent_digest", String.class)).startsWith("sha256:"); + assertThat(pending.get("outcome")).isNull(); + assertThat(pending.get("request_digest")).isNull(); + assertThat(pending.get("membership_id")).isNull(); + assertThat(publicJoinMembershipCount(fixture)).isZero(); + assertThat(publicJoinAuditCount(fixture)).isZero(); + + var continued = publicJoin(fixture); + + assertThat(continued.success()).isTrue(); + assertThat(continued.replayed()).isFalse(); + assertThat(continued.outcomeCode()).isEqualTo("JOINED"); + assertPublicJoinCommittedOnce(fixture); + assertThat(publicJoin(fixture).replayed()).isTrue(); + assertPublicJoinCommittedOnce(fixture); + } + + @Test + void publicJoinLostResponseThenExpiredScopePreservesTheCompleteCommittedOriginal() { + var fixture = publicJoinFixture(); + var readbackDropped = losePublicJoinTerminalResponse(fixture); + assertPublicJoinUnavailable(fixture); + assertThat(readbackDropped).isTrue(); + assertPublicJoinCommittedOnce(fixture); + var committed = publicJoinState(fixture); + String retainedExpiry = + dsl.resultQuery( + "SELECT s.connect_scope_expires_at FROM account_connect_scope_records s " + + "JOIN account_join_operations j ON j.scope_token_hash = s.scope_token_hash " + + "WHERE j.request_id = ?", + fixture.caller().requestId()) + .fetchOne(0, String.class); + assertThat(retainedExpiry).isNotBlank(); + Instant expiredNow = Instant.parse(retainedExpiry).plusSeconds(1); + + // Advance only the owner clock; never rewrite the original scope, intent or terminal row. + try (org.mockito.MockedStatic clock = + org.mockito.Mockito.mockStatic(Instant.class, org.mockito.Mockito.CALLS_REAL_METHODS)) { + clock.when(Instant::now).thenReturn(expiredNow); + var refused = publicJoin(fixture); + assertThat(refused.success()).isFalse(); + assertThat(refused.replayed()).isFalse(); + assertThat(refused.outcomeCode()).isEqualTo("CONNECT_SCOPE_INVALID"); + } + + assertThat(publicJoinState(fixture)).isEqualTo(committed); + assertPublicJoinCommittedOnce(fixture); + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void publicJoinUnavailableSubscriptionRetainsOriginalAndRecoversOnce(boolean ambiguous) { + var fixture = publicJoinFixture(); + var originalEvidence = publicJoinOriginalEvidence(fixture); + if (ambiguous) { + var duplicate = new net.firedevops.firemud.accountservice.entity.Subscription(); + duplicate.setAccount(accountRepository.findById(fixture.accountId()).orElseThrow()); + duplicate.setTenantId(fixture.tenantId()); + duplicate.setPlanId("join-proof-duplicate"); + duplicate.setStatus("active"); + subscriptionRepository.save(duplicate); + } else { + subscriptionRepository.deleteByAccountId(fixture.accountId(), fixture.tenantId()); + } + assertThat(subscriptionRepository.findByTenantId(fixture.tenantId())) + .hasSize(ambiguous ? 2 : 0); + + var unavailable = publicJoin(fixture); + + assertThat(unavailable.success()).isFalse(); + assertThat(unavailable.replayed()).isFalse(); + assertThat(unavailable.accountId()).isEqualTo(fixture.accountUuid()); + assertThat(unavailable.outcomeCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + assertPublicJoinUnboundPending(fixture, "ENTITLEMENT_UNAVAILABLE", "UNAVAILABLE"); + String originalIntent = + joinOperationRepository.find(fixture.caller().requestId()).orElseThrow().intentDigest(); + assertThat(publicJoinOriginalEvidence(fixture)).isEqualTo(originalEvidence); + + var stillUnavailable = publicJoin(fixture); + assertThat(stillUnavailable.outcomeCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + assertPublicJoinUnboundPending(fixture, "ENTITLEMENT_UNAVAILABLE", "UNAVAILABLE"); + assertThat( + joinOperationRepository.find(fixture.caller().requestId()).orElseThrow().intentDigest()) + .isEqualTo(originalIntent); + + // Restore explicit unique authority through the real repository, not a synthetic read result. + subscriptionRepository.deleteByAccountId(fixture.accountId(), fixture.tenantId()); + var restored = new net.firedevops.firemud.accountservice.entity.Subscription(); + restored.setAccount(accountRepository.findById(fixture.accountId()).orElseThrow()); + restored.setTenantId(fixture.tenantId()); + restored.setPlanId("join-proof-recovered"); + restored.setStatus("active"); + subscriptionRepository.save(restored); + assertThat(subscriptionRepository.findByTenantId(fixture.tenantId())).hasSize(1); + + var recovered = publicJoin(fixture); + assertThat(recovered.success()).isTrue(); + assertThat(recovered.replayed()).isFalse(); + assertThat(recovered.accountId()).isEqualTo(fixture.accountUuid()); + assertPublicJoinCommittedOnce(fixture); + assertThat( + joinOperationRepository.find(fixture.caller().requestId()).orElseThrow().intentDigest()) + .isEqualTo(originalIntent); + assertThat(publicJoinOriginalEvidence(fixture)).isEqualTo(originalEvidence); + var committed = publicJoinState(fixture); + assertThat(publicJoin(fixture).replayed()).isTrue(); + assertPublicJoinCommittedOnce(fixture); + assertThat(publicJoinState(fixture)).isEqualTo(committed); + } + + @Test + void publicJoinActualSqlAbortAtLockedReadRollsBackPolicyAndContinuesOriginalOnce() { + var fixture = publicJoinFixture(); + var originalEvidence = publicJoinOriginalEvidence(fixture); + var failOnce = new AtomicBoolean(true); + var rolledBack = new AtomicBoolean(); + var diagnosticWritten = new AtomicBoolean(); + var originalSqlFailure = new java.util.concurrent.atomic.AtomicReference(); + org.mockito.Mockito.doAnswer( + invocation -> { + assertThat(rolledBack).isTrue(); + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isTrue(); + invocation.callRealMethod(); + diagnosticWritten.set(true); + return null; + }) + .when(joinOperationRepository) + .recordAttemptFailure( + fixture.caller().requestId(), "UNAVAILABLE", "ENTITLEMENT_UNAVAILABLE"); + org.mockito.Mockito.doAnswer( + invocation -> { + var lockedRows = invocation.callRealMethod(); + if (failOnce.compareAndSet(true, false)) { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isTrue(); + // The initial available read and real policy UPDATE have already run in this tx. + var transientPolicy = + joinOperationRepository.find(fixture.caller().requestId()).orElseThrow(); + assertThat(transientPolicy.entitlementAuthorityAvailability()) + .isEqualTo("AVAILABLE"); + assertThat(transientPolicy.allowPublicJoin()).isTrue(); + assertThat(transientPolicy.entitlementVersion()).isEqualTo(1L); + assertThat(transientPolicy.requestDigest()).startsWith("sha256:"); + var independentRead = new TransactionTemplate(transactionManager); + independentRead.setPropagationBehavior( + org.springframework.transaction.TransactionDefinition.PROPAGATION_REQUIRES_NEW); + independentRead.executeWithoutResult( + status -> { + var committedIntent = + joinOperationRepository.find(fixture.caller().requestId()).orElseThrow(); + assertThat(committedIntent.status()).isEqualTo("PENDING"); + assertThat(committedIntent.requestDigest()).isNull(); + assertThat(committedIntent.intentDigest()) + .isEqualTo(transientPolicy.intentDigest()); + }); + org.springframework.transaction.support.TransactionSynchronizationManager + .registerSynchronization( + new org.springframework.transaction.support.TransactionSynchronization() { + @Override + public void afterCompletion(int status) { + rolledBack.set(status == STATUS_ROLLED_BACK); + } + }); + try { + // A real PostgreSQL error poisons this physical owner transaction; no savepoint. + dsl.fetch("SELECT 1 / 0"); + throw new AssertionError("PostgreSQL division by zero must fail"); + } catch (org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException ex) { + originalSqlFailure.set(ex); + throw ex; + } + } + return lockedRows; + }) + .when(subscriptionRepository) + .findByTenantIdForUpdate(fixture.tenantId()); + + var unavailable = publicJoin(fixture); + + assertThat(unavailable.success()).isFalse(); + assertThat(unavailable.replayed()).isFalse(); + assertThat(unavailable.outcomeCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + assertThat(originalSqlFailure.get()).isNotNull(); + assertThat(sqlState(originalSqlFailure.get())).isEqualTo("22012"); + assertThat(rolledBack).isTrue(); + assertThat(diagnosticWritten).isTrue(); + org.mockito.Mockito.verify(joinOperationRepository) + .recordAttemptFailure( + fixture.caller().requestId(), "UNAVAILABLE", "ENTITLEMENT_UNAVAILABLE"); + assertPublicJoinUnboundPending(fixture, "ENTITLEMENT_UNAVAILABLE", "UNAVAILABLE"); + String originalIntent = + joinOperationRepository.find(fixture.caller().requestId()).orElseThrow().intentDigest(); + assertThat(publicJoinOriginalEvidence(fixture)).isEqualTo(originalEvidence); + + var recovered = publicJoin(fixture); + assertThat(recovered.success()).isTrue(); + assertThat(recovered.replayed()).isFalse(); + assertThat(recovered.accountId()).isEqualTo(fixture.accountUuid()); + assertPublicJoinCommittedOnce(fixture); + assertThat( + joinOperationRepository.find(fixture.caller().requestId()).orElseThrow().intentDigest()) + .isEqualTo(originalIntent); + assertThat(publicJoinOriginalEvidence(fixture)).isEqualTo(originalEvidence); + var committed = publicJoinState(fixture); + assertThat(publicJoin(fixture).replayed()).isTrue(); + assertPublicJoinCommittedOnce(fixture); + assertThat(publicJoinState(fixture)).isEqualTo(committed); + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void publicJoinTerminalEntitlementOutagePreservesOriginalBytes(boolean storageFailure) { + var fixture = publicJoinFixture(); + var originalResult = publicJoin(fixture); + assertThat(originalResult.success()).isTrue(); + assertPublicJoinCommittedOnce(fixture); + var committed = publicJoinState(fixture); + var originalEvidence = publicJoinOriginalEvidence(fixture); + var subscription = subscriptionRepository.findByTenantId(fixture.tenantId()).getFirst(); + var outage = new AtomicBoolean(true); + var sqlFailure = new java.util.concurrent.atomic.AtomicReference(); + if (storageFailure) { + org.mockito.Mockito.doAnswer( + invocation -> { + var rows = invocation.callRealMethod(); + if (outage.get()) { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + try { + dsl.fetch("SELECT 1 / 0"); + throw new AssertionError("PostgreSQL division by zero must fail"); + } catch (org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException ex) { + sqlFailure.set(ex); + throw ex; + } + } + return rows; + }) + .when(subscriptionRepository) + .findByTenantIdForUpdate(fixture.tenantId()); + } else { + subscriptionRepository.deleteByAccountId(fixture.accountId(), fixture.tenantId()); + } + + var unavailable = publicJoin(fixture); + + assertThat(unavailable.success()).isFalse(); + assertThat(unavailable.replayed()).isFalse(); + assertThat(unavailable.accountId()).isEqualTo(fixture.accountUuid()); + assertThat(unavailable.outcomeCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + if (storageFailure) { + assertThat(sqlFailure.get()).isNotNull(); + assertThat(sqlState(sqlFailure.get())).isEqualTo("22012"); + } + assertThat(publicJoinState(fixture)).isEqualTo(committed); + assertThat(publicJoinOriginalEvidence(fixture)).isEqualTo(originalEvidence); + assertPublicJoinCommittedOnce(fixture); + + outage.set(false); + if (!storageFailure) { + subscription.setId(null); + subscriptionRepository.save(subscription); + } + var replay = publicJoin(fixture); + assertThat(replay.success()).isTrue(); + assertThat(replay.replayed()).isTrue(); + assertThat(replay.accountId()).isEqualTo(originalResult.accountId()); + assertThat(replay.membershipId()).isEqualTo(originalResult.membershipId()); + assertThat(replay.membershipVersion()).isEqualTo(originalResult.membershipVersion()); + assertThat(replay.membershipAuthorityGeneration()) + .isEqualTo(originalResult.membershipAuthorityGeneration()); + assertThat(replay.outcomeCode()).isEqualTo(originalResult.outcomeCode()); + assertThat(publicJoinState(fixture)).isEqualTo(committed); + assertThat(publicJoinOriginalEvidence(fixture)).isEqualTo(originalEvidence); + assertPublicJoinCommittedOnce(fixture); + } + + @Test + void publicJoinChangedAvailablePolicyPreservesTheOriginalTerminalBytes() { + var fixture = publicJoinFixture(); + assertThat(publicJoin(fixture).success()).isTrue(); + assertPublicJoinCommittedOnce(fixture); + var committed = publicJoinState(fixture); + var originalEvidence = publicJoinOriginalEvidence(fixture); + var original = joinOperationRepository.find(fixture.caller().requestId()).orElseThrow(); + var subscription = subscriptionRepository.findByTenantId(fixture.tenantId()).getFirst(); + UUID originalGeneration = subscription.getTenantAuthorityGeneration(); + subscription.setStatus("trialing"); + subscriptionRepository.save(subscription); + assertThat(subscription.getEntitlementVersion()).isEqualTo(original.entitlementVersion() + 1L); + assertThat(subscription.getTenantAuthorityGeneration()).isNotEqualTo(originalGeneration); + var available = + accountService.getTenantEntitlementsForRuntime( + fixture.tenantId(), "changed-policy-" + fixture.caller().requestId()); + assertThat(available.gameplayAvailable()).isTrue(); + assertThat(available.allowPublicJoin()).isTrue(); + + var conflict = publicJoin(fixture); + + assertThat(conflict.success()).isFalse(); + assertThat(conflict.replayed()).isFalse(); + assertThat(conflict.accountId()).isEqualTo(fixture.accountUuid()); + assertThat(conflict.outcomeCode()).isEqualTo("IDEMPOTENCY_CONFLICT"); + assertThat(publicJoinState(fixture)).isEqualTo(committed); + assertThat(publicJoinOriginalEvidence(fixture)).isEqualTo(originalEvidence); + assertPublicJoinCommittedOnce(fixture); + } + + private static String sqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof java.sql.SQLException sql) { + return sql.getSQLState(); + } + } + return null; + } + + private void assertPublicJoinUnboundPending( + PublicJoinFixture fixture, String failureCode, String availability) { + var operation = joinOperationRepository.find(fixture.caller().requestId()).orElseThrow(); + var scope = connectScopeRepository.find(fixture.connectScopeId()).orElseThrow(); + assertThat(operation.accountId()).isEqualTo(fixture.accountId()); + assertThat(operation.tenantId()).isEqualTo(fixture.tenantId()); + assertThat(operation.callerBinding()).isEqualTo(fixture.caller().sessionId()); + assertThat(operation.scopeTokenHash()) + .isEqualTo( + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash( + fixture.connectScopeId())); + assertThat(operation.connectScopeDigest()).isEqualTo(scope.snapshotDigest()); + assertThat(operation.intentDigestVersion()).isEqualTo(1); + assertThat(operation.intentDigest()) + .isEqualTo( + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.intent( + fixture.caller().requestId(), scope, fixture.caller().sessionId())); + assertThat(operation.status()).isEqualTo("PENDING"); + assertThat(operation.outcome()).isNull(); + assertThat(operation.requestDigest()).isNull(); + assertThat(operation.requestDigestVersion()).isNull(); + assertThat(operation.allowPublicJoin()).isNull(); + assertThat(operation.entitlementVersion()).isNull(); + assertThat(operation.membershipId()).isNull(); + assertThat(operation.membershipVersion()).isNull(); + assertThat(operation.membershipAuthorityGeneration()).isNull(); + assertThat(operation.entitlementAuthorityAvailability()).isEqualTo(availability); + assertThat(operation.lastAttemptAuthorityAvailability()).isEqualTo(availability); + assertThat(operation.lastAttemptFailureCode()).isEqualTo(failureCode); + assertThat(publicJoinMembershipCount(fixture)).isZero(); + assertThat(publicJoinAuditCount(fixture)).isZero(); + } + + private List publicJoinOriginalEvidence(PublicJoinFixture fixture) { + assertThat(jwtUtil.parseToken(fixture.connectScopeId()).getPayload().getSubject()) + .isEqualTo(fixture.accountUuid()); + var account = accountRepository.findById(fixture.accountId()).orElseThrow(); + assertThat(account.getAccountUuid().toString()).isEqualTo(fixture.accountUuid()); + assertThat(account.getAccountUuidSourceNumericId()).isEqualTo(fixture.accountId()); + assertThat(account.getAccountUuidProvenance()) + .isEqualTo(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + return List.of( + dsl.resultQuery( + "SELECT row_to_json(a)::text FROM accounts a WHERE id = ?", fixture.accountId()) + .fetchOne(0, String.class), + dsl.resultQuery( + "SELECT COALESCE(json_agg(s ORDER BY outbox_stream_key)::text, '[]') " + + "FROM account_authority_source_records s WHERE account_uuid = ?", + UUID.fromString(fixture.accountUuid())) + .fetchOne(0, String.class), + dsl.resultQuery( + "SELECT COALESCE(json_agg(e ORDER BY outbox_sequence)::text, '[]') " + + "FROM account_authority_outbox_events e WHERE outbox_stream_key = ?", + "account:auth-authority:v1:account/" + fixture.accountUuid()) + .fetchOne(0, String.class), + dsl.resultQuery( + "SELECT row_to_json(s)::text FROM account_connect_scope_records s WHERE scope_token_hash = ?", + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash( + fixture.connectScopeId())) + .fetchOne(0, String.class)); + } + + private AtomicBoolean losePublicJoinTerminalResponse(PublicJoinFixture fixture) { + var committed = new AtomicBoolean(); + var readbackDropped = new AtomicBoolean(); + org.mockito.Mockito.doAnswer( + invocation -> { + invocation.callRealMethod(); + org.springframework.transaction.support.TransactionSynchronizationManager + .registerSynchronization( + new org.springframework.transaction.support.TransactionSynchronization() { + @Override + public void afterCommit() { + committed.set(true); + throw new IllegalStateException("Injected lost public JOIN commit ACK"); + } + }); + return null; + }) + .when(joinOperationRepository) + .finish( + org.mockito.ArgumentMatchers.eq(fixture.caller().requestId()), + org.mockito.ArgumentMatchers.eq("COMMITTED"), + org.mockito.ArgumentMatchers.eq("JOINED"), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.doAnswer( + invocation -> { + if (committed.get() && readbackDropped.compareAndSet(false, true)) { + throw new org.springframework.dao.DataAccessResourceFailureException( + "Injected unavailable first post-commit JOIN readback"); + } + return invocation.callRealMethod(); + }) + .when(joinOperationRepository) + .find(fixture.caller().requestId()); + return readbackDropped; + } + + private void assertPublicJoinUnavailable(PublicJoinFixture fixture) { + var unavailable = + org.junit.jupiter.api.Assertions.assertThrows( + AuthenticationException.class, () -> publicJoin(fixture)); + assertThat(unavailable.getCode()).isEqualTo("AUTH_UNAVAILABLE"); + } + + private JoinPublicProductionResult publicJoin(PublicJoinFixture fixture) { + return accountService.joinPublicProductionFromGameSession( + fixture.caller(), + new JoinPublicProductionRequest(fixture.connectScopeId(), fixture.caller().requestId())); + } + + private PublicJoinFixture publicJoinFixture() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String world = "join-" + suffix; + var account = + accountService.createAccount( + new CreateAccountRequest(world, world + "@example.com", "password123")); + long accountId = + java.util.Objects.requireNonNull( + dsl.resultQuery( + "SELECT id FROM accounts WHERE account_uuid = ?", UUID.fromString(account.id())) + .fetchOne(0, Long.class)); + long tenantId = 6000000000L + accountId; + dsl.execute( + "INSERT INTO subscription(account_id,plan_id,status,tenant_id,entitlement_version) " + + "VALUES(?,'join-proof','active',?,1)", + accountId, + tenantId); + UUID realmId = UUID.randomUUID(); + String namespace = UUID.randomUUID().toString(); + var realm = + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setTenantId(Long.toString(tenantId)) + .setRealmId(realmId.toString()) + .setWorldSlug(world) + .setRealmSlug("production") + .setPlayableStateNamespaceId(namespace) + .setStateScope("SHARED") + .setGameInstanceId("44") + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .build(); + var pointer = + net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() + .setTenantId(Long.toString(tenantId)) + .setRealmId(realmId.toString()) + .setWorldSlug(world) + .setRealmSlug("production") + .setPlayableStateNamespaceId(namespace) + .setStateScope("SHARED") + .setGameInstanceId("44") + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .build(); + org.mockito.Mockito.when(gameSessionClient.listGameplayRealms(world)) + .thenReturn(List.of(realm)); + org.mockito.Mockito.when(gameSessionClient.getAdmissionPointer(tenantId, world, "production")) + .thenReturn(pointer); + var caller = + new DirectTextCallerContext( + accountId, + tenantId, + realmId, + namespace, + "SHARED", + 44L, + "controlled-join-session-" + suffix, + "original-join-" + suffix); + var scope = + accountService.issueDirectTextConnectScope( + caller, + new DirectTextJoinTarget( + tenantId, realmId, world, "production", namespace, "SHARED", 44L, 23L, 17L)); + return new PublicJoinFixture(accountId, account.id(), tenantId, caller, scope.connectScopeId()); + } + + private long publicJoinMembershipCount(PublicJoinFixture fixture) { + return java.util.Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", + fixture.accountId(), + fixture.tenantId()) + .fetchOne(0, Long.class)); + } + + private UUID publicJoinAuditId(PublicJoinFixture fixture) { + return UUID.nameUUIDFromBytes( + ("account-join-audit/v1:" + fixture.caller().requestId()).getBytes(StandardCharsets.UTF_8)); + } + + private long publicJoinAuditCount(PublicJoinFixture fixture) { + return java.util.Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_audit_outbox WHERE audit_event_id = ?", + publicJoinAuditId(fixture)) + .fetchOne(0, Long.class)); + } + + private void assertPublicJoinCommittedOnce(PublicJoinFixture fixture) { + assertThat(publicJoinMembershipCount(fixture)).isEqualTo(1L); + assertThat(publicJoinAuditCount(fixture)).isEqualTo(1L); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM account_join_operations j " + + "JOIN account_tenant_membership m ON m.id = j.membership_id " + + "WHERE j.request_id = ? AND j.status = 'COMMITTED' AND j.outcome = 'JOINED' " + + "AND j.account_id = ? AND j.tenant_id = ? " + + "AND m.account_id = j.account_id AND m.tenant_id = j.tenant_id " + + "AND m.lifecycle_state = 'ACTIVE' AND m.authority_provenance = 'EXPLICIT_JOIN' " + + "AND m.membership_version = 1 AND m.membership_authority_generation = 1 " + + "AND j.outcome_membership_version = m.membership_version " + + "AND j.outcome_membership_authority_generation = m.membership_authority_generation", + fixture.caller().requestId(), + fixture.accountId(), + fixture.tenantId())) + .isEqualTo(1L); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM account_audit_outbox " + + "WHERE audit_event_id = ? AND scope = 'tenant' AND tenant_id = ? " + + "AND producer_service = 'account-service' " + + "AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION' " + + "AND payload::jsonb ->> 'requestId' = ? " + + "AND payload::jsonb ->> 'accountId' = ? " + + "AND payload::jsonb ->> 'membershipVersion' = '1'", + publicJoinAuditId(fixture), + fixture.tenantId(), + fixture.caller().requestId(), + Long.toString(fixture.accountId()))) + .isEqualTo(1L); + } + + private List publicJoinState(PublicJoinFixture fixture) { + return List.of( + dsl.resultQuery( + "SELECT row_to_json(j)::text FROM account_join_operations j WHERE request_id = ?", + fixture.caller().requestId()) + .fetchOne(0, String.class), + dsl.resultQuery( + "SELECT row_to_json(m)::text FROM account_tenant_membership m " + + "WHERE account_id = ? AND tenant_id = ?", + fixture.accountId(), + fixture.tenantId()) + .fetchOne(0, String.class), + dsl.resultQuery( + // Delivery retry diagnostics may advance independently of original JOIN evidence. + "SELECT (to_jsonb(a) - ARRAY['attempt_count','last_attempt_at','next_attempt_at'])::text " + + "FROM account_audit_outbox a WHERE audit_event_id = ?", + publicJoinAuditId(fixture)) + .fetchOne(0, String.class), + dsl.resultQuery( + "SELECT row_to_json(s)::text FROM account_connect_scope_records s " + + "JOIN account_join_operations j ON j.scope_token_hash = s.scope_token_hash " + + "WHERE j.request_id = ?", + fixture.caller().requestId()) + .fetchOne(0, String.class)); + } + + private record PublicJoinFixture( + long accountId, + String accountUuid, + long tenantId, + DirectTextCallerContext caller, + String connectScopeId) {} + @Test void publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly() throws Exception { String suffix = UUID.randomUUID().toString().substring(0, 8); @@ -478,7 +1140,7 @@ void publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly() throws } @Test - void ordinaryUuidPasswordOtpBootstrapJourneysPreserveIdentityWithPublicConsumersHeld() + void ordinaryUuidPasswordOtpBootstrapAndScopeJourneysPreservePersistedIdentity() throws Exception { String suffix = UUID.randomUUID().toString().substring(0, 8); String username = "auth-uuid-" + suffix; @@ -569,58 +1231,14 @@ void ordinaryUuidPasswordOtpBootstrapJourneysPreserveIdentityWithPublicConsumers assertThat(bootstrapClaims.getSubject()).isEqualTo(persistedAccountUuid.toString()); assertThat(bootstrapClaims.get("accountId", String.class)) .isEqualTo(persistedAccountUuid.toString()); + org.mockito.Mockito.when(gameSessionClient.listGameplayWorlds()) + .thenReturn(java.util.List.of()); String passwordBootstrap = bootstrapData.path("bootstrapToken").asText(); - assertThat(bootstrapClaims.getAudience()).containsExactly("player-bootstrap"); - assertThat(realAccountSessions.isAccountSessionActive(numericAccountId, passwordBootstrap)) - .isTrue(); - HttpResponse heldPasswordWorlds = bootstrapWorlds(passwordBootstrap); - assertThat(heldPasswordWorlds.statusCode()).isEqualTo(503); - assertThat(heldPasswordWorlds.body()).contains("AUTH_UNAVAILABLE"); - // This foundation has genuine Account identity/session issuance but no public selector or - // admission composition. The complete positive public journeys are retained in the successor. - for (Runnable held : - List.of( - () -> accountService.listBootstrapWorlds(passwordBootstrap), - () -> accountService.listBootstrapRealms(passwordBootstrap, "world"), - () -> - accountService.listBootstrapCharacters( - passwordBootstrap, "world", "production", "uncomposed-scope"), - () -> - accountService.joinPublicProduction( - passwordBootstrap, - new JoinPublicProductionRequest("uncomposed-scope", "foundation-join")), - () -> accountService.issueDirectTextConnectScope(null, null), - () -> - accountService.joinPublicProductionFromGameSession( - null, - new JoinPublicProductionRequest("uncomposed-scope", "foundation-direct-join")), - () -> - accountService.issueConnectToken( - passwordBootstrap, - new ConnectTokenRequest("uncomposed-scope", "foundation-connect")))) { - assertThatThrownBy(held::run) - .isInstanceOf(AuthenticationException.class) - .extracting(value -> ((AuthenticationException) value).getCode()) - .isEqualTo("AUTH_UNAVAILABLE"); - } - assertThat( - dsl.fetchValue( - "SELECT COUNT(*) FROM account_tenant_membership WHERE account_id = ?", - numericAccountId)) - .isEqualTo(0L); - assertThat( - dsl.fetchValue( - "SELECT COUNT(*) FROM account_connect_scope_records WHERE account_id = ?", - numericAccountId)) - .isEqualTo(0L); - assertThat( - dsl.fetchValue( - "SELECT COUNT(*) FROM account_join_operations WHERE account_id = ?", - numericAccountId)) - .isEqualTo(0L); + assertThat(bootstrapWorlds(passwordBootstrap).statusCode()).isEqualTo(200); invalidateBootstrapSession(numericAccountId, passwordBootstrap); - assertThat(realAccountSessions.isAccountSessionActive(numericAccountId, passwordBootstrap)) - .isFalse(); + HttpResponse expiredPassword = bootstrapWorlds(passwordBootstrap); + assertThat(expiredPassword.statusCode()).isEqualTo(401); + assertThat(expiredPassword.body()).contains("CONNECT_CONTEXT_INVALID"); accountService.requestEmailVerification(email); String verificationToken = @@ -678,14 +1296,9 @@ void ordinaryUuidPasswordOtpBootstrapJourneysPreserveIdentityWithPublicConsumers "Expected challenge-count record") .get(0, Long.class)) .isZero(); - assertThat(otpClaims.getAudience()).containsExactly("player-bootstrap"); - assertThat(realAccountSessions.isAccountSessionActive(numericAccountId, otpBootstrap)).isTrue(); - HttpResponse heldOtpWorlds = bootstrapWorlds(otpBootstrap); - assertThat(heldOtpWorlds.statusCode()).isEqualTo(503); - assertThat(heldOtpWorlds.body()).contains("AUTH_UNAVAILABLE"); + assertThat(bootstrapWorlds(otpBootstrap).statusCode()).isEqualTo(200); invalidateBootstrapSession(numericAccountId, otpBootstrap); - assertThat(realAccountSessions.isAccountSessionActive(numericAccountId, otpBootstrap)) - .isFalse(); + assertThat(bootstrapWorlds(otpBootstrap).statusCode()).isEqualTo(401); // Obtain a fresh real challenge: bootstrap issuance consumed the preceding one. accountService.requestEmailLoginOtp(email); @@ -784,28 +1397,182 @@ void ordinaryUuidPasswordOtpBootstrapJourneysPreserveIdentityWithPublicConsumers } @Test - void retainedProfileUuidProjectionAndControlAuthorizationPreservePersistedIdentity() - throws Exception { + void browserAndControlledDirectScopesRetainUuidClaimsAndPrivateJoinRows() throws Exception { String suffix = UUID.randomUUID().toString().substring(0, 8); - String username = "profile-" + suffix; + String username = "scope-" + suffix; var account = accountService.createAccount( - new CreateAccountRequest(username, username + "@example.com", "password123")); + new net.firedevops.firemud.accountservice.dto.CreateAccountRequest( + username, username + "@example.com", "password123")); + var persistedAccount = + java.util.Objects.requireNonNull( + dsl.fetchOne( + "SELECT id FROM accounts WHERE account_uuid=?", UUID.fromString(account.id())), + "Expected persisted Account"); long row = - Objects.requireNonNull( - dsl.fetchOne( - "SELECT id FROM accounts WHERE account_uuid = ?", - UUID.fromString(account.id()))) - .get(0, Long.class); + java.util.Objects.requireNonNull( + persistedAccount.get(0, Long.class), "Expected persisted Account storage key"); long tenant = 500000000L + Integer.toUnsignedLong(suffix.hashCode()); - // Retained profile access checks relationship existence; this quarantined row grants no - // gameplay. dsl.execute( - "INSERT INTO account_tenant_membership (account_id, tenant_id, lifecycle_state, " - + "gameplay_admission_allowed, membership_version, membership_authority_generation, authority_provenance) " - + "VALUES (?, ?, 'LEGACY_UNVERIFIED', FALSE, 1, 1, 'LEGACY_UNVERIFIED')", + "INSERT INTO subscription(account_id,plan_id,status,tenant_id,entitlement_version) VALUES(?,'scope-proof','active',?,1)", row, tenant); + String realm = UUID.randomUUID().toString(); + String namespace = UUID.randomUUID().toString(); + var target = + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("scope-proof") + .setRealmSlug("production") + .setDisplayName("Scope proof") + .setTenantId(Long.toString(tenant)) + .setGameInstanceId("44") + .setRealmId(realm) + .setPlayableStateNamespaceId(namespace) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build(); + org.mockito.Mockito.when(gameSessionClient.listGameplayRealms("scope-proof")) + .thenReturn(java.util.List.of(target)); + org.mockito.Mockito.when( + gameSessionClient.getAdmissionPointer(tenant, "scope-proof", "production")) + .thenReturn( + net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() + .setWorldSlug("scope-proof") + .setRealmSlug("production") + .setTenantId(Long.toString(tenant)) + .setGameInstanceId("44") + .setRealmId(realm) + .setPlayableStateNamespaceId(namespace) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build()); + var bootstrap = accountService.issuePlayerBootstrap(username, "password123"); + String browser = + accountService + .listBootstrapRealms(bootstrap.bootstrapToken(), "scope-proof") + .getFirst() + .connectScopeId(); + var player = + net.firedevops.firemud.shared.v1.PlayerExecutionContext.newBuilder() + .setAccountId(account.id()) + .setTenantId(Long.toString(tenant)) + .setRealmId(realm) + .setPlayableStateNamespaceId(namespace) + .setPlayableStateScope("SHARED") + .setGameInstanceId("44") + .setSessionId("controlled-session") + .setRequestId("scope-direct-" + suffix) + .build(); + var request = + net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeRequest.newBuilder() + .setPlayerContext(player) + .setTenantId(Long.toString(tenant)) + .setRealmId(realm) + .setWorldSlug("scope-proof") + .setRealmSlug("production") + .setPlayableStateNamespaceId(namespace) + .setPlayableStateScope("SHARED") + .setGameInstanceId("44") + .setCatalogRevision(23L) + .setPointerVersion(17L) + .build(); + var response = + new java.util.concurrent.atomic.AtomicReference< + net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse>(); + var receiver = + new net.firedevops.firemud.accountservice.service.impl.AccountGrpcService( + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.service.PingService.class), + accountService, + null, + "test"); + var context = + io.grpc.Context.ROOT.withValue( + net.firedevops.firemud.common.grpc.GrpcPeerIdentity.CONTEXT_KEY, + new net.firedevops.firemud.common.grpc.GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/game-session-service", + "test", + "game-session-service")); + context.run( + () -> + receiver.issueDirectTextConnectScope( + request, + new io.grpc.stub.StreamObserver<>() { + @Override + public void onNext( + net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable error) { + org.junit.jupiter.api.Assertions.fail(error); + } + + @Override + public void onCompleted() {} + })); + var directResponse = + java.util.Objects.requireNonNull(response.get(), "Expected controlled direct response"); + assertThat(directResponse.hasError()).isFalse(); + String direct = directResponse.getConnectScopeId(); + var scopes = + new net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository(dsl); + for (String token : java.util.List.of(browser, direct)) { + var claims = jwtUtil.parseToken(token).getPayload(); + assertThat(claims.getSubject()).isEqualTo(account.id()); + assertThat(claims.get("accountId", String.class)).isEqualTo(account.id()); + var retained = scopes.find(token).orElseThrow(); + assertThat(retained.accountId()).isEqualTo(row); + assertThat(retained.snapshotDigest()) + .isEqualTo(net.firedevops.firemud.accountservice.dto.AccountJoinDigest.scope(retained)); + var held = + org.junit.jupiter.api.Assertions.assertThrows( + net.firedevops.firemud.accountservice.service.exception.AuthenticationException.class, + () -> + accountService.issueConnectToken( + bootstrap.bootstrapToken(), + new net.firedevops.firemud.accountservice.dto.ConnectTokenRequest( + token, "held-" + suffix))); + assertThat(held.getCode()).isEqualTo("AUTH_UNAVAILABLE"); + assertThat(scopes.find(token)).contains(retained); + } + var browserJoin = + new net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest( + browser, "scope-browser-" + suffix); + var first = accountService.joinPublicProduction(bootstrap.bootstrapToken(), browserJoin); + assertThat(first.success()).isTrue(); + assertThat(first.accountId()).isEqualTo(account.id()); + assertThat( + accountService.joinPublicProduction(bootstrap.bootstrapToken(), browserJoin).replayed()) + .isTrue(); + var caller = + new net.firedevops.firemud.accountservice.dto.DirectTextCallerContext( + row, + tenant, + UUID.fromString(realm), + namespace, + "SHARED", + 44L, + "controlled-session", + "scope-direct-" + suffix); + var directJoin = + new net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest( + direct, caller.requestId()); + assertThat(accountService.joinPublicProductionFromGameSession(caller, directJoin).success()) + .isTrue(); + assertThat(accountService.joinPublicProductionFromGameSession(caller, directJoin).replayed()) + .isTrue(); + assertThat(accountService.joinPublicProductionFromGameSession(caller, directJoin).accountId()) + .isEqualTo(account.id()); dsl.execute( "INSERT INTO profiles(account_id,tenant_id,display_name,bio,presence_visibility_policy) " + "VALUES(?,?,?,?, 'HIDDEN_STAFF')", @@ -1054,6 +1821,8 @@ void retainedProfileUuidProjectionAndControlAuthorizationPreservePersistedIdenti "Expected retained private profile owner row") .get(0, Long.class)) .isEqualTo(row); + assertThat(scopes.find(browser)).isPresent(); + assertThat(scopes.find(direct)).isPresent(); } private void assertOrdinaryCredentialPreservesSocialGuildSelf( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java new file mode 100644 index 0000000000..1f5d79c7b6 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java @@ -0,0 +1,614 @@ +package net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.grpc.ManagedChannel; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.io.IOException; +import java.net.URI; +import java.net.URLEncoder; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.cert.CertificateEncodingException; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.client.GameSessionClient; +import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus; +import net.firedevops.firemud.entitymanagement.mapper.CharacterMapper; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.service.PlayableStateKeyResolver; +import net.firedevops.firemud.entitymanagement.service.ScopedCharacterResolver; +import net.firedevops.firemud.entitymanagement.service.impl.CharacterServiceImpl; +import net.firedevops.firemud.entitymanagement.service.impl.EntityManagementGrpcService; +import net.firedevops.firemud.entitymanagement.v1.EntityManagementServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountRequest; +import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.test.GatewayTestProperties; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.flywaydb.core.api.configuration.FluentConfiguration; +import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.mapstruct.factory.Mappers; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.cache.concurrent.ConcurrentMapCacheManager; +import org.springframework.http.HttpHeaders; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Composes real Account bootstrap HTTP with its mTLS Entity roster client and real Entity storage. + * Game Session target reads, test-owned membership rows, and test PKI are controlled fixtures; this + * proves neither World-owned active lifecycle nor public admission or first OPEN. Entity RPCs not + * used by ordinary roster reads remain mocked. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + webEnvironment = WebEnvironment.RANDOM_PORT, + classes = AccountServiceApplication.class, + properties = { + "spring.config.import=classpath:account-main-application.yml", + "spring.grpc.server.port=0", + "firemud.grpc.workload-namespace=test", + GatewayTestProperties.SPRING_GRPC_SERVER_SSL_DISABLED, + "firemud.mail.verification-url=https://account.test/verify-email?token=%s" + }) +class BootstrapCharacterUuidEntityCompositionIntegrationTest { + private static final String TEST_NAMESPACE = "test"; + private static final String TEST_ACCOUNT_PEER = "spiffe://firemud/ns/test/sa/account-service"; + private static final String TEST_ENTITY_PEER = + "spiffe://firemud/ns/test/sa/entity-management-service"; + private static final long TARGET_TENANT_ID = 1L; + private static final long TARGET_GAME_INSTANCE_ID = 44L; + private static final String WORLD_SLUG = "uuid-bootstrap-proof"; + private static final String REALM_SLUG = "production"; + private static final UUID TARGET_REALM_ID = + UUID.fromString("d8f8de2e-89fd-4432-8cb4-93f241f56af6"); + private static final UUID TARGET_NAMESPACE_ID = + UUID.fromString("f711c0c9-c1fc-46fb-8ff2-1af7c4d96a67"); + private static final long RETAINED_NUMERIC_ACCOUNT_ID = 98765L; + + private static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient(); + private static final Path PKI_DIRECTORY = createTemporaryDirectory(); + private static final LoopbackMtlsTestPki.Pki TEST_PKI = createTestPki(); + private static final CommonGrpcClientProperties ACCOUNT_CLIENT_TLS = createAccountClientTls(); + private static final PostgreSQLContainer entityPostgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static PostgreSQLContainer accountPostgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + private static volatile EntityRuntime entityRuntime; + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, accountPostgres, "account_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + registry.add("firemud.services.entity-management-service", () -> entityServiceTarget()); + registry.add("FIREMUD_GRPC_CERT_CHAIN_PATH", ACCOUNT_CLIENT_TLS::getCertChain); + registry.add("FIREMUD_GRPC_PRIVATE_KEY_PATH", ACCOUNT_CLIENT_TLS::getPrivateKey); + registry.add("FIREMUD_GRPC_CA_CERT_PATH", ACCOUNT_CLIENT_TLS::getCaCert); + } + + @LocalServerPort private int accountHttpPort; + @Autowired private DSLContext accountDsl; + @Autowired private JwtUtil jwtUtil; + + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private LoggingAdminClient loggingAdminClient; + @MockitoBean private JavaMailSender mailSender; + + private final JsonMapper jsonMapper = JsonMapper.builder().build(); + + @org.junit.jupiter.api.AfterAll + static void stopEntityRuntime() throws InterruptedException { + EntityRuntime runtime = entityRuntime; + if (runtime != null) { + runtime.server().shutdownNow(); + assertThat(runtime.server().awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + runtime.meters().close(); + } + if (entityPostgres.isRunning()) { + entityPostgres.stop(); + } + } + + @org.junit.jupiter.api.Test + void bootstrapCharactersUsePersistedUuidAcrossHttpAndRealEntityOwnerReads() throws Exception { + stubControlledCurrentTarget(); + + String suffix = UUID.randomUUID().toString().substring(0, 8); + TestAccount ownerA = registerAccount("uuid-owner-a-" + suffix); + TestAccount ownerB = registerAccount("uuid-owner-b-" + suffix); + assertThat(ownerA.accountUuid()).isNotEqualTo(ownerB.accountUuid()); + seedAdmittingMembership(ownerA.storageId()); + seedAdmittingMembership(ownerB.storageId()); + seedActiveSubscription(ownerA.storageId()); + + EntityRuntime entity = requireEntityRuntime(); + String ownerACharacterName = "owned-by-a-" + suffix; + String ownerBCharacterName = "owned-by-b-" + suffix; + String wrongTenantCharacterName = "wrong-tenant-a-" + suffix; + var ownerACharacter = + saveOrdinaryCharacter( + entity, TARGET_TENANT_ID, ownerA.accountUuid(), ownerACharacterName, "shared-live"); + var ownerBCharacter = + saveOrdinaryCharacter( + entity, TARGET_TENANT_ID, ownerB.accountUuid(), ownerBCharacterName, "shared-live"); + var wrongTenantCharacter = + saveOrdinaryCharacter( + entity, + TARGET_TENANT_ID + 1, + ownerA.accountUuid(), + wrongTenantCharacterName, + "shared-live"); + + assertOrdinaryUuidRowIsQuarantined(entity, ownerACharacter.getId(), ownerA.accountUuid()); + assertOrdinaryUuidRowIsQuarantined(entity, ownerBCharacter.getId(), ownerB.accountUuid()); + assertOrdinaryUuidRowIsQuarantined(entity, wrongTenantCharacter.getId(), ownerA.accountUuid()); + + var retainedBefore = retainedNumericOwnerRow(entity); + assertThat(retainedBefore).hasSize(1); + + String ownerAToken = issuePlayerBootstrap(ownerA); + String ownerBToken = issuePlayerBootstrap(ownerB); + String ownerAScope = discoverConnectScope(ownerA, ownerAToken); + String ownerBScope = discoverConnectScope(ownerB, ownerBToken); + + JsonNode ownerACharacters = listBootstrapCharacters(ownerAToken, ownerAScope); + JsonNode ownerBCharacters = listBootstrapCharacters(ownerBToken, ownerBScope); + + assertThat(characterNames(ownerACharacters)).containsExactly(ownerACharacterName); + assertThat(characterNames(ownerACharacters)) + .doesNotContain(ownerBCharacterName, wrongTenantCharacterName); + assertThat(characterNames(ownerBCharacters)).containsExactly(ownerBCharacterName); + assertThat(characterNames(ownerBCharacters)).doesNotContain(ownerACharacterName); + + var retainedAccountIdRequest = + ListCharactersByAccountRequest.newBuilder() + .setTenantId(Long.toString(TARGET_TENANT_ID)) + .setAccountId(Long.toString(RETAINED_NUMERIC_ACCOUNT_ID)) + .setGameInstanceId(Long.toString(TARGET_GAME_INSTANCE_ID)) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .build(); + var retainedOwnerResponse = listCharactersDirectlyAsAccount(retainedAccountIdRequest); + assertThat(retainedOwnerResponse.hasError()).isTrue(); + assertThat(retainedOwnerResponse.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(retainedOwnerResponse.getCharactersList()).isEmpty(); + assertThat(retainedNumericOwnerRow(entity)).isEqualTo(retainedBefore); + } + + private TestAccount registerAccount(String username) throws Exception { + String email = username + "@example.com"; + HttpRequest request = + HttpRequest.newBuilder(URI.create(accountBaseUrl() + "/accounts")) + .header(HttpHeaders.CONTENT_TYPE, "application/json") + .POST( + HttpRequest.BodyPublishers.ofString( + jsonMapper.writeValueAsString( + Map.of("username", username, "email", email, "password", "password123")))) + .build(); + HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); + assertThat(response.statusCode()).as(response.body()).isEqualTo(200); + + String responseUuid = jsonMapper.readTree(response.body()).path("data").path("id").asText(); + UUID accountUuid = UUID.fromString(responseUuid); + Number accountId = + accountDsl + .resultQuery("SELECT id FROM accounts WHERE email = ?", email) + .fetchOne(0, Number.class); + assertThat(accountId).isNotNull(); + long storageId = accountId.longValue(); + assertThat( + accountDsl + .resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", storageId) + .fetchOne(0, UUID.class)) + .isEqualTo(accountUuid); + assertThat( + accountDsl + .resultQuery( + "SELECT account_uuid_source_numeric_id FROM accounts WHERE id = ?", storageId) + .fetchOne(0, Long.class)) + .isEqualTo(storageId); + assertThat( + accountDsl + .resultQuery("SELECT account_uuid_provenance FROM accounts WHERE id = ?", storageId) + .fetchOne(0, String.class)) + .isEqualTo("ACCOUNT_REPOSITORY_INSERT"); + return new TestAccount(username, email, storageId, accountUuid); + } + + private void seedAdmittingMembership(long accountId) { + // This is test-owned Account state for the existing roster guard, not canonical membership + // proof. + accountDsl.execute( + "INSERT INTO account_tenant_membership " + + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " + + "membership_version, membership_authority_generation, authority_provenance) " + + "VALUES (?, ?, TRUE, 'ACTIVE', 1, 1, 'SEEDED_DEMO')", + accountId, + TARGET_TENANT_ID); + } + + private void seedActiveSubscription(long accountId) { + accountDsl.execute( + "INSERT INTO subscription " + + "(account_id, plan_id, status, tenant_id, entitlement_version) " + + "VALUES (?, 'uuid-bootstrap-composition', 'active', ?, 1)", + accountId, + TARGET_TENANT_ID); + } + + private String issuePlayerBootstrap(TestAccount account) throws Exception { + HttpRequest request = + HttpRequest.newBuilder(URI.create(accountBaseUrl() + "/auth/player-bootstrap")) + .header(HttpHeaders.CONTENT_TYPE, "application/json") + .POST( + HttpRequest.BodyPublishers.ofString( + jsonMapper.writeValueAsString( + Map.of("accountIdentifier", account.username(), "secret", "password123")))) + .build(); + HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); + assertThat(response.statusCode()).as(response.body()).isEqualTo(200); + JsonNode data = jsonMapper.readTree(response.body()).path("data"); + assertThat(data.path("accountId").asText()).isEqualTo(account.accountUuid().toString()); + String bootstrapToken = data.path("bootstrapToken").asText(); + var claims = jwtUtil.parseToken(bootstrapToken).getPayload(); + assertThat(claims.getSubject()).isEqualTo(account.accountUuid().toString()); + assertThat(claims.get("accountId", String.class)).isEqualTo(account.accountUuid().toString()); + return bootstrapToken; + } + + private String discoverConnectScope(TestAccount account, String bootstrapToken) throws Exception { + HttpRequest request = + HttpRequest.newBuilder( + URI.create(accountBaseUrl() + "/auth/bootstrap/worlds/" + WORLD_SLUG + "/realms")) + .header(HttpHeaders.AUTHORIZATION, "Bearer " + bootstrapToken) + .GET() + .build(); + HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); + assertThat(response.statusCode()).as(response.body()).isEqualTo(200); + JsonNode realms = jsonMapper.readTree(response.body()).path("data"); + assertThat(realms.isArray()).isTrue(); + assertThat(realms.size()).isEqualTo(1); + JsonNode realm = realms.get(0); + assertThat(realm.path("tenantId").asLong()).isEqualTo(TARGET_TENANT_ID); + String scope = realm.path("connectScopeId").asText(); + var claims = jwtUtil.parseToken(scope).getPayload(); + assertThat(claims.getSubject()).isEqualTo(account.accountUuid().toString()); + assertThat(claims.get("accountId", String.class)).isEqualTo(account.accountUuid().toString()); + return scope; + } + + private JsonNode listBootstrapCharacters(String bootstrapToken, String connectScopeId) + throws Exception { + String encodedScope = URLEncoder.encode(connectScopeId, StandardCharsets.UTF_8); + HttpRequest request = + HttpRequest.newBuilder( + URI.create( + accountBaseUrl() + + "/auth/bootstrap/worlds/" + + WORLD_SLUG + + "/realms/" + + REALM_SLUG + + "/characters?connectScopeId=" + + encodedScope)) + .header(HttpHeaders.AUTHORIZATION, "Bearer " + bootstrapToken) + .GET() + .build(); + HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); + assertThat(response.statusCode()).as(response.body()).isEqualTo(200); + return jsonMapper.readTree(response.body()).path("data"); + } + + private ListCharactersByAccountResponse listCharactersDirectlyAsAccount( + ListCharactersByAccountRequest request) throws Exception { + EntityRuntime runtime = requireEntityRuntime(); + var identity = TEST_PKI.identity("account"); + ManagedChannel channel = + NettyChannelBuilder.forAddress("localhost", runtime.server().getPort()) + .sslContext( + GrpcSslContexts.forClient() + .trustManager(TEST_PKI.caCertificate()) + .keyManager( + identity.privateKey(), identity.certificate(), TEST_PKI.caCertificate()) + .build()) + .intercept(new GrpcServerPeerIdentityClientInterceptor(TEST_ENTITY_PEER)) + .build(); + try { + return EntityManagementServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .listCharactersByAccount(request); + } finally { + channel.shutdownNow(); + assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + + private void stubControlledCurrentTarget() { + var realm = + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug(WORLD_SLUG) + .setRealmSlug(REALM_SLUG) + .setDisplayName("Controlled UUID composition target") + .setTenantId(Long.toString(TARGET_TENANT_ID)) + .setGameInstanceId(Long.toString(TARGET_GAME_INSTANCE_ID)) + .setRealmId(TARGET_REALM_ID.toString()) + .setPlayableStateNamespaceId(TARGET_NAMESPACE_ID.toString()) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build(); + var pointer = + net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() + .setWorldSlug(WORLD_SLUG) + .setRealmSlug(REALM_SLUG) + .setTenantId(Long.toString(TARGET_TENANT_ID)) + .setGameInstanceId(Long.toString(TARGET_GAME_INSTANCE_ID)) + .setRealmId(TARGET_REALM_ID.toString()) + .setPlayableStateNamespaceId(TARGET_NAMESPACE_ID.toString()) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build(); + Mockito.when(gameSessionClient.listGameplayRealms(WORLD_SLUG)).thenReturn(List.of(realm)); + Mockito.when(gameSessionClient.getAdmissionPointer(TARGET_TENANT_ID, WORLD_SLUG, REALM_SLUG)) + .thenReturn(pointer); + } + + private static net.firedevops.firemud.entitymanagement.entity.Character saveOrdinaryCharacter( + EntityRuntime runtime, + long tenantId, + UUID accountUuid, + String name, + String playableStateKey) { + var character = new net.firedevops.firemud.entitymanagement.entity.Character(); + character.setTenantId(tenantId); + character.setAccountUuid(accountUuid); + character.setPlayableStateKey(playableStateKey); + character.setName(name); + return runtime.characterRepository().save(character); + } + + private static void assertOrdinaryUuidRowIsQuarantined( + EntityRuntime runtime, long characterId, UUID accountUuid) { + var persisted = runtime.characterRepository().findById(characterId).orElseThrow(); + assertThat(persisted.getAccountUuid()).isEqualTo(accountUuid); + assertThat(persisted.getAccountId()).isNull(); + assertThat(persisted.getActorIdentity().status()).isEqualTo(ActorIdentityStatus.QUARANTINED); + assertThat(persisted.getActorIdentity().tenantUuid()).isNull(); + assertThat(persisted.getActorIdentity().playableStateNamespaceId()).isNull(); + } + + private static List> retainedNumericOwnerRow(EntityRuntime runtime) { + return runtime + .jdbc() + .queryForList( + "SELECT *, xmin::text AS retained_xmin FROM characters WHERE account_id = ?", + RETAINED_NUMERIC_ACCOUNT_ID); + } + + private static List characterNames(JsonNode characters) { + return java.util.stream.StreamSupport.stream(characters.spliterator(), false) + .map(character -> character.path("characterName").asText()) + .toList(); + } + + private String accountBaseUrl() { + return "http://localhost:" + accountHttpPort; + } + + private static String entityServiceTarget() { + return "localhost:" + requireEntityRuntime().server().getPort(); + } + + private static synchronized EntityRuntime requireEntityRuntime() { + if (entityRuntime != null) { + return entityRuntime; + } + try { + if (!entityPostgres.isRunning()) { + entityPostgres.start(); + } + var dataSource = + new DriverManagerDataSource( + entityPostgres.getJdbcUrl(), + entityPostgres.getUsername(), + entityPostgres.getPassword()); + String migrationProperty = + System.getProperty("firemud.entity-management.migration-directory"); + if (migrationProperty == null || migrationProperty.isBlank()) { + throw new IllegalStateException("Entity migration directory property is missing or blank"); + } + Path migrationDirectory = Path.of(migrationProperty); + if (!Files.isDirectory(migrationDirectory)) { + throw new IllegalStateException( + "Entity migration directory is unavailable: " + migrationDirectory); + } + entityMigrationConfiguration(dataSource, migrationDirectory) + .target(MigrationVersion.fromVersion("1023")) + .load() + .migrate(); + var jdbc = new JdbcTemplate(dataSource); + jdbc.update( + "INSERT INTO characters (tenant_id, account_id, name) VALUES (?, ?, ?)", + TARGET_TENANT_ID, + RETAINED_NUMERIC_ACCOUNT_ID, + "retained-numeric-owner"); + entityMigrationConfiguration(dataSource, migrationDirectory).load().migrate(); + + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + var repository = new CharacterRepository(dsl); + var stateKeys = new PlayableStateKeyResolver(); + var meters = new SimpleMeterRegistry(); + var characterService = + new CharacterServiceImpl( + repository, + Mappers.getMapper(CharacterMapper.class), + new ConcurrentMapCacheManager("characterGraph"), + meters, + stateKeys, + new ScopedCharacterResolver(repository, stateKeys)); + var receiver = + new EntityManagementGrpcService( + Mockito.mock(net.firedevops.firemud.entitymanagement.service.PingService.class), + characterService, + Mockito.mock(net.firedevops.firemud.entitymanagement.service.ActorStateService.class), + Mockito.mock( + net.firedevops.firemud.entitymanagement.service.ActorConditionMutationService + .class), + Mockito.mock( + net.firedevops.firemud.entitymanagement.service.EntityDraftDesignDigestService + .class), + Mockito.mock(net.firedevops.firemud.entitymanagement.service.EquipmentService.class), + Mockito.mock(net.firedevops.firemud.entitymanagement.service.InventoryService.class), + Mockito.mock(net.firedevops.firemud.entitymanagement.service.ContainerService.class), + Mockito.mock(net.firedevops.firemud.entitymanagement.service.RoomEntityService.class), + Mockito.mock( + net.firedevops.firemud.entitymanagement.service.RuntimeInstanceCleanupService + .class), + Mockito.mock( + net.firedevops.firemud.entitymanagement.service.impl + .EntityMutationEffectReplayService.class), + Mockito.mock( + net.firedevops.firemud.entitymanagement.service.EntityUpgradeValidationService + .class), + Mockito.mock( + net.firedevops.firemud.entitymanagement.service.EntityTemplateReferenceService + .class), + Mockito.mock( + net.firedevops.firemud.common.security.GameplaySessionAttestationService.class), + meters, + Mockito.mock( + net.firedevops.firemud.entitymanagement.effect.EffectPayloadParser.class), + TEST_NAMESPACE); + var entityIdentity = TEST_PKI.identity("entity"); + Server server = + NettyServerBuilder.forPort(0) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + entityIdentity.privateKey(), entityIdentity.certificate())) + .trustManager(TEST_PKI.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(receiver, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + entityRuntime = new EntityRuntime(repository, jdbc, server, meters); + return entityRuntime; + } catch (IOException | RuntimeException failure) { + if (entityPostgres.isRunning()) { + entityPostgres.stop(); + } + throw new IllegalStateException( + "Could not start the real Entity mTLS owner fixture", failure); + } + } + + private static FluentConfiguration entityMigrationConfiguration( + DriverManagerDataSource dataSource, Path migrationDirectory) { + FluentConfiguration configuration = + Flyway.configure() + .dataSource(dataSource) + .locations( + "filesystem:" + migrationDirectory, + "filesystem:" + + migrationDirectory + .resolve( + "../../../../../../common-saga/src/main/resources/db/migration/saga") + .normalize()) + .placeholders(Map.of("serviceSchema", "public")); + configuration + .getConfigurationExtension(PostgreSQLConfigurationExtension.class) + .setTransactionalLock(false); + return configuration; + } + + private static Path createTemporaryDirectory() { + try { + return Files.createTempDirectory("firemud-account-entity-composition-"); + } catch (Exception failure) { + throw new ExceptionInInitializerError(failure); + } + } + + private static LoopbackMtlsTestPki.Pki createTestPki() { + try { + return LoopbackMtlsTestPki.create( + PKI_DIRECTORY, + "Account-to-Entity composition proof CA", + new LoopbackMtlsTestPki.IdentitySpec("entity", TEST_ENTITY_PEER, true), + new LoopbackMtlsTestPki.IdentitySpec("account", TEST_ACCOUNT_PEER, false)); + } catch (Exception failure) { + throw new ExceptionInInitializerError(failure); + } + } + + private static CommonGrpcClientProperties createAccountClientTls() { + try { + return TEST_PKI.clientProperties(PKI_DIRECTORY, TEST_PKI.identity("account")); + } catch (CertificateEncodingException | java.io.IOException failure) { + throw new ExceptionInInitializerError(failure); + } + } + + private record TestAccount(String username, String email, long storageId, UUID accountUuid) {} + + private record EntityRuntime( + CharacterRepository characterRepository, + JdbcTemplate jdbc, + Server server, + SimpleMeterRegistry meters) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java index 5bd793cce0..706cd84e0c 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java @@ -38,7 +38,6 @@ import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; import net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository; -import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback.LatestSourceSnapshot; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; @@ -786,6 +785,7 @@ private AccountServiceImpl newService( fixture.logoutAllOperations(), fixture.securityStateOperations(), fixture.sourceChanges(), + null, // audit outbox null, // connect scopes null, // join operations null, // email login challenges @@ -795,8 +795,7 @@ private AccountServiceImpl newService( null, // profiles null, // profile mapper null, // payment transactions - // retained subscription evidence - org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), + null, // subscriptions null, // external account identities fixture.tokens(), null, // email verification tokens @@ -807,6 +806,8 @@ private AccountServiceImpl newService( null, null, null, + null, + null, fixture.transactionManager()); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityCurrentnessIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityCurrentnessIntegrationTest.java index 9cdae492d6..efbabc1e55 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityCurrentnessIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityCurrentnessIntegrationTest.java @@ -1,9 +1,7 @@ package integration.net.firedevops.firemud.accountservice.repository; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import java.time.Duration; import java.time.Instant; import java.util.List; import java.util.Map; @@ -16,12 +14,9 @@ import java.util.concurrent.TimeUnit; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountRealmAccessGrant; -import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; -import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; -import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionCurrentReceipt; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Outcome; +import net.firedevops.firemud.accountservice.entity.Subscription; import net.firedevops.firemud.accountservice.repository.AccountRealmAccessGrantRepository; +import net.firedevops.firemud.accountservice.repository.SubscriptionRepository; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; @@ -34,7 +29,7 @@ import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.transaction.support.TransactionTemplate; -/** Canonical hosting lifecycle/source currentness and separate realm-grant tombstone/CAS proof. */ +/** Physical V31/V32 currentness proof, isolated from Account lifecycle/source writers. */ class AccountAuthorityCurrentnessIntegrationTest { private static final AccountPostgresIntegrationFixture postgres = new AccountPostgresIntegrationFixture(); @@ -64,115 +59,39 @@ void subscriptionAndRealmGrantMutationsAdvanceCurrentnessAndKeepRevocationTombst JdbcTemplate jdbc = new JdbcTemplate(dataSource); DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); - var fixture = CanonicalHostingSubscriptionTestFixture.create(dataSource); - var claim = - fixture - .service() - .claimProvisioning(fixture.creation().requestId(), 1, UUID.randomUUID()) - .claim(); - UUID initialRequest = UUID.randomUUID(); - var initialCommit = - fixture - .service() - .reconcile( - initialRequest, - fixture.creation().requestId(), - claim.subscriptionRowVersion(), - fixture.providerId(), - claim.attemptId()); - assertThat(initialCommit.outcome()).isEqualTo(Outcome.COMMITTED); - var initial = fixture.service().readCurrent(fixture.tenantId()); - assertThat(initial.entitlementVersion()).isOne(); - assertCanonicalCheckpoint(fixture, initial); - int initialReads = fixture.transport().reads(); - assertThat( - fixture - .service() - .reconcile( - initialRequest, - fixture.creation().requestId(), - claim.subscriptionRowVersion(), - fixture.providerId(), - claim.attemptId())) - .isEqualTo(initialCommit); - assertThat(fixture.transport().reads()).isEqualTo(initialReads); - var initialRetry = fixture.service().readCurrent(fixture.tenantId()); - assertThat(initialRetry.receiptRequestId()).isEqualTo(initial.receiptRequestId()); - assertThat(initialRetry.tenantAuthorityEvent().payload()) - .isEqualTo(initial.tenantAuthorityEvent().payload()); - - fixture.clock().advance(Duration.ofSeconds(1)); - fixture.providerStatus("past_due"); - UUID changedRequest = UUID.randomUUID(); - var changedCommit = - fixture - .service() - .reconcile( - changedRequest, - fixture.creation().requestId(), - initial.current().rowVersion(), - fixture.providerId(), - null); - assertThat(changedCommit.outcome()).isEqualTo(Outcome.COMMITTED); - var changed = fixture.service().readCurrent(fixture.tenantId()); - assertThat(changed.rawProviderStatus()).isEqualTo("past_due"); - assertThat(changed.entitlementVersion()).isGreaterThan(initial.entitlementVersion()); - assertThat(changed.tenantBillingSequence()).isGreaterThan(initial.tenantBillingSequence()); - assertThat(changed.tenantAuthorityEvent().tenantAuthorityGeneration()) - .isGreaterThan(initial.tenantAuthorityEvent().tenantAuthorityGeneration()); - assertThat(changed.tenantAuthorityEvent().outboxSequence()) - .isGreaterThan(initial.tenantAuthorityEvent().outboxSequence()); - assertThat(changed.tenantAuthorityEvent().eventId()) - .isNotEqualTo(initial.tenantAuthorityEvent().eventId()); - assertCanonicalCheckpoint(fixture, changed); - - assertThatThrownBy( - () -> - jdbc.update( - "UPDATE subscription SET status = 'active', row_version = row_version + 1 WHERE subscription_id = ?", - fixture.creation().subscriptionId())) - .isInstanceOf(org.springframework.dao.DataIntegrityViolationException.class); - int changedReads = fixture.transport().reads(); - assertThat( - fixture - .service() - .reconcile( - changedRequest, - fixture.creation().requestId(), - initial.current().rowVersion(), - fixture.providerId(), - null)) - .isEqualTo(changedCommit); - assertThat(fixture.transport().reads()).isEqualTo(changedReads); - var changedRetry = fixture.service().readCurrent(fixture.tenantId()); - assertThat(changedRetry.current()).isEqualTo(changed.current()); - assertThat(changedRetry.receiptRequestId()).isEqualTo(changed.receiptRequestId()); - assertThat(changedRetry.tenantAuthorityEvent().payload()) - .isEqualTo(changed.tenantAuthorityEvent().payload()); - assertCanonicalCheckpoint(fixture, changedRetry); - assertThat( - jdbc.queryForObject( - "SELECT payload FROM account_authority_outbox_events WHERE outbox_stream_key = ? AND outbox_sequence = ?", - byte[].class, - initial.tenantAuthorityEvent().outboxStreamKey(), - initial.tenantAuthorityEvent().outboxSequence())) - .isEqualTo(initial.tenantAuthorityEvent().payload()); - assertThat( - jdbc.queryForObject( - "SELECT count(*) FROM account_authority_outbox_events WHERE outbox_stream_key = ?", - Long.class, - changed.tenantAuthorityEvent().outboxStreamKey())) - .isEqualTo(2L); - assertThat( + Long accountId = + Objects.requireNonNull( jdbc.queryForObject( - "SELECT count(*) FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ?", + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", Long.class, - fixture.tenantId())) - .isEqualTo(2L); + "currentness-" + UUID.randomUUID(), + "currentness-" + UUID.randomUUID() + "@example.test", + "test-hash")); - // Realm grants retain their separate authority and numeric legacy scope in this existing proof. - long accountId = fixture.accountId(); long tenantId = 7_654_322L; + jdbc.update( + "INSERT INTO subscription (account_id, plan_id, status, tenant_id, entitlement_version) " + + "VALUES (?, 'test-plan', 'active', ?, 1)", + accountId, + tenantId); + SubscriptionRepository subscriptions = new SubscriptionRepository(dsl); + Subscription subscription = subscriptions.findByTenantId(tenantId).getFirst(); + UUID initialTenantGeneration = subscription.getTenantAuthorityGeneration(); + assertThat(initialTenantGeneration).isNotNull(); + assertThat(subscription.getEntitlementVersion()).isEqualTo(1L); + + subscription.setStatus("past_due"); + subscriptions.save(subscription); + Subscription repositoryUpdated = subscriptions.findByTenantId(tenantId).getFirst(); + assertThat(repositoryUpdated.getTenantAuthorityGeneration()) + .isNotEqualTo(initialTenantGeneration); + assertThat(repositoryUpdated.getEntitlementVersion()).isEqualTo(2L); + + jdbc.update("UPDATE subscription SET status = 'active' WHERE tenant_id = ?", tenantId); + Subscription directlyUpdated = subscriptions.findByTenantId(tenantId).getFirst(); + assertThat(directlyUpdated.getTenantAuthorityGeneration()) + .isNotEqualTo(repositoryUpdated.getTenantAuthorityGeneration()); + assertThat(directlyUpdated.getEntitlementVersion()).isEqualTo(3L); Account account = new Account(); account.setId(accountId); @@ -222,57 +141,6 @@ void subscriptionAndRealmGrantMutationsAdvanceCurrentnessAndKeepRevocationTombst .isFalse(); } - private static void assertCanonicalCheckpoint( - CanonicalHostingSubscriptionTestFixture.Fixture fixture, - AccountHostingSubscriptionCurrentReceipt receipt) { - var event = receipt.tenantAuthorityEvent(); - assertThat(event.tenantId()).isEqualTo(fixture.tenantId()); - assertThat(event.tenantBillingSequence()).isEqualTo(receipt.tenantBillingSequence()); - assertThat(event.tenantBillingEventId()).isEqualTo(receipt.billingEventId()); - assertThat(event.tenantBillingEventDigest()).isEqualTo(receipt.billingEventDigest()); - fixture - .transaction() - .executeWithoutResult( - status -> { - var currentGeneration = - new AccountAuthorityGenerationRepository(fixture.dsl()) - .read(AuthorityScope.tenant(fixture.tenantId())); - assertThat(currentGeneration.generation()) - .isEqualTo(event.tenantAuthorityGeneration()); - assertThat(currentGeneration.sourceVersion()) - .isEqualTo(event.tenantAuthoritySourceVersion()); - var checkpoint = - new AccountAuthorityOutboxRepository(fixture.dsl()) - .readCheckpoint(event.outboxStreamKey()) - .orElseThrow(); - assertThat(checkpoint.outboxSequence()).isEqualTo(event.outboxSequence()); - assertThat(checkpoint.sourceEventId()).isEqualTo(event.eventId().toString()); - assertThat(checkpoint.sourceEventDigest()).isEqualTo(event.eventDigest()); - assertThat( - fixture - .jdbc() - .queryForObject( - "SELECT event_digest FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ? AND tenant_billing_sequence = ? AND event_id = ?", - String.class, - fixture.tenantId(), - receipt.tenantBillingSequence(), - receipt.billingEventId())) - .isEqualTo(receipt.billingEventDigest()); - assertThat( - fixture - .jdbc() - .queryForMap( - "SELECT current_generation, tenant_billing_sequence, last_outbox_sequence, " - + "last_event_id, last_event_digest FROM account_tenant_authority_source_records WHERE tenant_uuid = ?", - fixture.tenantId())) - .containsEntry("current_generation", event.tenantAuthorityGeneration()) - .containsEntry("tenant_billing_sequence", receipt.tenantBillingSequence()) - .containsEntry("last_outbox_sequence", checkpoint.outboxSequence()) - .containsEntry("last_event_id", event.eventId().toString()) - .containsEntry("last_event_digest", event.eventDigest()); - }); - } - @Test void concurrentRealmGrantWritersCannotOverwriteAnObservedGeneration() throws Exception { String schema = "account_grant_cas_" + UUID.randomUUID().toString().replace("-", ""); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java index a052837a81..caba218cf3 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java @@ -123,6 +123,7 @@ void preV40RetainedPasswordResetFailsTypedAndRollsBackWithoutInventingSource() { .AccountSecurityStateOperationRepository(dsl), new net.firedevops.firemud.accountservice.service .AccountPasswordResetDraftSourceChangeRepository(dsl), + null, // audit outbox null, null, null, @@ -143,6 +144,8 @@ void preV40RetainedPasswordResetFailsTypedAndRollsBackWithoutInventingSource() { null, null, null, + null, + null, manager); // remote clients/JWT/session are not used by reset UUID accountUuid = accounts.findById(accountId).orElseThrow().getAccountUuid(); var beforeToken = diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java index cd5a6a33dd..a36e2e21ba 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java @@ -1434,8 +1434,21 @@ Fixture newFixture(AccountGameplayDelegationRedisClient redisClient) throws Exce return newFixture(redisClient, "latest"); } + Fixture newPlayerEntitlementFixture(AccountGameplayDelegationRedisClient redisClient) + throws Exception { + return newFixture(redisClient, "latest", true); + } + private Fixture newFixture( AccountGameplayDelegationRedisClient redisClient, String migrationTarget) throws Exception { + return newFixture(redisClient, migrationTarget, false); + } + + private Fixture newFixture( + AccountGameplayDelegationRedisClient redisClient, + String migrationTarget, + boolean currentScope) + throws Exception { String schema = SCHEMA_PREFIX + UUID.randomUUID().toString().replace("-", ""); if (schema.length() > 63) throw new IllegalStateException("Generated schema name is too long"); runOwnedSchemas.add(schema); @@ -1452,7 +1465,8 @@ private Fixture newFixture( DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); DataSourceTransactionManager manager = new DataSourceTransactionManager(dataSource); - return new Fixture(schema, dataSource, dsl, manager, temporaryDirectory, redisClient); + return new Fixture( + schema, dataSource, dsl, manager, temporaryDirectory, redisClient, currentScope); } private static int awaitBackendBlockedBy( @@ -2041,7 +2055,8 @@ private Fixture( DSLContext dsl, DataSourceTransactionManager manager, Path temporaryDirectory, - AccountGameplayDelegationRedisClient redisClient) + AccountGameplayDelegationRedisClient redisClient, + boolean currentScope) throws Exception { this.schema = schema; this.dataSource = dataSource; @@ -2111,7 +2126,31 @@ private Fixture( newAccount.setPasswordHash("integration-fixture-password-hash"); newAccount.setRole("player"); this.account = transaction.execute(status -> accounts.save(newAccount)); - this.joinScope = canonicalJoinScope(account.getAccountUuid(), tenantUuid); + var retainedScope = canonicalJoinScope(account.getAccountUuid(), tenantUuid); + this.joinScope = + currentScope + ? new CanonicalJoinScopeV2( + retainedScope.connectScopeId(), + retainedScope.accountId(), + retainedScope.tenantId(), + retainedScope.realmId(), + retainedScope.tenantSlug(), + retainedScope.worldSlug(), + retainedScope.realmSlug(), + retainedScope.playableStateNamespaceId(), + retainedScope.playableStateScope(), + retainedScope.gameInstanceId(), + retainedScope.catalogRevision(), + retainedScope.pointerVersion(), + Instant.now() + .truncatedTo(java.time.temporal.ChronoUnit.SECONDS) + .minusSeconds(5) + .toString(), + Instant.now() + .truncatedTo(java.time.temporal.ChronoUnit.SECONDS) + .plusSeconds(120) + .toString()) + : retainedScope; establishTenantEntitlementAndMembership(connectScopes); AccountAuthEvidenceBundleRepository bundles = @@ -2125,6 +2164,61 @@ private Fixture( this.committedCandidate = createCommittedIssuanceCandidate(bundles, redisClient); } + CanonicalJoinScopeV2 playerEntitlementScope() { + return joinScope; + } + + void beginPlayerEntitlementLoginRevocation() { + var identity = tokenIdentity(committedCandidate); + UUID requestId = UUID.randomUUID(); + transaction.execute( + status -> + tokenFences.beginRevocationIntent( + identity, + requestId, + AccountGameplayTokenIdentityFenceRepository.revocationDigest( + identity, requestId))); + } + + net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner + playerEntitlementOwner(CanonicalGameplayAdmissionDecisionReadClient protectedTargets) { + var scopes = + new AccountConnectScopeRepository( + dsl, + new AccountTenantIdentityResolver( + mock(ApprovedLegacyTenantAssociationRepository.class), TEST_NAMESPACE), + freshTenants); + var snapshots = + new AccountCanonicalRuntimeMembershipSnapshotRepository( + accounts, + generations, + sourceEvidence, + tenantAuthorityEvents, + freshTenants, + memberships, + membershipPairs, + membershipRoles, + authorityOutbox); + return new net.firedevops.firemud.accountservice.service + .AccountPlayerAdmissionEntitlementOwner( + dsl, + accounts, + new AccountGameplayAdmissionCallerVerifier( + signerFixture.trustedJwksSource(), committedIssuanceOwner, Clock.systemUTC()), + issuance, + snapshots, + scopes, + mock(AccountHostingSubscriptionLifecycleRepository.class), + mock( + net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver.class), + demoEntitlements, + tenantAuthorityEvents, + protectedTargets, + manager, + Clock.systemUTC(), + TEST_NAMESPACE); + } + private void establishTenantEntitlementAndMembership( AccountConnectScopeRepository connectScopes) { transaction.execute( 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 deleted file mode 100644 index 266839459d..0000000000 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java +++ /dev/null @@ -1,818 +0,0 @@ -package net.firedevops.firemud.accountservice.repository; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -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.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.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 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 expiredExactAttemptReturnsTypedPendingWithoutMutationAndStaleReplacementStillRefuses() { - Fixture f = fixture("1032"); - var original = claim(f, 1); - prepareAndRead(f, original); - f.clock().advance(Duration.ofSeconds(11)); - var before = new java.util.LinkedHashMap>>(); - for (String table : - List.of( - "subscription", - "subscription_provisioning_work", - "subscription_provisioning_attempts", - "subscription_instrument_reservations")) { - 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()); - assertThatThrownBy(() -> f.tx().execute(status -> f.owner().deferUnresolved(original))) - .hasMessageContaining("stale worker"); - 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. - f.clock().advance(Duration.ofSeconds(11)); - 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(); - f.clock().advance(Duration.ofSeconds(10)); - 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); - f.clock().advance(Duration.ofSeconds(11)); - 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(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 realInitialSdkCreateFlowsThroughExistingLifecycleCommitAndIndependentCurrentRead() { - Fixture f = fixture("1032"); - var result = - (AccountHostingSubscriptionProvisioningService.Committed) - service(f).provision(claim(f, 1), 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); - assertThat(f.transport().subscriptionReads).isGreaterThanOrEqualTo(3); - } - - @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().emptySearchesRemaining = 1; - f.clock().advance(Duration.ofSeconds(2)); - var second = claim(f, first.subscriptionRowVersion()); - var delayed = - (AccountHostingSubscriptionProvisioningService.Pending) - service(f).provision(second, UUID.randomUUID(), UUID.randomUUID()); - assertThat(delayed.disposition()).isEqualTo(Disposition.WAITING); - assertThat(delayed.providerResult()) - .isEqualTo( - new StripeHostingSubscriptionProvisioner.Pending("PROVIDER_LOOKUP_UNRESOLVED", null)); - assertThat(f.transport().creates).isEqualTo(1); - f.clock().advance(Duration.ofSeconds(2)); - var third = claim(f, second.subscriptionRowVersion()); - var result = - (AccountHostingSubscriptionProvisioningService.Committed) - service(f).provision(third, UUID.randomUUID(), UUID.randomUUID()); - assertThat(result.current().current().providerSubscriptionId()).isEqualTo("sub_exact"); - assertThat(f.transport().creates).isEqualTo(1); - assertThat(f.transport().searches).isEqualTo(3); - 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; - ProvisioningClaim previous = first; - for (int attempt = 2; attempt <= 3; attempt++) { - f.clock().advance(Duration.ofSeconds(2)); - 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().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"); - } - - 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) { - return Objects.requireNonNull( - f.tx() - .execute( - s -> - f.owner().claim(f.creation().requestId(), version, UUID.randomUUID()).claim())); - } - - private static AccountHostingSubscriptionProvisioningService service(Fixture f) { - var stripe = new com.stripe.StripeClient(f.transport()); - var lifecycle = - new AccountHostingSubscriptionLifecycleService( - f.owner(), - new StripeHostingSubscriptionObserver( - stripe, f.clock(), Duration.ofMillis(250), Duration.ofSeconds(1)), - new DataSourceTransactionManager(f.source())); - return new AccountHostingSubscriptionProvisioningService( - f.owner(), - new StripeHostingSubscriptionProvisioner( - stripe, f.clock(), false, Duration.ofMillis(250), Duration.ofSeconds(1)), - lifecycle, - new DataSourceTransactionManager(f.source())); - } - - private static Fixture fixture(String target) { - 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, Duration.ofSeconds(10), Duration.ofSeconds(1), Duration.ofHours(1)), - 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) { - Flyway.configure() - .dataSource(source) - .schemas(schema) - .defaultSchema(schema) - .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration", "classpath:db/migration/saga") - .target(target) - .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; - } - - private void advance(Duration duration) { - now = now.plus(duration); - } - - @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 loseCreateResponse; - private int emptySearchesRemaining; - private int searches; - private int creates; - private int subscriptionReads; - - 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 (path.equals("/v1/subscriptions") && method == RequestMethod.POST) { - creates++; - exists = true; - assertThat(options.getIdempotencyKey()) - .isEqualTo(creation.subscriptionProvisioningRequestId().toString()); - assertThat(params) - .containsEntry("customer", creation.providerCustomerId()) - .containsEntry("default_payment_method", paymentMethod); - assertThat(params.get("items")) - .isEqualTo( - List.of( - Map.of( - "price", - creation.planQuote().providerPriceId(), - "quantity", - creation.planQuote().providerQuantity()))); - if (loseCreateResponse) { - throw org.mockito.Mockito.mock(StripeException.class); - } - response = subscription(); - } else if (path.equals("/v1/subscriptions/sub_exact")) { - subscriptionReads++; - response = subscription(); - } else { - throw new AssertionError("Unexpected provider path " + path); - } - return (T) com.stripe.net.ApiResource.GSON.fromJson(response, type); - } - - private String subscription() { - return "{\"object\":\"subscription\",\"id\":\"sub_exact\",\"customer\":\"" - + creation.providerCustomerId() - + "\",\"default_payment_method\":\"" - + paymentMethod - + "\",\"livemode\":false,\"status\":\"active\",\"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 deleted file mode 100644 index d22db0d47d..0000000000 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecyclePostgresIntegrationTest.java +++ /dev/null @@ -1,1940 +0,0 @@ -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 - configuredRecoveryAndEffectiveCancellationAdvanceMonotonicCutoffWithoutPrematureReservationRelease() { - Context c = context("1030"); - Fixture f = fixture(c); - activate(f); - f.transport().json = response(f, "past_due"); - refresh(f); - assertThat(f.service().readCurrent(f.creation().tenantId()).subscriptionStatus()) - .isEqualTo(Status.PAST_DUE); - f.clock().advance(Duration.ofSeconds(30)); - assertThat(f.service().readCurrent(f.creation().tenantId()).subscriptionStatus()) - .isEqualTo(Status.PAST_DUE); - f.clock().advance(Duration.ofSeconds(30)); - assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) - .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); - refresh(f); - var grace = f.service().readCurrent(f.creation().tenantId()); - assertThat(grace.subscriptionStatus()).isEqualTo(Status.GRACE); - assertThat(grace.gameplayAvailable()).isTrue(); - assertThat(grace.allowPublicJoin()).isFalse(); - assertThat(grace.allowNewInstanceStarts()).isFalse(); - f.clock().advance(Duration.ofSeconds(30)); - assertThat(f.service().readCurrent(f.creation().tenantId()).subscriptionStatus()) - .isEqualTo(Status.GRACE); - f.clock().advance(Duration.ofSeconds(90)); - assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) - .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); - refresh(f); - var suspended = f.service().readCurrent(f.creation().tenantId()); - assertThat(suspended.subscriptionStatus()).isEqualTo(Status.SUSPENDED); - assertThat(suspended.gameplayAvailable()).isFalse(); - assertThat(suspended.tenantBillingSequence()).isEqualTo(4); - assertThat( - new String( - one( - c, - "SELECT payload FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ? AND tenant_billing_sequence = 4", - f.creation().tenantId()) - .get("payload", byte[].class), - java.nio.charset.StandardCharsets.UTF_8)) - .contains("TenantBillingStateChanged"); - assertThat(suspended.cutoffAt()).isEqualTo(f.clock().instant()); - Instant originalSuspensionCutoff = suspended.cutoffAt(); - f.clock().advance(Duration.ofSeconds(30)); - var laterSuspended = f.service().readCurrent(f.creation().tenantId()); - assertThat(laterSuspended.subscriptionStatus()).isEqualTo(Status.SUSPENDED); - assertThat(laterSuspended.cutoffAt()).isEqualTo(originalSuspensionCutoff); - assertThat(laterSuspended.gameplayAvailable()).isFalse(); - assertThat(laterSuspended.validUntil()).isEqualTo(f.clock().instant().plusSeconds(15)); - assertThat(laterSuspended.tenantBillingSequence()).isEqualTo(4); - assertThat(count(c, "subscription_lifecycle_receipts")).isEqualTo(4); - f.transport().json = response(f, "active"); - refresh(f); - Instant cancellation = f.clock().instant().plusSeconds(2); - f.transport().json = - response(f, "active") - .replace("\"cancel_at\":null", "\"cancel_at\":" + cancellation.getEpochSecond()); - refresh(f); - f.clock().advance(Duration.ofSeconds(2)); - 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.tenantBillingSequence()).isEqualTo(7); - 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(8); - 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(8); - 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/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java new file mode 100644 index 0000000000..b7fec29bc4 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java @@ -0,0 +1,344 @@ +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.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import io.grpc.Server; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.Arrays; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.AuthenticateRequest; +import net.firedevops.firemud.account.v1.AuthenticateResponse; +import net.firedevops.firemud.account.v1.GameplayLoginSourceContext; +import net.firedevops.firemud.account.v1.GameplayLoginTransportClass; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; +import net.firedevops.firemud.accountservice.dto.InitialGameplayLoginResult; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; +import net.firedevops.firemud.accountservice.service.impl.AccountPlayerAdmissionEntitlementGrpcService; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.GatewayFirstPartyConnectContextEnvelope.ContextClaims; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.gamesession.client.AccountPlayerAdmissionEntitlementClient; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +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.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Actual committed LOGIN recovery/currentness, PostgreSQL DEMO and membership owners, Account + * receiver and Game Session consumer. Test signer/JWKS custody, initial response delivery and + * protected published Game Session/World inputs remain controlled. This does not prove public + * ingress, the default PLAY route, production custody, admission or activation. + */ +class AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest { + private static final String NAMESPACE = "test"; + private static final String PEER = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final Clock CLOCK = Clock.systemUTC(); + private final AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest fixtures = + new AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest(); + @TempDir Path directory; + + @BeforeAll + static void startPostgres() { + AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.startPostgres(); + } + + @AfterAll + static void stopPostgres() { + AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.stopPostgres(); + } + + @AfterEach + void dropSchemas() { + fixtures.dropRunOwnedSchemas(); + } + + @Test + void actualRecoveredLoginFlowsThroughPlayerAdmissionOwnerAndConsumer() throws Exception { + fixtures.temporaryDirectory = directory; + var pki = + LoopbackMtlsTestPki.create( + directory, + "Actual LOGIN player entitlement composition", + new LoopbackMtlsTestPki.IdentitySpec("client", PEER, false), + new LoopbackMtlsTestPki.IdentitySpec( + "account", "spiffe://firemud/ns/test/sa/account-service", true)); + try (var redis = + AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.PhysicalRedisFixture + .start()) { + var f = fixtures.newPlayerEntitlementFixture(redis.client()); + var identity = f.committedCandidate.identity(); + var initial = + InitialGameplayLoginResult.fromRecoveredCredential( + f.responseRecoveryOwner.recoverInitialLoginResponse( + identity.requestId(), + identity.accountId(), + new CallerIdentity(identity.callerWorkload(), identity.callerContextId()))); + var trusted = f.signerFixture.trustedJwksSource(); + var jwks = + new AccountPublicJwksCache( + trusted, trusted.sourceIdentity(), CLOCK, Duration.ofSeconds(30)); + var request = + AuthenticateRequest.newBuilder() + .setRequestId(initial.requestId().toString()) + .setEmail("controlled-delivery@example.test") + .setPassword("controlled-input") + .setSourceContext( + GameplayLoginSourceContext.newBuilder() + .setCallerContextId(initial.callerContextId().toString()) + .setCanonicalClientAddress("203.0.113.10") + .setTransportClass( + GameplayLoginTransportClass + .GAMEPLAY_LOGIN_TRANSPORT_CLASS_TRUSTED_TCP_PROXY)) + .build(); + try (var login = + CanonicalGameplayLoginResult.fromAuthenticatedResponse( + projectRecoveredInitial(initial), + request, + new AccountAsymmetricJwtVerifier(jwks, CLOCK), + CLOCK)) { + var scope = f.playerEntitlementScope(); + var protectedTargets = mock(CanonicalGameplayAdmissionDecisionReadClient.class); + controlledTarget(protectedTargets); + var owner = f.playerEntitlementOwner(protectedTargets); + var selector = + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector( + UUID.randomUUID(), + scope.accountId(), + NAMESPACE, + scope.tenantId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmId(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion()); + var ownerRequest = + new net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner + .Request(selector, scope.connectScopeId(), PEER); + byte[] compact = login.compactJwtBytes(); + net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence + expected; + try { + expected = owner.evaluate(ownerRequest, new String(compact, StandardCharsets.US_ASCII)); + } finally { + Arrays.fill(compact, (byte) 0); + } + var targetFields = (Map) expected.fields().get("target"); + var sources = (Map) expected.fields().get("sourceReferences"); + var target = mock(CanonicalPlayableTarget.class); + when(target.targetNamespace()).thenReturn(NAMESPACE); + when(target.canonicalTenantId()).thenReturn(scope.tenantId()); + when(target.tenantSlug()).thenReturn(scope.tenantSlug()); + when(target.worldSlug()).thenReturn(scope.worldSlug()); + when(target.realmId()).thenReturn(scope.realmId()); + when(target.realmSlug()).thenReturn(scope.realmSlug()); + when(target.playableStateNamespaceId()).thenReturn(scope.playableStateNamespaceId()); + when(target.playableStateScope()).thenReturn(scope.playableStateScope()); + when(target.characterCreationPolicy()).thenReturn("PRESEEDED_ONLY"); + when(target.canonicalGameInstanceId()).thenReturn(scope.gameInstanceId()); + when(target.canonicalVersionId()) + .thenReturn(UUID.fromString((String) targetFields.get("canonicalVersionId"))); + when(target.catalogRevision()).thenReturn(scope.catalogRevision()); + when(target.pointerVersion()).thenReturn(scope.pointerVersion()); + when(target.activeWorldEpoch()) + .thenReturn(Long.parseLong((String) targetFields.get("activeWorldEpoch"))); + when(target.admissionPointerSnapshotDigest()) + .thenReturn((String) sources.get("admissionPointerSnapshotDigest")); + when(target.ownerProofDigest()) + .thenReturn((String) sources.get("gameSessionOwnerProofDigest")); + var claims = mock(ContextClaims.class); + when(claims.expiresAtMillis()) + .thenReturn(Instant.parse(scope.connectScopeExpiresAt()).toEpochMilli()); + var context = mock(FirstPartyConnectContext.class); + when(context.hasCompleteRoutingScope()).thenReturn(true); + when(context.claims()).thenReturn(claims); + when(context.accountId()).thenReturn(scope.accountId().toString()); + when(context.connectScopeId()).thenReturn(scope.connectScopeId()); + when(context.resolvedTarget()).thenReturn(target); + Server server = + new AccountPlayerAdmissionEntitlementGrpcService(owner, NAMESPACE) + .createUnregisteredServer( + "127.0.0.1:0", + pki.keyManagerFactory(pki.identity("account")), + pki.trustManagerFactory()); + server.start(); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + server.getPort()); + try (var client = + new AccountPlayerAdmissionEntitlementClient( + endpoints, + pki.clientProperties(directory, pki.identity("client")), + new GrpcChannelFactory(), + NAMESPACE, + CLOCK)) { + client.init(); + var result = client.read(context, selector.readRequestId(), login, () -> true); + assertThat(result.fields()) + .containsEntry("variant", "PLAYER_ADMISSION") + .containsEntry("sourceKind", "NON_PAID_DEMO"); + assertThat(result.membershipSource().membershipExists()).isTrue(); + assertThat(result.membershipSource().gameplayAdmissionAllowed()).isTrue(); + var receivedSources = (Map) result.fields().get("sourceReferences"); + assertThat(receivedSources.get("callerTokenSha256")).isEqualTo(initial.tokenSha256()); + assertThat(receivedSources.get("callerTokenJti")) + .isEqualTo(initial.tokenJti().toString()); + assertThatThrownBy(() -> client.read(context, UUID.randomUUID(), login, () -> false)) + .isInstanceOf(RuntimeException.class); + // Retaining valid signature bytes and local custody is insufficient after Account moves. + f.beginPlayerEntitlementLoginRevocation(); + assertThatThrownBy(() -> client.read(context, UUID.randomUUID(), login, () -> true)) + .isInstanceOf(RuntimeException.class); + login.close(); + assertThatThrownBy(() -> client.read(context, UUID.randomUUID(), login, () -> true)) + .isInstanceOf(RuntimeException.class); + } finally { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + } + } + + /** Controlled protected-client double: no physical GS/World source provenance is claimed. */ + private static void controlledTarget(CanonicalGameplayAdmissionDecisionReadClient targets) { + when(targets.resolvePublishedRealmAdmissionTarget(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + var selector = + invocation.getArgument( + 0, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector.class); + var target = mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target.class); + when(target.targetNamespace()).thenReturn(selector.targetNamespace()); + when(target.canonicalTenantId()).thenReturn(selector.tenantId()); + when(target.tenantSlug()).thenReturn(selector.tenantSlug()); + when(target.worldSlug()).thenReturn(selector.worldSlug()); + when(target.realmId()).thenReturn(selector.realmId()); + when(target.realmSlug()).thenReturn(selector.realmSlug()); + when(target.playableStateNamespaceId()) + .thenReturn(selector.playableStateNamespaceId()); + when(target.playableStateScope()).thenReturn(selector.playableStateScope()); + when(target.canonicalGameInstanceId()).thenReturn(selector.gameInstanceId()); + when(target.catalogRevision()).thenReturn(selector.catalogRevision()); + when(target.pointerVersion()).thenReturn(selector.pointerVersion()); + when(target.characterCreationPolicy()).thenReturn("PRESEEDED_ONLY"); + when(target.ownerProofOutcome()) + .thenReturn( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome.COMMITTED); + UUID version = UUID.fromString("33333333-3333-4333-8333-333333333333"); + when(target.canonicalVersionId()).thenReturn(version); + when(target.activeWorldEpoch()).thenReturn(5L); + var strict = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + selector.readRequestId(), + selector.accountId(), + selector.targetNamespace(), + selector.tenantId(), + selector.worldSlug(), + selector.realmId(), + selector.realmSlug(), + selector.playableStateNamespaceId(), + selector.playableStateScope(), + selector.gameInstanceId(), + version, + selector.catalogRevision(), + selector.pointerVersion(), + 5L); + var resolved = + mock( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.ResolvedPublishedTarget + .class); + when(resolved.selector()).thenReturn(selector); + when(resolved.currentTarget()).thenReturn(target); + when(resolved.strictSelector()).thenReturn(strict); + var read = + mock( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class); + when(read.selector()).thenReturn(strict); + when(read.currentTarget()).thenReturn(target); + var source = mock(CanonicalGameplayRosterOwnerReadEvidence.class); + when(source.admissionPointerSnapshotDigest()).thenReturn("a".repeat(64)); + var policies = mock(PublishedRealmEntryPolicySetEvidence.class); + when(policies.policySetDigest()).thenReturn("sha256:" + "b".repeat(64)); + when(source.publishedPolicySetEvidence()).thenReturn(policies); + var ownerProof = + mock( + net.firedevops.firemud.common.world + .GameSessionCanonicalInitialAdmissionOwnerProof.class); + when(ownerProof.proofDigest()).thenReturn("sha256:" + "c".repeat(64)); + when(source.gameSessionOwnerProof()).thenReturn(ownerProof); + when(read.sourceEvidence()).thenReturn(source); + var world = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(world.canonicalBytes()) + .thenReturn( + "controlled-complete-world-source" + .getBytes(java.nio.charset.StandardCharsets.UTF_8)); + when(world.captureId()) + .thenReturn(UUID.fromString("44444444-4444-4444-8444-444444444444")); + when(world.rowVersion()).thenReturn(2L); + when(read.worldLifecycleEvidence()).thenReturn(world); + when(targets.readPublishedRealmAdmissionOwner(strict)) + .thenAnswer( + readCall -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isFalse(); + return read; + }); + return resolved; + }); + } + + private static AuthenticateResponse projectRecoveredInitial(InitialGameplayLoginResult result) { + byte[] token = result.compactJwtBytes(); + try { + return AuthenticateResponse.newBuilder() + .setAuthToken(new String(token, StandardCharsets.US_ASCII)) + .setAccountId(result.accountId().toString()) + .setRequestId(result.requestId().toString()) + .setCallerContextId(result.callerContextId().toString()) + .setTokenJti(result.tokenJti().toString()) + .setTokenSha256(result.tokenSha256()) + .setTokenProfile(result.profile()) + .setIssuedAtEpochSeconds(result.issuedAtEpochSecond()) + .setNotBeforeEpochSeconds(result.notBeforeEpochSecond()) + .setExpiresAtEpochSeconds(result.expiresAtEpochSecond()) + .setTokenGeneration(result.tokenGeneration()) + .setIssuanceFence(result.issuanceFence()) + .setAuthorityTupleCanonicalJson(ByteString.copyFrom(result.authorityTupleCanonicalJson())) + .setOutboxCheckpointsCanonicalJson( + ByteString.copyFrom(result.outboxCheckpointsCanonicalJson())) + .setOutboxSourceEventEvidenceCanonicalJson( + ByteString.copyFrom(result.outboxSourceEventEvidenceCanonicalJson())) + .build(); + } finally { + Arrays.fill(token, (byte) 0); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java index 8e9c5d1650..eb3bc68da2 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java @@ -4,7 +4,6 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; -import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.sql.SQLException; import java.time.Duration; @@ -522,36 +521,28 @@ void auditAttemptTimesUseUtcLocalDateTimeUnderNonUtcDatabaseSession() { } @Test - void canonicalSubscriptionOriginalBindingLocksRequiredOwnerChainThroughCommit() throws Exception { - var fixture = CanonicalHostingSubscriptionTestFixture.create(dataSource); - var claim = - fixture - .service() - .claimProvisioning(fixture.creation().requestId(), 1, UUID.randomUUID()) - .claim(); - assertThat( - fixture - .service() - .reconcile( - UUID.randomUUID(), - fixture.creation().requestId(), - claim.subscriptionRowVersion(), - fixture.providerId(), - claim.attemptId()) - .outcome()) - .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Outcome.COMMITTED); - var receipt = fixture.service().readCurrent(fixture.tenantId()); + void subscriptionForUpdateLocksOnlySubscriptionAndKeepsThatLockThroughTransaction() + throws Exception { JdbcTemplate jdbc = new JdbcTemplate(dataSource); - long unrelatedAccountId = + long accountId = Objects.requireNonNull( jdbc.queryForObject( "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", Long.class, - "unrelated-subscription-lock", - "unrelated-subscription-lock@example.com", + "subscription-lock", + "subscription-lock@example.com", "hash")); + long tenantId = 7654321L; + jdbc.update( + "INSERT INTO subscription (account_id, plan_id, status, tenant_id, entitlement_version) " + + "VALUES (?, 'test-plan', 'active', ?, 1)", + accountId, + tenantId); + TransactionAwareDataSourceProxy transactionAwareDataSource = new TransactionAwareDataSourceProxy(dataSource); + DSLContext transactionDsl = DSL.using(transactionAwareDataSource, SQLDialect.POSTGRES); + SubscriptionRepository subscriptions = new SubscriptionRepository(transactionDsl); TransactionTemplate lockTransaction = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); CountDownLatch subscriptionLocked = new CountDownLatch(1); @@ -562,15 +553,7 @@ void canonicalSubscriptionOriginalBindingLocksRequiredOwnerChainThroughCommit() () -> lockTransaction.executeWithoutResult( status -> { - assertThat( - fixture - .intents() - .lockForLifecycle( - fixture.creation().requestId(), - receipt.current().rowVersion())) - .isEqualTo(receipt.current()); - assertThat(fixture.intents().findCreation(fixture.creation().requestId())) - .contains(fixture.creation()); + assertThat(subscriptions.findByTenantIdForUpdate(tenantId)).hasSize(1); subscriptionLocked.countDown(); try { if (!releaseSubscriptionLock.await(10, TimeUnit.SECONDS)) { @@ -589,33 +572,16 @@ void canonicalSubscriptionOriginalBindingLocksRequiredOwnerChainThroughCommit() TransactionTemplate conflictingTransaction = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); JdbcTemplate conflictingJdbc = new JdbcTemplate(transactionAwareDataSource); - // These are the mutable rows actually locked by the canonical original-binding reader. - // Creation intent is immutable and validated above; it is not a competing mutable row. - Map lockedRows = - Map.of( - "SELECT 1 FROM accounts WHERE account_uuid = ? FOR UPDATE", fixture.accountUuid(), - "SELECT 1 FROM billing_customer WHERE account_uuid = ? FOR UPDATE", - fixture.accountUuid(), - "SELECT 1 FROM payment_instrument WHERE instrument_uuid = ? FOR UPDATE", - fixture.instrument().instrumentUuid(), - "SELECT 1 FROM account_tenant_billing_owners WHERE tenant_uuid = ? FOR UPDATE", - fixture.tenantId(), - "SELECT 1 FROM subscription WHERE subscription_id = ? FOR UPDATE", - fixture.creation().subscriptionId(), - "SELECT 1 FROM subscription_instrument_reservations WHERE request_id = ? FOR UPDATE", - fixture.creation().requestId()); - for (var row : lockedRows.entrySet()) { - assertThatThrownBy( - () -> - conflictingTransaction.executeWithoutResult( - status -> { - conflictingJdbc.execute("SET LOCAL lock_timeout = '250ms'"); - conflictingJdbc.queryForObject( - row.getKey(), Integer.class, row.getValue()); - })) - .as("owner-chain lock retained: %s", row.getKey()) - .hasMessageContaining("lock timeout"); - } + assertThatThrownBy( + () -> + conflictingTransaction.executeWithoutResult( + status -> { + conflictingJdbc.execute("SET LOCAL lock_timeout = '250ms'"); + conflictingJdbc.update( + "UPDATE subscription SET status = status WHERE tenant_id = ?", + tenantId); + })) + .hasMessageContaining("lock timeout"); Integer updatedAccounts = conflictingTransaction.execute( @@ -623,8 +589,8 @@ void canonicalSubscriptionOriginalBindingLocksRequiredOwnerChainThroughCommit() conflictingJdbc.execute("SET LOCAL lock_timeout = '2s'"); return conflictingJdbc.update( "UPDATE accounts SET email = ? WHERE id = ?", - "unrelated-subscription-lock-updated@example.com", - unrelatedAccountId); + "subscription-lock-updated@example.com", + accountId); }); assertThat(updatedAccounts).isEqualTo(1); } finally { @@ -635,19 +601,6 @@ void canonicalSubscriptionOriginalBindingLocksRequiredOwnerChainThroughCommit() executor.shutdownNow(); } } - // The same real owner operation succeeds from an independent transaction after holder commit. - lockTransaction.executeWithoutResult( - status -> { - jdbc.execute("SET LOCAL lock_timeout = '2s'"); - assertThat( - fixture - .intents() - .lockForLifecycle( - fixture.creation().requestId(), receipt.current().rowVersion())) - .isEqualTo(receipt.current()); - }); - assertThat(fixture.intents().findCreation(fixture.creation().requestId())) - .contains(fixture.creation()); } @Test @@ -690,13 +643,16 @@ void privateRealmGrantRevocationRetainsMonotonicCurrentnessForRevalidation() { null, null, null, + null, grants, null, null, null, null, null, - org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), + null, + null, + null, null, null, null, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSecuritySourceOwnerGuardPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSecuritySourceOwnerGuardPostgresIntegrationTest.java index e00336b1cc..37e1cfda6f 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSecuritySourceOwnerGuardPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSecuritySourceOwnerGuardPostgresIntegrationTest.java @@ -26,7 +26,6 @@ import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; import net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository; -import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; import net.firedevops.firemud.accountservice.service.AccountLogoutAllAuthorityEventProducer; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; @@ -303,6 +302,7 @@ private AccountServiceImpl newPasswordResetService( logoutOperations, securityOperations, resetSourceChanges, + null, // audit outbox null, // connect scopes null, // join operations null, // email login challenges @@ -312,8 +312,7 @@ private AccountServiceImpl newPasswordResetService( null, // profiles null, // profile mapper null, // payment transactions - // retained subscription evidence - org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), + null, // subscriptions null, // external account identities tokens, null, // email verification tokens @@ -324,6 +323,8 @@ private AccountServiceImpl newPasswordResetService( null, null, null, + null, + null, context.transactionManager()); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java index dbb5872a20..83e548e6dc 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java @@ -196,16 +196,10 @@ void actualDefaultLocationsFreshBootstrapAppliesFullCombinedHistoryAndEnabledGua var dsl = DSL.using(source, SQLDialect.POSTGRES); assertThat( dsl.fetchSingle( - "SELECT count(*) FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ? AND NOT t.tgisinternal AND t.tgenabled NOT IN ('O', 'A')", + "SELECT count(*) FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ? AND NOT t.tgisinternal AND t.tgenabled <> 'O'", schema) .get(0, Long.class)) .isZero(); - assertThat( - dsl.fetchSingle( - "SELECT count(*) FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ? AND c.relname = 'account_retained_subscription_evidence' AND t.tgname = 'account_retained_subscription_evidence_immutable' AND t.tgenabled = 'A'", - schema) - .get(0, Long.class)) - .isEqualTo(1L); for (String signature : List.of( "account_ss_admission_assert_current(account_start_session_admission_protections,boolean)", 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 deleted file mode 100644 index b5265f0885..0000000000 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentPostgresIntegrationTest.java +++ /dev/null @@ -1,1751 +0,0 @@ -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.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)); - Instant start = created.createdAt().plusSeconds(1); - UUID attemptId = UUID.randomUUID(); - var first = - Objects.requireNonNull( - c.tx().execute(s -> lifecycle(c, start).claim(created.requestId(), 1, attemptId))) - .claim(); - assertThat(first.creation()).isEqualTo(created); - assertThat(first.subscriptionRowVersion()).isEqualTo(2); - assertThat(first.reconciliationRequiredBeforeCreate()).isFalse(); - 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, start).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(); - var waiting = - Objects.requireNonNull( - c.tx() - .execute( - s -> - lifecycle(c, start.plusSeconds(5)) - .claim(created.requestId(), 2, UUID.randomUUID()))); - assertThat(waiting.disposition()) - .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Disposition.WAITING); - Instant recoveryTime = start.plusSeconds(12); - var recovered = - Objects.requireNonNull( - c.tx() - .execute( - s -> - lifecycle(c, recoveryTime) - .claim(created.requestId(), 2, UUID.randomUUID()))) - .claim(); - assertThat(recovered.reconciliationRequiredBeforeCreate()).isTrue(); - 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, recoveryTime).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)); - Instant start = created.createdAt().plusSeconds(1); - var first = - Objects.requireNonNull( - c.tx() - .execute( - s -> lifecycle(c, start).claim(created.requestId(), 1, UUID.randomUUID()))) - .claim(); - var firstDeferred = c.tx().execute(s -> lifecycle(c, start).deferUnresolved(first)); - assertThat(firstDeferred) - .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Disposition.WAITING); - Instant retryAt = start.plusSeconds(1); - var second = - Objects.requireNonNull( - c.tx() - .execute( - s -> - lifecycle(c, retryAt).claim(created.requestId(), 2, UUID.randomUUID()))) - .claim(); - var exhausted = c.tx().execute(s -> lifecycle(c, retryAt).deferUnresolved(second)); - assertThat(exhausted) - .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Disposition.TERMINAL_FAILURE); - var exhaustedReplay = c.tx().execute(s -> lifecycle(c, retryAt).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")); - } - - @Test - void claimRollbackAndStaleReservedWalletCannotLeaveProvisioningWork() { - Context c = context(); - configuration(c).target("1030").load().migrate(); - Seed seed = seed(c); - var created = create(c, request(seed, UUID.randomUUID(), 1, null)); - Instant start = created.createdAt().plusSeconds(1); - c.tx() - .executeWithoutResult( - s -> { - lifecycle(c, start).claim(created.requestId(), 1, UUID.randomUUID()); - s.setRollbackOnly(); - }); - assertThat(count(c, "subscription_provisioning_work")).isZero(); - assertThat(count(c, "subscription_provisioning_attempts")).isZero(); - assertThat(c.repository().findCurrentByTenant(seed.tenant()).orElseThrow().status()) - .isEqualTo("pending"); - c.tx() - .executeWithoutResult( - s -> advanceWallet(c, seed.instrument().instrumentUuid(), UUID.randomUUID())); - assertThatThrownBy( - () -> - c.tx() - .execute( - s -> lifecycle(c, start).claim(created.requestId(), 1, UUID.randomUUID()))) - .isInstanceOf(FenceRejectedException.class); - assertThat(count(c, "subscription_provisioning_work")).isZero(); - assertThat(c.repository().findCurrentByTenant(seed.tenant()).orElseThrow().rowVersion()) - .isOne(); - } - - @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)); - Instant start = created.createdAt().plusSeconds(1); - Supplier attempt = - () -> { - try { - return Objects.requireNonNull( - c.tx() - .execute( - s -> - lifecycle(c, start) - .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)); - var expired = - Objects.requireNonNull( - c.tx() - .execute( - s -> - lifecycle(c, created.createdAt().plusSeconds(3600)) - .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, Instant now) { - return new AccountHostingSubscriptionLifecycleRepository( - c.dsl(), - c.repository(), - Clock.fixed(now, ZoneOffset.UTC), - new AccountHostingSubscriptionLifecycleRepository.ReconciliationLimits( - 2, 3, Duration.ofSeconds(10), Duration.ofSeconds(1), Duration.ofHours(1)), - new AccountHostingSubscriptionLifecyclePolicy( - Duration.ofSeconds(15), - new AccountHostingSubscriptionLifecyclePolicy.RecoveryTiming( - Duration.ofSeconds(60), Duration.ofSeconds(120))), - "prod", - false); - } - - @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 attempted = new CountDownLatch(1); - CountDownLatch release = new CountDownLatch(1); - var executor = Executors.newFixedThreadPool(2); - try { - var holder = - executor.submit( - () -> - c.tx() - .executeWithoutResult( - s -> { - 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( - () -> { - attempted.countDown(); - return attemptCreate(c, request); - }); - assertThat(attempted.await(5, TimeUnit.SECONDS)).isTrue(); - release.countDown(); - holder.get(15, TimeUnit.SECONDS); - assertThat(contender.get(15, TimeUnit.SECONDS)).isEqualTo("FENCED"); - } finally { - release.countDown(); - executor.shutdownNow(); - } - } - - /** 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 deleted file mode 100644 index 62f15145c9..0000000000 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionPostgresIntegrationTest.java +++ /dev/null @@ -1,351 +0,0 @@ -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") - .target("1030") - .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/repository/CanonicalHostingSubscriptionTestFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java deleted file mode 100644 index bfd24c3ba5..0000000000 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java +++ /dev/null @@ -1,502 +0,0 @@ -package integration.net.firedevops.firemud.accountservice.repository; - -import static org.assertj.core.api.Assertions.assertThat; - -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.time.Clock; -import java.time.Duration; -import java.time.Instant; -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.atomic.AtomicLong; -import java.util.function.Supplier; -import javax.sql.DataSource; -import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; -import net.firedevops.firemud.accountservice.entity.Account; -import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; -import net.firedevops.firemud.accountservice.repository.AccountBillingCustomerRecord; -import net.firedevops.firemud.accountservice.repository.AccountBillingCustomerRepository; -import net.firedevops.firemud.accountservice.repository.AccountHostingPlanCatalog; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy.RecoveryTiming; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReconciliationLimits; -import net.firedevops.firemud.accountservice.repository.AccountInitialTenantBillingOwnerRepository; -import net.firedevops.firemud.accountservice.repository.AccountPaymentInstrumentRecord; -import net.firedevops.firemud.accountservice.repository.AccountPaymentInstrumentRecord.DisplayMetadata; -import net.firedevops.firemud.accountservice.repository.AccountPaymentInstrumentRecord.State; -import net.firedevops.firemud.accountservice.repository.AccountPaymentInstrumentRepository; -import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest; -import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.OwnerFence; -import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.ProducerEvidence; -import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreationRecord; -import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository; -import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; -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 org.jooq.DSLContext; -import org.jooq.SQLDialect; -import org.jooq.impl.DSL; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.datasource.DataSourceTransactionManager; -import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; -import org.springframework.transaction.support.TransactionSynchronizationManager; -import org.springframework.transaction.support.TransactionTemplate; - -/** - * Controlled local source setup plus the real hosting lifecycle owner and Stripe SDK read path. The - * caller must migrate its isolated Account schema before using this fixture. The fresh-tenant, - * creator/consent, customer, wallet, and transport inputs are controlled; they do not qualify their - * authenticated producers, PKI, Stripe, runtime registration, or production entitlement use. - */ -public final class CanonicalHostingSubscriptionTestFixture { - private static final String DIGEST = "sha256:" + "a".repeat(64); - private static final AtomicLong GAME_ROWS = new AtomicLong(20_000); - - private CanonicalHostingSubscriptionTestFixture() {} - - public static Fixture create(DataSource source) { - return createInternal(source, null); - } - - /** Reuses the exact persisted Account of a genuine actor/authentication composition. */ - public static Fixture create(DataSource source, Account account) { - return createInternal(source, Objects.requireNonNull(account, "persisted Account required")); - } - - private static Fixture createInternal(DataSource source, Account existingAccount) { - Objects.requireNonNull(source, "migrated Account datasource is required"); - JdbcTemplate jdbc = new JdbcTemplate(source); - DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); - TransactionTemplate transaction = - new TransactionTemplate(new DataSourceTransactionManager(source)); - AccountHostingPlanCatalog catalog = - new AccountHostingPlanCatalog( - List.of( - new AccountHostingPlanCatalog.ConfiguredPlan( - "hosting", "price_controlled", "1", "100", "2", "1048576"))); - AccountSubscriptionIntentRepository intents = - new AccountSubscriptionIntentRepository(dsl, catalog); - - long row = GAME_ROWS.incrementAndGet(); - var accountRow = - existingAccount == null - ? dsl.fetchOne( - "INSERT INTO accounts (username, email, password_hash) " - + "VALUES (?, ?, 'controlled-hash') RETURNING id, account_uuid", - "hosting-fixture-" + row, - "hosting-fixture-" + row + "@example.test") - : dsl.fetchOne( - "SELECT id, account_uuid FROM accounts WHERE id = ? AND account_uuid = ?", - Objects.requireNonNull(existingAccount.getId(), "persisted Account ID required"), - Objects.requireNonNull( - existingAccount.getAccountUuid(), "persisted Account UUID required")); - Objects.requireNonNull(accountRow, "Exact persisted Account row required"); - long accountId = accountRow.get("id", Long.class); - UUID accountUuid = accountRow.get("account_uuid", UUID.class); - - UUID tenantId = UUID.randomUUID(); - UUID tenantCreateRequest = UUID.randomUUID(); - UUID tenantCreateOperation = UUID.randomUUID(); - String tenantKey = "hosting-fixture-game-" + row; - String tenantRequestDigest = - GameTenantCreationDigest.requestDigest( - "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 = - pendingCustomer.state() == AccountBillingCustomerRecord.State.CONFIRMED - ? pendingCustomer - : in( - transaction, - () -> - customers.recordObservation( - accountUuid, - pendingCustomer.customerProvisioningRequestId(), - pendingCustomer.rowVersion(), - 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, - State.ATTACHABLE, - new 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))); - - MutableClock clock = new MutableClock(creation.createdAt().plusSeconds(1)); - ControlledStripeTransport transport = new ControlledStripeTransport(); - var lifecycleRepository = - new AccountHostingSubscriptionLifecycleRepository( - 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); - var observer = - new StripeHostingSubscriptionObserver( - new com.stripe.StripeClient(transport), - clock, - Duration.ofMillis(250), - Duration.ofSeconds(1)); - var service = - new AccountHostingSubscriptionLifecycleService( - lifecycleRepository, observer, new DataSourceTransactionManager(source)); - Fixture fixture = - new Fixture( - jdbc, - dsl, - transaction, - accountId, - accountUuid, - tenantId, - creation, - intents, - instrument, - "sub_" + row, - clock, - transport, - service, - lifecycleRepository, - observer); - fixture.providerStatus("active"); - return fixture; - } - - private static T in(TransactionTemplate transaction, Supplier body) { - return Objects.requireNonNull(transaction.execute(status -> body.get())); - } - - public static final class Fixture { - private final JdbcTemplate jdbc; - private final DSLContext dsl; - private final TransactionTemplate transaction; - private final long accountId; - private final UUID accountUuid; - private final UUID tenantId; - private final AccountSubscriptionCreationRecord creation; - private final AccountSubscriptionIntentRepository intents; - private final AccountPaymentInstrumentRecord instrument; - private final String providerId; - private final MutableClock clock; - private final ControlledStripeTransport transport; - private final AccountHostingSubscriptionLifecycleService service; - private final AccountHostingSubscriptionLifecycleRepository lifecycleRepository; - private final StripeHostingSubscriptionObserver observer; - - private Fixture( - JdbcTemplate jdbc, - DSLContext dsl, - TransactionTemplate transaction, - long accountId, - UUID accountUuid, - UUID tenantId, - AccountSubscriptionCreationRecord creation, - AccountSubscriptionIntentRepository intents, - AccountPaymentInstrumentRecord instrument, - String providerId, - MutableClock clock, - ControlledStripeTransport transport, - AccountHostingSubscriptionLifecycleService service, - AccountHostingSubscriptionLifecycleRepository lifecycleRepository, - StripeHostingSubscriptionObserver observer) { - this.jdbc = jdbc; - this.dsl = dsl; - this.transaction = transaction; - this.accountId = accountId; - this.accountUuid = accountUuid; - this.tenantId = tenantId; - this.creation = creation; - this.intents = intents; - this.instrument = instrument; - this.providerId = providerId; - this.clock = clock; - this.transport = transport; - this.service = service; - this.lifecycleRepository = lifecycleRepository; - this.observer = observer; - } - - @SuppressFBWarnings( - value = "EI_EXPOSE_REP", - justification = - "Integration tests intentionally inspect the fixture's actual JdbcTemplate and datasource; copying it would change the physical SQL boundary.") - public JdbcTemplate jdbc() { - return jdbc; - } - - @SuppressFBWarnings( - value = "EI_EXPOSE_REP", - justification = - "Integration tests intentionally use this exact datasource-backed DSLContext for physical SQL assertions; a copy would change the fixture boundary.") - public DSLContext dsl() { - return dsl; - } - - @SuppressFBWarnings( - value = "EI_EXPOSE_REP", - justification = - "Integration tests intentionally use this exact TransactionTemplate to exercise the fixture's real transaction boundary; a copy would change it.") - public TransactionTemplate transaction() { - return transaction; - } - - public long accountId() { - return accountId; - } - - public UUID accountUuid() { - return accountUuid; - } - - public UUID tenantId() { - return tenantId; - } - - public AccountSubscriptionCreationRecord creation() { - return creation; - } - - public AccountSubscriptionIntentRepository intents() { - return intents; - } - - public AccountPaymentInstrumentRecord instrument() { - return instrument; - } - - public String providerId() { - return providerId; - } - - public MutableClock clock() { - return clock; - } - - public ControlledStripeTransport transport() { - return transport; - } - - public AccountHostingSubscriptionLifecycleService service() { - return service; - } - - /** Actual source collaborators for explicit prepare/observe/final-transaction tests. */ - public AccountHostingSubscriptionLifecycleRepository lifecycleRepository() { - return lifecycleRepository; - } - - public StripeHostingSubscriptionObserver observer() { - return observer; - } - - public void providerStatus(String status) { - transport.json = response(this, status); - } - } - - public static final class MutableClock extends Clock { - private Instant current; - - private MutableClock(Instant current) { - this.current = current; - } - - public void advance(Duration duration) { - current = current.plus(duration); - } - - @Override - public ZoneId getZone() { - return ZoneOffset.UTC; - } - - @Override - public Clock withZone(ZoneId zone) { - return this; - } - - @Override - public Instant instant() { - return current; - } - } - - public static final class ControlledStripeTransport implements StripeResponseGetter { - private String json; - private int reads; - private Runnable duringRead; - - public int reads() { - return reads; - } - - /** One-shot owner mutation while the real SDK request is outside Account SQL. */ - public void duringRead(Runnable action) { - if (duringRead != null) throw new IllegalStateException("A provider-read action is pending"); - duringRead = Objects.requireNonNull(action); - } - - @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(); - 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 Stripe streaming or provider mutations are allowed"); - } - } - - @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 fixture, String status) { - String endedAt = - "canceled".equals(status) - ? Long.toString(fixture.clock().instant().getEpochSecond()) - : "null"; - 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":%s, - "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( - fixture.providerId(), - fixture.creation().providerCustomerId(), - fixture.instrument().providerPaymentMethodId(), - status, - endedAt, - fixture.creation().subscriptionProvisioningRequestId(), - fixture.creation().subscriptionId(), - fixture.providerId(), - fixture.creation().createdAt().getEpochSecond(), - fixture.creation().createdAt().getEpochSecond() + 3600, - fixture.creation().planQuote().providerPriceId()); - } -} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/RetainedSubscriptionEvidencePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/RetainedSubscriptionEvidencePostgresIntegrationTest.java deleted file mode 100644 index fa81372c91..0000000000 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/RetainedSubscriptionEvidencePostgresIntegrationTest.java +++ /dev/null @@ -1,233 +0,0 @@ -package net.firedevops.firemud.accountservice.repository; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.UUID; -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.DriverManagerDataSource; -import org.testcontainers.containers.PostgreSQLContainer; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; - -/** - * Populated, combined-history forward upgrade; no generated or synthetic canonical subscription. - */ -@Testcontainers(disabledWithoutDocker = true) -class RetainedSubscriptionEvidencePostgresIntegrationTest { - private static final String EVIDENCE = "account_retained_subscription_evidence"; - - @Container - private static final PostgreSQLContainer POSTGRES = - new PostgreSQLContainer<>(TestContainerImages.postgres()); - - @Test - void forwardUpgradePreservesEveryValueHeapIdentityXminAndPublishedFlywayHistory() { - Context context = predecessor(); - DSLContext dsl = context.dsl(); - List> before = rows(dsl, "subscription"); - List> history = history(dsl); - Long originalOid = relationOid(dsl, "subscription"); - List> accounts = - dsl.fetch( - "SELECT row_to_json(a)::text AS value, xmin::text AS xmin FROM accounts a ORDER BY id") - .intoMaps(); - - configuration(context).load().migrate(); - - assertThat(rows(dsl, EVIDENCE)).isEqualTo(before); - assertThat(relationOid(dsl, EVIDENCE)).isEqualTo(originalOid); - var afterHistory = history(dsl); - assertThat(afterHistory).hasSize(history.size() + 4); - assertThat(afterHistory.subList(history.size(), afterHistory.size())) - .extracting(row -> row.get("version")) - .containsExactly("1027", "1027.1", "1027.2", "1028"); - assertThat(afterHistory.subList(0, history.size())).containsExactlyElementsOf(history); - assertThat(history(dsl).getLast().get("version")).isEqualTo("1028"); - assertThat( - dsl.fetch( - "SELECT version FROM flyway_schema_history WHERE version IN ('1000', '1001', '1002')")) - .hasSize(3); - assertThat( - dsl.fetch( - "SELECT row_to_json(a)::text AS value, xmin::text AS xmin FROM accounts a ORDER BY id") - .intoMaps()) - .isEqualTo(accounts); - assertThat(scalar(dsl, "SELECT to_regclass('subscription')", String.class)).isNull(); - assertThat( - scalar( - dsl, - "SELECT to_regprocedure('advance_subscription_authority_generation()')", - String.class)) - .isNull(); - assertThat( - dsl.fetch( - "SELECT conname FROM pg_constraint WHERE conrelid = ?::regclass ORDER BY conname", - EVIDENCE) - .getValues(0, String.class)) - .containsExactly( - "account_retained_subscription_evidence_account_fk", - "account_retained_subscription_evidence_generation_non_nil", - "account_retained_subscription_evidence_pkey", - "account_retained_subscription_evidence_version_positive", - "subscription_account_id_not_null", - "subscription_entitlement_version_not_null", - "subscription_id_not_null", - "subscription_plan_id_not_null", - "subscription_status_not_null", - "subscription_tenant_authority_generation_not_null", - "subscription_tenant_id_not_null"); - assertThat( - dsl.fetch( - "SELECT indexname FROM pg_indexes WHERE schemaname = current_schema() AND tablename = ?", - EVIDENCE) - .getValues(0, String.class)) - .containsExactlyInAnyOrder( - "account_retained_subscription_evidence_pkey", - "idx_account_retained_subscription_evidence_account", - "idx_account_retained_subscription_evidence_tenant"); - assertThat( - scalar( - dsl, - "SELECT to_regclass('account_retained_subscription_evidence_id_seq')", - String.class)) - .isNotNull(); - configuration(context).load().validate(); - } - - @Test - void archiveRefusesAllMutationIncludingNoOpEmptyStatementsAndTruncateCascade() { - Context context = predecessor(); - configuration(context).load().migrate(); - DSLContext dsl = context.dsl(); - var before = rows(dsl, EVIDENCE); - for (String sql : - List.of( - "INSERT INTO " + EVIDENCE + " SELECT * FROM " + EVIDENCE + " WHERE false", - "INSERT INTO " - + EVIDENCE - + " (id, account_id, plan_id, status, tenant_id) VALUES (9999, " - + context.accountId() - + ", 'forbidden', 'active', 7)", - "UPDATE " + EVIDENCE + " SET status = status", - "UPDATE " + EVIDENCE + " SET tenant_id = 99 WHERE false", - "DELETE FROM " + EVIDENCE + " WHERE false", - "DELETE FROM " + EVIDENCE, - "TRUNCATE " + EVIDENCE, - "TRUNCATE " + EVIDENCE + " RESTART IDENTITY CASCADE")) { - assertThatThrownBy(() -> dsl.execute(sql)) - .hasMessageContaining("Retained subscription evidence is immutable and non-authorizing"); - assertThat(rows(dsl, EVIDENCE)).isEqualTo(before); - } - // Account FK remains restrictive even for terminal-looking historical rows. - assertThatThrownBy(() -> dsl.execute("DELETE FROM accounts WHERE id = ?", context.accountId())) - .hasMessageContaining("account_retained_subscription_evidence_account_fk"); - // Other retained Account families can refuse first; no cascade may erase this evidence. - assertThatThrownBy(() -> dsl.execute("TRUNCATE accounts CASCADE")) - .isInstanceOf(org.jooq.exception.DataAccessException.class); - assertThat(rows(dsl, EVIDENCE)).isEqualTo(before); - } - - @Test - void historicalRepositoryReadsOnlyTheRequestedAccountWithoutChoosingATenantWinner() { - Context context = predecessor(); - configuration(context).load().migrate(); - var repository = new RetainedSubscriptionEvidenceRepository(context.dsl()); - var history = repository.findHistoryByAccountId(context.accountId()); - assertThat(history).hasSize(4); - assertThat(history) - .extracting(row -> row.status()) - .containsExactly("active", "canceled", "grace", "provider_unknown"); - assertThat(history).extracting(row -> row.accountId()).containsOnly(context.accountId()); - assertThat(history).extracting(row -> row.tenantId()).containsExactly(7L, 7L, 8L, 8L); - assertThat(repository.findHistoryByAccountId(-1L)).isEmpty(); - assertThat(rows(context.dsl(), EVIDENCE)).hasSize(6); - } - - private static List> rows(DSLContext dsl, String relation) { - return dsl.fetch( - "SELECT row_to_json(s)::text AS value, xmin::text AS xmin, ctid::text AS ctid FROM " - + relation - + " s ORDER BY id") - .intoMaps(); - } - - private static List> history(DSLContext dsl) { - return dsl.fetch("SELECT * FROM flyway_schema_history ORDER BY installed_rank").intoMaps(); - } - - private static T scalar(DSLContext dsl, String sql, Class type, Object... bindings) { - return Objects.requireNonNull(dsl.fetchOne(sql, bindings)).get(0, type); - } - - private static Long relationOid(DSLContext dsl, String relation) { - return scalar(dsl, "SELECT ?::regclass::oid::bigint", Long.class, relation); - } - - private static FluentConfiguration configuration(Context context) { - return Flyway.configure() - .dataSource(context.source()) - .target("1028") - .schemas(context.schema()) - .defaultSchema(context.schema()) - .placeholders(Map.of("serviceSchema", context.schema())) - .locations("classpath:db/migration", "classpath:db/migration/saga"); - } - - private static Context predecessor() { - String schema = "subscription_retention_" + UUID.randomUUID().toString().replace("-", ""); - var source = - new DriverManagerDataSource( - POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); - source.setSchema(schema); - DSLContext dsl = DSL.using(source, SQLDialect.POSTGRES); - var empty = new Context(source, schema, dsl, 0L); - configuration(empty).target("1026").load().migrate(); - Long accountId = - Objects.requireNonNull( - scalar( - dsl, - "INSERT INTO accounts(username,email,password_hash) VALUES ('retained','retained@example.test','hash') RETURNING id", - Long.class)); - Long otherAccount = - Objects.requireNonNull( - scalar( - dsl, - "INSERT INTO accounts(username,email,password_hash) VALUES ('other','other@example.test','hash') RETURNING id", - Long.class)); - dsl.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,?::uuid)," - + "(92,?,'retained-canceled','canceled',NULL,'2025-02-03 04:05:06.654321',7,21,?::uuid)," - + "(93,?,'grace','grace',NULL,NULL,8,1,?::uuid)," - + "(94,?,'unknown','provider_unknown',NULL,NULL,8,2,?::uuid)," - + "(95,?,'other-account','active',NULL,NULL,7,5,?::uuid)", - accountId, - UUID.randomUUID(), - accountId, - UUID.randomUUID(), - accountId, - UUID.randomUUID(), - accountId, - UUID.randomUUID(), - otherAccount, - UUID.randomUUID()); - // Preserve V5's numeric default as historical evidence, not canonical tenant provenance. - dsl.execute( - "INSERT INTO subscription(id,account_id,plan_id,status) VALUES (96,?,'default-tenant','active')", - otherAccount); - return new Context(source, schema, dsl, accountId); - } - - private record Context( - DriverManagerDataSource source, String schema, DSLContext dsl, Long accountId) {} -} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java new file mode 100644 index 0000000000..c94ecd8279 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java @@ -0,0 +1,718 @@ +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.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.sql.Connection; +import java.sql.SQLException; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.HexFormat; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +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.AccountCanonicalRuntimeMembershipSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBinding; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +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.AccountPlayerAdmissionEntitlementOwner.Request; +import net.firedevops.firemud.accountservice.service.impl.AccountPlayerAdmissionEntitlementGrpcService; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier.VerifiedCaller; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner.AuthenticatedSignerCorrespondence; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference; +import net.firedevops.firemud.common.security.GatewayFirstPartyConnectContextEnvelope.ContextClaims; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.gamesession.client.AccountPlayerAdmissionEntitlementClient; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +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.junit.jupiter.api.io.TempDir; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Physical canonical Account/membership/scope/demo composition and lock/commit proof definitions. + * JWT/JWKS/Redis caller verification and current committed issuance are controlled doubles here; + * the protected GS/World client is also controlled. This does not prove custody, actual issuance, + * paid composition or physical published routing. The explicit loopback composition additionally + * uses the actual Account receiver and Game Session client over mTLS; its LOGIN and target inputs + * remain controlled doubles, not genuine custody or production activation. + */ +class AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest { + private static final String SCHEMA_PREFIX = "player_entitlement_"; + // Syntax-only credential for the explicitly mocked caller verifier, not a signed LOGIN. + private static final String CONTROLLED_COMPACT_TOKEN = "e30.e30.c2lnbmF0dXJl"; + private static final String NAMESPACE = "player-entitlement-proof"; + private static final String ISSUER = "firemud-account-service"; + private static final String PEER = + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service"; + private static final Instant NOW = Instant.parse("2026-11-02T00:00:00Z"); + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + @TempDir Path certificateDirectory; + private final Set schemas = ConcurrentHashMap.newKeySet(); + + @BeforeAll + static void startPostgres() { + POSTGRES.start(); + } + + @AfterAll + static void stopPostgres() { + POSTGRES.stop(); + } + + @AfterEach + void dropOwnedSchemas() { + JdbcTemplate jdbc = new JdbcTemplate(POSTGRES.dataSource()); + for (String schema : schemas) { + if (!schema.startsWith(SCHEMA_PREFIX) || !schema.matches("[a-z][a-z0-9_]{0,62}")) { + throw new IllegalStateException("Refusing cleanup of an unowned schema"); + } + jdbc.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } + schemas.clear(); + } + + @Test + void controlledOwnerReceiverAndGameSessionClientComposeWithoutGrantingAdmission() + throws Exception { + var pki = + LoopbackMtlsTestPki.create( + certificateDirectory, + "Controlled player admission composition", + new LoopbackMtlsTestPki.IdentitySpec("client", PEER, false), + new LoopbackMtlsTestPki.IdentitySpec( + "account", "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service", true)); + for (boolean joined : new boolean[] {false, true}) { + Fixture f = fixture(joined); + var request = f.request(); + var expected = f.owner.evaluate(request, CONTROLLED_COMPACT_TOKEN); + var targetFields = (Map) expected.fields().get("target"); + var sources = (Map) expected.fields().get("sourceReferences"); + // Only the upstream target/custody are doubles. No owner, receiver or consumer is mocked. + var target = mock(CanonicalPlayableTarget.class); + when(target.targetNamespace()).thenReturn(NAMESPACE); + when(target.canonicalTenantId()).thenReturn(f.tenantId); + when(target.tenantSlug()).thenReturn(f.scope.tenantSlug()); + when(target.worldSlug()).thenReturn(f.scope.worldSlug()); + when(target.realmId()).thenReturn(f.scope.realmId()); + when(target.realmSlug()).thenReturn(f.scope.realmSlug()); + when(target.playableStateNamespaceId()).thenReturn(f.scope.playableStateNamespaceId()); + when(target.playableStateScope()).thenReturn("SHARED"); + when(target.characterCreationPolicy()).thenReturn("PRESEEDED_ONLY"); + when(target.canonicalGameInstanceId()).thenReturn(f.scope.gameInstanceId()); + when(target.canonicalVersionId()) + .thenReturn(UUID.fromString((String) targetFields.get("canonicalVersionId"))); + when(target.catalogRevision()).thenReturn(f.scope.catalogRevision()); + when(target.pointerVersion()).thenReturn(f.scope.pointerVersion()); + when(target.activeWorldEpoch()) + .thenReturn(Long.parseLong((String) targetFields.get("activeWorldEpoch"))); + when(target.admissionPointerSnapshotDigest()) + .thenReturn((String) sources.get("admissionPointerSnapshotDigest")); + when(target.ownerProofDigest()) + .thenReturn((String) sources.get("gameSessionOwnerProofDigest")); + var claims = mock(ContextClaims.class); + when(claims.expiresAtMillis()).thenReturn(NOW.plusSeconds(120).toEpochMilli()); + var context = mock(FirstPartyConnectContext.class); + when(context.hasCompleteRoutingScope()).thenReturn(true); + when(context.claims()).thenReturn(claims); + when(context.accountId()).thenReturn(f.account.getAccountUuid().toString()); + when(context.connectScopeId()).thenReturn(f.scope.connectScopeId()); + when(context.resolvedTarget()).thenReturn(target); + var login = mock(CanonicalGameplayLoginResult.class); + when(login.compactJwtBytes()) + .thenAnswer(invocation -> CONTROLLED_COMPACT_TOKEN.getBytes(StandardCharsets.US_ASCII)); + when(login.evidence()) + .thenReturn( + new CanonicalGameplayLoginResult.NonSecretEvidence( + f.account.getAccountUuid(), + UUID.randomUUID(), + UUID.fromString((String) sources.get("callerContextId")), + UUID.fromString((String) sources.get("callerTokenJti")), + controlledTokenDigest(), + GameSessionAccountDelegationProfile.PROFILE, + NOW.minusSeconds(10).getEpochSecond(), + NOW.minusSeconds(10).getEpochSecond(), + NOW.plusSeconds(120).getEpochSecond(), + "1", + "1", + ByteString.EMPTY, + ByteString.EMPTY, + ByteString.EMPTY)); + var receiver = new AccountPlayerAdmissionEntitlementGrpcService(f.owner, NAMESPACE); + var server = + receiver.createUnregisteredServer( + "127.0.0.1:0", + pki.keyManagerFactory(pki.identity("account")), + pki.trustManagerFactory()); + server.start(); + long membershipsBefore = f.dsl.fetchCount(DSL.table("account_tenant_membership")); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + server.getPort()); + try (var client = + new AccountPlayerAdmissionEntitlementClient( + endpoints, + pki.clientProperties(certificateDirectory, pki.identity("client")), + new GrpcChannelFactory(), + NAMESPACE, + Clock.fixed(NOW, ZoneOffset.UTC))) { + client.init(); + var received = client.read(context, request.requestId(), login, () -> true); + assertThat(received.canonicalBytes()).isEqualTo(expected.canonicalBytes()); + assertThat(received.membershipSource().membershipExists()).isEqualTo(joined); + assertThat(received.membershipSource().gameplayAdmissionAllowed()).isEqualTo(joined); + assertThat(new String(received.canonicalBytes(), StandardCharsets.UTF_8)) + .doesNotContain(CONTROLLED_COMPACT_TOKEN); + assertThatThrownBy(() -> client.read(context, UUID.randomUUID(), login, () -> false)) + .isInstanceOf(RuntimeException.class); + assertThat(f.dsl.fetchCount(DSL.table("account_tenant_membership"))) + .isEqualTo(membershipsBefore); + } finally { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + } + + private static String controlledTokenDigest() { + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(CONTROLLED_COMPACT_TOKEN.getBytes(StandardCharsets.US_ASCII))); + } catch (java.security.NoSuchAlgorithmException unavailable) { + throw new IllegalStateException(unavailable); + } + } + + @Test + void actualAbsenceBaselineReturnsNonadmittingPlayerEvidenceWithoutCreatingMembership() { + Fixture f = fixture(false); + long before = f.dsl.fetchCount(DSL.table("account_tenant_membership")); + var value = f.owner.evaluate(f.request(), CONTROLLED_COMPACT_TOKEN); + assertThat(value.fields()).containsEntry("variant", "PLAYER_ADMISSION"); + assertThat(value.membershipSource().accountId()) + .isEqualTo(f.account.getAccountUuid().toString()); + assertThat(value.membershipSource().tenantId()).isEqualTo(f.tenantId.toString()); + assertThat(value.membershipSource().membershipExists()).isFalse(); + assertThat(value.membershipSource().membershipLifecycleState()).isEqualTo("MISSING"); + assertThat(value.membershipSource().gameplayAdmissionAllowed()).isFalse(); + assertThat(value.fields()).containsEntry("sourceKind", "NON_PAID_DEMO"); + assertThat(f.dsl.fetchCount(DSL.table("account_tenant_membership"))).isEqualTo(before); + var missing = + f.transaction.execute( + status -> f.memberships.findFreshMembership(f.account.getAccountUuid(), f.tenantId)); + assertThat(missing).isEmpty(); + assertThat(value.membershipSource().checkpoints()) + .anySatisfy( + checkpoint -> { + assertThat(checkpoint.outboxStreamKey()).contains("membership/"); + assertThat(checkpoint.outboxSequence()).isEqualTo("0"); + }); + assertThat(value.membershipSource().sourceEvidence()).isNotEmpty(); + } + + @Test + void actualFirstJoinRetainsItsPositiveMembershipAndExactScopeBinding() { + Fixture f = fixture(true); + var value = f.owner.evaluate(f.request(), CONTROLLED_COMPACT_TOKEN); + assertThat(value.membershipSource().membershipExists()).isTrue(); + assertThat(value.membershipSource().membershipVersion()) + .containsExactlyEntriesOf(Map.of(f.tenantId.toString(), "2")); + assertThat(value.membershipSource().membershipAuthorityGeneration()).isEqualTo("1"); + assertThat(value.membershipSource().gameplayAdmissionAllowed()).isTrue(); + var binding = (Map) value.fields().get("target"); + assertThat(binding.get("realmId")).isEqualTo(f.scope.realmId().toString()); + assertThat(binding.get("playableStateNamespaceId")) + .isEqualTo(f.scope.playableStateNamespaceId().toString()); + assertThat(binding.get("gameInstanceId")).isEqualTo(f.scope.gameInstanceId().toString()); + assertThat(binding.get("catalogRevision")).isEqualTo("7"); + assertThat(binding.get("pointerVersion")).isEqualTo("3"); + assertThat(value.toString()).doesNotContain(f.scope.connectScopeId(), CONTROLLED_COMPACT_TOKEN); + } + + @Test + void captureHoldsActualAccountWriterLockAndFailureBeforeCommitExposesNoValue() { + Fixture f = fixture(false); + AtomicBoolean competingWriterRefused = new AtomicBoolean(); + doAnswer( + invocation -> { + Object snapshot = invocation.callRealMethod(); + try (Connection contender = f.dataSource.getConnection()) { + contender.setAutoCommit(false); + try (var statement = contender.createStatement()) { + statement.execute("SET LOCAL lock_timeout = '150ms'"); + try (var select = + contender.prepareStatement( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE")) { + select.setObject(1, f.account.getAccountUuid()); + try { + select.executeQuery().close(); + throw new AssertionError( + "Account source lock did not exclude a competing writer"); + } catch (SQLException expectedLockTimeout) { + assertThat(expectedLockTimeout.getSQLState()).isEqualTo("55P03"); + competingWriterRefused.set(true); + } + } finally { + contender.rollback(); + } + } + } + TransactionSynchronizationManager.registerSynchronization( + new TransactionSynchronization() { + @Override + public void beforeCommit(boolean readOnly) { + throw new IllegalStateException("controlled final source commit refusal"); + } + }); + return snapshot; + }) + .when(f.demos) + .readCurrent(f.tenantId); + assertThatThrownBy(() -> f.owner.evaluate(f.request(), CONTROLLED_COMPACT_TOKEN)) + .hasMessageContaining("controlled final source commit refusal"); + assertThat(competingWriterRefused.get()).isTrue(); + var unlocked = + f.transaction.execute( + status -> f.accounts.findByAccountUuidForUpdate(f.account.getAccountUuid())); + assertThat(unlocked).isPresent(); + } + + private Fixture fixture(boolean join) { + String schema = SCHEMA_PREFIX + UUID.randomUUID().toString().replace("-", ""); + schemas.add(schema); + DriverManagerDataSource dataSource = POSTGRES.dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + return new Fixture(dataSource, join); + } + + /** Controlled protected-client double: no physical GS/World source provenance is claimed. */ + private static void controlledTarget(CanonicalGameplayAdmissionDecisionReadClient targets) { + when(targets.resolvePublishedRealmAdmissionTarget(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + var selector = + invocation.getArgument( + 0, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector.class); + var target = mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target.class); + when(target.targetNamespace()).thenReturn(selector.targetNamespace()); + when(target.canonicalTenantId()).thenReturn(selector.tenantId()); + when(target.tenantSlug()).thenReturn(selector.tenantSlug()); + when(target.worldSlug()).thenReturn(selector.worldSlug()); + when(target.realmId()).thenReturn(selector.realmId()); + when(target.realmSlug()).thenReturn(selector.realmSlug()); + when(target.playableStateNamespaceId()) + .thenReturn(selector.playableStateNamespaceId()); + when(target.playableStateScope()).thenReturn(selector.playableStateScope()); + when(target.canonicalGameInstanceId()).thenReturn(selector.gameInstanceId()); + when(target.catalogRevision()).thenReturn(selector.catalogRevision()); + when(target.pointerVersion()).thenReturn(selector.pointerVersion()); + when(target.characterCreationPolicy()).thenReturn("PRESEEDED_ONLY"); + when(target.ownerProofOutcome()) + .thenReturn( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome.COMMITTED); + UUID version = UUID.fromString("33333333-3333-4333-8333-333333333333"); + when(target.canonicalVersionId()).thenReturn(version); + when(target.activeWorldEpoch()).thenReturn(5L); + var strict = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + selector.readRequestId(), + selector.accountId(), + selector.targetNamespace(), + selector.tenantId(), + selector.worldSlug(), + selector.realmId(), + selector.realmSlug(), + selector.playableStateNamespaceId(), + selector.playableStateScope(), + selector.gameInstanceId(), + version, + selector.catalogRevision(), + selector.pointerVersion(), + 5L); + var resolved = + mock( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.ResolvedPublishedTarget + .class); + when(resolved.selector()).thenReturn(selector); + when(resolved.currentTarget()).thenReturn(target); + when(resolved.strictSelector()).thenReturn(strict); + var read = + mock( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class); + when(read.selector()).thenReturn(strict); + when(read.currentTarget()).thenReturn(target); + var source = mock(CanonicalGameplayRosterOwnerReadEvidence.class); + when(source.admissionPointerSnapshotDigest()).thenReturn("a".repeat(64)); + var policies = mock(PublishedRealmEntryPolicySetEvidence.class); + when(policies.policySetDigest()).thenReturn("sha256:" + "b".repeat(64)); + when(source.publishedPolicySetEvidence()).thenReturn(policies); + var ownerProof = + mock( + net.firedevops.firemud.common.world + .GameSessionCanonicalInitialAdmissionOwnerProof.class); + when(ownerProof.proofDigest()).thenReturn("sha256:" + "c".repeat(64)); + when(source.gameSessionOwnerProof()).thenReturn(ownerProof); + when(read.sourceEvidence()).thenReturn(source); + var world = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(world.canonicalBytes()) + .thenReturn( + "controlled-complete-world-source" + .getBytes(java.nio.charset.StandardCharsets.UTF_8)); + when(world.captureId()) + .thenReturn(UUID.fromString("44444444-4444-4444-8444-444444444444")); + when(world.rowVersion()).thenReturn(2L); + when(read.worldLifecycleEvidence()).thenReturn(world); + when(targets.readPublishedRealmAdmissionOwner(strict)) + .thenAnswer( + readCall -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isFalse(); + return read; + }); + return resolved; + }); + } + + private static final class Fixture { + private final DriverManagerDataSource dataSource; + private final DSLContext dsl; + private final TransactionTemplate transaction; + private final AccountRepository accounts; + private final AccountTenantMembershipRepository memberships; + private final AccountDemoTenantEntitlementRepository demos; + private final Account account; + private final UUID tenantId = UUID.randomUUID(); + private final CanonicalJoinScopeV2 scope; + private final AccountPlayerAdmissionEntitlementOwner owner; + + private Fixture(DriverManagerDataSource dataSource, boolean join) { + this.dataSource = dataSource; + dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var transactions = new DataSourceTransactionManager(dataSource); + transaction = new TransactionTemplate(transactions); + accounts = new AccountRepository(dsl); + var tenants = new FreshTenantIdentityAssociationRepository(dsl, NAMESPACE); + var pairs = new AccountMembershipPairAuthorityRepository(dsl); + memberships = new AccountTenantMembershipRepository(dsl, accounts, tenants, pairs); + var roles = new AccountTenantMembershipRoleSnapshotRepository(dsl); + var generations = new AccountAuthorityGenerationRepository(dsl); + var outbox = new AccountAuthorityOutboxRepository(dsl); + var sources = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); + var billing = new AccountTenantEntitlementOutboxRepository(dsl); + var tenantEvents = + new AccountTenantAuthorityEventRepository(dsl, outbox, billing, tenants, generations); + demos = + spy( + new AccountDemoTenantEntitlementRepository( + dsl, tenants, generations, billing, tenantEvents)); + var scopes = + new AccountConnectScopeRepository( + dsl, + new AccountTenantIdentityResolver( + mock(ApprovedLegacyTenantAssociationRepository.class), NAMESPACE), + tenants); + var operations = new AccountJoinOperationRepository(dsl, scopes); + var membershipProducer = + new AccountMembershipAuthorityEventProducer( + operations, + accounts, + pairs, + memberships, + roles, + generations, + outbox, + sources, + tenantEvents, + demos); + var terminal = + new AccountCanonicalFirstJoinTerminalCoordinator( + accounts, + operations, + memberships, + roles, + outbox, + pairs, + new AccountAuditOutboxRepository(dsl), + membershipProducer); + var snapshots = + new AccountCanonicalRuntimeMembershipSnapshotRepository( + accounts, + generations, + sources, + tenantEvents, + tenants, + memberships, + pairs, + roles, + outbox); + Account input = new Account(); + String suffix = UUID.randomUUID().toString().replace("-", ""); + input.setUsername("player-" + suffix); + input.setEmail("player-entitlement-" + suffix + "@example.test"); + input.setPasswordHash("controlled-password-hash"); + // Gameplay player roles belong to the canonical tenant membership. + account = transaction.execute(status -> accounts.save(input)); + if (account == null) throw new IllegalStateException("Account insertion is absent"); + FreshTenantCreationEvidence tenantSource = tenantSource(tenantId); + var provenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + tenantSource.operationId(), + tenantSource.evidenceDigest()); + scope = + new CanonicalJoinScopeV2( + "scope-" + UUID.randomUUID(), + account.getAccountUuid(), + tenantId, + UUID.randomUUID(), + "tenant", + "world", + "production", + UUID.randomUUID(), + "SHARED", + UUID.randomUUID(), + 7, + 3, + NOW.minusSeconds(20).toString(), + NOW.plusSeconds(120).toString()); + String joinRequestId = UUID.randomUUID().toString(); + String callerBinding = "controlled-join-caller"; + transaction.execute( + status -> { + tenants.importVerified(tenantSource); + sources.initializeIssuerIfAbsent(ISSUER); + generations.initializeTenantIfAbsent(tenantId); + generations.initialize( + AccountAuthorityGenerationRepository.AuthorityScope.membership( + account.getAccountUuid(), tenantId)); + scopes.insertCanonical(account.getId(), scope, provenance); + operations.insertCanonicalIntent(joinRequestId, scope, callerBinding); + return null; + }); + var entitlement = + transaction.execute( + status -> + demos.provision( + new DemoTenantEntitlementRequest( + UUID.randomUUID(), + tenantId, + tenantSource.creationRequestId(), + tenantSource.requestDigest(), + null, + null, + null, + true, + true, + true, + true, + new DemoTenantEntitlementRequest.Quotas(3, 2, 4096)), + tenantSource)); + if (entitlement == null) throw new IllegalStateException("Demo source is absent"); + transaction.execute( + status -> { + operations.bindCanonicalPolicyEvidence( + joinRequestId, + scope, + callerBinding, + entitlement.allowPublicJoin(), + entitlement.entitlementVersion()); + if (join) { + terminal.commitCanonicalFirstJoin(scope, joinRequestId, callerBinding); + } else { + accounts.findByAccountUuidForUpdate(account.getAccountUuid()).orElseThrow(); + memberships.prepareFreshCreatorAbsence(account.getAccountUuid(), tenantId); + } + return null; + }); + var issuances = mock(AccountGameplayDelegationIssuanceRepository.class); + var callers = mock(AccountGameplayAdmissionCallerVerifier.class); + var identity = + new AccountGameplayDelegationPendingIdentity( + UUID.randomUUID(), + UUID.randomUUID(), + account.getAccountUuid(), + PEER, + UUID.randomUUID(), + mock(AccountGameplayCredentialRequestBinding.class), + "a".repeat(64), + UUID.randomUUID(), + NOW.minusSeconds(10).getEpochSecond(), + NOW.minusSeconds(10).getEpochSecond(), + NOW.plusSeconds(120).getEpochSecond()); + var candidate = mock(CommittedCandidateVerificationData.class); + when(candidate.identity()).thenReturn(identity); + when(candidate.authoritySnapshot()) + .thenReturn( + new AccountAuthoritySnapshot( + account.getAccountUuid(), 1, 1, 1, 1, 1, 1, Optional.empty())); + when(candidate.evidenceBundleReference()).thenReturn(mock(EvidenceBundleReference.class)); + when(candidate.signerCorrespondence()) + .thenReturn(mock(AuthenticatedSignerCorrespondence.class)); + when(candidate.tokenSha256()).thenReturn(controlledTokenDigest()); + when(candidate.signerKid()).thenReturn("controlled-kid"); + when(candidate.signerGeneration()).thenReturn("1"); + when(candidate.canonicalRegistryRecordSha256()).thenReturn("b".repeat(64)); + when(candidate.commitProofSha256()).thenReturn("c".repeat(64)); + when(candidate.envelopeKeyId()).thenReturn("controlled-key"); + when(candidate.envelopeSha256()).thenReturn("d".repeat(64)); + var caller = mock(VerifiedCaller.class); + when(caller.identity()).thenReturn(identity); + when(caller.currentCandidate()).thenReturn(candidate); + when(callers.verifyPresentedCompactToken(CONTROLLED_COMPACT_TOKEN)).thenReturn(caller); + when(issuances.readCurrentCommittedCandidateByJti(identity.tokenJti())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + dsl.connection( + connection -> + assertThat(connection.getTransactionIsolation()) + .isEqualTo(Connection.TRANSACTION_SERIALIZABLE)); + return Optional.of(candidate); + }); + var targets = mock(CanonicalGameplayAdmissionDecisionReadClient.class); + controlledTarget(targets); + owner = + new AccountPlayerAdmissionEntitlementOwner( + dsl, + accounts, + callers, + issuances, + snapshots, + scopes, + mock(AccountHostingSubscriptionLifecycleRepository.class), + mock(StripeHostingSubscriptionObserver.class), + demos, + tenantEvents, + targets, + transactions, + Clock.fixed(NOW, ZoneOffset.UTC), + NAMESPACE); + } + + private Request request() { + return new Request( + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector( + UUID.randomUUID(), + account.getAccountUuid(), + NAMESPACE, + tenantId, + scope.tenantSlug(), + scope.worldSlug(), + scope.realmId(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion()), + scope.connectScopeId(), + PEER); + } + } + + private static FreshTenantCreationEvidence tenantSource(UUID tenantId) { + UUID requestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String sourceKey = "w-" + UUID.randomUUID().toString().replace("-", ""); + String requestDigest = + GameTenantCreationDigest.requestDigest(NAMESPACE, requestId, sourceKey, "World", null); + return new FreshTenantCreationEvidence( + 1, + NAMESPACE, + requestId, + operationId, + requestDigest, + tenantId, + 17, + sourceKey, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + NAMESPACE, + requestId, + operationId, + requestDigest, + tenantId, + 17, + sourceKey, + "NEW_GAME_ROW")); + } +} 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 deleted file mode 100644 index db8088530b..0000000000 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerPostgresIntegrationTest.java +++ /dev/null @@ -1,330 +0,0 @@ -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().fetchOne("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") - .target("1030") - .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/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java index ad7f8f1ff4..43a3e85b93 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java @@ -31,7 +31,6 @@ import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; import net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository; -import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; @@ -441,6 +440,7 @@ public Account updatePasswordHashForLockedAccount(Account expected, String passw logoutAllOperations, securityStateOperations, resetSourceChanges, + null, // Audit outbox is not used by credential/reset owner tests. null, // Connect scopes are not used by credential/reset owner tests. null, // JOIN operations are not used by credential/reset owner tests. challenges, @@ -450,8 +450,7 @@ public Account updatePasswordHashForLockedAccount(Account expected, String passw null, // Profiles are not used by primary authentication. null, // Profile mapper is not used by primary authentication. null, // Payment transactions are not used by primary authentication. - // Retained evidence is not read by primary authentication. - org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), + null, // Subscriptions are not used by primary authentication. null, // External identities are not used by primary authentication. resetTokens, null, // Email verification tokens are not used by primary authentication. @@ -459,6 +458,8 @@ public Account updatePasswordHashForLockedAccount(Account expected, String passw null, // Email delivery is not used by primary authentication. null, // Mail properties are not used by primary authentication. null, // Token properties are not used by primary authentication. + null, // JWT auth properties are not used by primary authentication. + null, // Game Session client is not used by primary authentication. null, // Entity Management client is not used by primary authentication. null, // JWT utility is not used by primary authentication. null, // Session service is not used by primary authentication. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java index 22d0ca18e9..62ee56af53 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java @@ -70,7 +70,6 @@ import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; import net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository; -import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountGenerationProjection; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; @@ -2508,6 +2507,7 @@ private static AccountServiceImpl primaryCredentialAuthority( null, null, null, + null, challenges, null, null, @@ -2515,7 +2515,9 @@ private static AccountServiceImpl primaryCredentialAuthority( null, null, null, - org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), + null, + null, + null, null, null, null, @@ -3114,6 +3116,7 @@ private static void commitPasswordResetAuthorityChange( logoutAllOperations, securityStateOperations, sourceChanges, + null, // audit outbox null, // connect scopes null, // join operations null, // email login challenges @@ -3123,8 +3126,7 @@ private static void commitPasswordResetAuthorityChange( null, // profiles null, // profile mapper null, // payment transactions - // retained subscription evidence - org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), + null, // subscriptions null, // external account identities resetTokens, null, // email verification tokens @@ -3135,6 +3137,8 @@ private static void commitPasswordResetAuthorityChange( null, null, null, + null, + null, context.manager()); inTransaction( context, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierPostgresIntegrationTest.java index 124b9a3fac..696ffe803a 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierPostgresIntegrationTest.java @@ -31,7 +31,6 @@ import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; -import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.accountservice.service.session.AccountGameplayCanonicalLoginOwner; @@ -295,6 +294,7 @@ private static Harness harness(String authModes, boolean expired) { null, null, null, + null, challenges, null, null, @@ -302,7 +302,9 @@ private static Harness harness(String authModes, boolean expired) { null, null, null, - org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), + null, + null, + null, null, null, null, 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 deleted file mode 100644 index ac2bc07df9..0000000000 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionCompositionPostgresIntegrationTest.java +++ /dev/null @@ -1,538 +0,0 @@ -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.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 realAccountAuthorityAdvanceDuringSdkReadRejectsBeforeMutationAndKeepsOtp() 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"); - return issued.sources().accounts.save(account); - })); - assertThatThrownBy(() -> resolve(failed, issued.account().getEmail(), OTP)) - .isExactlyInstanceOf(IllegalStateException.class) - .hasMessage("Exact current authenticated initial creator required"); - 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(), - 2, - 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/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java index 8731b20cf2..d11ddd6fad 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java @@ -37,13 +37,13 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; 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.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; -import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; @@ -1892,6 +1892,7 @@ private static Context contextAtVersion( mock(AccountSecurityStateOperationRepository.class), mock(AccountPasswordResetDraftSourceChangeRepository.class), mock(AccountAuditOutboxRepository.class), + mock(AccountConnectScopeRepository.class), mock(AccountJoinOperationRepository.class), challenges, null, @@ -1900,7 +1901,9 @@ private static Context contextAtVersion( null, null, null, - org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), + null, + null, + null, null, null, null, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionPostgresIntegrationTest.java index 0b6d5c792c..be5a5fdb41 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionPostgresIntegrationTest.java @@ -22,13 +22,13 @@ 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.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; -import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.test.TestContainerImages; @@ -513,6 +513,7 @@ private static Context context() { mock(AccountSecurityStateOperationRepository.class), mock(AccountPasswordResetDraftSourceChangeRepository.class), mock(AccountAuditOutboxRepository.class), + mock(AccountConnectScopeRepository.class), mock(AccountJoinOperationRepository.class), challenges, null, @@ -521,7 +522,9 @@ private static Context context() { null, null, null, - org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), + null, + null, + null, null, null, null, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java index 0d552450fc..95aabd3c51 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java @@ -42,6 +42,7 @@ 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.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountInitialTenantBillingOwnerRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; @@ -54,7 +55,6 @@ import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; -import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountCreatorMembershipSourceReader; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapAuthorizationSource; @@ -1267,6 +1267,7 @@ private static StorageContext storageContext(int recentAgeSeconds, int maxClockS mock(AccountSecurityStateOperationRepository.class), mock(AccountPasswordResetDraftSourceChangeRepository.class), mock(AccountAuditOutboxRepository.class), + mock(AccountConnectScopeRepository.class), mock(AccountJoinOperationRepository.class), challenges, null, @@ -1275,7 +1276,9 @@ private static StorageContext storageContext(int recentAgeSeconds, int maxClockS null, null, null, - org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), + null, + null, + null, null, null, null, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationSourceOrderPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationSourceOrderPostgresIntegrationTest.java index d8c9ba3a53..78248339c5 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationSourceOrderPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationSourceOrderPostgresIntegrationTest.java @@ -49,13 +49,13 @@ 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.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; -import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; @@ -916,6 +916,7 @@ private static Context context() { mock(AccountSecurityStateOperationRepository.class), mock(AccountPasswordResetDraftSourceChangeRepository.class), mock(AccountAuditOutboxRepository.class), + mock(AccountConnectScopeRepository.class), mock(AccountJoinOperationRepository.class), challenges, null, @@ -924,7 +925,9 @@ private static Context context() { null, null, null, - org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), + null, + null, + null, null, null, null, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClientMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClientMtlsTest.java new file mode 100644 index 0000000000..728fa4a612 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClientMtlsTest.java @@ -0,0 +1,316 @@ +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 io.grpc.Context; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +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.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.net.InetSocketAddress; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +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.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterActor; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadRequest; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadResponse; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadServiceGrpc; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import net.firedevops.firemud.test.LoopbackMtlsTestPki.IdentitySpec; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Physical transport/projection proof only; published GS/World source facts are controlled inputs. + */ +class AccountBootstrapRosterReadClientMtlsTest { + private static final UUID ACCOUNT = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID REALM = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID NAMESPACE_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID INSTANCE = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID VERSION = UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final UUID ACTOR = UUID.fromString("77777777-7777-4777-8777-777777777777"); + @TempDir static Path directory; + private static LoopbackMtlsTestPki.Pki pki; + + @BeforeAll + static void createCertificates() throws Exception { + pki = + LoopbackMtlsTestPki.create( + directory, + "Account bootstrap Entity read CA", + new IdentitySpec("account", "spiffe://firemud/ns/test/sa/account-service", false), + new IdentitySpec( + "entity", "spiffe://firemud/ns/test/sa/entity-management-service", true), + new IdentitySpec( + "wrong-service", "spiffe://firemud/ns/test/sa/game-session-service", true), + new IdentitySpec( + "wrong-namespace", "spiffe://firemud/ns/other/sa/entity-management-service", true)); + } + + @AfterEach + void clearContext() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void exactEntityPeerPreservesRequestNamespaceAndActualLevelIncludingZero() throws Exception { + Probe service = new Probe(); + service.respond = + request -> + AccountBootstrapRosterReadResponse.newBuilder() + .setRequest(request) + .addActors(actor().setLevel(0)) + .build(); + try (var server = server("entity", service); + var client = client(server.port())) { + client.init(); + UUID requestId = UUID.randomUUID(); + var actors = client.read(requestId, ACCOUNT, published()); + assertThat(actors) + .containsExactly(new AccountBootstrapRosterReadClient.Actor(ACTOR, "Mara", 0)); + assertThat(service.request.get().getRequestUuid()).isEqualTo(requestId.toString()); + assertThat(service.request.get().getCanonicalAccountUuid()).isEqualTo(ACCOUNT.toString()); + assertThat(service.request.get().getExpectedTarget().getPlayableStateNamespaceUuid()) + .isEqualTo(NAMESPACE_ID.toString()); + assertThat(service.peer.get().isService("account-service")).isTrue(); + assertThat(service.peer.get().isInNamespace("test")).isTrue(); + service.respond = + request -> AccountBootstrapRosterReadResponse.newBuilder().setRequest(request).build(); + assertThat(client.read(UUID.randomUUID(), ACCOUNT, published())).isEmpty(); + } + } + + @Test + void localBrowserContextIsPreservedWithoutAnOutboundBearerCredential() throws Exception { + Probe service = new Probe(); + try (var server = server("entity", service); + var client = client(server.port())) { + client.init(); + SessionContext.setContext( + ACCOUNT.toString(), List.of("player"), Map.of(TENANT.toString(), List.of("tenantAdmin"))); + assertThat(client.read(UUID.randomUUID(), ACCOUNT, published())).isEmpty(); + assertThat(SessionContext.getAccountId()).isEqualTo(ACCOUNT.toString()); + assertThat(SessionContext.getScopedRoles(TENANT.toString())).containsExactly("tenantAdmin"); + assertThat(service.authorization.get()).isNull(); + assertThat(service.peer.get().isService("account-service")).isTrue(); + } + } + + @Test + void foreignEntityIdentityIsRefusedBeforeApplicationDispatch() throws Exception { + for (String identity : List.of("wrong-service", "wrong-namespace")) { + Probe service = new Probe(); + try (var server = server(identity, service); + var client = client(server.port())) { + client.init(); + assertThatThrownBy(() -> client.read(UUID.randomUUID(), ACCOUNT, published())) + .isInstanceOf(StatusRuntimeException.class); + assertThat(service.calls.get()).isZero(); + } + } + } + + @Test + void mismatchedDuplicateAndMissingLevelResponsesNeverBecomeAnEmptySuccess() throws Exception { + Probe service = new Probe(); + try (var server = server("entity", service); + var client = client(server.port())) { + client.init(); + service.respond = + request -> + AccountBootstrapRosterReadResponse.newBuilder() + .setRequest(request.toBuilder().setCanonicalAccountUuid(TENANT.toString())) + .build(); + assertThatThrownBy(() -> client.read(UUID.randomUUID(), ACCOUNT, published())) + .isInstanceOf(IllegalStateException.class); + service.respond = + request -> + AccountBootstrapRosterReadResponse.newBuilder() + .setRequest(request) + .addActors(actor()) + .build(); + assertThatThrownBy(() -> client.read(UUID.randomUUID(), ACCOUNT, published())) + .isInstanceOf(IllegalStateException.class); + service.respond = + request -> + AccountBootstrapRosterReadResponse.newBuilder() + .setRequest(request) + .addActors(actor().setLevel(2)) + .addActors(actor().setLevel(2)) + .build(); + assertThatThrownBy(() -> client.read(UUID.randomUUID(), ACCOUNT, published())) + .isInstanceOf(IllegalStateException.class); + } + } + + @Test + void ambientSqlRefusesBeforeTheEntityRead() throws Exception { + Probe service = new Probe(); + try (var server = server("entity", service); + var client = client(server.port())) { + client.init(); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.read(UUID.randomUUID(), ACCOUNT, published())) + .isInstanceOf(IllegalStateException.class); + assertThat(service.calls.get()).isZero(); + } + } + + private static AccountBootstrapRosterActor.Builder actor() { + return AccountBootstrapRosterActor.newBuilder() + .setCharacterUuid(ACTOR.toString()) + .setDisplayName("Mara"); + } + + private static CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence + published() { + var target = mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target.class); + when(target.targetNamespace()).thenReturn("test"); + when(target.canonicalTenantId()).thenReturn(TENANT); + when(target.realmId()).thenReturn(REALM); + when(target.worldSlug()).thenReturn("world"); + when(target.realmSlug()).thenReturn("production"); + when(target.canonicalGameInstanceId()).thenReturn(INSTANCE); + when(target.canonicalVersionId()).thenReturn(VERSION); + when(target.playableStateNamespaceId()).thenReturn(NAMESPACE_ID); + when(target.playableStateScope()).thenReturn("SHARED"); + when(target.characterCreationPolicy()).thenReturn("PRESEEDED_ONLY"); + when(target.catalogRevision()).thenReturn(1L); + when(target.pointerVersion()).thenReturn(1L); + when(target.activeWorldEpoch()).thenReturn(1L); + when(target.admissionPointerSnapshotDigest()).thenReturn("a".repeat(64)); + when(target.ownerProofDigest()).thenReturn("sha256:" + "b".repeat(64)); + var policy = mock(PublishedRealmEntryPolicyEvidence.class); + when(policy.policyDigest()).thenReturn("sha256:" + "c".repeat(64)); + var policySet = mock(PublishedRealmEntryPolicySetEvidence.class); + when(policySet.publishedReleaseBundleRef()).thenReturn("controlled-release"); + var source = mock(CanonicalGameplayRosterOwnerReadEvidence.class); + when(source.selectedPolicyEvidence()).thenReturn(policy); + when(source.publishedPolicySetEvidence()).thenReturn(policySet); + var result = mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class); + when(result.currentTarget()).thenReturn(target); + when(result.sourceEvidence()).thenReturn(source); + when(result.selector()) + .thenReturn( + new CanonicalGameplayRosterOwnerReadEvidence.Request( + UUID.randomUUID(), + ACCOUNT, + "test", + TENANT, + "world", + REALM, + "production", + NAMESPACE_ID, + "SHARED", + INSTANCE, + VERSION, + 1L, + 1L, + 1L)); + return result; + } + + private static AccountBootstrapRosterReadClient client(int port) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setEntityManagementService("127.0.0.1:" + port); + return new AccountBootstrapRosterReadClient( + endpoints, + pki.clientProperties(directory, pki.identity("account")), + new GrpcChannelFactory(), + "test"); + } + + private static Loopback server(String alias, Probe service) throws Exception { + var identity = pki.identity(alias); + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, + new GrpcPeerIdentityInterceptor(), + new io.grpc.ServerInterceptor() { + @Override + public io.grpc.ServerCall.Listener interceptCall( + io.grpc.ServerCall call, + io.grpc.Metadata headers, + io.grpc.ServerCallHandler next) { + service.authorization.set( + headers.get( + io.grpc.Metadata.Key.of( + "authorization", io.grpc.Metadata.ASCII_STRING_MARSHALLER))); + return next.startCall(call, headers); + } + })) + .build() + .start(); + return new Loopback(server); + } + + private record Loopback(Server server) implements AutoCloseable { + int port() { + return server.getPort(); + } + + @Override + public void close() throws InterruptedException { + server.shutdownNow(); + if (!server.awaitTermination(2L, TimeUnit.SECONDS)) + throw new IllegalStateException("Entity discovery fixture did not terminate"); + } + } + + private static final class Probe + extends AccountBootstrapRosterReadServiceGrpc.AccountBootstrapRosterReadServiceImplBase { + final AtomicInteger calls = new AtomicInteger(); + final AtomicReference request = new AtomicReference<>(); + final AtomicReference peer = new AtomicReference<>(); + final AtomicReference authorization = new AtomicReference<>(); + Function respond = + value -> AccountBootstrapRosterReadResponse.newBuilder().setRequest(value).build(); + + @Override + public void readAccountBootstrapRoster( + AccountBootstrapRosterReadRequest value, + StreamObserver observer) { + calls.incrementAndGet(); + request.set(value); + peer.set(GrpcPeerIdentity.current()); + assertThat(Context.current().getDeadline()).isNotNull(); + observer.onNext(respond.apply(value)); + observer.onCompleted(); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/data/TestDataSeederTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/data/TestDataSeederTest.java index 9f17499d2c..b76fe71ace 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/data/TestDataSeederTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/data/TestDataSeederTest.java @@ -4,6 +4,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; @@ -11,13 +14,17 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.time.LocalDateTime; +import java.util.List; import java.util.Optional; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; import net.firedevops.firemud.accountservice.entity.Profile; +import net.firedevops.firemud.accountservice.entity.Subscription; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.ProfileRepository; +import net.firedevops.firemud.accountservice.repository.SubscriptionRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -29,6 +36,7 @@ class TestDataSeederTest { @Mock AccountRepository accountRepository; @Mock AccountTenantMembershipRepository accountTenantMembershipRepository; @Mock ProfileRepository profileRepository; + @Mock SubscriptionRepository subscriptionRepository; private TestDataSeeder seeder; @@ -36,11 +44,15 @@ class TestDataSeederTest { void setup() { MockitoAnnotations.openMocks(this); seeder = - new TestDataSeeder(accountRepository, accountTenantMembershipRepository, profileRepository); + new TestDataSeeder( + accountRepository, + accountTenantMembershipRepository, + profileRepository, + subscriptionRepository); } @Test - void runSeedsDemoAccountMembershipAndProfileWhenMissing() { + void runSeedsDemoAccountMembershipProfileAndSubscriptionWhenMissing() { Account account = new Account(); account.setId(1L); account.setEmail("demo@example.com"); @@ -50,12 +62,23 @@ void runSeedsDemoAccountMembershipAndProfileWhenMissing() { when(accountTenantMembershipRepository.findByAccountIdAndTenantId(1L, 1L)) .thenReturn(Optional.empty()); when(profileRepository.findByAccountIdAndTenantId(1L, 1L)).thenReturn(Optional.empty()); + when(subscriptionRepository.findByTenantId(1L)).thenReturn(List.of()); seeder.run(new DefaultApplicationArguments(new String[] {})); verify(accountRepository).save(any(Account.class)); verify(accountTenantMembershipRepository).save(any(AccountTenantMembership.class)); verify(profileRepository).save(any(Profile.class)); + ArgumentCaptor subscriptionCaptor = ArgumentCaptor.forClass(Subscription.class); + verify(subscriptionRepository).save(subscriptionCaptor.capture()); + Subscription seededSubscription = subscriptionCaptor.getValue(); + assertAll( + () -> assertSame(account, seededSubscription.getAccount()), + () -> assertEquals("local-smoke", seededSubscription.getPlanId()), + () -> assertEquals("active", seededSubscription.getStatus()), + () -> assertNotNull(seededSubscription.getStartedAt()), + () -> assertNull(seededSubscription.getEndedAt()), + () -> assertEquals(1L, seededSubscription.getTenantId())); } @Test @@ -73,6 +96,7 @@ void runReassertsExistingDemoAccountWithoutOverwritingExplicitJoin() throws Exce .thenReturn(Optional.of(explicitJoin)); when(profileRepository.findByAccountIdAndTenantId(1L, 1L)) .thenReturn(Optional.of(new Profile())); + when(subscriptionRepository.findByTenantId(1L)).thenReturn(List.of()); seeder.run(new DefaultApplicationArguments(new String[] {})); @@ -102,6 +126,7 @@ void runReassertsExistingDemoAccountWithoutOverwritingExplicitJoin() throws Exce org.junit.jupiter.api.Assertions.assertEquals( "EXPLICIT_JOIN", explicitJoin.getAuthorityProvenance())); verify(profileRepository, never()).save(any(Profile.class)); + verify(subscriptionRepository).save(any(Subscription.class)); } @Test @@ -111,6 +136,11 @@ void runIsIdempotentWhenInvokedTwice() { account.setEmail("demo@example.com"); AccountTenantMembership seededMembership = membership(account, 1L, "ACTIVE", "SEEDED_DEMO", true); + Subscription seededSubscription = new Subscription(); + seededSubscription.setAccount(account); + seededSubscription.setPlanId("local-smoke"); + seededSubscription.setStatus("active"); + seededSubscription.setTenantId(1L); when(accountRepository.findByEmail("demo@example.com")) .thenReturn(Optional.empty(), Optional.of(account)); @@ -119,12 +149,82 @@ void runIsIdempotentWhenInvokedTwice() { .thenReturn(Optional.empty(), Optional.of(seededMembership)); when(profileRepository.findByAccountIdAndTenantId(1L, 1L)) .thenReturn(Optional.empty(), Optional.of(new Profile())); + when(subscriptionRepository.findByTenantId(1L)) + .thenReturn(List.of(), List.of(seededSubscription)); seeder.run(new DefaultApplicationArguments(new String[] {})); seeder.run(new DefaultApplicationArguments(new String[] {})); verify(accountTenantMembershipRepository, times(1)).save(any(AccountTenantMembership.class)); verify(profileRepository, times(1)).save(any(Profile.class)); + verify(subscriptionRepository, times(1)).save(any(Subscription.class)); + } + + @Test + void runRetainsExistingSubscriptionWithoutOverwritingItsStatus() { + Account account = new Account(); + account.setId(1L); + account.setEmail("demo@example.com"); + Account billingOwner = new Account(); + billingOwner.setId(2L); + AccountTenantMembership explicitJoin = membership(account, 1L, "ACTIVE", "EXPLICIT_JOIN", true); + explicitJoin.setMembershipVersion(4L); + explicitJoin.setMembershipAuthorityGeneration(8L); + Subscription existingSubscription = new Subscription(); + existingSubscription.setAccount(billingOwner); + existingSubscription.setPlanId("billing-owned-plan"); + existingSubscription.setStatus("canceled"); + existingSubscription.setEndedAt(LocalDateTime.of(2025, 1, 2, 3, 4)); + existingSubscription.setTenantId(1L); + + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); + when(accountRepository.save(any(Account.class))).thenReturn(account); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(1L, 1L)) + .thenReturn(Optional.of(explicitJoin)); + when(profileRepository.findByAccountIdAndTenantId(1L, 1L)) + .thenReturn(Optional.of(new Profile())); + when(subscriptionRepository.findByTenantId(1L)).thenReturn(List.of(existingSubscription)); + + seeder.run(new DefaultApplicationArguments(new String[] {})); + + assertAll( + () -> assertSame(billingOwner, existingSubscription.getAccount()), + () -> assertEquals("canceled", existingSubscription.getStatus()), + () -> assertEquals("billing-owned-plan", existingSubscription.getPlanId()), + () -> assertEquals(LocalDateTime.of(2025, 1, 2, 3, 4), existingSubscription.getEndedAt())); + verify(accountTenantMembershipRepository, never()).save(any(AccountTenantMembership.class)); + verify(subscriptionRepository, never()).save(any(Subscription.class)); + } + + @Test + void runFailsClosedWhenExistingTenantSubscriptionsAreAmbiguous() { + Account account = new Account(); + account.setId(1L); + account.setEmail("demo@example.com"); + AccountTenantMembership explicitJoin = membership(account, 1L, "ACTIVE", "EXPLICIT_JOIN", true); + Subscription active = new Subscription(); + active.setStatus("active"); + active.setTenantId(1L); + Subscription canceled = new Subscription(); + canceled.setStatus("canceled"); + canceled.setTenantId(1L); + + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); + when(accountRepository.save(any(Account.class))).thenReturn(account); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(1L, 1L)) + .thenReturn(Optional.of(explicitJoin)); + when(profileRepository.findByAccountIdAndTenantId(1L, 1L)) + .thenReturn(Optional.of(new Profile())); + when(subscriptionRepository.findByTenantId(1L)).thenReturn(List.of(active, canceled)); + + IllegalStateException exception = + assertThrows( + IllegalStateException.class, + () -> seeder.run(new DefaultApplicationArguments(new String[] {}))); + + assertTrue(exception.getMessage().contains("ambiguous subscription authority")); + verify(accountTenantMembershipRepository, never()).save(any(AccountTenantMembership.class)); + verify(subscriptionRepository, never()).save(any(Subscription.class)); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/CanonicalJoinScopeV2Test.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/CanonicalJoinScopeV2Test.java index 0ee7acf515..92cd994074 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/CanonicalJoinScopeV2Test.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/CanonicalJoinScopeV2Test.java @@ -1,5 +1,6 @@ package unit.net.firedevops.firemud.accountservice.dto; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; @@ -75,6 +76,14 @@ void preservesExactSelectorAndUtcTimestampBytesInDigestInput() { assertNotEquals(AccountJoinDigest.scopeV2(scope), AccountJoinDigest.scopeV2(alternateSelector)); } + @Test + void redactsBearerFromDiagnosticStringWithoutChangingItsWireAccessor() { + CanonicalJoinScopeV2 scope = scope(); + + assertEquals("connect-scope-42", scope.connectScopeId()); + assertThat(scope.toString()).contains("").doesNotContain(scope.connectScopeId()); + } + private static Class componentType(RecordComponent[] components, String name) { return Arrays.stream(components) .filter(component -> component.getName().equals(name)) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountPlayerAdmissionEntitlementWorkloadGuardTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountPlayerAdmissionEntitlementWorkloadGuardTest.java new file mode 100644 index 0000000000..6a57f07a05 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountPlayerAdmissionEntitlementWorkloadGuardTest.java @@ -0,0 +1,117 @@ +package net.firedevops.firemud.accountservice.security; + +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.when; + +import io.grpc.Attributes; +import io.grpc.Context; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import javax.net.ssl.SSLSession; +import net.firedevops.firemud.account.v1.AccountPlayerAdmissionEntitlementReadServiceGrpc; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +class AccountPlayerAdmissionEntitlementWorkloadGuardTest { + private final AccountPlayerAdmissionEntitlementWorkloadGuard guard = + new AccountPlayerAdmissionEntitlementWorkloadGuard("firemud"); + + @AfterEach + void clear() { + SessionContext.clear(); + } + + @Test + void onlyExactTlsGameSessionAndMethodCanInstallPrivateAssertion() throws Exception { + var method = + AccountPlayerAdmissionEntitlementReadServiceGrpc.getReadPlayerAdmissionEntitlementMethod(); + assertThat(invoke(method, tls("firemud", "game-session-service"))).isNull(); + assertThatThrownBy(guard::requireAuthenticatedGameSessionCaller) + .isInstanceOf(StatusRuntimeException.class); + assertThat(invoke(method, tls("other", "game-session-service")).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(invoke(method, tls("firemud", "account-service")).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + invoke(AccountServiceGrpc.getGetProfileMethod(), tls("firemud", "game-session-service")) + .getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } + + @Test + void arbitraryPeerContextAndSessionClaimsNeverAuthenticate() throws Exception { + var method = + AccountPlayerAdmissionEntitlementReadServiceGrpc.getReadPlayerAdmissionEntitlementMethod(); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/firemud/sa/game-session-service") + .orElseThrow()) + .run( + () -> { + assertThat(invoke(method, null).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThatThrownBy(guard::requireAuthenticatedGameSessionCaller) + .isInstanceOf(StatusRuntimeException.class); + }); + for (boolean internal : List.of(true, false)) { + if (internal) + SessionContext.setContext( + null, List.of(), Map.of(), true, "game-session-service", "instance"); + else SessionContext.setContext("caller", List.of(), Map.of()); + assertThat(invoke(method, tls("firemud", "game-session-service")).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + SessionContext.clear(); + } + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private Status invoke(MethodDescriptor method, SSLSession ssl) { + ServerCall call = mock(ServerCall.class); + when(call.getMethodDescriptor()).thenReturn(method); + when(call.getAttributes()) + .thenReturn( + ssl == null + ? Attributes.EMPTY + : Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, ssl).build()); + AtomicInteger starts = new AtomicInteger(); + ServerCallHandler next = + (ignored, headers) -> { + assertThat(guard.requireAuthenticatedGameSessionCaller()) + .isEqualTo("spiffe://firemud/ns/firemud/sa/game-session-service"); + starts.incrementAndGet(); + return new ServerCall.Listener() {}; + }; + guard.interceptCall(call, new Metadata(), next); + var captured = ArgumentCaptor.forClass(Status.class); + verify(call, org.mockito.Mockito.atMostOnce()).close(captured.capture(), any(Metadata.class)); + assertThat(starts.get()).isEqualTo(captured.getAllValues().isEmpty() ? 1 : 0); + return captured.getAllValues().isEmpty() ? null : captured.getValue(); + } + + private static SSLSession tls(String namespace, String service) throws Exception { + var leaf = mock(X509Certificate.class); + when(leaf.getSubjectAlternativeNames()) + .thenReturn(List.of(List.of(6, "spiffe://firemud/ns/" + namespace + "/sa/" + service))); + var ssl = mock(SSLSession.class); + when(ssl.getPeerCertificates()).thenReturn(new Certificate[] {leaf}); + return ssl; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReaderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReaderTest.java new file mode 100644 index 0000000000..611243e7a8 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReaderTest.java @@ -0,0 +1,490 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.jsonwebtoken.Claims; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Consumer; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository.CanonicalConnectScopeEvidence; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.service.AccountCanonicalConnectScopeReader; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountCanonicalConnectScopeReaderTest { + private static final UUID ACCOUNT = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID REALM = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID NAMESPACE = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID GAME_INSTANCE = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID OPERATION = UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final String SECRET = "controlled-account-canonical-connect-scope-key-0123456789"; + private static final String PROVENANCE_DIGEST = "sha256:" + "a".repeat(64); + private static final long TOKEN_LIFETIME_MILLIS = 300_000L; + + @AfterEach + void clearThreadContexts() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void returnsExactSignedV2SelectorOnlyAfterMatchingAccountHashAndProvenanceReadback() { + Fixture f = new Fixture(); + SessionContext.setContext( + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + List.of("tenantAdmin"), + Map.of(TENANT.toString(), List.of("tenantAdmin"))); + String originalSessionAccount = SessionContext.getAccountId(); + + CanonicalJoinScopeV2 actual = f.reader.read(ACCOUNT, f.scope.connectScopeId()); + + assertThat(actual).isEqualTo(f.scope); + assertThat(f.clock.instant()).isAfter(Instant.parse(f.scope.evaluatedAt())); + assertThat(f.jwt.parseToken(f.scope.connectScopeId()).getPayload().getIssuedAt().toInstant()) + .isAfter(Instant.parse(f.scope.evaluatedAt())); + assertThat(SessionContext.getAccountId()).isEqualTo(originalSessionAccount); + assertThat(SessionContext.getScopedRoles(TENANT.toString())).containsExactly("tenantAdmin"); + assertThat(f.transactions.started).isEqualTo(1); + assertThat(f.transactions.commits).isEqualTo(1); + assertThat(f.transactions.rollbacks).isZero(); + verify(f.scopes).findCanonical(f.scope.connectScopeId()); + verify(f.scopes) + .findCanonicalEvidenceByTokenHash(AccountJoinDigest.tokenHash(f.scope.connectScopeId())); + } + + @Test + void refusesWrongExpectedUuidBeforeReadingAccountStorage() { + Fixture f = new Fixture(); + + assertCode( + "CONNECT_SCOPE_INVALID", + () -> + f.reader.read( + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), f.scope.connectScopeId())); + + assertThat(f.transactions.started).isZero(); + verifyNoInteractions(f.scopes); + } + + @Test + void refusesMissingOrMalformedSignedProfileBeforeAccountRead() { + Fixture f = new Fixture(); + + assertCode("CONNECT_SCOPE_INVALID", () -> f.reader.read(ACCOUNT, "not-a-jwt")); + assertCode( + "CONNECT_SCOPE_INVALID", + () -> f.reader.read(ACCOUNT, f.issue(claims -> claims.put("aud", "player-bootstrap")))); + assertCode( + "CONNECT_SCOPE_INVALID", + () -> + f.reader.read( + ACCOUNT, + f.issue( + claims -> + claims.put( + "aud", List.of("bootstrap-connect-scope", "player-bootstrap"))))); + assertCode( + "CONNECT_SCOPE_INVALID", + () -> f.reader.read(ACCOUNT, f.issue(claims -> claims.put("targetClass", "PRIVATE")))); + assertCode( + "CONNECT_SCOPE_INVALID", + () -> f.reader.read(ACCOUNT, f.issue(claims -> claims.put("scopeDigestVersion", 1L)))); + assertCode( + "CONNECT_SCOPE_INVALID", + () -> f.reader.read(ACCOUNT, f.issue(claims -> claims.put("accountId", "123")))); + assertThat(f.transactions.started).isZero(); + verifyNoInteractions(f.scopes); + } + + @Test + void rejectsNumericTenantFallbackAndNoncanonicalOrNilUuidClaims() { + Fixture f = new Fixture(); + + assertCode( + "CONNECT_SCOPE_INVALID", + () -> f.reader.read(ACCOUNT, f.issue(claims -> claims.put("tenantId", 42L)))); + assertCode( + "CONNECT_SCOPE_INVALID", + () -> + f.reader.read( + ACCOUNT, + f.issue(claims -> claims.put("tenantId", "22222222-2222-4222-8222-22222222222")))); + assertCode( + "CONNECT_SCOPE_INVALID", + () -> + f.reader.read( + ACCOUNT, + f.issue(claims -> claims.put("realmId", "00000000-0000-0000-0000-000000000000")))); + assertThat(f.transactions.started).isZero(); + verifyNoInteractions(f.scopes); + } + + @Test + void rejectsInvalidRuntimeSelectorsAndNoncanonicalTimeClaims() { + Fixture f = new Fixture(); + + assertCode( + "CONNECT_SCOPE_INVALID", + () -> f.reader.read(ACCOUNT, f.issue(claims -> claims.put("catalogRevision", 0L)))); + assertCode( + "CONNECT_SCOPE_INVALID", + () -> f.reader.read(ACCOUNT, f.issue(claims -> claims.put("pointerVersion", "9")))); + assertCode( + "CONNECT_SCOPE_INVALID", + () -> + f.reader.read(ACCOUNT, f.issue(claims -> claims.put("playableStateScope", "shared")))); + assertCode( + "CONNECT_SCOPE_INVALID", + () -> + f.reader.read( + ACCOUNT, + f.issue(claims -> claims.put("evaluatedAt", "2026-10-03T01:02:03+00:00")))); + assertThat(f.transactions.started).isZero(); + verifyNoInteractions(f.scopes); + } + + @Test + void rejectsFutureEvaluationExpiredScopeAndJwtExpiryContradiction() { + Fixture f = new Fixture(); + + assertCode( + "CONNECT_SCOPE_INVALID", + () -> + f.reader.read( + ACCOUNT, + f.issue( + claims -> + claims.put("evaluatedAt", Instant.now().plusSeconds(30).toString())))); + assertCode( + "CONNECT_SCOPE_INVALID", + () -> + new AccountCanonicalConnectScopeReader( + f.jwt, + f.scopes, + new RecordingTransactions(), + Clock.offset(f.clock, Duration.ofMinutes(6))) + .read(ACCOUNT, f.scope.connectScopeId())); + assertCode( + "CONNECT_SCOPE_INVALID", + () -> + f.reader.read( + ACCOUNT, + f.issue( + claims -> + claims.put( + "connectScopeExpiresAt", + Instant.parse((String) claims.get("connectScopeExpiresAt")) + .plusSeconds(1) + .toString())))); + assertThat(f.transactions.started).isZero(); + verifyNoInteractions(f.scopes); + } + + @Test + void refusesAbsentScopeAndMismatchWithImmutablePersistedV2Evidence() { + Fixture f = new Fixture(); + when(f.scopes.findCanonical(f.scope.connectScopeId())).thenReturn(Optional.empty()); + assertCode("CONNECT_SCOPE_INVALID", () -> f.reader.read(ACCOUNT, f.scope.connectScopeId())); + assertThat(f.transactions.rollbacks).isEqualTo(1); + + Fixture changed = new Fixture(); + CanonicalJoinScopeV2 different = changed.copyWithWorldSlug("other-world"); + when(changed.scopes.findCanonical(changed.scope.connectScopeId())) + .thenReturn(Optional.of(different)); + assertCode( + "CONNECT_SCOPE_INVALID", + () -> changed.reader.read(ACCOUNT, changed.scope.connectScopeId())); + assertThat(changed.transactions.rollbacks).isEqualTo(1); + + Fixture wrongDigest = new Fixture(); + CanonicalConnectScopeEvidence validEvidence = evidence(wrongDigest.scope); + when(wrongDigest.scopes.findCanonicalEvidenceByTokenHash( + AccountJoinDigest.tokenHash(wrongDigest.scope.connectScopeId()))) + .thenReturn(Optional.of(withDigest(validEvidence, "sha256:" + "b".repeat(64)))); + assertCode( + "CONNECT_SCOPE_INVALID", + () -> wrongDigest.reader.read(ACCOUNT, wrongDigest.scope.connectScopeId())); + assertThat(wrongDigest.transactions.rollbacks).isEqualTo(1); + } + + @Test + void mapsDatabaseFailureAndCommitFailureToSafeAuthorityUnavailable() { + Fixture readFailure = new Fixture(); + when(readFailure.scopes.findCanonical(readFailure.scope.connectScopeId())) + .thenThrow(new org.jooq.exception.DataAccessException("controlled storage failure")); + assertCode( + "AUTH_UNAVAILABLE", + () -> readFailure.reader.read(ACCOUNT, readFailure.scope.connectScopeId())); + assertThat(readFailure.transactions.rollbacks).isEqualTo(1); + + Fixture commitFailure = new Fixture(); + commitFailure.transactions.failCommit = true; + assertCode( + "AUTH_UNAVAILABLE", + () -> commitFailure.reader.read(ACCOUNT, commitFailure.scope.connectScopeId())); + + Fixture rollbackFailure = new Fixture(); + when(rollbackFailure.scopes.findCanonical(rollbackFailure.scope.connectScopeId())) + .thenReturn(Optional.empty()); + rollbackFailure.transactions.failRollback = true; + assertCode( + "AUTH_UNAVAILABLE", + () -> rollbackFailure.reader.read(ACCOUNT, rollbackFailure.scope.connectScopeId())); + } + + @Test + void refusesAmbientTransactionWithoutChangingCallerSessionContext() { + Fixture f = new Fixture(); + SessionContext.setContext(ACCOUNT.toString(), List.of("player"), Map.of()); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> f.reader.read(ACCOUNT, f.scope.connectScopeId())) + .isInstanceOf(IllegalStateException.class); + + assertThat(SessionContext.getAccountId()).isEqualTo(ACCOUNT.toString()); + assertThat(f.transactions.started).isZero(); + verifyNoInteractions(f.scopes); + } + + private static void assertCode(String expected, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(AuthenticationException.class) + .satisfies( + failure -> { + AuthenticationException authentication = (AuthenticationException) failure; + assertThat(authentication.getCode()).isEqualTo(expected); + assertThat(authentication.getMessage()).doesNotContain("eyJ"); + }); + } + + private static CanonicalJoinScopeV2 scope(String token, String evaluatedAt, String expiresAt) { + return new CanonicalJoinScopeV2( + token, + ACCOUNT, + TENANT, + REALM, + "acme-worlds", + "demo", + "main", + NAMESPACE, + "SHARED", + GAME_INSTANCE, + 9L, + 13L, + evaluatedAt, + expiresAt); + } + + private static CanonicalJoinScopeV2 copyWithWorldSlug( + CanonicalJoinScopeV2 original, String world) { + return new CanonicalJoinScopeV2( + original.connectScopeId(), + original.accountId(), + original.tenantId(), + original.realmId(), + original.tenantSlug(), + world, + original.realmSlug(), + original.playableStateNamespaceId(), + original.playableStateScope(), + original.gameInstanceId(), + original.catalogRevision(), + original.pointerVersion(), + original.evaluatedAt(), + original.connectScopeExpiresAt()); + } + + private static final class Fixture { + private final Clock clock; + private final JwtUtil jwt = new JwtUtil(SECRET, TOKEN_LIFETIME_MILLIS); + private final AccountConnectScopeRepository scopes = + Mockito.mock(AccountConnectScopeRepository.class); + private final RecordingTransactions transactions = new RecordingTransactions(); + private final AccountCanonicalConnectScopeReader reader; + private final CanonicalJoinScopeV2 scope; + + private Fixture() { + Token token = AccountCanonicalConnectScopeReaderTest.issue(jwt, claims -> {}); + Claims claims = jwt.parseToken(token.value()).getPayload(); + String expiresAt = claims.get("connectScopeExpiresAt", String.class); + clock = + Clock.fixed( + Instant.parse(claims.get("evaluatedAt", String.class)).plusSeconds(1), + ZoneOffset.UTC); + scope = scope(token.value(), claims.get("evaluatedAt", String.class), expiresAt); + when(scopes.findCanonical(token.value())).thenReturn(Optional.of(scope)); + when(scopes.findCanonicalEvidenceByTokenHash(AccountJoinDigest.tokenHash(token.value()))) + .thenReturn(Optional.of(evidence(scope))); + reader = new AccountCanonicalConnectScopeReader(jwt, scopes, transactions, clock); + } + + private String issue(Consumer> mutation) { + return AccountCanonicalConnectScopeReaderTest.issue(jwt, mutation).value(); + } + + private CanonicalJoinScopeV2 copyWithWorldSlug(String world) { + return AccountCanonicalConnectScopeReaderTest.copyWithWorldSlug(scope, world); + } + } + + private static Token issue(JwtUtil jwt, Consumer> mutation) { + for (int attempt = 0; attempt < 100; attempt++) { + long before = System.currentTimeMillis(); + Instant expiresAt = + Instant.ofEpochMilli(before) + .truncatedTo(ChronoUnit.SECONDS) + .plusMillis(TOKEN_LIFETIME_MILLIS); + Map claims = new LinkedHashMap<>(); + claims.put("aud", "bootstrap-connect-scope"); + claims.put("accountId", ACCOUNT.toString()); + claims.put("targetClass", "PUBLIC_PRODUCTION"); + claims.put("scopeDigestVersion", 2L); + claims.put("tenantId", TENANT.toString()); + claims.put("tenantSlug", "acme-worlds"); + claims.put("worldSlug", "demo"); + claims.put("realmId", REALM.toString()); + claims.put("realmSlug", "main"); + claims.put("playableStateNamespaceId", NAMESPACE.toString()); + claims.put("playableStateScope", "SHARED"); + claims.put("gameInstanceId", GAME_INSTANCE.toString()); + claims.put("catalogRevision", 9L); + claims.put("pointerVersion", 13L); + claims.put("evaluatedAt", Instant.ofEpochMilli(before - 2_000L).toString()); + claims.put("connectScopeExpiresAt", expiresAt.toString()); + claims.put("jti", UUID.randomUUID().toString()); + mutation.accept(claims); + String value = + jwt.generateToken( + ACCOUNT.toString(), expiresAt.toEpochMilli() - System.currentTimeMillis(), claims); + Instant actualExpiry = jwt.parseToken(value).getPayload().getExpiration().toInstant(); + if (expiresAt.equals(actualExpiry)) return new Token(value); + } + throw new IllegalStateException("Could not create exact test JWT expiry"); + } + + private static CanonicalConnectScopeEvidence evidence(CanonicalJoinScopeV2 scope) { + return new CanonicalConnectScopeEvidence( + AccountJoinDigest.tokenHash(scope.connectScopeId()), + 41L, + "PUBLIC_PRODUCTION", + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt(), + 2, + AccountJoinDigest.scopeV2(scope), + new VerifiedTenantProvenance( + null, TenantProvenanceKind.FRESH_GAME_DESIGN, OPERATION, PROVENANCE_DIGEST)); + } + + private static CanonicalConnectScopeEvidence withDigest( + CanonicalConnectScopeEvidence evidence, String digest) { + return new CanonicalConnectScopeEvidence( + evidence.scopeTokenHash(), + evidence.privateAccountId(), + evidence.targetClass(), + evidence.accountUuid(), + evidence.tenantUuid(), + evidence.realmId(), + evidence.tenantSlug(), + evidence.worldSlug(), + evidence.realmSlug(), + evidence.playableStateNamespaceUuid(), + evidence.playableStateScope(), + evidence.gameInstanceUuid(), + evidence.catalogRevision(), + evidence.pointerVersion(), + evidence.evaluatedAt(), + evidence.connectScopeExpiresAt(), + evidence.scopeDigestVersion(), + digest, + evidence.tenantProvenance()); + } + + private record Token(String value) {} + + private static final class RecordingTransactions implements PlatformTransactionManager { + private int started; + private int commits; + private int rollbacks; + private boolean failCommit; + private boolean failRollback; + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + TransactionDefinition actual = + definition == null ? TransactionDefinition.withDefaults() : definition; + assertThat(actual.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(actual.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_SERIALIZABLE); + assertThat(actual.getTimeout()).isEqualTo(5); + assertThat(actual.isReadOnly()).isFalse(); + started++; + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + try { + if (failCommit) throw new IllegalStateException("controlled commit failure"); + commits++; + } finally { + clearTransaction(); + } + } + + @Override + public void rollback(TransactionStatus status) { + rollbacks++; + try { + if (failRollback) throw new IllegalStateException("controlled rollback failure"); + } finally { + clearTransaction(); + } + } + + private static void clearTransaction() { + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java new file mode 100644 index 0000000000..9e3654d9da --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java @@ -0,0 +1,941 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.sql.Connection; +import java.time.Clock; +import java.time.Instant; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +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.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository.CanonicalConnectScopeEvidence; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBinding; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; +import net.firedevops.firemud.accountservice.repository.AccountHostingPlanQuote; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionCurrentReceipt; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy.Status; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReadFence; +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.AccountSubscriptionCurrentRecord; +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.service.AccountPlayerAdmissionEntitlementOwner; +import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner.Request; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier.VerifiedCaller; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner.AuthenticatedSignerCorrespondence; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Checkpoint; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import org.jooq.ConnectionRunnable; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Controlled source doubles prove composition and denial, not authenticated custody or SQL locks. + */ +class AccountPlayerAdmissionEntitlementOwnerTest { + private static final UUID ACCOUNT = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final String ISSUER = "firemud-account-service"; + private static final String PEER = "spiffe://firemud/ns/prod/sa/game-session-service"; + private static final String PREFIX = "account:auth-authority:v1:"; + private static final Instant NOW = Instant.parse("2026-11-02T00:00:00Z"); + private static final String HASH = "a".repeat(64); + + @AfterEach + void clearTransactionFlags() { + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } + + @Test + void missingMembershipRemainsAnExplicitNonadmittingBaselineWithActualCallerAndTarget() + throws Exception { + Fixture f = new Fixture(false); + var value = f.owner.evaluate(f.request, "controlled-token"); + assertThat(value.fields()).containsEntry("variant", "PLAYER_ADMISSION"); + assertThat(value.fields().get("requestId")).isEqualTo(f.request.requestId().toString()); + assertThat(value.fields().get("callerWorkload")).isEqualTo(PEER); + assertThat(value.membershipSource().accountId()).isEqualTo(ACCOUNT.toString()); + assertThat(value.membershipSource().tenantId()).isEqualTo(TENANT.toString()); + assertThat(value.membershipSource().membershipExists()).isFalse(); + assertThat(value.membershipSource().membershipLifecycleState()).isEqualTo("MISSING"); + assertThat(value.membershipSource().gameplayAdmissionAllowed()).isFalse(); + assertThat(value.membershipSource().authorityTuple().issuerAuthGeneration()).isEqualTo("1"); + assertThat(value.membershipSource().authorityTuple().accountAuthorityGeneration()) + .isEqualTo("1"); + assertThat(value.membershipSource().authorityTuple().membershipAuthorityGeneration()) + .containsExactlyEntriesOf(Map.of(TENANT.toString(), "1")); + assertThat(value.fields()) + .containsEntry("verifiedConnectScopeId", f.scope.connectScopeId()) + .containsEntry("sourceKind", "NON_PAID_DEMO"); + var binding = (Map) value.fields().get("target"); + assertThat(binding.get("realmId")).isEqualTo(f.scope.realmId().toString()); + assertThat(binding.get("pointerVersion")).isEqualTo("3"); + assertThat(value.toString()).doesNotContain("controlled-token", f.scope.connectScopeId()); + assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "commit"); + verifyNoInteractions(f.hosting, f.observer); + } + + @Test + void existingMembershipCarriesItsIndependentVersionAndPositiveCheckpoint() throws Exception { + Fixture f = new Fixture(true); + var value = f.owner.evaluate(f.request, "controlled-token"); + assertThat(value.membershipSource().membershipExists()).isTrue(); + assertThat(value.membershipSource().membershipVersion()) + .containsExactlyEntriesOf(Map.of(TENANT.toString(), "1")); + assertThat(value.membershipSource().gameplayAdmissionAllowed()).isTrue(); + assertThat(value.membershipSource().sourceEvidence()) + .anySatisfy( + source -> { + assertThat(source.eventId()).isEqualTo("membership-event-1"); + assertThat(source.eventDigest()).startsWith("sha256:"); + }); + var order = inOrder(f.accounts, f.issuances, f.memberships, f.scopes, f.demos); + order.verify(f.accounts).findByAccountUuidForUpdate(ACCOUNT); + order.verify(f.issuances).readCurrentCommittedCandidateByJti(f.identity.tokenJti()); + order.verify(f.memberships).readCurrent(ACCOUNT, TENANT); + order.verify(f.scopes).findCanonical(f.scope.connectScopeId()); + order + .verify(f.scopes) + .findCanonicalEvidenceByTokenHash(AccountJoinDigest.tokenHash(f.scope.connectScopeId())); + order.verify(f.demos).readCurrent(TENANT); + } + + @ParameterizedTest + @EnumSource(Status.class) + void paidReadRunsProviderOutsideSqlThenCapturesCurrentReceiptAndPlayerInFinalTransaction( + Status status) throws Exception { + Fixture f = new Fixture(true); + when(f.sources.readCurrentSourceSelection(TENANT)) + .thenReturn(new SourceSelection(SourceKind.PAID_HOSTING, f.tenantEvent)); + var fence = mock(ReadFence.class); + var observed = mock(StripeHostingSubscriptionObserver.ObservedSubscription.class); + when(f.hosting.prepareCurrentRead(TENANT)) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + return fence; + }); + when(f.observer.observe(fence.binding())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return observed; + }); + when(f.hosting.readCurrent(fence, observed)) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + return f.receipt(status); + }); + var value = f.owner.evaluate(f.request, "controlled-token"); + assertThat(value.fields()) + .containsEntry("sourceKind", "PAID_HOSTING") + .containsEntry("subscriptionStatus", status.storageValue()) + .containsEntry("tenantBillingSequence", "1") + .containsEntry("tenantAuthorityGeneration", "2"); + boolean available = status != Status.SUSPENDED && status != Status.CANCELED; + assertThat(value.fields()) + .containsEntry("gameplayAvailable", available) + .containsEntry("allowPublicJoin", available && status != Status.GRACE) + .containsEntry("allowNewGameplayBindings", available && status != Status.GRACE) + .containsEntry("allowNewInstanceStarts", available && status != Status.GRACE); + assertThat(f.transactions.events) + .containsExactly("begin", "commit", "begin", "commit", "begin", "commit"); + var order = inOrder(f.observer, f.accounts, f.hosting); + order.verify(f.hosting).prepareCurrentRead(TENANT); + order.verify(f.observer).observe(fence.binding()); + order.verify(f.accounts).findByAccountUuidForUpdate(ACCOUNT); + order.verify(f.hosting).readCurrent(fence, observed); + } + + @Test + void scopeDeadlineReachedDuringFinalCommitReturnsNoValue() throws Exception { + Fixture f = new Fixture(false); + f.transactions.afterSecondCommit = () -> f.time.set(NOW.plusSeconds(60)); + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .hasMessageContaining("expired"); + assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "commit"); + } + + @Test + void callerAccountMismatchFailsBeforeAnySourceRead() throws Exception { + Fixture f = new Fixture(false); + var original = f.request.target(); + var other = + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector( + original.readRequestId(), + UUID.randomUUID(), + original.targetNamespace(), + original.tenantId(), + original.tenantSlug(), + original.worldSlug(), + original.realmId(), + original.realmSlug(), + original.playableStateNamespaceId(), + original.playableStateScope(), + original.gameInstanceId(), + original.catalogRevision(), + original.pointerVersion()); + assertThatThrownBy( + () -> + f.owner.evaluate( + new Request(other, f.scope.connectScopeId(), PEER), "controlled-token")) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + verifyNoInteractions( + f.accounts, + f.issuances, + f.memberships, + f.scopes, + f.sources, + f.demos, + f.hosting, + f.observer, + f.targets); + } + + @Test + void unavailableOrChangedAccountSourceHeadNeverChoosesAnotherFamily() throws Exception { + Fixture f = new Fixture(false); + when(f.sources.readCurrentSourceSelection(TENANT)) + .thenThrow(new IllegalStateException("controlled missing source")); + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .hasMessageContaining("controlled missing source"); + verifyNoInteractions(f.demos, f.hosting, f.observer, f.targets); + + Fixture changed = new Fixture(false); + when(changed.sources.readCurrentSourceSelection(TENANT)) + .thenReturn( + new SourceSelection(SourceKind.NON_PAID_DEMO, changed.tenantEvent), + new SourceSelection(SourceKind.PAID_HOSTING, changed.tenantEvent)); + assertThatThrownBy(() -> changed.owner.evaluate(changed.request, "controlled-token")) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + verifyNoInteractions(changed.demos, changed.hosting, changed.observer); + } + + @Test + void currentCallerLossDoesNotBecomeTenantOrBillingOwnerAuthority() throws Exception { + Fixture f = new Fixture(false); + when(f.issuances.readCurrentCommittedCandidateByJti(f.identity.tokenJti())) + .thenReturn(Optional.empty()); + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + verifyNoInteractions(f.memberships, f.scopes, f.demos, f.hosting, f.observer); + assertThat(f.transactions.events).containsExactly("begin", "rollback"); + } + + @Test + void absentCanonicalScopeRefusesPrivatePlaytestAndNumericScopeAliases() throws Exception { + Fixture f = new Fixture(false); + when(f.scopes.findCanonical(f.scope.connectScopeId())).thenReturn(Optional.empty()); + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + verifyNoInteractions(f.demos, f.hosting, f.observer); + } + + @Test + void anotherAccountsScopeFailsBeforeEntitlementCapture() throws Exception { + Fixture f = new Fixture(false); + when(f.scopes.findCanonicalEvidenceByTokenHash( + AccountJoinDigest.tokenHash(f.scope.connectScopeId()))) + .thenReturn( + Optional.of(f.scopeEvidence(UUID.randomUUID(), f.scope.connectScopeExpiresAt()))); + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + verifyNoInteractions(f.demos); + } + + @Test + void expiredScopeDoesNotReturnCapturedAuthority() throws Exception { + Fixture f = new Fixture(false); + when(f.scopes.findCanonicalEvidenceByTokenHash( + AccountJoinDigest.tokenHash(f.scope.connectScopeId()))) + .thenReturn(Optional.of(f.scopeEvidence(ACCOUNT, NOW.toString()))); + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + assertThat(f.transactions.events).containsExactly("begin", "commit"); + } + + @Test + void changedTenantCheckpointCannotBeCombinedWithAnOlderEntitlement() throws Exception { + Fixture f = new Fixture(false); + var original = f.demo; + var changed = + new DemoTenantEntitlementSnapshot( + TENANT, + f.source, + "NON_PAID_DEMO", + "ACTIVE", + null, + false, + true, + true, + true, + true, + original.quotas(), + 1, + 2, + 2, + original.outboxStreamKey(), + 1, + original.eventId(), + original.eventDigest(), + original.snapshotIdentity(), + original.tenantAuthorityOutboxStreamKey(), + 2, + original.tenantAuthorityEventId(), + original.tenantAuthorityEventDigest()); + when(f.demos.readCurrent(TENANT)).thenReturn(changed); + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "rollback"); + } + + @Test + void commitFailureReturnsNoEvidence() throws Exception { + Fixture f = new Fixture(false); + f.transactions.failCommit = true; + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .hasMessageContaining("controlled commit failure"); + assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "commit"); + } + + @Test + void wrongWorkloadAndAmbientTransactionFailBeforeCallerOrSourceReads() throws Exception { + Fixture f = new Fixture(false); + Request wrongPeer = + new Request( + f.request.target(), + f.scope.connectScopeId(), + "spiffe://firemud/ns/other/sa/game-session-service"); + assertThatThrownBy(() -> f.owner.evaluate(wrongPeer, "controlled-token")) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + verifyNoInteractions( + f.callers, + f.accounts, + f.issuances, + f.memberships, + f.scopes, + f.demos, + f.hosting, + f.observer); + } + + @Test + void unavailableProtectedTargetReturnsNoValueOrAlternateEntitlementSource() throws Exception { + Fixture f = new Fixture(false); + doThrow(new IllegalStateException("controlled target unavailable")) + .when(f.targets) + .resolvePublishedRealmAdmissionTarget(any()); + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .hasMessageContaining("controlled target unavailable"); + verifyNoInteractions(f.demos, f.hosting, f.observer); + assertThat(f.transactions.events).containsExactly("begin", "commit"); + } + + @Test + void changedOwnerPointerFailsExactRetainedTargetComparison() throws Exception { + Fixture f = new Fixture(false); + var selector = + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector( + f.request.requestId(), + ACCOUNT, + "prod", + TENANT, + f.scope.tenantSlug(), + f.scope.worldSlug(), + f.scope.realmId(), + f.scope.realmSlug(), + f.scope.playableStateNamespaceId(), + "SHARED", + f.scope.gameInstanceId(), + f.scope.catalogRevision(), + f.scope.pointerVersion()); + var resolved = f.targets.resolvePublishedRealmAdmissionTarget(selector); + when(resolved.currentTarget().pointerVersion()).thenReturn(f.scope.pointerVersion() + 1); + doReturn(resolved).when(f.targets).resolvePublishedRealmAdmissionTarget(selector); + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .hasMessageContaining("retained"); + verifyNoInteractions(f.demos, f.hosting, f.observer); + } + + @Test + void scopeChangedDuringProtectedTargetReadCannotBindFinalAccountEvidence() throws Exception { + Fixture f = new Fixture(false); + var original = f.scopeEvidence(ACCOUNT, f.scope.connectScopeExpiresAt()); + var changed = f.scopeEvidence(ACCOUNT, NOW.plusSeconds(50).toString()); + when(f.scopes.findCanonicalEvidenceByTokenHash( + AccountJoinDigest.tokenHash(f.scope.connectScopeId()))) + .thenReturn(Optional.of(original), Optional.of(changed)); + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + verifyNoInteractions(f.demos); + assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "rollback"); + } + + @Test + void strictProtectedReadFailureNeverProducesCanonicalPlayerEvidence() throws Exception { + Fixture f = new Fixture(false); + var selector = + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector( + f.request.requestId(), + ACCOUNT, + "prod", + TENANT, + f.scope.tenantSlug(), + f.scope.worldSlug(), + f.scope.realmId(), + f.scope.realmSlug(), + f.scope.playableStateNamespaceId(), + "SHARED", + f.scope.gameInstanceId(), + f.scope.catalogRevision(), + f.scope.pointerVersion()); + var resolved = f.targets.resolvePublishedRealmAdmissionTarget(selector); + when(f.targets.readPublishedRealmAdmissionOwner(resolved.strictSelector())) + .thenThrow(new IllegalStateException("controlled World source stale")); + // Keep that exact resolver result so the strict-read denial cannot be replaced by new stubbing. + doReturn(resolved).when(f.targets).resolvePublishedRealmAdmissionTarget(selector); + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .hasMessageContaining("controlled World source stale"); + verifyNoInteractions(f.demos, f.hosting, f.observer); + } + + /** Controlled protected-client double: no physical GS/World source provenance is claimed. */ + private static void controlledTarget(CanonicalGameplayAdmissionDecisionReadClient targets) { + when(targets.resolvePublishedRealmAdmissionTarget(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + var selector = + invocation.getArgument( + 0, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector.class); + var target = mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target.class); + when(target.targetNamespace()).thenReturn(selector.targetNamespace()); + when(target.canonicalTenantId()).thenReturn(selector.tenantId()); + when(target.tenantSlug()).thenReturn(selector.tenantSlug()); + when(target.worldSlug()).thenReturn(selector.worldSlug()); + when(target.realmId()).thenReturn(selector.realmId()); + when(target.realmSlug()).thenReturn(selector.realmSlug()); + when(target.playableStateNamespaceId()) + .thenReturn(selector.playableStateNamespaceId()); + when(target.playableStateScope()).thenReturn(selector.playableStateScope()); + when(target.canonicalGameInstanceId()).thenReturn(selector.gameInstanceId()); + when(target.catalogRevision()).thenReturn(selector.catalogRevision()); + when(target.pointerVersion()).thenReturn(selector.pointerVersion()); + when(target.characterCreationPolicy()).thenReturn("PRESEEDED_ONLY"); + when(target.ownerProofOutcome()) + .thenReturn( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome.COMMITTED); + UUID version = UUID.fromString("33333333-3333-4333-8333-333333333333"); + when(target.canonicalVersionId()).thenReturn(version); + when(target.activeWorldEpoch()).thenReturn(5L); + var strict = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + selector.readRequestId(), + selector.accountId(), + selector.targetNamespace(), + selector.tenantId(), + selector.worldSlug(), + selector.realmId(), + selector.realmSlug(), + selector.playableStateNamespaceId(), + selector.playableStateScope(), + selector.gameInstanceId(), + version, + selector.catalogRevision(), + selector.pointerVersion(), + 5L); + var resolved = + mock( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.ResolvedPublishedTarget + .class); + when(resolved.selector()).thenReturn(selector); + when(resolved.currentTarget()).thenReturn(target); + when(resolved.strictSelector()).thenReturn(strict); + var read = + mock( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class); + when(read.selector()).thenReturn(strict); + when(read.currentTarget()).thenReturn(target); + var source = mock(CanonicalGameplayRosterOwnerReadEvidence.class); + when(source.admissionPointerSnapshotDigest()).thenReturn("a".repeat(64)); + var policies = mock(PublishedRealmEntryPolicySetEvidence.class); + when(policies.policySetDigest()).thenReturn("sha256:" + "b".repeat(64)); + when(source.publishedPolicySetEvidence()).thenReturn(policies); + var ownerProof = + mock( + net.firedevops.firemud.common.world + .GameSessionCanonicalInitialAdmissionOwnerProof.class); + when(ownerProof.proofDigest()).thenReturn("sha256:" + "c".repeat(64)); + when(source.gameSessionOwnerProof()).thenReturn(ownerProof); + when(read.sourceEvidence()).thenReturn(source); + var world = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(world.canonicalBytes()) + .thenReturn( + "controlled-complete-world-source" + .getBytes(java.nio.charset.StandardCharsets.UTF_8)); + when(world.captureId()) + .thenReturn(UUID.fromString("44444444-4444-4444-8444-444444444444")); + when(world.rowVersion()).thenReturn(2L); + when(read.worldLifecycleEvidence()).thenReturn(world); + when(targets.readPublishedRealmAdmissionOwner(strict)) + .thenAnswer( + readCall -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isFalse(); + return read; + }); + return resolved; + }); + } + + private static final class Fixture { + private final AccountRepository accounts = mock(AccountRepository.class); + private final AccountGameplayAdmissionCallerVerifier callers = + mock(AccountGameplayAdmissionCallerVerifier.class); + private final AccountGameplayDelegationIssuanceRepository issuances = + mock(AccountGameplayDelegationIssuanceRepository.class); + private final AccountCanonicalRuntimeMembershipSnapshotRepository memberships = + mock(AccountCanonicalRuntimeMembershipSnapshotRepository.class); + private final AccountConnectScopeRepository scopes = mock(AccountConnectScopeRepository.class); + private final AccountHostingSubscriptionLifecycleRepository hosting = + mock(AccountHostingSubscriptionLifecycleRepository.class); + private final StripeHostingSubscriptionObserver observer = + mock(StripeHostingSubscriptionObserver.class); + private final AccountDemoTenantEntitlementRepository demos = + mock(AccountDemoTenantEntitlementRepository.class); + private final AccountTenantAuthorityEventRepository sources = + mock(AccountTenantAuthorityEventRepository.class); + private final CanonicalGameplayAdmissionDecisionReadClient targets = + mock(CanonicalGameplayAdmissionDecisionReadClient.class); + private final RecordingTransactions transactions = new RecordingTransactions(); + private final java.util.concurrent.atomic.AtomicReference time = + new java.util.concurrent.atomic.AtomicReference<>(NOW); + private final FreshTenantCreationEvidence source = source(); + private final TenantAuthorityEventV1Codec.Event tenantEvent = tenantEvent(source); + private final CanonicalJoinScopeV2 scope = + new CanonicalJoinScopeV2( + "private-bearer-" + UUID.randomUUID(), + ACCOUNT, + TENANT, + UUID.randomUUID(), + "tenant", + "world", + "production", + UUID.randomUUID(), + "SHARED", + UUID.randomUUID(), + 7, + 3, + NOW.minusSeconds(20).toString(), + NOW.plusSeconds(60).toString()); + private final AccountGameplayDelegationPendingIdentity identity = + new AccountGameplayDelegationPendingIdentity( + UUID.randomUUID(), + UUID.randomUUID(), + ACCOUNT, + PEER, + UUID.randomUUID(), + mock(AccountGameplayCredentialRequestBinding.class), + HASH, + UUID.randomUUID(), + NOW.minusSeconds(10).getEpochSecond(), + NOW.minusSeconds(10).getEpochSecond(), + NOW.plusSeconds(120).getEpochSecond()); + private final DemoTenantEntitlementSnapshot demo = + new DemoTenantEntitlementSnapshot( + TENANT, + source, + "NON_PAID_DEMO", + "ACTIVE", + null, + false, + true, + true, + true, + true, + new DemoTenantEntitlementRequest.Quotas(3, 2, 4096), + 1, + 2, + 2, + tenantEvent.tenantBillingStreamKey(), + 1, + tenantEvent.tenantBillingEventId(), + tenantEvent.tenantBillingEventDigest(), + tenantEvent.tenantBillingEventDigest(), + tenantEvent.outboxStreamKey(), + 1, + tenantEvent.eventId(), + tenantEvent.eventDigest()); + private final Request request = + new Request( + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector( + UUID.randomUUID(), + ACCOUNT, + "prod", + TENANT, + scope.tenantSlug(), + scope.worldSlug(), + scope.realmId(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion()), + scope.connectScopeId(), + PEER); + private final AccountPlayerAdmissionEntitlementOwner owner; + + private Fixture(boolean exists) throws Exception { + controlledTarget(targets); + var dsl = mock(DSLContext.class); + var connection = mock(Connection.class); + when(connection.getTransactionIsolation()).thenReturn(Connection.TRANSACTION_SERIALIZABLE); + doAnswer( + invocation -> { + invocation.getArgument(0, ConnectionRunnable.class).run(connection); + return null; + }) + .when(dsl) + .connection(any(ConnectionRunnable.class)); + var candidate = mock(CommittedCandidateVerificationData.class); + when(candidate.identity()).thenReturn(identity); + when(candidate.authoritySnapshot()) + .thenReturn(new AccountAuthoritySnapshot(ACCOUNT, 1, 1, 1, 1, 1, 1, Optional.empty())); + when(candidate.evidenceBundleReference()).thenReturn(mock(EvidenceBundleReference.class)); + when(candidate.signerCorrespondence()) + .thenReturn(mock(AuthenticatedSignerCorrespondence.class)); + when(candidate.tokenSha256()).thenReturn(HASH); + when(candidate.signerKid()).thenReturn("controlled-kid"); + when(candidate.signerGeneration()).thenReturn("1"); + when(candidate.canonicalRegistryRecordSha256()).thenReturn(HASH); + when(candidate.commitProofSha256()).thenReturn(HASH); + when(candidate.envelopeKeyId()).thenReturn("controlled-envelope-key"); + when(candidate.envelopeSha256()).thenReturn(HASH); + var caller = mock(VerifiedCaller.class); + when(caller.identity()).thenReturn(identity); + when(caller.currentCandidate()).thenReturn(candidate); + when(callers.verifyPresentedCompactToken("controlled-token")) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return caller; + }); + Account account = new Account(); + account.setId(10L); + account.setAccountUuid(ACCOUNT); + when(accounts.findByAccountUuidForUpdate(ACCOUNT)).thenReturn(Optional.of(account)); + when(issuances.readCurrentCommittedCandidateByJti(identity.tokenJti())) + .thenReturn(Optional.of(candidate)); + when(memberships.readCurrent(ACCOUNT, TENANT)).thenReturn(snapshot(exists)); + when(scopes.findCanonical(scope.connectScopeId())).thenReturn(Optional.of(scope)); + when(scopes.findCanonicalEvidenceByTokenHash( + AccountJoinDigest.tokenHash(scope.connectScopeId()))) + .thenReturn(Optional.of(scopeEvidence(ACCOUNT, scope.connectScopeExpiresAt()))); + when(demos.readCurrent(TENANT)).thenReturn(demo); + when(sources.readCurrentSourceSelection(TENANT)) + .thenReturn(new SourceSelection(SourceKind.NON_PAID_DEMO, tenantEvent)); + Clock clock = mock(Clock.class); + when(clock.instant()).thenAnswer(invocation -> time.get()); + owner = + new AccountPlayerAdmissionEntitlementOwner( + dsl, + accounts, + callers, + issuances, + memberships, + scopes, + hosting, + observer, + demos, + sources, + targets, + transactions, + clock, + "prod"); + } + + private CanonicalConnectScopeEvidence scopeEvidence(UUID account, String expiry) { + return new CanonicalConnectScopeEvidence( + AccountJoinDigest.tokenHash(scope.connectScopeId()), + 10, + "PUBLIC_PRODUCTION", + account, + TENANT, + scope.realmId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + expiry, + 2, + AccountJoinDigest.scopeV2(scope), + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + source.operationId(), + source.evidenceDigest())); + } + + private AccountHostingSubscriptionCurrentReceipt receipt(Status status) { + var current = mock(AccountSubscriptionCurrentRecord.class); + when(current.tenantId()).thenReturn(TENANT); + when(current.subscriptionId()).thenReturn(UUID.randomUUID()); + when(current.rowVersion()).thenReturn(2L); + when(current.planQuote()) + .thenReturn(new AccountHostingPlanQuote("standard", "price_Test", 1, 3, 2, 4096)); + return new AccountHostingSubscriptionCurrentReceipt( + current, + UUID.randomUUID(), + status, + status != Status.SUSPENDED && status != Status.CANCELED, + status != Status.SUSPENDED && status != Status.CANCELED && status != Status.GRACE, + status != Status.SUSPENDED && status != Status.CANCELED && status != Status.GRACE, + status != Status.SUSPENDED && status != Status.CANCELED && status != Status.GRACE, + 1, + 1, + tenantEvent.tenantBillingEventId(), + tenantEvent.tenantBillingEventDigest(), + tenantEvent, + "active", + NOW.minusSeconds(100), + NOW.plusSeconds(1000), + false, + null, + null, + NOW, + NOW.plusSeconds(60)); + } + + private Snapshot snapshot(boolean exists) { + var cutoff = new TenantBillingCutoff("2", "1", tenantEvent.outboxStreamKey(), "1"); + var tuple = + new AuthorityTuple( + "1", + "1", + Map.of(TENANT.toString(), "2"), + Map.of(TENANT.toString(), "1"), + List.of(), + Optional.empty(), + Optional.of(Map.of(TENANT.toString(), cutoff))); + List events = new ArrayList<>(); + if (exists) { + Map event = new LinkedHashMap<>(); + event.put("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION); + event.put("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE); + event.put("eventId", "membership-event-1"); + event.put("requestId", "membership-request-1"); + event.put("outboxStreamKey", memberStream()); + event.put("outboxSequence", "1"); + event.put("sourceScope", "membership/" + ACCOUNT + "/" + TENANT); + event.put("accountId", ACCOUNT.toString()); + event.put("tenantId", TENANT.toString()); + event.put("membershipExists", true); + event.put("membershipLifecycleState", "ACTIVE"); + event.put("membershipVersion", Map.of(TENANT.toString(), "1")); + event.put("membershipAuthorityGeneration", "1"); + event.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(TENANT.toString(), "2"), + "membershipAuthorityGeneration", + Map.of(TENANT.toString(), "1"), + "privateRealmGrantVersions", + List.of(), + "tenantBillingCutoff", + Map.of( + TENANT.toString(), + Map.of( + "tenantAuthorityGeneration", + "2", + "tenantBillingSequence", + "1", + "outboxStreamKey", + tenantEvent.outboxStreamKey(), + "outboxSequence", + "1")))); + event.put("issuanceFence", "1"); + event.put("roles", List.of("player")); + event.put("gameplayAdmissionAllowed", true); + event.put("callerBoundAuthorityInvalidated", false); + var sealed = MembershipAuthorityEventV1Codec.seal(event); + events.add( + new SourceEvidence( + memberStream(), + "1", + sealed.eventId(), + sealed.eventDigest(), + sealed.canonicalJson())); + } + events.add( + new SourceEvidence( + tenantEvent.outboxStreamKey(), + "1", + tenantEvent.eventId().toString(), + tenantEvent.eventDigest(), + new String(tenantEvent.payload(), java.nio.charset.StandardCharsets.UTF_8))); + return new Snapshot( + ISSUER, + ACCOUNT.toString(), + TENANT.toString(), + exists, + exists ? "ACTIVE" : "MISSING", + exists, + Map.of(TENANT.toString(), "1"), + "1", + exists ? List.of("player") : List.of(), + tuple, + "1", + List.of( + new Checkpoint(PREFIX + "account/" + ACCOUNT, "0"), + new Checkpoint(PREFIX + "issuer/" + ISSUER, "0"), + new Checkpoint(memberStream(), exists ? "1" : "0"), + new Checkpoint(tenantEvent.outboxStreamKey(), "1")), + events); + } + } + + private static String memberStream() { + return PREFIX + "membership/" + ACCOUNT + "/" + TENANT; + } + + private static FreshTenantCreationEvidence source() { + UUID requestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String requestDigest = + GameTenantCreationDigest.requestDigest("prod", requestId, "world", "World", null); + return new FreshTenantCreationEvidence( + 1, + "prod", + requestId, + operationId, + requestDigest, + TENANT, + 17, + "world", + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "prod", requestId, operationId, requestDigest, TENANT, 17, "world", "NEW_GAME_ROW")); + } + + private static TenantAuthorityEventV1Codec.Event tenantEvent(FreshTenantCreationEvidence source) { + UUID requestId = UUID.randomUUID(); + var request = + new TenantAuthorityEventV1Codec.AuthorityRequest( + requestId, + "sha256:" + HASH, + TENANT, + source.creationRequestId(), + source.requestDigest()); + var receipt = + new TenantAuthorityEventV1Codec.BillingReceipt( + TENANT, + requestId, + "sha256:" + HASH, + TenantAuthorityEventV1Codec.tenantBillingStreamKey(TENANT), + 1, + TenantAuthorityEventV1Codec.tenantBillingEventId(requestId), + "sha256:" + HASH); + return TenantAuthorityEventV1Codec.seal(request, source, 2, 2, 1, receipt); + } + + private static final class RecordingTransactions implements PlatformTransactionManager { + private final List events = new ArrayList<>(); + private boolean failCommit; + private Runnable afterSecondCommit = () -> {}; + + @Override + public TransactionStatus getTransaction( + @org.jspecify.annotations.Nullable TransactionDefinition definition) { + if (definition != null) { + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_SERIALIZABLE); + assertThat(definition.isReadOnly()).isFalse(); + } + events.add("begin"); + TransactionSynchronizationManager.setActualTransactionActive(true); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + events.add("commit"); + TransactionSynchronizationManager.setActualTransactionActive(false); + if (events.size() == 4) afterSecondCommit.run(); + if (failCommit && events.size() == 4) + throw new IllegalStateException("controlled commit failure"); + } + + @Override + public void rollback(TransactionStatus status) { + events.add("rollback"); + TransactionSynchronizationManager.setActualTransactionActive(false); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java index f66f27186a..fc6bdb624c 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java @@ -89,6 +89,23 @@ void returnsSortedPublicWorldsAfterCompleteStableReorderedSourceAndFinalCallerCh verify(f.sessions, times(2)).isAccountSessionActive(ACCOUNT_ID, TOKEN); } + @Test + void mixedPublicCreationPoliciesBothParticipateInCompleteWorldDiscovery() { + Fixture f = new Fixture(); + var seeded = target(TENANT_A, "tenant-a", "seeded", "Seeded", 1); + var created = target(TENANT_B, "tenant-b", "created", "Created", 1, "PLAYER_CREATED"); + f.stubTargetReads(List.of(seeded, created), List.of(created, seeded)); + when(f.entitlements.evaluate(TENANT_A)) + .thenReturn(evaluation(TENANT_A, true, NOW.plusSeconds(30))); + when(f.entitlements.evaluate(TENANT_B)) + .thenReturn(evaluation(TENANT_B, true, NOW.plusSeconds(30))); + assertThat(f.owner.listWorlds(TOKEN)) + .containsExactly( + new BootstrapWorldDto("created", "Created"), new BootstrapWorldDto("seeded", "Seeded")); + verify(f.entitlements, times(1)).evaluate(TENANT_A); + verify(f.entitlements, times(1)).evaluate(TENANT_B); + } + @Test void denialFiltersGameplayUnavailableTenantButDoesNotRequireJoinEligibility() { Fixture f = new Fixture(); @@ -386,6 +403,16 @@ private static Evaluation evaluation(UUID tenantId, boolean available, Instant v private static Target target( UUID tenantId, String tenantSlug, String worldSlug, String displayName, long pointerVersion) { + return target(tenantId, tenantSlug, worldSlug, displayName, pointerVersion, "PRESEEDED_ONLY"); + } + + private static Target target( + UUID tenantId, + String tenantSlug, + String worldSlug, + String displayName, + long pointerVersion, + String creationPolicy) { String suffix = tenantId.toString(); return new Target( "prod", @@ -425,7 +452,7 @@ private static Target target( OwnerProofOutcome.COMMITTED, false, NOW, - "PRESEEDED_ONLY"); + creationPolicy); } private static Account account(long id) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java new file mode 100644 index 0000000000..ce61e144dd --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java @@ -0,0 +1,47 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementRequest; +import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementResponse; +import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +/** Direct method calls cannot install the receiver's TLS-derived private peer assertion. */ +class AccountPlayerAdmissionEntitlementGrpcServiceTest { + @Test + @SuppressWarnings("unchecked") + void authenticationPrecedesEvenNullMalformedAndOversizedCredentialParsing() { + var owner = mock(AccountPlayerAdmissionEntitlementOwner.class); + var service = new AccountPlayerAdmissionEntitlementGrpcService(owner, "prod"); + for (var request : + new ReadPlayerAdmissionEntitlementRequest[] { + null, + ReadPlayerAdmissionEntitlementRequest.getDefaultInstance(), + ReadPlayerAdmissionEntitlementRequest.newBuilder() + .addInitialLoginJwt("private-token".repeat(4000)) + .build() + }) { + StreamObserver observer = mock(StreamObserver.class); + + service.readPlayerAdmissionEntitlement(request, observer); + + var failure = ArgumentCaptor.forClass(Throwable.class); + verify(observer).onError(failure.capture()); + assertThat(Status.fromThrowable(failure.getValue()).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(failure.getValue().getMessage()).doesNotContain("private-token"); + verify(observer, never()).onNext(any()); + verify(observer, never()).onCompleted(); + } + verifyNoInteractions(owner); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 691b47977e..ec8ae17445 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.verifyNoInteractions; @@ -18,20 +19,29 @@ import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.firedevops.firemud.account.AuthenticationErrorCodes; +import net.firedevops.firemud.accountservice.client.EntityManagementClient; +import net.firedevops.firemud.accountservice.client.GameSessionClient; import net.firedevops.firemud.accountservice.config.AccountTokenProperties; import net.firedevops.firemud.accountservice.config.MailProperties; import net.firedevops.firemud.accountservice.dto.AccountDto; import net.firedevops.firemud.accountservice.dto.AuthenticationResult; import net.firedevops.firemud.accountservice.dto.ConnectTokenRequest; +import net.firedevops.firemud.accountservice.dto.ConnectTokenResult; import net.firedevops.firemud.accountservice.dto.CreateAccountRequest; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinScope; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; import net.firedevops.firemud.accountservice.dto.PasswordResetRequest; import net.firedevops.firemud.accountservice.dto.PlayerBootstrapResult; import net.firedevops.firemud.accountservice.dto.RealmAccessGrantRequest; import net.firedevops.firemud.accountservice.dto.UpdateAccountLoginAuthModesRequest; +import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; @@ -41,13 +51,14 @@ import net.firedevops.firemud.accountservice.entity.EmailVerificationToken; import net.firedevops.firemud.accountservice.entity.Profile; import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; -import net.firedevops.firemud.accountservice.entity.RetainedSubscriptionEvidence; +import net.firedevops.firemud.accountservice.entity.Subscription; import net.firedevops.firemud.accountservice.mapper.AccountMapper; import net.firedevops.firemud.accountservice.mapper.ProfileMapper; 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.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; @@ -60,7 +71,7 @@ import net.firedevops.firemud.accountservice.repository.ExternalAccountRepository; import net.firedevops.firemud.accountservice.repository.PaymentTransactionRepository; import net.firedevops.firemud.accountservice.repository.ProfileRepository; -import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.SubscriptionRepository; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; import net.firedevops.firemud.accountservice.service.EmailService; import net.firedevops.firemud.accountservice.service.NotificationService; @@ -71,22 +82,32 @@ import net.firedevops.firemud.common.security.JwtAuthProperties; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.common.security.ReloadableJwtUtil; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; import org.mapstruct.factory.Mappers; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.slf4j.LoggerFactory; +import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.SimpleTransactionStatus; class AccountServiceImplTest { private static final String JWT_SECRET = "mysecretkey123456789012345678901"; + private static final String REALM_ID = "4c4b57d8-e3a2-48fe-9977-e7df0fdce901"; + private static final String PLAYABLE_STATE_NAMESPACE_ID = "c6ed6a44-c7e7-4f18-81fc-078a74e67c07"; + private static final String PLAYABLE_STATE_NAMESPACE_ID_TENANT_8 = + "a741a4b8-a2cb-405e-a330-8fbf3dfb841f"; @Mock private AccountRepository accountRepository; @Mock private AccountAuthorityGenerationRepository accountAuthorityGenerationRepository; @Mock private AccountAuthoritySourceEvidenceRepository accountAuthoritySourceEvidenceRepository; @@ -100,6 +121,7 @@ class AccountServiceImplTest { accountPasswordResetDraftSourceChangeRepository; @Mock private AccountAuditOutboxRepository accountAuditOutboxRepository; + @Mock private AccountConnectScopeRepository accountConnectScopeRepository; @Mock private AccountJoinOperationRepository accountJoinOperationRepository; @Mock private AccountEmailLoginChallengeRepository accountEmailLoginChallengeRepository; @Mock private AccountRealmAccessGrantRepository accountRealmAccessGrantRepository; @@ -111,9 +133,11 @@ class AccountServiceImplTest { @Mock private MailProperties mailProperties; private final AccountTokenProperties tokenProperties = new AccountTokenProperties(); private final JwtAuthProperties jwtAuthProperties = new JwtAuthProperties(); + @Mock private GameSessionClient gameSessionClient; + @Mock private EntityManagementClient entityManagementClient; @Mock private SessionService sessionService; @Mock private PaymentTransactionRepository paymentTransactionRepository; - @Mock private RetainedSubscriptionEvidenceRepository retainedSubscriptionEvidenceRepository; + @Mock private SubscriptionRepository subscriptionRepository; @Mock private ExternalAccountRepository externalAccountRepository; @Mock private PlatformTransactionManager transactionManager; @@ -132,6 +156,18 @@ void setup() { when(transactionManager.getTransaction( org.mockito.ArgumentMatchers.any(TransactionDefinition.class))) .thenAnswer(invocation -> new SimpleTransactionStatus()); + Subscription explicitActiveEntitlement = new Subscription(); + explicitActiveEntitlement.setId(1L); + explicitActiveEntitlement.setTenantId(7L); + explicitActiveEntitlement.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)) + .thenReturn(java.util.List.of(explicitActiveEntitlement)); + Subscription explicitActiveEntitlementForSecondTenant = new Subscription(); + explicitActiveEntitlementForSecondTenant.setId(2L); + explicitActiveEntitlementForSecondTenant.setTenantId(8L); + explicitActiveEntitlementForSecondTenant.setStatus("active"); + when(subscriptionRepository.findByTenantId(8L)) + .thenReturn(java.util.List.of(explicitActiveEntitlementForSecondTenant)); AccountMapper mapper = Mappers.getMapper(AccountMapper.class); jwtUtil = org.mockito.Mockito.spy(new ReloadableJwtUtil(JWT_SECRET, 3600000L)); jwtAuthProperties.setJwtSecret(JWT_SECRET); @@ -139,6 +175,51 @@ void setup() { tokenProperties.setConnectScopeExpirationMs(120000L); tokenProperties.setConnectTokenExpirationMs(30000L); tokenProperties.setSessionExpirationMs(3600000L); + when(gameSessionClient.listGameplayWorlds()) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() + .setWorldSlug("demo") + .setDisplayName("Demo World") + .build())); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("production") + .setDisplayName("Live Realm") + .setTenantId("7") + .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) + .thenReturn( + net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() + .setWorldSlug("demo") + .setWorldDisplayName("Demo World") + .setRealmSlug("production") + .setRealmDisplayName("Live Realm") + .setTenantId("7") + .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build()); when(mailProperties.getResetUrl()).thenReturn("http://reset/%s"); when(mailProperties.getVerificationUrl()).thenReturn("http://verify/%s"); service = @@ -152,6 +233,7 @@ void setup() { accountSecurityStateOperationRepository, accountPasswordResetDraftSourceChangeRepository, accountAuditOutboxRepository, + accountConnectScopeRepository, accountJoinOperationRepository, accountEmailLoginChallengeRepository, accountRealmAccessGrantRepository, @@ -160,7 +242,7 @@ void setup() { profileRepository, profileMapper, paymentTransactionRepository, - retainedSubscriptionEvidenceRepository, + subscriptionRepository, externalAccountRepository, passwordResetTokenRepository, emailVerificationTokenRepository, @@ -169,6 +251,8 @@ void setup() { mailProperties, tokenProperties, jwtAuthProperties, + gameSessionClient, + entityManagementClient, jwtUtil, sessionService, transactionManager); @@ -181,109 +265,6 @@ private enum OrdinaryIssuance { PLAYER_BOOTSTRAP } - private enum PublicGameplayOperation { - WORLDS, - REALMS, - CHARACTERS, - BROWSER_JOIN, - DIRECT_SCOPE, - DIRECT_JOIN, - CONNECT_TOKEN - } - - /** The complete canonical positive fixtures remain in the public-facade successor. */ - @ParameterizedTest - @EnumSource(PublicGameplayOperation.class) - void publicGameplayRemainsUnavailableBeforeReadingAnyCallerOrAuthority( - PublicGameplayOperation operation) { - AuthenticationException unavailable = - assertThrows( - AuthenticationException.class, - () -> invokePublicGameplayOperation(operation, null, null)); - - assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); - verifyPublicGameplayHasNoIo(); - } - - @ParameterizedTest - @EnumSource( - value = PublicGameplayOperation.class, - names = "DIRECT_SCOPE", - mode = EnumSource.Mode.EXCLUDE) - void retainedNumericSignedCarriersCannotReenablePublicGameplay( - PublicGameplayOperation operation) { - String bootstrap = - jwtUtil.generateToken("11", 300000L, Map.of("aud", "player-bootstrap", "accountId", "11")); - String scope = - jwtUtil.generateToken( - "11", - 120000L, - Map.of( - "aud", - "bootstrap-connect-scope", - "accountId", - "11", - "tenantId", - "7", - "gameInstanceId", - "44")); - org.mockito.Mockito.clearInvocations(jwtUtil); - - AuthenticationException unavailable = - assertThrows( - AuthenticationException.class, - () -> invokePublicGameplayOperation(operation, bootstrap, scope)); - - assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); - verifyPublicGameplayHasNoIo(); - } - - private void invokePublicGameplayOperation( - PublicGameplayOperation operation, String bootstrap, String scope) { - JoinPublicProductionRequest join = - scope == null ? null : new JoinPublicProductionRequest(scope, UUID.randomUUID().toString()); - switch (operation) { - case WORLDS -> service.listBootstrapWorlds(bootstrap); - case REALMS -> service.listBootstrapRealms(bootstrap, "demo"); - case CHARACTERS -> service.listBootstrapCharacters(bootstrap, "demo", "production", scope); - case BROWSER_JOIN -> service.joinPublicProduction(bootstrap, join); - case DIRECT_SCOPE -> service.issueDirectTextConnectScope(null, null); - case DIRECT_JOIN -> service.joinPublicProductionFromGameSession(null, join); - case CONNECT_TOKEN -> - service.issueConnectToken( - bootstrap, - scope == null ? null : new ConnectTokenRequest(scope, UUID.randomUUID().toString())); - } - } - - private void verifyPublicGameplayHasNoIo() { - verifyNoInteractions( - accountRepository, - accountAuthorityGenerationRepository, - accountAuthoritySourceEvidenceRepository, - accountAuthorityOutboxRepository, - accountPasswordResetOperationRepository, - accountLogoutAllOperationRepository, - accountSecurityStateOperationRepository, - accountPasswordResetDraftSourceChangeRepository, - accountAuditOutboxRepository, - accountJoinOperationRepository, - accountEmailLoginChallengeRepository, - accountRealmAccessGrantRepository, - accountTenantMembershipRepository, - retainedSubscriptionEvidenceRepository, - paymentTransactionRepository, - profileRepository, - externalAccountRepository, - passwordResetTokenRepository, - emailVerificationTokenRepository, - notificationService, - emailService, - sessionService, - transactionManager, - jwtUtil); - } - private enum IdentityFailure { MISSING_UUID, NIL_UUID, @@ -705,657 +686,5216 @@ void createAccountMapsSpringDataIntegrityConflict() { } @Test - void emailLoginOtpRequestIsNeutralForUnknownEmail() { - when(accountRepository.findByEmail("unknown@example.com")).thenReturn(Optional.empty()); - - service.requestEmailLoginOtp("unknown@example.com"); - - verifyNoInteractions(emailService, accountEmailLoginChallengeRepository); - } - - @ParameterizedTest - @EnumSource( - value = AccountLifecycleState.class, - names = {"SECURITY_LOCKED", "DEACTIVATED_PENDING_DELETE", "DELETED"}) - void emailLoginOtpRequestIsNeutralForIneligibleLifecycleState( - AccountLifecycleState lifecycleState) { - Account account = new Account(); - account.setId(9L); - account.setEmail("verified@example.com"); - account.setEmailVerified(true); - account.setLifecycleState(lifecycleState); - when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); - - service.requestEmailLoginOtp("verified@example.com"); - - verifyNoInteractions( - accountTenantMembershipRepository, accountEmailLoginChallengeRepository, emailService); - } - - @Test - void emailLoginOtpRequestPersistsOnlyHashedChallengeAndSendsSixDigitCode() { + void joinPublicProductionRetainsReceiptAfterProjectionFailureAndReplaysWithoutDuplicateEffects() { Account account = new Account(); - account.setId(9L); - account.setEmail("verified@example.com"); - account.setEmailVerified(true); - when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); - when(accountEmailLoginChallengeRepository.findByAccountId(9L)).thenReturn(Optional.empty()); - when(accountEmailLoginChallengeRepository.save(org.mockito.ArgumentMatchers.any())) + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + AtomicReference joinedMembership = new AtomicReference<>(); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenAnswer(invocation -> Optional.ofNullable(joinedMembership.get())); + when(accountTenantMembershipRepository.save(org.mockito.ArgumentMatchers.any())) .thenAnswer( invocation -> { - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = - invocation.getArgument(0); - challenge.setId(3L); - return challenge; + AccountTenantMembership membership = invocation.getArgument(0); + membership.setId(701L); + joinedMembership.set(membership); + return membership; }); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + String requestId = "j".repeat(128); + assertEquals(128, requestId.length()); + JoinPublicProductionRequest request = + new JoinPublicProductionRequest(connectScopeId, requestId); - service.requestEmailLoginOtp("verified@example.com"); + org.mockito.Mockito.doAnswer( + invocation -> { + when(accountRepository.findByAccountUuid(account.getAccountUuid())) + .thenReturn(Optional.empty()); + return null; + }) + .when(transactionManager) + .commit(org.mockito.ArgumentMatchers.any()); + AuthenticationException firstProjectionFailure = + assertThrows( + AuthenticationException.class, + () -> service.joinPublicProduction(bootstrap.bootstrapToken(), request)); + assertEquals("AUTH_UNAVAILABLE", firstProjectionFailure.getCode()); + assertEquals("COMMITTED", retainedOperation.get().status()); + org.mockito.Mockito.verify(transactionManager, org.mockito.Mockito.never()) + .rollback(org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.doNothing() + .when(transactionManager) + .commit(org.mockito.ArgumentMatchers.any()); + when(accountRepository.findByAccountUuid(account.getAccountUuid())) + .thenReturn(Optional.of(account)); + JoinPublicProductionResult recovered = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + assertTrue(recovered.replayed()); + JoinPublicProductionResult first = recovered; + assertEquals(account.getAccountUuid().toString(), recovered.accountId()); + var committedOperation = retainedOperation.get(); + org.mockito.Mockito.clearInvocations(transactionManager, gameSessionClient); + JoinPublicProductionResult retried = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + var normalReplayOrder = org.mockito.Mockito.inOrder(transactionManager, gameSessionClient); + normalReplayOrder + .verify(transactionManager) + .getTransaction(org.mockito.ArgumentMatchers.any(TransactionDefinition.class)); + normalReplayOrder.verify(transactionManager).commit(org.mockito.ArgumentMatchers.any()); + normalReplayOrder.verify(gameSessionClient).listGameplayRealms("demo"); - org.mockito.ArgumentCaptor< - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge> - challengeCaptor = - org.mockito.ArgumentCaptor.forClass( - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge.class); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository) - .save(challengeCaptor.capture()); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(9L); - assertEquals(9L, challengeCaptor.getValue().getAccountId()); - assertFalse(challengeCaptor.getValue().getCodeHash().matches("\\d{6}")); - org.mockito.Mockito.verify(emailService) - .sendEmail( - org.mockito.ArgumentMatchers.eq("verified@example.com"), + org.mockito.Mockito.doThrow( + new DataAccessResourceFailureException("terminal operation lock read failed")) + .when(accountJoinOperationRepository) + .findForUpdate(requestId); + org.mockito.Mockito.clearInvocations(transactionManager, gameSessionClient); + JoinPublicProductionResult readbackReplay = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + var readbackReplayOrder = org.mockito.Mockito.inOrder(transactionManager, gameSessionClient); + readbackReplayOrder + .verify(transactionManager) + .getTransaction(org.mockito.ArgumentMatchers.any(TransactionDefinition.class)); + readbackReplayOrder.verify(transactionManager).rollback(org.mockito.ArgumentMatchers.any()); + readbackReplayOrder.verify(gameSessionClient).listGameplayRealms("demo"); + + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.times(1)) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(4)) + .findByTenantIdForUpdate(7L); + org.mockito.Mockito.clearInvocations( + sessionService, + accountTenantMembershipRepository, + gameSessionClient, + subscriptionRepository); + AuthenticationException connectTokenUnavailable = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), + new ConnectTokenRequest(connectScopeId, "first-play-after-join"))); + + assertTrue(first.success()); + assertEquals(account.getAccountUuid().toString(), first.accountId()); + assertEquals("JOINED", first.outcomeCode()); + assertEquals(701L, first.membershipId()); + assertEquals(1L, first.membershipVersion()); + assertTrue(retried.success()); + assertTrue(retried.replayed()); + assertTrue(readbackReplay.success()); + assertTrue(readbackReplay.replayed()); + assertEquals(committedOperation, retainedOperation.get()); + assertEquals("AUTH_UNAVAILABLE", connectTokenUnavailable.getCode()); + assertNoLegacyConnectTokenEffects(); + assertEquals(REALM_ID, retainedScope.get().realmId().toString()); + assertEquals( + first, + new JoinPublicProductionResult( + retried.success(), + retried.outcomeCode(), + retried.accountId(), + retried.tenantId(), + retried.membershipId(), + retried.membershipVersion(), + retried.membershipAuthorityGeneration(), + true)); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.times(1)) + .bindPolicyEvidence( + org.mockito.ArgumentMatchers.eq(requestId), org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.matches(".*\\b\\d{6}\\b.*")); - verifyNoInteractions(accountTenantMembershipRepository); - } + org.mockito.ArgumentMatchers.eq(1L), + org.mockito.ArgumentMatchers.eq(true)); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.times(1)) + .finish( + org.mockito.ArgumentMatchers.eq(requestId), + org.mockito.ArgumentMatchers.eq("COMMITTED"), + org.mockito.ArgumentMatchers.eq("JOINED"), + org.mockito.ArgumentMatchers.eq(701L), + org.mockito.ArgumentMatchers.eq(1L), + org.mockito.ArgumentMatchers.eq(1L)); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .recordAttemptFailure( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.verify(accountAuditOutboxRepository, org.mockito.Mockito.times(1)) + .append( + org.mockito.ArgumentMatchers.any(java.util.UUID.class), + org.mockito.ArgumentMatchers.eq("tenant"), + org.mockito.ArgumentMatchers.eq(7L), + org.mockito.ArgumentMatchers.eq("ACCOUNT_JOINED_PUBLIC_PRODUCTION"), + org.mockito.ArgumentMatchers.contains(requestId)); + assertEquals("COMMITTED", retainedOperation.get().status()); - @Test - void emailLoginOtpVerificationAuthenticatesAndConsumesMatchingChallenge() { - Account account = new Account(); - account.setId(9L); - setPersistedAuthenticationIdentity(account); - account.setEmail("verified@example.com"); - account.setEmailVerified(true); - account.setRole("player"); - when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); - when(accountEmailLoginChallengeRepository.findByAccountId(9L)).thenReturn(Optional.empty()); - when(accountEmailLoginChallengeRepository.save(org.mockito.ArgumentMatchers.any())) - .thenAnswer(invocation -> invocation.getArgument(0)); + AuthenticationException changedDigest = + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest("different-scope", requestId))); + assertEquals("IDEMPOTENCY_CONFLICT", changedDigest.getCode()); - service.requestEmailLoginOtp("verified@example.com"); + when(accountRepository.findByAccountUuid(account.getAccountUuid())) + .thenReturn(Optional.of(account), Optional.empty()); + AuthenticationException projectionFailure = + assertThrows( + AuthenticationException.class, + () -> service.joinPublicProduction(bootstrap.bootstrapToken(), request)); + assertEquals("AUTH_UNAVAILABLE", projectionFailure.getCode()); + assertEquals(committedOperation, retainedOperation.get()); + when(accountRepository.findByAccountUuid(account.getAccountUuid())) + .thenReturn(Optional.of(account)); + assertEquals( + account.getAccountUuid().toString(), + service.joinPublicProduction(bootstrap.bootstrapToken(), request).accountId()); + } - org.mockito.ArgumentCaptor< - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge> - challengeCaptor = - org.mockito.ArgumentCaptor.forClass( - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge.class); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository) - .save(challengeCaptor.capture()); - org.mockito.ArgumentCaptor emailBodyCaptor = - org.mockito.ArgumentCaptor.forClass(String.class); - org.mockito.Mockito.verify(emailService) - .sendEmail( - org.mockito.ArgumentMatchers.eq("verified@example.com"), - org.mockito.ArgumentMatchers.anyString(), - emailBodyCaptor.capture()); - Matcher codeMatcher = Pattern.compile("\\b(\\d{6})\\b").matcher(emailBodyCaptor.getValue()); - assertTrue(codeMatcher.find()); - when(accountEmailLoginChallengeRepository.findByAccountId(9L)) - .thenReturn(Optional.of(challengeCaptor.getValue())); + @Test + void joinPublicProductionRejectsRequestIdLongerThan128BeforeIntentLookupOrMutation() { + Account account = directTextAccount(); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + String requestId = "j".repeat(129); + DirectTextCallerContext baseCaller = directTextCaller(); + DirectTextCallerContext caller = + new DirectTextCallerContext( + baseCaller.accountId(), + baseCaller.tenantId(), + baseCaller.realmId(), + baseCaller.playableStateNamespaceId(), + baseCaller.playableStateScope(), + baseCaller.gameInstanceId(), + baseCaller.sessionId(), + requestId); - AuthenticationResult result = - service.verifyEmailLoginOtp("verified@example.com", codeMatcher.group(1)); + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProductionFromGameSession( + caller, new JoinPublicProductionRequest("retained-scope", requestId))); - assertEquals(account.getAccountUuid().toString(), result.accountId()); - assertNotNull(result.authToken()); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository) - .delete(challengeCaptor.getValue()); - org.mockito.Mockito.verify(sessionService) - .storeAccountSession( - org.mockito.ArgumentMatchers.eq(9L), - org.mockito.ArgumentMatchers.eq(result.authToken()), - org.mockito.ArgumentMatchers.eq(jwtAuthProperties.getJwtExpirationMs())); - verifyNoInteractions(accountTenantMembershipRepository); + assertEquals("INVALID_ARGUMENT", exception.getCode()); + verifyNoInteractions( + accountJoinOperationRepository, + accountTenantMembershipRepository, + accountAuditOutboxRepository); } - @Test - void authenticateUsesMatchingEmailLoginOtpBeforePasswordFallback() { + @ParameterizedTest + @CsvSource({ + "SECURITY_LOCKED, AUTH_ACCOUNT_LOCKED", + "DEACTIVATED_PENDING_DELETE, AUTH_INVALID_CREDENTIALS" + }) + void joinPublicProductionRejectsStillActiveBootstrapForIneligibleLifecycleState( + AccountLifecycleState lifecycleState, String expectedCode) { Account account = new Account(); - account.setId(9L); + account.setId(11L); setPersistedAuthenticationIdentity(account); - account.setEmail("demo@example.com"); + account.setUsername("demo"); account.setPasswordHash(hash("password")); - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = - new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); - challenge.setId(3L); - challenge.setAccountId(9L); - challenge.setCodeHash(hash("123456")); - challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); - when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); - when(accountEmailLoginChallengeRepository.findByAccountId(9L)) - .thenReturn(Optional.of(challenge)); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); - AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "123456"); + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + account.setLifecycleState(lifecycleState); - assertEquals(account.getAccountUuid().toString(), result.accountId()); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).delete(challenge); - org.mockito.Mockito.verify(sessionService) - .storeAccountSession(9L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); - verifyNoInteractions(accountTenantMembershipRepository); + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest(connectScopeId, "join-ineligible-1"))); + + assertEquals(expectedCode, exception.getCode()); + verifyNoInteractions( + accountJoinOperationRepository, + accountTenantMembershipRepository, + accountAuditOutboxRepository); } @Test - void authenticateFallsBackToPasswordWithoutBurningUnmatchedEmailLoginOtp() { + void closedPublicJoinRetainsFailureAndCannotCreateMembershipOrAudit() { Account account = new Account(); - account.setId(9L); + account.setId(11L); setPersistedAuthenticationIdentity(account); - account.setEmail("demo@example.com"); + account.setUsername("demo"); account.setPasswordHash(hash("password")); - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = - new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); - challenge.setId(3L); - challenge.setAccountId(9L); - challenge.setCodeHash(hash("123456")); - challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); - when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); - when(accountEmailLoginChallengeRepository.findByAccountId(9L)) - .thenReturn(Optional.of(challenge)); - - AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "password"); - - assertEquals(account.getAccountUuid().toString(), result.accountId()); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) - .delete(challenge); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) - .save(challenge); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + Subscription grace = new Subscription(); + grace.setId(22L); + grace.setTenantId(7L); + grace.setStatus("grace"); + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of(grace)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(grace)); + JoinPublicProductionRequest request = + new JoinPublicProductionRequest(connectScopeId, "join-closed-1"); + + JoinPublicProductionResult denied = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + JoinPublicProductionResult retry = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + assertFalse(denied.success()); + assertEquals("PUBLIC_PRODUCTION_ADMISSION_DENIED", denied.outcomeCode()); + assertFalse(retry.success()); + assertTrue(retry.replayed()); + assertEquals(denied.outcomeCode(), retry.outcomeCode()); + assertEquals("FAILED", retainedOperation.get().status()); + var storedDeniedOperation = retainedOperation.get(); + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of()); + JoinPublicProductionResult unavailableAuthorityReplay = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + assertFalse(unavailableAuthorityReplay.success()); + assertFalse(unavailableAuthorityReplay.replayed()); + assertEquals("ENTITLEMENT_UNAVAILABLE", unavailableAuthorityReplay.outcomeCode()); + assertEquals(storedDeniedOperation, retainedOperation.get()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) + .findByTenantIdForUpdate(7L); } @Test - void authenticateCountsFailedMixedModeSecretAgainstActiveEmailLoginOtp() { + void committedJoinRetryRejectsChangedPolicyWithoutMutatingStoredOutcomeOrMembership() { Account account = new Account(); - account.setId(9L); + account.setId(11L); setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + AtomicReference joinedMembership = new AtomicReference<>(); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenAnswer(invocation -> Optional.ofNullable(joinedMembership.get())); + when(accountTenantMembershipRepository.save(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + AccountTenantMembership membership = invocation.getArgument(0); + membership.setId(701L); + joinedMembership.set(membership); + return membership; + }); + Subscription originalPolicy = new Subscription(); + originalPolicy.setId(22L); + originalPolicy.setTenantId(7L); + originalPolicy.setStatus("active"); + originalPolicy.setEntitlementVersion(5L); + Subscription changedPolicy = new Subscription(); + changedPolicy.setId(22L); + changedPolicy.setTenantId(7L); + changedPolicy.setStatus("active"); + changedPolicy.setEntitlementVersion(6L); + when(subscriptionRepository.findByTenantIdForUpdate(7L)) + .thenReturn(java.util.List.of(originalPolicy), java.util.List.of(changedPolicy)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(originalPolicy)); + JoinPublicProductionRequest request = + new JoinPublicProductionRequest(connectScopeId, "join-terminal-policy-change-1"); + + JoinPublicProductionResult joined = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + var committedOperation = retainedOperation.get(); + AccountTenantMembership membership = joinedMembership.get(); + JoinPublicProductionResult retry = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + assertTrue(joined.success()); + assertFalse(retry.success()); + assertFalse(retry.replayed()); + assertEquals("IDEMPOTENCY_CONFLICT", retry.outcomeCode()); + assertEquals(committedOperation, retainedOperation.get()); + assertEquals("COMMITTED", retainedOperation.get().status()); + assertEquals("JOINED", retainedOperation.get().outcome()); + assertEquals(5L, retainedOperation.get().entitlementVersion()); + assertEquals(membership, joinedMembership.get()); + assertEquals("ACTIVE", membership.getLifecycleState()); + assertEquals(1L, membership.getMembershipVersion()); + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of()); + JoinPublicProductionResult unavailableAuthorityRetry = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + assertFalse(unavailableAuthorityRetry.success()); + assertFalse(unavailableAuthorityRetry.replayed()); + assertEquals("ENTITLEMENT_UNAVAILABLE", unavailableAuthorityRetry.outcomeCode()); + assertEquals(committedOperation, retainedOperation.get()); + assertEquals(membership, joinedMembership.get()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.times(1)) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verify(accountAuditOutboxRepository, org.mockito.Mockito.times(1)) + .append( + org.mockito.ArgumentMatchers.any(java.util.UUID.class), + org.mockito.ArgumentMatchers.eq("tenant"), + org.mockito.ArgumentMatchers.eq(7L), + org.mockito.ArgumentMatchers.eq("ACCOUNT_JOINED_PUBLIC_PRODUCTION"), + org.mockito.ArgumentMatchers.contains("join-terminal-policy-change-1")); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(3)) + .findByTenantIdForUpdate(7L); + } + + @ParameterizedTest + @MethodSource("unavailableJoinReads") + void unavailableEntitlementRetainsJoinReceiptAndRecoversOnce( + boolean lockedRead, UnavailableEntitlement failure) { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + Subscription recovered = new Subscription(); + recovered.setId(22L); + recovered.setTenantId(7L); + recovered.setStatus("active"); + recovered.setEntitlementVersion(1L); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.empty()); + when(accountTenantMembershipRepository.save(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + AccountTenantMembership membership = invocation.getArgument(0); + membership.setId(701L); + return membership; + }); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + AtomicBoolean authorityRecovered = new AtomicBoolean(); + when(subscriptionRepository.findByTenantId(7L)) + .thenAnswer( + invocation -> + lockedRead || authorityRecovered.get() + ? java.util.List.of(recovered) + : failure.rows()); + when(subscriptionRepository.findByTenantIdForUpdate(7L)) + .thenAnswer( + invocation -> authorityRecovered.get() ? java.util.List.of(recovered) : failure.rows()); + org.mockito.Mockito.clearInvocations(accountConnectScopeRepository); + JoinPublicProductionRequest request = + new JoinPublicProductionRequest(connectScopeId, "join-unavailable-1"); + + JoinPublicProductionResult first = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + assertFalse(first.success()); + assertEquals("ENTITLEMENT_UNAVAILABLE", first.outcomeCode()); + assertEquals("PENDING", retainedOperation.get().status()); + assertEquals(null, retainedOperation.get().outcome()); + assertEquals("ENTITLEMENT_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); + assertEquals("UNAVAILABLE", retainedOperation.get().lastAttemptAuthorityAvailability()); + assertNotNull(retainedOperation.get().intentDigest()); + String intentDigest = retainedOperation.get().intentDigest(); + String boundDigest = retainedOperation.get().requestDigest(); + if (lockedRead) { + assertEquals( + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.request( + retainedScope.get(), retainedOperation.get().callerBinding(), true, 1L), + boundDigest); + assertEquals(1, retainedOperation.get().requestDigestVersion()); + assertEquals(true, retainedOperation.get().allowPublicJoin()); + assertEquals(1L, retainedOperation.get().entitlementVersion()); + assertEquals("AVAILABLE", retainedOperation.get().entitlementAuthorityAvailability()); + } else { + assertNull(boundDigest); + assertNull(retainedOperation.get().requestDigestVersion()); + assertNull(retainedOperation.get().allowPublicJoin()); + assertNull(retainedOperation.get().entitlementVersion()); + } + verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); + org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + + JoinPublicProductionResult stillUnavailable = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + assertEquals("ENTITLEMENT_UNAVAILABLE", stillUnavailable.outcomeCode()); + assertEquals("PENDING", retainedOperation.get().status()); + assertEquals(intentDigest, retainedOperation.get().intentDigest()); + assertEquals(boundDigest, retainedOperation.get().requestDigest()); + assertEquals(lockedRead ? Boolean.TRUE : null, retainedOperation.get().allowPublicJoin()); + assertEquals( + lockedRead ? Long.valueOf(1L) : null, retainedOperation.get().entitlementVersion()); + verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); + + authorityRecovered.set(true); + JoinPublicProductionResult retriedAfterRecovery = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + assertTrue(retriedAfterRecovery.success()); + assertEquals("JOINED", retriedAfterRecovery.outcomeCode()); + assertEquals("COMMITTED", retainedOperation.get().status()); + assertEquals("AVAILABLE", retainedOperation.get().entitlementAuthorityAvailability()); + assertEquals(1L, retainedOperation.get().entitlementVersion()); + assertEquals(true, retainedOperation.get().allowPublicJoin()); + assertNotNull(retainedOperation.get().requestDigest()); + assertEquals(intentDigest, retainedOperation.get().intentDigest()); + if (lockedRead) { + assertEquals(boundDigest, retainedOperation.get().requestDigest()); + } + JoinPublicProductionResult replay = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + assertTrue(replay.success()); + assertTrue(replay.replayed()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.times(1)) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verify(accountAuditOutboxRepository, org.mockito.Mockito.times(1)) + .append( + org.mockito.ArgumentMatchers.any(java.util.UUID.class), + org.mockito.ArgumentMatchers.eq("tenant"), + org.mockito.ArgumentMatchers.eq(7L), + org.mockito.ArgumentMatchers.eq("ACCOUNT_JOINED_PUBLIC_PRODUCTION"), + org.mockito.ArgumentMatchers.contains("join-unavailable-1")); + org.mockito.Mockito.verify( + subscriptionRepository, org.mockito.Mockito.times(lockedRead ? 4 : 2)) + .findByTenantIdForUpdate(7L); + } + + private static java.util.stream.Stream unavailableJoinReads() { + return java.util.stream.Stream.of(false, true) + .flatMap( + locked -> + java.util.Arrays.stream(UnavailableEntitlement.values()) + .filter(failure -> failure.cause == null) + .map(failure -> Arguments.of(locked, failure))); + } + + private static java.util.stream.Stream storageJoinReads() { + return java.util.stream.Stream.of(false, true) + .flatMap( + locked -> + java.util.Arrays.stream(UnavailableEntitlement.values()) + .filter(failure -> failure.cause != null) + .map(failure -> Arguments.of(locked, failure))); + } + + @ParameterizedTest + @MethodSource("storageJoinReads") + void joinStorageOutageRollsBackBeforeRecordingFailureAndRecoversOriginalOnce( + boolean lockedRead, UnavailableEntitlement failure) { + Account account = directTextAccount(); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String scope = + service + .issueDirectTextConnectScope(directTextCaller(), directTextTarget()) + .connectScopeId(); + AtomicBoolean recovered = new AtomicBoolean(); + Subscription available = new Subscription(); + available.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)) + .thenAnswer( + invocation -> lockedRead || recovered.get() ? List.of(available) : failure.rows()); + when(subscriptionRepository.findByTenantIdForUpdate(7L)) + .thenAnswer(invocation -> recovered.get() ? List.of(available) : failure.rows()); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.empty()); + when(accountTenantMembershipRepository.save(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + AccountTenantMembership membership = invocation.getArgument(0); + membership.setId(701L); + return membership; + }); + org.mockito.Mockito.clearInvocations( + transactionManager, accountConnectScopeRepository, accountJoinOperationRepository); + var request = new JoinPublicProductionRequest(scope, directTextCaller().requestId()); + + var unavailable = service.joinPublicProductionFromGameSession(directTextCaller(), request); + + assertFalse(unavailable.success()); + assertEquals("ENTITLEMENT_UNAVAILABLE", unavailable.outcomeCode()); + assertEquals("PENDING", retainedOperation.get().status()); + assertNull(retainedOperation.get().outcome()); + assertEquals("ENTITLEMENT_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); + assertEquals("UNAVAILABLE", retainedOperation.get().lastAttemptAuthorityAvailability()); + String originalIntent = retainedOperation.get().intentDigest(); + assertNotNull(originalIntent); + var order = org.mockito.Mockito.inOrder(transactionManager, accountJoinOperationRepository); + order.verify(transactionManager).rollback(org.mockito.ArgumentMatchers.any()); + order + .verify(transactionManager) + .getTransaction(org.mockito.ArgumentMatchers.any(TransactionDefinition.class)); + order.verify(accountJoinOperationRepository).findForUpdate(request.requestId()); + order + .verify(accountJoinOperationRepository) + .recordAttemptFailure(request.requestId(), "UNAVAILABLE", "ENTITLEMENT_UNAVAILABLE"); + order.verify(transactionManager).commit(org.mockito.ArgumentMatchers.any()); + verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); + org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + // AtomicReference fixtures do not physically roll back policy writes; PostgreSQL proves that. + recovered.set(true); + var joined = service.joinPublicProductionFromGameSession(directTextCaller(), request); + assertTrue(joined.success()); + assertFalse(joined.replayed()); + assertEquals(originalIntent, retainedOperation.get().intentDigest()); + var committed = retainedOperation.get(); + assertTrue(service.joinPublicProductionFromGameSession(directTextCaller(), request).replayed()); + assertEquals(committed, retainedOperation.get()); + org.mockito.Mockito.verify(accountTenantMembershipRepository) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verify(accountAuditOutboxRepository) + .append( + org.mockito.ArgumentMatchers.any(UUID.class), + org.mockito.ArgumentMatchers.eq("tenant"), + org.mockito.ArgumentMatchers.eq(7L), + org.mockito.ArgumentMatchers.eq("ACCOUNT_JOINED_PUBLIC_PRODUCTION"), + org.mockito.ArgumentMatchers.anyString()); + } + + @ParameterizedTest + @MethodSource("terminalJoinReadFailures") + void terminalJoinEntitlementOutagePreservesCompleteOriginal( + UnavailableEntitlement failure, String programmingFault) { + Account account = directTextAccount(); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String scope = + service + .issueDirectTextConnectScope(directTextCaller(), directTextTarget()) + .connectScopeId(); + Subscription available = new Subscription(); + available.setStatus("active"); + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(List.of(available)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.empty()); + when(accountTenantMembershipRepository.save(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + AccountTenantMembership membership = invocation.getArgument(0); + membership.setId(701L); + return membership; + }); + var request = new JoinPublicProductionRequest(scope, directTextCaller().requestId()); + var originalResult = service.joinPublicProductionFromGameSession(directTextCaller(), request); + assertTrue(originalResult.success()); + var original = retainedOperation.get(); + var originalScope = retainedScope.get(); + AtomicBoolean recovered = new AtomicBoolean(); + when(subscriptionRepository.findByTenantIdForUpdate(7L)) + .thenAnswer( + invocation -> { + if (recovered.get()) { + return List.of(available); + } + if (programmingFault != null) { + throw entitlementProgrammingFault(programmingFault); + } + return failure.rows(); + }); + org.mockito.Mockito.clearInvocations( + accountTenantMembershipRepository, + accountAuditOutboxRepository, + accountJoinOperationRepository, + accountConnectScopeRepository); + + var unavailable = service.joinPublicProductionFromGameSession(directTextCaller(), request); + + assertFalse(unavailable.success()); + assertFalse(unavailable.replayed()); + assertEquals( + programmingFault == null ? "ENTITLEMENT_UNAVAILABLE" : "AUTH_UNAVAILABLE", + unavailable.outcomeCode()); + assertEquals(original, retainedOperation.get()); + assertEquals(originalScope, retainedScope.get()); + recovered.set(true); + var replay = service.joinPublicProductionFromGameSession(directTextCaller(), request); + assertTrue(replay.success()); + assertTrue(replay.replayed()); + assertEquals(originalResult.accountId(), replay.accountId()); + assertEquals(originalResult.membershipId(), replay.membershipId()); + assertEquals(originalResult.membershipVersion(), replay.membershipVersion()); + assertEquals( + originalResult.membershipAuthorityGeneration(), replay.membershipAuthorityGeneration()); + assertEquals(originalResult.outcomeCode(), replay.outcomeCode()); + assertEquals(original, retainedOperation.get()); + verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .recordAttemptFailure( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .bindPolicyEvidence( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyBoolean()); + org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + } + + private static java.util.stream.Stream terminalJoinReadFailures() { + return java.util.stream.Stream.concat( + java.util.Arrays.stream(UnavailableEntitlement.values()) + .map(failure -> Arguments.of(failure, null)), + java.util.stream.Stream.of("mapping", "configuration") + .map(fault -> Arguments.of(null, fault))); + } + + @ParameterizedTest + @CsvSource({"false,mapping", "true,mapping", "false,configuration", "true,configuration"}) + void joinMappingAndConfigurationFaultsRetainUnexpectedFailureBoundary( + boolean lockedRead, String fault) { + Account account = directTextAccount(); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String scope = + service + .issueDirectTextConnectScope(directTextCaller(), directTextTarget()) + .connectScopeId(); + RuntimeException cause = entitlementProgrammingFault(fault); + if (lockedRead) { + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenThrow(cause); + } else { + when(subscriptionRepository.findByTenantId(7L)).thenThrow(cause); + } + org.mockito.Mockito.clearInvocations(transactionManager, accountConnectScopeRepository); + + AuthenticationException unavailable = + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProductionFromGameSession( + directTextCaller(), + new JoinPublicProductionRequest(scope, directTextCaller().requestId()))); + + assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); + assertSame(cause, unavailable.getCause()); + assertEquals("PENDING", retainedOperation.get().status()); + assertNotNull(retainedOperation.get().intentDigest()); + assertNull(retainedOperation.get().outcome()); + assertEquals("AUTH_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); + org.mockito.Mockito.verify(transactionManager).rollback(org.mockito.ArgumentMatchers.any()); + verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); + org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + } + + @Test + void lateDuplicateRealmKeepsJoinPendingWithoutMembershipEffects() { + Account account = directTextAccount(); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String scope = + service + .issueDirectTextConnectScope(directTextCaller(), directTextTarget()) + .connectScopeId(); + var realm = gameSessionClient.listGameplayRealms("demo").getFirst(); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn(List.of(realm), List.of(realm, realm)); + org.mockito.Mockito.clearInvocations(subscriptionRepository, accountConnectScopeRepository); + + JoinPublicProductionResult result = + service.joinPublicProductionFromGameSession( + directTextCaller(), + new JoinPublicProductionRequest(scope, directTextCaller().requestId())); + + assertFalse(result.success()); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", result.outcomeCode()); + assertEquals("PENDING", retainedOperation.get().status()); + assertEquals(true, retainedOperation.get().allowPublicJoin()); + assertEquals(1L, retainedOperation.get().entitlementVersion()); + assertNotNull(retainedOperation.get().requestDigest()); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); + verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.never()) + .findByTenantIdForUpdate(7L); + org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + } + + private static RuntimeException entitlementProgrammingFault(String fault) { + return "mapping".equals(fault) + ? new org.jooq.exception.MappingException("subscription mapping fault") + : new org.jooq.exception.ConfigurationException("subscription configuration fault"); + } + + private enum UnavailableEntitlement { + MISSING, + AMBIGUOUS, + NULL_LIST, + NULL_ROW, + ZERO_VERSION, + NEGATIVE_VERSION, + JOOQ_STORAGE(new org.jooq.exception.DataAccessException("subscription store unavailable")), + SPRING_STORAGE(new DataAccessResourceFailureException("subscription store unavailable")); + + private final RuntimeException cause; + + UnavailableEntitlement() { + this(null); + } + + UnavailableEntitlement(RuntimeException cause) { + this.cause = cause; + } + + private List rows() { + if (cause != null) { + throw cause; + } + return switch (this) { + case MISSING -> List.of(); + case AMBIGUOUS -> List.of(new Subscription(), new Subscription()); + case NULL_LIST -> null; + case NULL_ROW -> java.util.Collections.singletonList(null); + case ZERO_VERSION, NEGATIVE_VERSION -> { + Subscription invalid = new Subscription(); + invalid.setStatus("active"); + invalid.setEntitlementVersion(this == ZERO_VERSION ? 0L : -1L); + yield List.of(invalid); + } + default -> throw new IllegalStateException("Storage failure must have a cause"); + }; + } + } + + @Test + void joinPublicProductionRevalidatesPolicyAtTheMembershipCommitGate() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + Subscription initialPolicy = new Subscription(); + initialPolicy.setId(22L); + initialPolicy.setTenantId(7L); + initialPolicy.setStatus("active"); + initialPolicy.setEntitlementVersion(5L); + Subscription changedPolicy = new Subscription(); + changedPolicy.setId(22L); + changedPolicy.setTenantId(7L); + changedPolicy.setStatus("active"); + changedPolicy.setEntitlementVersion(6L); + when(subscriptionRepository.findByTenantIdForUpdate(7L)) + .thenReturn(java.util.List.of(changedPolicy)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.empty()); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(initialPolicy)); + org.mockito.Mockito.clearInvocations(gameSessionClient, subscriptionRepository); + + JoinPublicProductionResult result = + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest(connectScopeId, "join-race-1")); + + assertFalse(result.success()); + assertEquals("IDEMPOTENCY_CONFLICT", result.outcomeCode()); + assertEquals("FAILED", retainedOperation.get().status()); + assertEquals("IDEMPOTENCY_CONFLICT", retainedOperation.get().outcome()); + assertEquals(5L, retainedOperation.get().entitlementVersion()); + assertEquals(true, retainedOperation.get().allowPublicJoin()); + assertEquals(1, retainedOperation.get().requestDigestVersion()); + assertNotNull(retainedOperation.get().requestDigest()); + assertEquals(null, retainedOperation.get().lastAttemptFailureCode()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(1)) + .findByTenantIdForUpdate(7L); + var order = org.mockito.Mockito.inOrder(gameSessionClient, subscriptionRepository); + order.verify(gameSessionClient).listGameplayRealms("demo"); + order.verify(gameSessionClient).getAdmissionPointer(7L, "demo", "production"); + order.verify(subscriptionRepository).findByTenantId(7L); + order.verify(gameSessionClient).listGameplayRealms("demo"); + order.verify(gameSessionClient).getAdmissionPointer(7L, "demo", "production"); + order.verify(subscriptionRepository).findByTenantIdForUpdate(7L); + org.mockito.Mockito.verifyNoMoreInteractions(gameSessionClient); + } + + @Test + void changedPolicyOnRetryTerminalizesPreviouslyBoundPendingJoin() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + Subscription initialPolicy = new Subscription(); + initialPolicy.setId(22L); + initialPolicy.setTenantId(7L); + initialPolicy.setStatus("active"); + initialPolicy.setEntitlementVersion(5L); + Subscription changedPolicy = new Subscription(); + changedPolicy.setId(22L); + changedPolicy.setTenantId(7L); + changedPolicy.setStatus("active"); + changedPolicy.setEntitlementVersion(6L); + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of()); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + when(subscriptionRepository.findByTenantId(7L)) + .thenReturn(java.util.List.of(initialPolicy), java.util.List.of(changedPolicy)); + JoinPublicProductionRequest request = + new JoinPublicProductionRequest(connectScopeId, "join-policy-retry-1"); + + JoinPublicProductionResult pending = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + String boundDigest = retainedOperation.get().requestDigest(); + String intentDigest = retainedOperation.get().intentDigest(); + + assertFalse(pending.success()); + assertEquals("ENTITLEMENT_UNAVAILABLE", pending.outcomeCode()); + assertEquals("PENDING", retainedOperation.get().status()); + assertEquals(5L, retainedOperation.get().entitlementVersion()); + assertEquals("ENTITLEMENT_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); + + JoinPublicProductionResult changedPolicyRetry = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + assertFalse(changedPolicyRetry.success()); + assertEquals("IDEMPOTENCY_CONFLICT", changedPolicyRetry.outcomeCode()); + assertEquals("FAILED", retainedOperation.get().status()); + assertEquals("IDEMPOTENCY_CONFLICT", retainedOperation.get().outcome()); + assertEquals(intentDigest, retainedOperation.get().intentDigest()); + assertEquals(boundDigest, retainedOperation.get().requestDigest()); + assertEquals(5L, retainedOperation.get().entitlementVersion()); + assertEquals(true, retainedOperation.get().allowPublicJoin()); + assertEquals(null, retainedOperation.get().lastAttemptFailureCode()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(1)) + .findByTenantIdForUpdate(7L); + } + + @Test + void unboundFailedJoinReplaysOnlyAfterCurrentScopeAndAuthorityChecks() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + var exactRealm = gameSessionClient.listGameplayRealms("demo").getFirst(); + var exactPointer = gameSessionClient.getAdmissionPointer(7L, "demo", "production"); + var changedRealm = exactRealm.toBuilder().setPointerVersion(18L).build(); + var changedPointer = exactPointer.toBuilder().setPointerVersion(18L).build(); + when(gameSessionClient.listGameplayRealms("demo")).thenReturn(java.util.List.of(changedRealm)); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) + .thenReturn(changedPointer); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of(active)); + org.mockito.Mockito.clearInvocations(gameSessionClient, subscriptionRepository); + JoinPublicProductionRequest request = + new JoinPublicProductionRequest(connectScopeId, "join-unbound-failure-1"); + + JoinPublicProductionResult originalFailure = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + var storedFailure = retainedOperation.get(); + + assertFalse(originalFailure.success()); + assertEquals("CONNECT_SCOPE_MISMATCH", originalFailure.outcomeCode()); + assertEquals("FAILED", storedFailure.status()); + assertEquals(originalFailure.outcomeCode(), storedFailure.outcome()); + assertNull(storedFailure.requestDigest()); + + JoinPublicProductionResult changedTargetDenial = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + assertFalse(changedTargetDenial.success()); + assertFalse(changedTargetDenial.replayed()); + assertEquals("CONNECT_SCOPE_MISMATCH", changedTargetDenial.outcomeCode()); + assertEquals(storedFailure, retainedOperation.get()); + + when(gameSessionClient.listGameplayRealms("demo")).thenReturn(java.util.List.of(exactRealm)); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")).thenReturn(exactPointer); + JoinPublicProductionResult replay = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + assertFalse(replay.success()); + assertTrue(replay.replayed()); + assertEquals(originalFailure.outcomeCode(), replay.outcomeCode()); + assertEquals(storedFailure, retainedOperation.get()); + + VerifiedJoinScope originalScope = retainedScope.get(); + VerifiedJoinScope alteredScopeWithoutDigest = + new VerifiedJoinScope( + originalScope.connectScopeId(), + originalScope.accountId(), + originalScope.tenantId(), + originalScope.realmId(), + originalScope.worldSlug(), + originalScope.realmSlug(), + originalScope.playableStateNamespaceId(), + originalScope.playableStateScope(), + originalScope.gameInstanceId(), + originalScope.catalogRevision(), + originalScope.pointerVersion() + 1, + originalScope.evaluatedAt(), + originalScope.connectScopeExpiresAt(), + ""); + retainedScope.set( + new VerifiedJoinScope( + alteredScopeWithoutDigest.connectScopeId(), + alteredScopeWithoutDigest.accountId(), + alteredScopeWithoutDigest.tenantId(), + alteredScopeWithoutDigest.realmId(), + alteredScopeWithoutDigest.worldSlug(), + alteredScopeWithoutDigest.realmSlug(), + alteredScopeWithoutDigest.playableStateNamespaceId(), + alteredScopeWithoutDigest.playableStateScope(), + alteredScopeWithoutDigest.gameInstanceId(), + alteredScopeWithoutDigest.catalogRevision(), + alteredScopeWithoutDigest.pointerVersion(), + alteredScopeWithoutDigest.evaluatedAt(), + alteredScopeWithoutDigest.connectScopeExpiresAt(), + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.scope( + alteredScopeWithoutDigest))); + + AuthenticationException changedScope = + assertThrows( + AuthenticationException.class, + () -> service.joinPublicProduction(bootstrap.bootstrapToken(), request)); + assertEquals("IDEMPOTENCY_CONFLICT", changedScope.getCode()); + assertEquals(storedFailure, retainedOperation.get()); + + retainedScope.set(originalScope); + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of()); + JoinPublicProductionResult unavailableAuthority = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + assertFalse(unavailableAuthority.success()); + assertFalse(unavailableAuthority.replayed()); + assertEquals("ENTITLEMENT_UNAVAILABLE", unavailableAuthority.outcomeCode()); + assertEquals(storedFailure, retainedOperation.get()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) + .findByTenantIdForUpdate(7L); + } + + @Test + void joinIntentCommitsSeparatelyWhenPolicyTransactionRollsBack() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + when(subscriptionRepository.findByTenantId(7L)) + .thenThrow(new IllegalStateException("entitlement storage unavailable")); + + AuthenticationException unavailable = + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest(connectScopeId, "join-txn-boundary-1"))); + + assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); + assertEquals("PENDING", retainedOperation.get().status()); + assertEquals(null, retainedOperation.get().outcome()); + assertNotNull(retainedOperation.get().intentDigest()); + assertEquals(null, retainedOperation.get().requestDigest()); + assertEquals("AUTH_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); + org.mockito.Mockito.verify(transactionManager, org.mockito.Mockito.times(2)) + .commit(org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(transactionManager, org.mockito.Mockito.times(1)) + .rollback(org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); + } + + @Test + void expiredPersistedPendingJoinFailsTerminallyWithoutAuthorityOrMembershipTransition() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = "expired-connect-scope"; + JoinPublicProductionRequest request = + new JoinPublicProductionRequest(connectScopeId, "join-expired-pending-1"); + + VerifiedJoinScope expiredScope = + new VerifiedJoinScope( + connectScopeId, + 11L, + 7L, + UUID.fromString(REALM_ID), + "demo", + "production", + PLAYABLE_STATE_NAMESPACE_ID, + "SHARED", + 44L, + 23L, + 17L, + "1999-12-31T23:59:00Z", + "2000-01-01T00:00:00Z", + ""); + expiredScope = + new VerifiedJoinScope( + expiredScope.connectScopeId(), + expiredScope.accountId(), + expiredScope.tenantId(), + expiredScope.realmId(), + expiredScope.worldSlug(), + expiredScope.realmSlug(), + expiredScope.playableStateNamespaceId(), + expiredScope.playableStateScope(), + expiredScope.gameInstanceId(), + expiredScope.catalogRevision(), + expiredScope.pointerVersion(), + expiredScope.evaluatedAt(), + expiredScope.connectScopeExpiresAt(), + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.scope(expiredScope)); + retainedScope.set(expiredScope); + String callerBinding = + new JwtUtil(JWT_SECRET, 300000L) + .parseToken(bootstrap.bootstrapToken()) + .getPayload() + .get("jti") + .toString(); + retainedOperation.set( + new AccountJoinOperationRepository.JoinOperation( + expiredScope.accountId(), + expiredScope.tenantId(), + expiredScope.realmId(), + callerBinding, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash(connectScopeId), + expiredScope.snapshotDigest(), + "UNAVAILABLE", + null, + null, + null, + null, + "PENDING", + null, + null, + null, + null, + 1, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.intent( + request.requestId(), expiredScope, callerBinding), + "ENTITLEMENT_UNAVAILABLE", + "UNAVAILABLE")); + + JoinPublicProductionResult expiredRetry = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + var expiredTerminalOperation = retainedOperation.get(); + JoinPublicProductionResult terminalReadback = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + assertFalse(expiredRetry.success()); + assertEquals("CONNECT_SCOPE_INVALID", expiredRetry.outcomeCode()); + assertFalse(terminalReadback.success()); + assertFalse(terminalReadback.replayed()); + assertEquals("CONNECT_SCOPE_INVALID", terminalReadback.outcomeCode()); + assertEquals(expiredTerminalOperation, retainedOperation.get()); + assertEquals("FAILED", retainedOperation.get().status()); + assertEquals("CONNECT_SCOPE_INVALID", retainedOperation.get().outcome()); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.times(1)) + .finish( + org.mockito.ArgumentMatchers.eq(request.requestId()), + org.mockito.ArgumentMatchers.eq("FAILED"), + org.mockito.ArgumentMatchers.eq("CONNECT_SCOPE_INVALID"), + org.mockito.ArgumentMatchers.isNull(), + org.mockito.ArgumentMatchers.isNull(), + org.mockito.ArgumentMatchers.isNull()); + verifyNoInteractions( + subscriptionRepository, accountTenantMembershipRepository, accountAuditOutboxRepository); + } + + @Test + void expiredTerminalJoinScopeFailsClosedWithoutReplayingStoredSuccess() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = "expired-committed-connect-scope"; + JoinPublicProductionRequest request = + new JoinPublicProductionRequest(connectScopeId, "join-expired-committed-1"); + VerifiedJoinScope unsignedExpiredScope = + new VerifiedJoinScope( + connectScopeId, + 11L, + 7L, + UUID.fromString(REALM_ID), + "demo", + "production", + PLAYABLE_STATE_NAMESPACE_ID, + "SHARED", + 44L, + 23L, + 17L, + "1999-12-31T23:59:00Z", + "2000-01-01T00:00:00Z", + ""); + VerifiedJoinScope expiredScope = + new VerifiedJoinScope( + unsignedExpiredScope.connectScopeId(), + unsignedExpiredScope.accountId(), + unsignedExpiredScope.tenantId(), + unsignedExpiredScope.realmId(), + unsignedExpiredScope.worldSlug(), + unsignedExpiredScope.realmSlug(), + unsignedExpiredScope.playableStateNamespaceId(), + unsignedExpiredScope.playableStateScope(), + unsignedExpiredScope.gameInstanceId(), + unsignedExpiredScope.catalogRevision(), + unsignedExpiredScope.pointerVersion(), + unsignedExpiredScope.evaluatedAt(), + unsignedExpiredScope.connectScopeExpiresAt(), + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.scope( + unsignedExpiredScope)); + retainedScope.set(expiredScope); + String callerBinding = + new JwtUtil(JWT_SECRET, 300000L) + .parseToken(bootstrap.bootstrapToken()) + .getPayload() + .get("jti") + .toString(); + var committedOperation = + new AccountJoinOperationRepository.JoinOperation( + expiredScope.accountId(), + expiredScope.tenantId(), + expiredScope.realmId(), + callerBinding, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash(connectScopeId), + expiredScope.snapshotDigest(), + "AVAILABLE", + true, + 1L, + 1, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.request( + expiredScope, callerBinding, true, 1L), + "COMMITTED", + "JOINED", + 701L, + 1L, + 1L, + 1, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.intent( + request.requestId(), expiredScope, callerBinding), + null, + "AVAILABLE"); + retainedOperation.set(committedOperation); + + JoinPublicProductionResult retry = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + assertFalse(retry.success()); + assertFalse(retry.replayed()); + assertEquals("CONNECT_SCOPE_INVALID", retry.outcomeCode()); + assertEquals(committedOperation, retainedOperation.get()); + assertEquals("COMMITTED", retainedOperation.get().status()); + assertEquals("JOINED", retainedOperation.get().outcome()); + assertEquals(701L, retainedOperation.get().membershipId()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .finish( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.nullable(Long.class), + org.mockito.ArgumentMatchers.nullable(Long.class), + org.mockito.ArgumentMatchers.nullable(Long.class)); + verifyNoInteractions(subscriptionRepository, accountAuditOutboxRepository); + } + + @ParameterizedTest + @ValueSource(strings = {"PENDING", "COMMITTED", "FAILED"}) + void joinPublicProductionHidesAnotherAccountsGlobalRequestIdEvidence(String originalStatus) { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + VerifiedJoinScope scope = retainedScope.get(); + String requestId = "join-global-collision-" + originalStatus.toLowerCase(); + String originalOutcome = + switch (originalStatus) { + case "COMMITTED" -> "JOINED"; + case "FAILED" -> "PUBLIC_PRODUCTION_ADMISSION_DENIED"; + default -> null; + }; + Long originalMembershipId = "COMMITTED".equals(originalStatus) ? 812L : null; + AccountJoinOperationRepository.JoinOperation originalOperation = + new AccountJoinOperationRepository.JoinOperation( + 12L, + scope.tenantId(), + scope.realmId(), + "different-caller", + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash(connectScopeId), + scope.snapshotDigest(), + "COMMITTED".equals(originalStatus) || "FAILED".equals(originalStatus) + ? "AVAILABLE" + : "NOT_EVALUATED", + "PENDING".equals(originalStatus) ? null : true, + "PENDING".equals(originalStatus) ? null : 7L, + "PENDING".equals(originalStatus) ? null : 1, + "PENDING".equals(originalStatus) ? null : "original-request-digest", + originalStatus, + originalOutcome, + originalMembershipId, + originalMembershipId == null ? null : 9L, + originalMembershipId == null ? null : 5L, + 1, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.intent( + requestId, scope, "different-caller"), + null, + "AVAILABLE"); + retainedOperation.set(originalOperation); + + AuthenticationException conflict = + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest(connectScopeId, requestId))); + + assertEquals("IDEMPOTENCY_CONFLICT", conflict.getCode()); + assertEquals("JOIN request ID was reused with different input", conflict.getMessage()); + assertFalse(conflict.getMessage().contains("JOINED")); + assertFalse(conflict.getMessage().contains("PUBLIC_PRODUCTION_ADMISSION_DENIED")); + assertFalse(conflict.getMessage().contains("812")); + assertEquals(originalOperation, retainedOperation.get()); + assertEquals(originalStatus, retainedOperation.get().status()); + assertEquals(originalOutcome, retainedOperation.get().outcome()); + assertEquals(originalMembershipId, retainedOperation.get().membershipId()); + org.mockito.Mockito.verify(accountJoinOperationRepository) + .find(org.mockito.ArgumentMatchers.eq(requestId)); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .insertIntent( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .bindPolicyEvidence( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyBoolean()); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .finish( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.nullable(Long.class), + org.mockito.ArgumentMatchers.nullable(Long.class), + org.mockito.ArgumentMatchers.nullable(Long.class)); + verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); + } + + @Test + void reclaimedScopeRaceReturnsConnectScopeInvalid() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + VerifiedJoinScope scope = retainedScope.get(); + org.mockito.Mockito.clearInvocations( + subscriptionRepository, accountTenantMembershipRepository, accountAuditOutboxRepository); + when(accountConnectScopeRepository.find(connectScopeId)) + .thenReturn(Optional.of(scope), Optional.empty()); + org.mockito.Mockito.doThrow(new org.jooq.exception.DataAccessException("scope reclaimed")) + .when(accountJoinOperationRepository) + .insertIntent( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest(connectScopeId, "join-reclaimed-scope"))); + + assertEquals("CONNECT_SCOPE_INVALID", exception.getCode()); + verifyNoInteractions( + subscriptionRepository, accountTenantMembershipRepository, accountAuditOutboxRepository); + } + + @Test + void quarantinedLegacyMembershipIsNeverRestoredByPublicJoin() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + AccountTenantMembership quarantined = membership(account, 7L); + quarantined.setLifecycleState("LEGACY_UNVERIFIED"); + quarantined.setGameplayAdmissionAllowed(false); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(quarantined)); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + + JoinPublicProductionResult result = + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest(connectScopeId, "join-legacy-1")); + + assertFalse(result.success()); + assertEquals("MEMBERSHIP_RECONCILIATION_REQUIRED", result.outcomeCode()); + assertEquals("LEGACY_UNVERIFIED", quarantined.getLifecycleState()); + assertFalse(quarantined.isGameplayAdmissionAllowed()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); + } + + private void retainJoinEvidence( + AtomicReference retainedScope, + AtomicReference retainedOperation) { + org.mockito.Mockito.doAnswer( + invocation -> { + retainedScope.set(invocation.getArgument(0)); + return null; + }) + .when(accountConnectScopeRepository) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + when(accountConnectScopeRepository.find(org.mockito.ArgumentMatchers.anyString())) + .thenAnswer(invocation -> Optional.ofNullable(retainedScope.get())); + when(accountJoinOperationRepository.find(org.mockito.ArgumentMatchers.anyString())) + .thenAnswer(invocation -> Optional.ofNullable(retainedOperation.get())); + when(accountJoinOperationRepository.findForUpdate(org.mockito.ArgumentMatchers.anyString())) + .thenAnswer(invocation -> Optional.ofNullable(retainedOperation.get())); + org.mockito.Mockito.doAnswer( + invocation -> { + String requestId = invocation.getArgument(0); + VerifiedJoinScope scope = invocation.getArgument(1); + String callerBinding = invocation.getArgument(2); + String intentDigest = invocation.getArgument(3); + retainedOperation.set( + new AccountJoinOperationRepository.JoinOperation( + scope.accountId(), + scope.tenantId(), + scope.realmId(), + callerBinding, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash( + scope.connectScopeId()), + scope.snapshotDigest(), + "NOT_EVALUATED", + null, + null, + null, + null, + "PENDING", + null, + null, + null, + null, + 1, + intentDigest, + null, + "NOT_EVALUATED")); + return true; + }) + .when(accountJoinOperationRepository) + .insertIntent( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.doAnswer( + invocation -> { + var pending = retainedOperation.get(); + retainedOperation.set( + new AccountJoinOperationRepository.JoinOperation( + pending.accountId(), + pending.tenantId(), + pending.realmId(), + pending.callerBinding(), + pending.scopeTokenHash(), + pending.connectScopeDigest(), + "AVAILABLE", + invocation.getArgument(3), + invocation.getArgument(2), + 1, + invocation.getArgument(1), + pending.status(), + pending.outcome(), + pending.membershipId(), + pending.membershipVersion(), + pending.membershipAuthorityGeneration(), + pending.intentDigestVersion(), + pending.intentDigest(), + null, + "AVAILABLE")); + return null; + }) + .when(accountJoinOperationRepository) + .bindPolicyEvidence( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyBoolean()); + org.mockito.Mockito.doAnswer( + invocation -> { + var pending = retainedOperation.get(); + String availability = invocation.getArgument(1); + retainedOperation.set( + new AccountJoinOperationRepository.JoinOperation( + pending.accountId(), + pending.tenantId(), + pending.realmId(), + pending.callerBinding(), + pending.scopeTokenHash(), + pending.connectScopeDigest(), + pending.requestDigest() == null + ? availability + : pending.entitlementAuthorityAvailability(), + pending.allowPublicJoin(), + pending.entitlementVersion(), + pending.requestDigestVersion(), + pending.requestDigest(), + pending.status(), + pending.outcome(), + pending.membershipId(), + pending.membershipVersion(), + pending.membershipAuthorityGeneration(), + pending.intentDigestVersion(), + pending.intentDigest(), + invocation.getArgument(2), + availability)); + return null; + }) + .when(accountJoinOperationRepository) + .recordAttemptFailure( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.doAnswer( + invocation -> { + var pending = retainedOperation.get(); + retainedOperation.set( + new AccountJoinOperationRepository.JoinOperation( + pending.accountId(), + pending.tenantId(), + pending.realmId(), + pending.callerBinding(), + pending.scopeTokenHash(), + pending.connectScopeDigest(), + pending.entitlementAuthorityAvailability(), + pending.allowPublicJoin(), + pending.entitlementVersion(), + pending.requestDigestVersion(), + pending.requestDigest(), + invocation.getArgument(1), + invocation.getArgument(2), + invocation.getArgument(3), + invocation.getArgument(4), + invocation.getArgument(5), + pending.intentDigestVersion(), + pending.intentDigest(), + null, + pending.lastAttemptAuthorityAvailability())); + return null; + }) + .when(accountJoinOperationRepository) + .finish( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.nullable(Long.class), + org.mockito.ArgumentMatchers.nullable(Long.class), + org.mockito.ArgumentMatchers.nullable(Long.class)); + } + + @Test + void emailLoginOtpRequestIsNeutralForUnknownEmail() { + when(accountRepository.findByEmail("unknown@example.com")).thenReturn(Optional.empty()); + + service.requestEmailLoginOtp("unknown@example.com"); + + verifyNoInteractions(emailService, accountEmailLoginChallengeRepository); + } + + @ParameterizedTest + @EnumSource( + value = AccountLifecycleState.class, + names = {"SECURITY_LOCKED", "DEACTIVATED_PENDING_DELETE", "DELETED"}) + void emailLoginOtpRequestIsNeutralForIneligibleLifecycleState( + AccountLifecycleState lifecycleState) { + Account account = new Account(); + account.setId(9L); + account.setEmail("verified@example.com"); + account.setEmailVerified(true); + account.setLifecycleState(lifecycleState); + when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); + + service.requestEmailLoginOtp("verified@example.com"); + + verifyNoInteractions( + accountTenantMembershipRepository, accountEmailLoginChallengeRepository, emailService); + } + + @Test + void emailLoginOtpRequestPersistsOnlyHashedChallengeAndSendsSixDigitCode() { + Account account = new Account(); + account.setId(9L); + account.setEmail("verified@example.com"); + account.setEmailVerified(true); + when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); + when(accountEmailLoginChallengeRepository.findByAccountId(9L)).thenReturn(Optional.empty()); + when(accountEmailLoginChallengeRepository.save(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = + invocation.getArgument(0); + challenge.setId(3L); + return challenge; + }); + + service.requestEmailLoginOtp("verified@example.com"); + + org.mockito.ArgumentCaptor< + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge> + challengeCaptor = + org.mockito.ArgumentCaptor.forClass( + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge.class); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository) + .save(challengeCaptor.capture()); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(9L); + assertEquals(9L, challengeCaptor.getValue().getAccountId()); + assertFalse(challengeCaptor.getValue().getCodeHash().matches("\\d{6}")); + org.mockito.Mockito.verify(emailService) + .sendEmail( + org.mockito.ArgumentMatchers.eq("verified@example.com"), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.matches(".*\\b\\d{6}\\b.*")); + verifyNoInteractions(accountTenantMembershipRepository); + } + + @Test + void emailLoginOtpVerificationAuthenticatesAndConsumesMatchingChallenge() { + Account account = new Account(); + account.setId(9L); + setPersistedAuthenticationIdentity(account); + account.setEmail("verified@example.com"); + account.setEmailVerified(true); + account.setRole("player"); + when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); + when(accountEmailLoginChallengeRepository.findByAccountId(9L)).thenReturn(Optional.empty()); + when(accountEmailLoginChallengeRepository.save(org.mockito.ArgumentMatchers.any())) + .thenAnswer(invocation -> invocation.getArgument(0)); + + service.requestEmailLoginOtp("verified@example.com"); + + org.mockito.ArgumentCaptor< + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge> + challengeCaptor = + org.mockito.ArgumentCaptor.forClass( + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge.class); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository) + .save(challengeCaptor.capture()); + org.mockito.ArgumentCaptor emailBodyCaptor = + org.mockito.ArgumentCaptor.forClass(String.class); + org.mockito.Mockito.verify(emailService) + .sendEmail( + org.mockito.ArgumentMatchers.eq("verified@example.com"), + org.mockito.ArgumentMatchers.anyString(), + emailBodyCaptor.capture()); + Matcher codeMatcher = Pattern.compile("\\b(\\d{6})\\b").matcher(emailBodyCaptor.getValue()); + assertTrue(codeMatcher.find()); + when(accountEmailLoginChallengeRepository.findByAccountId(9L)) + .thenReturn(Optional.of(challengeCaptor.getValue())); + + AuthenticationResult result = + service.verifyEmailLoginOtp("verified@example.com", codeMatcher.group(1)); + + assertEquals(account.getAccountUuid().toString(), result.accountId()); + assertNotNull(result.authToken()); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository) + .delete(challengeCaptor.getValue()); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession( + org.mockito.ArgumentMatchers.eq(9L), + org.mockito.ArgumentMatchers.eq(result.authToken()), + org.mockito.ArgumentMatchers.eq(jwtAuthProperties.getJwtExpirationMs())); + verifyNoInteractions(accountTenantMembershipRepository); + } + + @Test + void authenticateUsesMatchingEmailLoginOtpBeforePasswordFallback() { + Account account = new Account(); + account.setId(9L); + setPersistedAuthenticationIdentity(account); + account.setEmail("demo@example.com"); + account.setPasswordHash(hash("password")); + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = + new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); + challenge.setId(3L); + challenge.setAccountId(9L); + challenge.setCodeHash(hash("123456")); + challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); + when(accountEmailLoginChallengeRepository.findByAccountId(9L)) + .thenReturn(Optional.of(challenge)); + + AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "123456"); + + assertEquals(account.getAccountUuid().toString(), result.accountId()); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).delete(challenge); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession(9L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); + verifyNoInteractions(accountTenantMembershipRepository); + } + + @Test + void authenticateFallsBackToPasswordWithoutBurningUnmatchedEmailLoginOtp() { + Account account = new Account(); + account.setId(9L); + setPersistedAuthenticationIdentity(account); + account.setEmail("demo@example.com"); + account.setPasswordHash(hash("password")); + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = + new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); + challenge.setId(3L); + challenge.setAccountId(9L); + challenge.setCodeHash(hash("123456")); + challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); + when(accountEmailLoginChallengeRepository.findByAccountId(9L)) + .thenReturn(Optional.of(challenge)); + + AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "password"); + + assertEquals(account.getAccountUuid().toString(), result.accountId()); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) + .delete(challenge); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) + .save(challenge); + } + + @Test + void authenticateCountsFailedMixedModeSecretAgainstActiveEmailLoginOtp() { + Account account = new Account(); + account.setId(9L); + setPersistedAuthenticationIdentity(account); + account.setEmail("demo@example.com"); + account.setPasswordHash(hash("password")); + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = + new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); + challenge.setId(3L); + challenge.setAccountId(9L); + challenge.setCodeHash(hash("123456")); + challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); + when(accountEmailLoginChallengeRepository.findByAccountId(9L)) + .thenReturn(Optional.of(challenge)); + when(accountEmailLoginChallengeRepository.save(challenge)).thenReturn(challenge); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.authenticateForGameplay("demo@example.com", "wrong")); + + assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, exception.getCode()); + assertEquals(1, challenge.getInvalidAttemptCount()); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).save(challenge); + verifyNoInteractions(sessionService); + } + + @Test + void passwordOnlyAccountsDoNotIssueEmailLoginChallenges() { + Account account = new Account(); + account.setId(9L); + account.setEmail("verified@example.com"); + account.setEmailVerified(true); + account.setLoginAuthModes("PASSWORD"); + when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); + + service.requestEmailLoginOtp("verified@example.com"); + + verifyNoInteractions( + accountTenantMembershipRepository, accountEmailLoginChallengeRepository, emailService); + } + + @ParameterizedTest + @EnumSource(AccountIdentityProvenance.class) + void gameplayAuthenticationAcceptsEveryRecognizedPersistedUuidProvenance( + AccountIdentityProvenance provenance) { + Account account = new Account(); + account.setId(31L); + account.setEmail("retained@example.com"); + account.setPasswordHash(hash("password")); + setPersistedAuthenticationIdentity(account, provenance); + when(accountRepository.findByEmail("retained@example.com")).thenReturn(Optional.of(account)); + + AuthenticationResult result = + service.authenticateForGameplay("retained@example.com", "password"); + var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); + + assertEquals(account.getAccountUuid().toString(), result.accountId()); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); + assertFalse(claims.containsKey("tenantId")); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession(31L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); + } + + @ParameterizedTest + @EnumSource(InvalidAuthenticationIdentity.class) + void gameplayAuthenticationRejectsUnprovedIdentityBeforeConsumingOtpOrMinting( + InvalidAuthenticationIdentity invalidIdentity) { + Account account = new Account(); + account.setId(32L); + account.setEmail("unproved@example.com"); + assignInvalidAuthenticationIdentity(account, invalidIdentity); + var challenge = new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); + challenge.setId(8L); + challenge.setAccountId(32L); + challenge.setCodeHash(hash("123456")); + challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); + when(accountRepository.findByEmail("unproved@example.com")).thenReturn(Optional.of(account)); + when(accountEmailLoginChallengeRepository.findByAccountId(32L)) + .thenReturn(Optional.of(challenge)); + + AuthenticationException unavailable = + assertThrows( + AuthenticationException.class, + () -> service.authenticateForGameplay("unproved@example.com", "123456")); + assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); + + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(32L); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).findByAccountId(32L); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) + .delete(challenge); + verifyNoInteractions(sessionService); + } + + @Test + void emailLoginOtpVerificationFailsClosedForUnknownEmail() { + when(accountRepository.findByEmail("unknown@example.com")).thenReturn(Optional.empty()); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.verifyEmailLoginOtp("unknown@example.com", "123456")); + + assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, exception.getCode()); + verifyNoInteractions(accountEmailLoginChallengeRepository, sessionService); + } + + @Test + void emailLoginOtpVerificationLocksChallengeBeforeConsumingIt() { + Account account = new Account(); + account.setId(9L); + setPersistedAuthenticationIdentity(account); + account.setEmail("verified@example.com"); + account.setRole("player"); + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = + new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); + challenge.setId(5L); + challenge.setAccountId(9L); + challenge.setCodeHash(hash("123456")); + challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(10)); + challenge.setInvalidAttemptCount(0); + when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); + when(accountEmailLoginChallengeRepository.findByAccountId(9L)) + .thenReturn(Optional.of(challenge)); + + AuthenticationResult result = service.verifyEmailLoginOtp("verified@example.com", "123456"); + + assertEquals(account.getAccountUuid().toString(), result.accountId()); + var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); + assertEquals("account-service", claims.getAudience().iterator().next()); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); + org.mockito.InOrder inOrder = org.mockito.Mockito.inOrder(accountEmailLoginChallengeRepository); + inOrder.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(9L); + inOrder.verify(accountEmailLoginChallengeRepository).findByAccountId(9L); + inOrder.verify(accountEmailLoginChallengeRepository).delete(challenge); + } + + @Test + void authenticateReturnsControlUiTokenWithoutGameplayMembership() { + Account account = new Account(); + account.setId(1L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + + AuthenticationResult result = service.authenticate("demo", "password"); + + assertNotNull(result.authToken()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); + var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); + assertEquals("control-ui", claims.getAudience().iterator().next()); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); + assertEquals(java.util.List.of(), claims.get("globalRoles")); + assertNotNull(claims.get("jti")); + assertFalse(claims.containsKey("tenantId")); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession(1L, result.authToken(), 3600000L); + verifyNoInteractions(accountTenantMembershipRepository); + } + + @ParameterizedTest + @CsvSource({ + "SECURITY_LOCKED, AUTH_ACCOUNT_LOCKED", + "DEACTIVATED_PENDING_DELETE, AUTH_INVALID_CREDENTIALS", + "DELETED, AUTH_INVALID_CREDENTIALS" + }) + void authenticateRejectsIneligibleLifecycleState( + AccountLifecycleState lifecycleState, String expectedCode) { + Account account = new Account(); + account.setId(1L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + account.setLifecycleState(lifecycleState); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + + AuthenticationException exception = + assertThrows(AuthenticationException.class, () -> service.authenticate("demo", "password")); + + assertEquals(expectedCode, exception.getCode()); + verifyNoInteractions(sessionService); + } + + @Test + void authenticateForGameplayReturnsTokenWhenPasswordMatches() { + Account account = new Account(); + account.setId(1L); + setPersistedAuthenticationIdentity(account); + account.setEmail("demo@example.com"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); + jwtAuthProperties.setJwtSecret(null); + + AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "password"); + + assertNotNull(result.authToken()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); + var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); + assertEquals("account-service", claims.getAudience().iterator().next()); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); + assertEquals(java.util.List.of(), claims.get("globalRoles")); + assertNotNull(claims.get("jti")); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession(1L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); + verifyNoInteractions(accountTenantMembershipRepository); + } + + @Test + void issuePlayerBootstrapReturnsShortLivedToken() { + Account account = new Account(); + account.setId(7L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + account.setLoginAuthModes("PASSWORD"); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + jwtAuthProperties.setJwtSecret(null); + + PlayerBootstrapResult result = service.issuePlayerBootstrap("demo", "password"); + + assertEquals(account.getAccountUuid().toString(), result.accountId()); + assertNotNull(result.bootstrapToken()); + assertNotNull(result.issuedAt()); + assertNotNull(result.expiresAt()); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession( + org.mockito.ArgumentMatchers.eq(7L), + org.mockito.ArgumentMatchers.eq(result.bootstrapToken()), + org.mockito.ArgumentMatchers.eq(300000L)); + var claims = new JwtUtil(JWT_SECRET, 300000L).parseToken(result.bootstrapToken()).getPayload(); + assertEquals("player-bootstrap", claims.getAudience().iterator().next()); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); + assertFalse(claims.containsKey("tenantId")); + assertEquals(300000L, claims.getExpiration().getTime() - claims.getIssuedAt().getTime()); + when(sessionService.isAccountSessionActive(7L, result.bootstrapToken())).thenReturn(true); + var worlds = service.listBootstrapWorlds(result.bootstrapToken()); + assertEquals("demo", worlds.getFirst().worldSlug()); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.times(2)) + .findByAccountUuid(account.getAccountUuid()); + org.mockito.Mockito.verify(sessionService).isAccountSessionActive(7L, result.bootstrapToken()); + verifyNoInteractions(accountEmailLoginChallengeRepository); + } + + @ParameterizedTest + @EnumSource(InvalidAuthenticationIdentity.class) + void issuePlayerBootstrapRejectsUnprovedIdentityBeforeConsumingOtpOrMinting( + InvalidAuthenticationIdentity invalidIdentity) { + Account account = new Account(); + account.setId(50L); + account.setUsername("demo"); + account.setLoginAuthModes("EMAIL_OTP"); + assignInvalidAuthenticationIdentity(account, invalidIdentity); + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = + new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); + challenge.setAccountId(50L); + challenge.setCodeHash(hash("123456")); + challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountEmailLoginChallengeRepository.findByAccountId(50L)) + .thenReturn(Optional.of(challenge)); + + AuthenticationException unavailable = + assertThrows( + AuthenticationException.class, () -> service.issuePlayerBootstrap("demo", "123456")); + assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); + + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(50L); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).findByAccountId(50L); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) + .delete(challenge); + verifyNoInteractions(sessionService); + } + + @Test + void issuePlayerBootstrapPrefersEmailLookupOverCollidingUsername() { + Account emailAccount = new Account(); + emailAccount.setId(7L); + setPersistedAuthenticationIdentity(emailAccount); + emailAccount.setUsername("email-owner"); + emailAccount.setEmail("player@example.com"); + emailAccount.setPasswordHash(hash("password")); + emailAccount.setLoginAuthModes("PASSWORD"); + when(accountRepository.findByEmail("player@example.com")).thenReturn(Optional.of(emailAccount)); + + PlayerBootstrapResult result = + service.issuePlayerBootstrap(" PLAYER@EXAMPLE.COM ", "password"); + + assertEquals(emailAccount.getAccountUuid().toString(), result.accountId()); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) + .findByUsername(org.mockito.ArgumentMatchers.anyString()); + } + + @Test + void issuePlayerBootstrapAcceptsAndConsumesEmailLoginOtp() { + Account account = new Account(); + account.setId(7L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setEmail("demo@example.com"); + account.setLoginAuthModes("EMAIL_OTP"); + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = + new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); + challenge.setAccountId(7L); + challenge.setCodeHash(hash("123456")); + challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountEmailLoginChallengeRepository.findByAccountId(7L)) + .thenReturn(Optional.of(challenge)); + + PlayerBootstrapResult result = service.issuePlayerBootstrap("demo", "123456"); + + assertEquals(account.getAccountUuid().toString(), result.accountId()); + org.mockito.InOrder inOrder = org.mockito.Mockito.inOrder(accountEmailLoginChallengeRepository); + inOrder.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(7L); + inOrder.verify(accountEmailLoginChallengeRepository).findByAccountId(7L); + inOrder.verify(accountEmailLoginChallengeRepository).delete(challenge); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession(7L, result.bootstrapToken(), 300000L); + } + + private static java.util.stream.Stream + invalidBootstrapAccountClaims() { + String valid = "10000000-0000-4000-8000-00000000000a"; + return java.util.stream.Stream.of( + org.junit.jupiter.params.provider.Arguments.of("11", "11"), + org.junit.jupiter.params.provider.Arguments.of((String) null, valid), + org.junit.jupiter.params.provider.Arguments.of( + valid.toUpperCase(java.util.Locale.ROOT), valid), + org.junit.jupiter.params.provider.Arguments.of(" " + valid, valid), + org.junit.jupiter.params.provider.Arguments.of(valid, (Object) null), + org.junit.jupiter.params.provider.Arguments.of(valid, ""), + org.junit.jupiter.params.provider.Arguments.of(valid, 11L), + org.junit.jupiter.params.provider.Arguments.of(valid, "11"), + org.junit.jupiter.params.provider.Arguments.of( + valid, "00000000-0000-0000-0000-000000000000"), + org.junit.jupiter.params.provider.Arguments.of( + "00000000-0000-0000-0000-000000000000", valid), + org.junit.jupiter.params.provider.Arguments.of(valid, "not-a-uuid"), + org.junit.jupiter.params.provider.Arguments.of( + valid, valid.toUpperCase(java.util.Locale.ROOT)), + org.junit.jupiter.params.provider.Arguments.of(valid, " " + valid), + org.junit.jupiter.params.provider.Arguments.of( + valid, "10000000-0000-4000-8000-000000000002")); + } + + @ParameterizedTest + @org.junit.jupiter.params.provider.MethodSource("invalidBootstrapAccountClaims") + void bootstrapReaderRejectsNonUuidOrContradictoryIdentityBeforeOwnerOrSessionUse( + String subject, Object accountClaim) { + Map claims = new java.util.HashMap<>(); + claims.put("aud", "player-bootstrap"); + if (accountClaim != null) { + claims.put("accountId", accountClaim); + } + String token = new JwtUtil(JWT_SECRET, 300000L).generateToken(subject, claims); + + AuthenticationException denied = + assertThrows(AuthenticationException.class, () -> service.listBootstrapWorlds(token)); + + assertEquals("CONNECT_CONTEXT_INVALID", denied.getCode()); + verifyNoInteractions(accountRepository, sessionService); + } + + @ParameterizedTest + @ValueSource(strings = {"missing", "wrong-owner-uuid", "unavailable"}) + void bootstrapReaderReportsOwnerReadbackFailureBeforeSessionUse(String failure) { + UUID uuid = UUID.fromString("10000000-0000-4000-8000-000000000001"); + if (failure.equals("unavailable")) { + when(accountRepository.findByAccountUuid(uuid)) + .thenThrow( + new org.springframework.dao.DataAccessResourceFailureException("private detail")); + } else if (failure.equals("wrong-owner-uuid")) { + Account owner = new Account(); + owner.setId(11L); + owner.setAccountUuid(UUID.randomUUID()); + owner.setAccountUuidSourceNumericId(11L); + owner.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + when(accountRepository.findByAccountUuid(uuid)).thenReturn(Optional.of(owner)); + } + String token = + new JwtUtil(JWT_SECRET, 300000L) + .generateToken( + uuid.toString(), Map.of("aud", "player-bootstrap", "accountId", uuid.toString())); + + AuthenticationException denied = + assertThrows(AuthenticationException.class, () -> service.listBootstrapWorlds(token)); + + assertEquals("AUTH_UNAVAILABLE", denied.getCode()); + assertEquals("Account authority is unavailable", denied.getMessage()); + verifyNoInteractions(sessionService); + } + + @Test + void bootstrapReaderResolvesUuidBeforeReadingPrivateAccountSession() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + String uuid = account.getAccountUuid().toString(); + String token = + new JwtUtil(JWT_SECRET, 300000L) + .generateToken(uuid, Map.of("aud", "player-bootstrap", "accountId", uuid)); + when(sessionService.isAccountSessionActive(11L, token)).thenReturn(true); + + assertFalse(service.listBootstrapWorlds(token).isEmpty()); + + org.mockito.InOrder reads = org.mockito.Mockito.inOrder(accountRepository, sessionService); + reads.verify(accountRepository).findByAccountUuid(account.getAccountUuid()); + reads.verify(sessionService).isAccountSessionActive(11L, token); + } + + @Test + void listBootstrapWorldsRejectsInactiveAccountBootstrapToken() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + String accountUuid = account.getAccountUuid().toString(); + String bootstrapToken = + new JwtUtil(JWT_SECRET, 300000L) + .generateToken( + accountUuid, Map.of("aud", "player-bootstrap", "accountId", accountUuid)); + + AuthenticationException ex = + assertThrows( + AuthenticationException.class, () -> service.listBootstrapWorlds(bootstrapToken)); + + assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); + assertEquals("Bootstrap token expired", ex.getMessage()); + org.mockito.Mockito.verify(sessionService).isAccountSessionActive(11L, bootstrapToken); + } + + @ParameterizedTest + @ValueSource( + strings = { + "not-a-uuid", + "abc", + "0", + "00000000-0000-0000-0000-000000000000", + "4C4B57D8-E3A2-48FE-9977-E7DF0FDCE901", + " 4c4b57d8-e3a2-48fe-9977-e7df0fdce901", + "4c4b57d8-e3a2-48fe-9977-e7df0fdce901 " + }) + void listBootstrapWorldsRejectsMalformedOrNoncanonicalBootstrapAccountUuid(String accountUuid) { + String malformedBootstrapToken = + new JwtUtil(JWT_SECRET, 300000L) + .generateToken( + accountUuid, Map.of("aud", "player-bootstrap", "accountId", accountUuid)); + + AuthenticationException ex = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapWorlds(malformedBootstrapToken)); + + assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); + verifyNoInteractions(accountRepository, sessionService); + } + + @Test + void listBootstrapWorldsRejectsBootstrapTokenAccountSubjectMismatch() { + String malformedBootstrapToken = + new JwtUtil(JWT_SECRET, 300000L) + .generateToken( + REALM_ID, + Map.of("aud", "player-bootstrap", "accountId", PLAYABLE_STATE_NAMESPACE_ID)); + + AuthenticationException ex = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapWorlds(malformedBootstrapToken)); + + assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); + verifyNoInteractions(accountRepository, sessionService); + } + + @Test + void listBootstrapWorldsRejectsLegacyNumericBootstrapTokenClaims() { + String malformedBootstrapToken = + new JwtUtil(JWT_SECRET, 300000L) + .generateToken("11", Map.of("aud", "player-bootstrap", "accountId", "11")); + + AuthenticationException ex = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapWorlds(malformedBootstrapToken)); + + assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); + } + + @Test + void listBootstrapWorldsRejectsBootstrapTokenWithoutAudience() { + String malformedBootstrapToken = + new JwtUtil(JWT_SECRET, 300000L).generateToken("11", Map.of("accountId", "11")); + + AuthenticationException ex = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapWorlds(malformedBootstrapToken)); + + assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); + } + + @Test + void listBootstrapWorldsDoesNotMaskUnexpectedJwtParserRuntimeFailure() { + JwtUtil jwtUtil = org.mockito.Mockito.mock(JwtUtil.class); + when(jwtUtil.parseToken("boom-token")).thenThrow(new IllegalStateException("boom")); + service = + new AccountServiceImpl( + accountRepository, + accountAuthorityGenerationRepository, + accountAuthoritySourceEvidenceRepository, + accountAuthorityOutboxRepository, + accountPasswordResetOperationRepository, + accountLogoutAllOperationRepository, + accountSecurityStateOperationRepository, + accountPasswordResetDraftSourceChangeRepository, + accountAuditOutboxRepository, + accountConnectScopeRepository, + accountJoinOperationRepository, + accountEmailLoginChallengeRepository, + accountRealmAccessGrantRepository, + accountTenantMembershipRepository, + Mappers.getMapper(AccountMapper.class), + profileRepository, + profileMapper, + paymentTransactionRepository, + subscriptionRepository, + externalAccountRepository, + passwordResetTokenRepository, + emailVerificationTokenRepository, + notificationService, + emailService, + mailProperties, + tokenProperties, + jwtAuthProperties, + gameSessionClient, + entityManagementClient, + jwtUtil, + sessionService, + transactionManager); + + IllegalStateException ex = + assertThrows(IllegalStateException.class, () -> service.listBootstrapWorlds("boom-token")); + + assertEquals("boom", ex.getMessage()); + } + + @Test + void listBootstrapWorldsRejectsWorldWithMalformedRuntimeRealmRow() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn( + java.util.Arrays.asList( + null, + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("broken") + .setDisplayName("Broken Realm") + .setTenantId("bad") + .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapWorlds(bootstrap.bootstrapToken())); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); + } + + @Test + void listBootstrapRealmsMapsZeroPublicAuthorityFromGameSession() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(gameSessionClient.listGameplayRealms("demo")) + .thenThrow( + new IllegalStateException( + "Gameplay realm discovery failed: invalid public realm cardinality")); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); + } + + @Test + void listBootstrapWorldsRejectsWorldWithUnknownStateScope() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("production") + .setDisplayName("Live Realm") + .setTenantId("7") + .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setRequiresCharacterSelection(false) + .setStateScope("UNKNOWN") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapWorlds(bootstrap.bootstrapToken())); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); + } + + @Test + void listBootstrapRealmsRejectsMultipleVisiblePublicRealms() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + var firstPublicRealm = gameSessionClient.listGameplayRealms("demo").getFirst(); + var secondPublicRealm = + firstPublicRealm.toBuilder() + .setRealmSlug("production-alt") + .setRealmId("57c58f36-c5ea-4aa8-8ef7-91a45e407f01") + .setGameInstanceId("45") + .build(); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn(java.util.List.of(firstPublicRealm, secondPublicRealm)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); + } + + @Test + void listBootstrapRealmsAcceptsExactlyOneVisiblePublicRealm() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + var realms = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); + + assertEquals(1, realms.size()); + assertEquals("production", realms.getFirst().realmSlug()); + } + + @Test + void bootstrapRealmDiscoveryAndDirectTextScopeIssuanceSuspendIncomingTransactions() + throws NoSuchMethodException { + Transactional listRealms = + AccountServiceImpl.class + .getMethod("listBootstrapRealms", String.class, String.class) + .getAnnotation(Transactional.class); + Transactional issueDirectTextScope = + AccountServiceImpl.class + .getMethod( + "issueDirectTextConnectScope", + DirectTextCallerContext.class, + DirectTextJoinTarget.class) + .getAnnotation(Transactional.class); + + assertNotNull(listRealms); + assertNotNull(issueDirectTextScope); + assertEquals(Propagation.NOT_SUPPORTED, listRealms.propagation()); + assertEquals(Propagation.NOT_SUPPORTED, issueDirectTextScope.propagation()); + } + + @Test + void listBootstrapRealmsDoesNotIssueScopeWhenPublicPointerBecomesPrivateBeforeFinalRead() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( + 11L, 7L, "demo", "production")) + .thenReturn(true); + + var initiallyPublic = gameSessionClient.listGameplayRealms("demo").getFirst(); + var currentlyPrivate = initiallyPublic.toBuilder().setPublicProductionRealm(false).build(); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn(java.util.List.of(initiallyPublic), java.util.List.of(currentlyPrivate)); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) + .thenReturn( + admissionPointer( + 7L, "demo", "production", "44", 17L, true, false, "SHARED", "ALLOW_NEW")); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); + org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any()); + } + + @Test + void listBootstrapRealmsDoesNotIssueScopeWhenPointerChangesDuringDiscovery() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + + var initiallyDiscovered = gameSessionClient.listGameplayRealms("demo").getFirst(); + var changedRealmId = "57c58f36-c5ea-4aa8-8ef7-91a45e407f01"; + var currentRealm = + initiallyDiscovered.toBuilder().setRealmId(changedRealmId).setPointerVersion(18L).build(); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn(java.util.List.of(initiallyDiscovered), java.util.List.of(currentRealm)); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) + .thenReturn( + admissionPointer(7L, "demo", "production", "44", 18L, true, true, "SHARED", "ALLOW_NEW") + .toBuilder() + .setRealmId(changedRealmId) + .build()); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); + org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any()); + } + + @ParameterizedTest + @ValueSource(strings = {"101", "not-a-uuid", "4C4B57D8-E3A2-48FE-9977-E7DF0FDCE901"}) + void listBootstrapRealmsRejectsNoncanonicalRealmIds(String realmId) { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("production") + .setDisplayName("Live Realm") + .setTenantId("7") + .setGameInstanceId("44") + .setRealmId(realmId) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); + } + + @Test + void issueConnectTokenRejectsMalformedConnectScopeId() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + AuthenticationException ex = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), new ConnectTokenRequest("bad", "req-err"))); + + assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); + } + + @Test + void issueConnectTokenRejectsNumericSignedConnectCarrierWithoutReplayMutation() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String numericConnectScopeId = + new JwtUtil(JWT_SECRET, 120000L) + .generateToken( + "11", + Map.ofEntries( + Map.entry("aud", "bootstrap-connect-scope"), + Map.entry("accountId", "11"), + Map.entry("tenantId", "7"), + Map.entry("realmId", REALM_ID), + Map.entry("worldSlug", "demo"), + Map.entry("realmSlug", "production"), + Map.entry("playableStateNamespaceId", PLAYABLE_STATE_NAMESPACE_ID), + Map.entry("playableStateScope", "SHARED"), + Map.entry("gameInstanceId", "44"), + Map.entry("catalogRevision", "23"), + Map.entry("pointerVersion", "17"), + Map.entry("evaluatedAt", java.time.Instant.now().toString()), + Map.entry( + "connectScopeExpiresAt", + java.time.Instant.now().plusSeconds(60).toString()), + Map.entry("jti", "numeric-account-id"))); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), + new ConnectTokenRequest(numericConnectScopeId, "req-numeric-account-id"))); + + assertEquals("CONNECT_SCOPE_INVALID", exception.getCode()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .getConnectTokenReplay( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeConnectTokenReplay( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyLong()); + } + + @Test + void issueConnectTokenRejectsBlankConnectScopeId() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + AuthenticationException ex = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), new ConnectTokenRequest(" ", "req-blank-scope"))); + + assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); + } + + @Test + void issueConnectTokenRejectsNonPositiveConnectScopeClaims() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String malformedConnectScopeId = + new JwtUtil(JWT_SECRET, 120000L) + .generateToken( + account.getAccountUuid().toString(), + Map.of( + "aud", + "bootstrap-connect-scope", + "accountId", + account.getAccountUuid().toString(), + "tenantId", + "7", + "worldSlug", + "demo", + "realmSlug", + "production", + "gameInstanceId", + "0", + "pointerVersion", + "17", + "connectScopeExpiresAt", + java.time.Instant.now().plusSeconds(3600).toString(), + "jti", + "invalid")); + + AuthenticationException ex = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), + new ConnectTokenRequest(malformedConnectScopeId, "req-err2"))); + + assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); + } + + @Test + void issueConnectTokenRejectsMalformedConnectScopeClaims() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String malformedConnectScopeId = + new JwtUtil(JWT_SECRET, 120000L) + .generateToken( + account.getAccountUuid().toString(), + Map.of( + "aud", + "bootstrap-connect-scope", + "accountId", + "abc", + "tenantId", + "7", + "worldSlug", + "demo", + "realmSlug", + "production", + "gameInstanceId", + "44", + "pointerVersion", + "17", + "connectScopeExpiresAt", + java.time.Instant.now().plusSeconds(3600).toString(), + "jti", + "invalid")); + + AuthenticationException ex = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), + new ConnectTokenRequest(malformedConnectScopeId, "req-err3"))); + + assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); + } + + @ParameterizedTest + @ValueSource(strings = {"101", "not-a-uuid", "4C4B57D8-E3A2-48FE-9977-E7DF0FDCE901"}) + void issueConnectTokenRejectsNoncanonicalRealmIdClaims(String realmId) { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String malformedConnectScopeId = + new JwtUtil(JWT_SECRET, 120000L) + .generateToken( + account.getAccountUuid().toString(), + Map.ofEntries( + Map.entry("aud", "bootstrap-connect-scope"), + Map.entry("accountId", account.getAccountUuid().toString()), + Map.entry("tenantId", "7"), + Map.entry("realmId", realmId), + Map.entry("worldSlug", "demo"), + Map.entry("realmSlug", "production"), + Map.entry("playableStateNamespaceId", PLAYABLE_STATE_NAMESPACE_ID), + Map.entry("playableStateScope", "SHARED"), + Map.entry("gameInstanceId", "44"), + Map.entry("catalogRevision", "23"), + Map.entry("pointerVersion", "17"), + Map.entry("evaluatedAt", java.time.Instant.now().toString()), + Map.entry( + "connectScopeExpiresAt", + java.time.Instant.now().plusSeconds(3600).toString()), + Map.entry("jti", "invalid-realm-id"))); + + AuthenticationException ex = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), + new ConnectTokenRequest(malformedConnectScopeId, "req-invalid-realm-id"))); + + assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); + verifyNoInteractions(accountConnectScopeRepository); + } + + @Test + void issueConnectTokenRejectsConnectScopeAccountSubjectMismatch() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String malformedConnectScopeId = + new JwtUtil(JWT_SECRET, 120000L) + .generateToken( + "4d3e9d15-a02e-41db-8648-0d2c68d0f0a3", + Map.of( + "aud", + "bootstrap-connect-scope", + "accountId", + account.getAccountUuid().toString(), + "tenantId", + "7", + "worldSlug", + "demo", + "realmSlug", + "production", + "gameInstanceId", + "44", + "pointerVersion", + "17", + "connectScopeExpiresAt", + java.time.Instant.now().plusSeconds(3600).toString(), + "jti", + "invalid")); + + AuthenticationException ex = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), + new ConnectTokenRequest(malformedConnectScopeId, "req-subject-mismatch"))); + + assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); + } + + @Test + void issueConnectTokenRejectsBlankWorldSlugConnectScopeClaims() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String malformedConnectScopeId = + new JwtUtil(JWT_SECRET, 120000L) + .generateToken( + account.getAccountUuid().toString(), + Map.of( + "aud", + "bootstrap-connect-scope", + "accountId", + account.getAccountUuid().toString(), + "tenantId", + "7", + "worldSlug", + " ", + "realmSlug", + "production", + "gameInstanceId", + "44", + "pointerVersion", + "17", + "connectScopeExpiresAt", + java.time.Instant.now().plusSeconds(3600).toString(), + "jti", + "invalid")); + + AuthenticationException ex = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), + new ConnectTokenRequest(malformedConnectScopeId, "req-err4"))); + + assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); + } + + @Test + void issueConnectTokenRejectsZeroPointerVersionInConnectScopeClaims() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String malformedConnectScopeId = + new JwtUtil(JWT_SECRET, 120000L) + .generateToken( + account.getAccountUuid().toString(), + Map.of( + "aud", + "bootstrap-connect-scope", + "accountId", + account.getAccountUuid().toString(), + "tenantId", + "7", + "worldSlug", + "demo", + "realmSlug", + "production", + "gameInstanceId", + "44", + "pointerVersion", + "0", + "connectScopeExpiresAt", + java.time.Instant.now().plusSeconds(3600).toString(), + "jti", + "invalid")); + + AuthenticationException ex = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), + new ConnectTokenRequest(malformedConnectScopeId, "req-err5"))); + + assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); + } + + @Test + void authenticateForGameplayUsesNormalizedEmailLookup() { + Account account = new Account(); + account.setId(1L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setEmail("demo@example.com"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); + + AuthenticationResult result = + service.authenticateForGameplay(" DEMO@example.com ", "password"); + + assertNotNull(result.authToken()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession(1L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); + verifyNoInteractions(accountTenantMembershipRepository); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) + .findByUsername(org.mockito.ArgumentMatchers.anyString()); + } + + @Test + void authenticateThrowsWhenInvalid() { + when(accountRepository.findByEmail("demo")).thenReturn(Optional.empty()); + AuthenticationException exception = + assertThrows( + AuthenticationException.class, () -> service.authenticateForGameplay("demo", "bad")); + assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, exception.getCode()); + } + + @Test + void authenticateDoesNotUseGlobalAccountFallback() { + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.empty()); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.authenticateForGameplay("demo@example.com", "password")); + + assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, exception.getCode()); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) + .findByUsername(org.mockito.ArgumentMatchers.anyString()); + } + + @Test + void authenticateAllowsGlobalIdentityWithoutTenantMembership() { + Account account = new Account(); + account.setId(7L); + setPersistedAuthenticationIdentity(account); + account.setEmail("demo@example.com"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); + AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "password"); + + assertEquals(account.getAccountUuid().toString(), result.accountId()); + assertNotNull(result.authToken()); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession(7L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); + verifyNoInteractions(accountTenantMembershipRepository); + } + + @Test + void getTenantMembershipForRuntimeReturnsAdmissionAllowedForExistingAccount() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setEmail("demo@example.com"); + account.setPasswordHash(hash("password")); + AccountTenantMembership activeMembership = membership(account, 7L); + activeMembership.setMembershipVersion(17L); + activeMembership.setMembershipAuthorityGeneration(29L); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(activeMembership)); + + var dto = service.getTenantMembershipForRuntime(11L, 7L, "req-1"); + + assertEquals(11L, dto.accountId()); + assertEquals(7L, dto.tenantId()); + assertTrue(dto.membershipExists()); + assertTrue(dto.gameplayAdmissionAllowed()); + assertEquals(17L, dto.membershipVersion()); + assertEquals("ACTIVE", dto.membershipLifecycleState()); + assertEquals(29L, dto.membershipAuthorityGeneration()); + assertNotNull(dto.evaluatedAt()); + } + + @Test + void getTenantMembershipForRuntimeReturnsCoherentMissingMembershipForExistingAccount() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setEmail("demo@example.com"); + account.setPasswordHash(hash("password")); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.empty()); + + var dto = service.getTenantMembershipForRuntime(11L, 7L, "req-1"); + + assertEquals(11L, dto.accountId()); + assertEquals(7L, dto.tenantId()); + assertFalse(dto.membershipExists()); + assertFalse(dto.gameplayAdmissionAllowed()); + assertEquals(0L, dto.membershipVersion()); + assertEquals("MISSING", dto.membershipLifecycleState()); + assertEquals(0L, dto.membershipAuthorityGeneration()); + assertNotNull(dto.evaluatedAt()); + } + + @Test + void getTenantMembershipForRuntimeReturnsInactiveMembershipWithIndependentGenerations() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = - new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); - challenge.setId(3L); - challenge.setAccountId(9L); - challenge.setCodeHash(hash("123456")); - challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); - when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); - when(accountEmailLoginChallengeRepository.findByAccountId(9L)) - .thenReturn(Optional.of(challenge)); - when(accountEmailLoginChallengeRepository.save(challenge)).thenReturn(challenge); + AccountTenantMembership inactiveMembership = membership(account, 7L); + inactiveMembership.setGameplayAdmissionAllowed(false); + inactiveMembership.setLifecycleState("INACTIVE"); + inactiveMembership.setMembershipVersion(23L); + inactiveMembership.setMembershipAuthorityGeneration(41L); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(inactiveMembership)); + + var dto = service.getTenantMembershipForRuntime(11L, 7L, "req-1"); + + assertEquals(11L, dto.accountId()); + assertEquals(7L, dto.tenantId()); + assertTrue(dto.membershipExists()); + assertFalse(dto.gameplayAdmissionAllowed()); + assertEquals(23L, dto.membershipVersion()); + assertEquals("INACTIVE", dto.membershipLifecycleState()); + assertEquals(41L, dto.membershipAuthorityGeneration()); + assertNotNull(dto.evaluatedAt()); + } + + @Test + void getTenantMembershipForRuntimeRejectsMissingAccount() { + when(accountRepository.findById(11L)).thenReturn(Optional.empty()); + + assertThrows( + IllegalArgumentException.class, + () -> service.getTenantMembershipForRuntime(11L, 7L, "req-1")); + } + + @ParameterizedTest + @CsvSource({ + "active,true,true", + "trialing,true,true", + "past_due,true,true", + "grace,true,false", + "canceled,false,false", + "unknown,false,false" + }) + void getTenantEntitlementsForRuntimeUsesCurrentSubscriptions( + String status, boolean gameplayAvailable, boolean allowPublicJoin) { + Subscription active = new Subscription(); + active.setId(31L); + active.setTenantId(7L); + active.setStatus(status); + active.setEntitlementVersion(9L); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + + var dto = service.getTenantEntitlementsForRuntime(7L, "req-2"); + + assertEquals(7L, dto.tenantId()); + assertEquals(gameplayAvailable, dto.gameplayAvailable()); + assertEquals(allowPublicJoin, dto.allowPublicJoin()); + assertEquals(9L, dto.entitlementVersion()); + assertEquals(9L, dto.tenantBillingSequence()); + assertNotNull(dto.evaluatedAt()); + } + + @Test + void getTenantEntitlementsForRuntimeTreatsMissingSubscriptionAsUnavailable() { + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of()); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.getTenantEntitlementsForRuntime(7L, "req-missing-entitlement")); + + assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + } + + @Test + void getTenantEntitlementsForRuntimeTreatsMixedSubscriptionRowsAsUnavailable() { + Subscription active = new Subscription(); + active.setId(31L); + active.setTenantId(7L); + active.setStatus("active"); + Subscription canceled = new Subscription(); + canceled.setId(32L); + canceled.setTenantId(7L); + canceled.setStatus("canceled"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active, canceled)); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.getTenantEntitlementsForRuntime(7L, "req-ambiguous-entitlement")); + + assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + } + + @Test + void issueDirectTextConnectScopeRejectsUnavailableEntitlementWithoutRetainingScope() { + Account account = directTextAccount(); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of()); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.issueDirectTextConnectScope(directTextCaller(), directTextTarget())); + + assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + } + + @ParameterizedTest + @ValueSource(strings = {"", " "}) + void issueDirectTextConnectScopeRejectsBlankRequestIdBeforeAuthorityOrScopeWork( + String requestId) { + DirectTextCallerContext caller = + new DirectTextCallerContext( + 11L, + 7L, + UUID.fromString(REALM_ID), + PLAYABLE_STATE_NAMESPACE_ID, + "SHARED", + 44L, + "session-1", + requestId); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.issueDirectTextConnectScope(caller, directTextTarget())); + + assertEquals("CONNECT_SCOPE_INVALID", exception.getCode()); + verifyNoInteractions(accountRepository, subscriptionRepository, accountConnectScopeRepository); + } + + @Test + void issueDirectTextConnectScopeRejectsBillingBlockedEntitlementWithoutRetainingScope() { + Account account = directTextAccount(); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + Subscription canceled = new Subscription(); + canceled.setId(31L); + canceled.setTenantId(7L); + canceled.setStatus("canceled"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(canceled)); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.issueDirectTextConnectScope(directTextCaller(), directTextTarget())); + + assertEquals("TENANT_BILLING_BLOCKED", exception.getCode()); + assertEquals("Gameplay is not available for this tenant", exception.getMessage()); + org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + } + + @Test + void issueDirectTextConnectScopeRetainsScopeForActiveEntitlement() { + Account account = directTextAccount(); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + + DirectTextJoinScope result = + service.issueDirectTextConnectScope(directTextCaller(), directTextTarget()); + + var claims = jwtUtil.parseToken(result.connectScopeId()).getPayload(); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); + assertNotNull(result.connectScopeId()); + assertNotNull(result.connectScopeExpiresAt()); + assertEquals(result.evaluatedAt(), claims.get("evaluatedAt", String.class)); + var retained = org.mockito.ArgumentCaptor.forClass(VerifiedJoinScope.class); + org.mockito.Mockito.verify(accountConnectScopeRepository).insert(retained.capture()); + assertEquals(result.evaluatedAt(), retained.getValue().evaluatedAt()); + assertEquals(result.connectScopeExpiresAt(), retained.getValue().connectScopeExpiresAt()); + } + + @Test + void graceAllowsDirectScopeDiscoveryWithoutPublicJoinAuthority() { + Account account = directTextAccount(); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + Subscription grace = new Subscription(); + grace.setTenantId(7L); + grace.setStatus("grace"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(List.of(grace)); + + var entitlement = service.getTenantEntitlementsForRuntime(7L, "grace-discovery"); + DirectTextJoinScope scope = + service.issueDirectTextConnectScope(directTextCaller(), directTextTarget()); + + assertTrue(entitlement.gameplayAvailable()); + assertFalse(entitlement.allowPublicJoin()); + assertNotNull(scope.connectScopeId()); + org.mockito.Mockito.verify(accountConnectScopeRepository) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + verifyNoInteractions( + accountJoinOperationRepository, + accountTenantMembershipRepository, + accountAuditOutboxRepository); + } + + @Test + void bothScopeProducersBindPersistedUuidWhileRetainedRowsKeepPrivateAccountKey() { + Account account = directTextAccount(); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String browser = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + String direct = + service + .issueDirectTextConnectScope(directTextCaller(), directTextTarget()) + .connectScopeId(); + for (String token : java.util.List.of(browser, direct)) { + var claims = jwtUtil.parseToken(token).getPayload(); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); + AuthenticationException held = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), new ConnectTokenRequest(token, "held-proof"))); + assertEquals("AUTH_UNAVAILABLE", held.getCode()); + } + var retained = org.mockito.ArgumentCaptor.forClass(VerifiedJoinScope.class); + org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.times(2)) + .insert(retained.capture()); + for (VerifiedJoinScope row : retained.getAllValues()) { + assertEquals(11L, row.accountId()); + assertEquals( + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.scope(row), + row.snapshotDigest()); + } + } + + @Test + void scopeReaderOwnerFailureIsUnavailableAndNumericScopesNeverReachOwnerLookup() { + Account account = directTextAccount(); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + String scope = + service + .issueDirectTextConnectScope(directTextCaller(), directTextTarget()) + .connectScopeId(); + var decoded = new java.util.HashMap(jwtUtil.parseToken(scope).getPayload()); + decoded.remove("iat"); + decoded.remove("exp"); + decoded.put("sub", "11"); + decoded.put("accountId", "11"); + String numeric = new JwtUtil(JWT_SECRET, 120000L).generateToken("11", decoded); + org.mockito.Mockito.clearInvocations(accountRepository); + AuthenticationException invalid = + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProductionFromGameSession( + directTextCaller(), + new JoinPublicProductionRequest(numeric, directTextCaller().requestId()))); + assertEquals("CONNECT_SCOPE_INVALID", invalid.getCode()); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) + .findByAccountUuid(org.mockito.ArgumentMatchers.any()); + when(accountRepository.findByAccountUuid(account.getAccountUuid())) + .thenThrow( + new org.springframework.dao.DataAccessResourceFailureException("private detail")); + AuthenticationException unavailable = + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProductionFromGameSession( + directTextCaller(), + new JoinPublicProductionRequest(scope, directTextCaller().requestId()))); + assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); + } + + @ParameterizedTest + @EnumSource(UnavailableEntitlement.class) + void runtimeAndDirectScopeTreatUnsafeEntitlementAsUnavailable(UnavailableEntitlement failure) { + when(subscriptionRepository.findByTenantId(7L)).thenAnswer(invocation -> failure.rows()); AuthenticationException exception = assertThrows( AuthenticationException.class, - () -> service.authenticateForGameplay("demo@example.com", "wrong")); + () -> service.getTenantEntitlementsForRuntime(7L, "req-entitlement-store-failure")); - assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, exception.getCode()); - assertEquals(1, challenge.getInvalidAttemptCount()); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).save(challenge); - verifyNoInteractions(sessionService); + assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + assertSame(failure.cause, exception.getCause()); + + Account account = directTextAccount(); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + AuthenticationException scopeFailure = + assertThrows( + AuthenticationException.class, + () -> service.issueDirectTextConnectScope(directTextCaller(), directTextTarget())); + assertEquals("ENTITLEMENT_UNAVAILABLE", scopeFailure.getCode()); + assertSame(failure.cause, scopeFailure.getCause()); + org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); + } + + @ParameterizedTest + @ValueSource(strings = {"mapping", "configuration"}) + void runtimeAndDirectScopePropagateEntitlementProgrammingFaults(String fault) { + RuntimeException cause = entitlementProgrammingFault(fault); + when(subscriptionRepository.findByTenantId(7L)).thenThrow(cause); + + assertSame( + cause, + assertThrows( + cause.getClass(), () -> service.getTenantEntitlementsForRuntime(7L, "req-fault"))); + Account account = directTextAccount(); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + assertSame( + cause, + assertThrows( + cause.getClass(), + () -> service.issueDirectTextConnectScope(directTextCaller(), directTextTarget()))); + org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); } @Test - void passwordOnlyAccountsDoNotIssueEmailLoginChallenges() { + void issueConnectTokenFailsClosedBeforeLegacyIssuanceOrReplayState() { + ConnectScopeFixture fixture = prepareConnectScopeForIssue(); + org.mockito.Mockito.clearInvocations( + sessionService, + accountTenantMembershipRepository, + gameSessionClient, + subscriptionRepository); + + AuthenticationException unavailable = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + fixture.bootstrapToken(), + new ConnectTokenRequest(fixture.connectScopeId(), "req-unavailable"))); + + assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); + assertNoLegacyConnectTokenEffects(); + } + + @Test + void issueConnectTokenDoesNotReturnCachedLegacySuccess() { + ConnectScopeFixture fixture = prepareConnectScopeForIssue(); + org.mockito.Mockito.clearInvocations( + sessionService, + accountTenantMembershipRepository, + gameSessionClient, + subscriptionRepository); + ConnectTokenResult cachedLegacySuccess = + new ConnectTokenResult( + 11L, + 7L, + 44L, + "production", + fixture.connectScopeId(), + "legacy-hmac-connect-token", + "legacy-jti", + "req-cached-success", + "2026-10-14T00:00:00Z", + "2026-10-14T00:00:30Z", + false); + when(sessionService.getConnectTokenReplay( + 7L, 11L, fixture.connectScopeId(), "req-cached-success")) + .thenReturn( + Optional.of(new SessionService.ConnectTokenReplay(true, cachedLegacySuccess, "", ""))); + + AuthenticationException unavailable = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + fixture.bootstrapToken(), + new ConnectTokenRequest(fixture.connectScopeId(), "req-cached-success"))); + + assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); + assertNoLegacyConnectTokenEffects(); + } + + private ConnectScopeFixture prepareConnectScopeForIssue() { Account account = new Account(); - account.setId(9L); - account.setEmail("verified@example.com"); - account.setEmailVerified(true); - account.setLoginAuthModes("PASSWORD"); - when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + return new ConnectScopeFixture(bootstrap.bootstrapToken(), connectScopeId); + } - service.requestEmailLoginOtp("verified@example.com"); + private void assertNoLegacyConnectTokenEffects() { + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .getConnectTokenReplay( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeConnectTokenReplay( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(SessionService.ConnectTokenReplay.class), + org.mockito.ArgumentMatchers.anyLong()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeSession( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong()); + verifyNoInteractions(accountTenantMembershipRepository); + org.mockito.Mockito.verify(gameSessionClient, org.mockito.Mockito.never()) + .getAdmissionPointer( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.never()) + .findByTenantId(org.mockito.ArgumentMatchers.anyLong()); + } - verifyNoInteractions( - accountTenantMembershipRepository, accountEmailLoginChallengeRepository, emailService); + private record ConnectScopeFixture(String bootstrapToken, String connectScopeId) {} + + @Test + void listBootstrapCharactersUsesEntityManagementForResolvedRealm() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + net.firedevops.firemud.entitymanagement.v1.Character character = + net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() + .setId("char-1") + .setName("Mara") + .setLevel(12) + .build(); + when(entityManagementClient.listCharactersByAccount( + 7L, account.getAccountUuid(), 44L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn(java.util.List.of(character)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + + var characters = + service.listBootstrapCharacters( + bootstrap.bootstrapToken(), "demo", "production", connectScopeId); + + assertEquals(1, characters.size()); + assertEquals("char-1", characters.getFirst().characterId()); + assertEquals("Mara", characters.getFirst().characterName()); + assertEquals("SHARED", characters.getFirst().stateScope()); + assertEquals("ALLOW_NEW", characters.getFirst().characterCreationPolicy()); + org.mockito.Mockito.verify(entityManagementClient) + .listCharactersByAccount( + 7L, account.getAccountUuid(), 44L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); } @ParameterizedTest - @EnumSource(AccountIdentityProvenance.class) - void gameplayAuthenticationAcceptsEveryRecognizedPersistedUuidProvenance( - AccountIdentityProvenance provenance) { + @CsvSource({"false", "true"}) + void listBootstrapCharactersDistinguishesMissingAndNonAdmittingMembership( + boolean membershipExists) { Account account = new Account(); - account.setId(31L); - account.setEmail("retained@example.com"); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); account.setPasswordHash(hash("password")); - setPersistedAuthenticationIdentity(account, provenance); - when(accountRepository.findByEmail("retained@example.com")).thenReturn(Optional.of(account)); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + if (membershipExists) { + AccountTenantMembership membership = membership(account, 7L); + membership.setGameplayAdmissionAllowed(false); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership)); + } else { + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.empty()); + } + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); - AuthenticationResult result = - service.authenticateForGameplay("retained@example.com", "password"); - var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - assertEquals(account.getAccountUuid().toString(), result.accountId()); - assertEquals(account.getAccountUuid().toString(), claims.getSubject()); - assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); - assertFalse(claims.containsKey("tenantId")); - org.mockito.Mockito.verify(sessionService) - .storeAccountSession(31L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.listBootstrapCharacters( + bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); + + if (membershipExists) { + assertEquals("CONNECT_TOKEN_REJECTED", exception.getCode()); + assertEquals("Gameplay admission is not allowed for this account", exception.getMessage()); + } else { + assertEquals("JOIN_REQUIRED", exception.getCode()); + assertEquals("Join the selected world before discovering characters", exception.getMessage()); + } + verifyNoInteractions(entityManagementClient); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .saveAndFlush(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + } + + @Test + void listBootstrapCharactersChecksPublicJoinPolicyBeforeReturningJoinRequired() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + Subscription grace = new Subscription(); + grace.setId(22L); + grace.setTenantId(7L); + grace.setStatus("grace"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(grace)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.listBootstrapCharacters( + bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); + + assertEquals("PUBLIC_PRODUCTION_ADMISSION_DENIED", exception.getCode()); + org.mockito.InOrder order = + org.mockito.Mockito.inOrder(subscriptionRepository, accountTenantMembershipRepository); + order.verify(subscriptionRepository, org.mockito.Mockito.times(2)).findByTenantId(7L); + order.verify(accountTenantMembershipRepository).findByAccountIdAndTenantId(11L, 7L); + verifyNoInteractions(entityManagementClient); } @ParameterizedTest - @EnumSource(InvalidAuthenticationIdentity.class) - void gameplayAuthenticationRejectsUnprovedIdentityBeforeConsumingOtpOrMinting( - InvalidAuthenticationIdentity invalidIdentity) { + @CsvSource({"active, JOIN_REQUIRED", "grace, PUBLIC_PRODUCTION_ADMISSION_DENIED"}) + void listBootstrapCharactersClassifiesInactivePublicMembershipByJoinPolicy( + String subscriptionStatus, String expectedCode) { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + AccountTenantMembership inactiveMembership = membership(account, 7L); + inactiveMembership.setLifecycleState("INACTIVE"); + inactiveMembership.setGameplayAdmissionAllowed(false); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(inactiveMembership)); + Subscription subscription = new Subscription(); + subscription.setId(22L); + subscription.setTenantId(7L); + subscription.setStatus(subscriptionStatus); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(subscription)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.listBootstrapCharacters( + bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); + + assertEquals(expectedCode, exception.getCode()); + if ("JOIN_REQUIRED".equals(expectedCode)) { + assertEquals("Join the selected world before discovering characters", exception.getMessage()); + } else { + assertEquals("Public joining is not allowed for the selected game", exception.getMessage()); + } + verifyNoInteractions(entityManagementClient); + } + + @Test + void listBootstrapCharactersKeepsSelectedTargetFailClosedWhenEntitlementsAreUnavailable() { Account account = new Account(); - account.setId(32L); - account.setEmail("unproved@example.com"); - assignInvalidAuthenticationIdentity(account, invalidIdentity); - var challenge = new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); - challenge.setId(8L); - challenge.setAccountId(32L); - challenge.setCodeHash(hash("123456")); - challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); - when(accountRepository.findByEmail("unproved@example.com")).thenReturn(Optional.of(account)); - when(accountEmailLoginChallengeRepository.findByAccountId(32L)) - .thenReturn(Optional.of(challenge)); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)) + .thenReturn(java.util.List.of(active), java.util.List.of()); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - AuthenticationException unavailable = + AuthenticationException exception = assertThrows( AuthenticationException.class, - () -> service.authenticateForGameplay("unproved@example.com", "123456")); - assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); + () -> + service.listBootstrapCharacters( + bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(32L); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).findByAccountId(32L); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) - .delete(challenge); - verifyNoInteractions(sessionService); + assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) + .findByTenantId(7L); + verifyNoInteractions(accountTenantMembershipRepository, entityManagementClient); } @Test - void emailLoginOtpVerificationFailsClosedForUnknownEmail() { - when(accountRepository.findByEmail("unknown@example.com")).thenReturn(Optional.empty()); + void listBootstrapCharactersDoesNotUsePublicJoinForPrivateMembershipLostAfterDiscovery() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L)), Optional.empty()); + when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( + 11L, 7L, "demo", "production")) + .thenReturn(true); + var privateRealm = + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("production") + .setDisplayName("Private Realm") + .setTenantId("7") + .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(false) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build(); + when(gameSessionClient.listGameplayRealms("demo")).thenReturn(java.util.List.of(privateRealm)); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) + .thenReturn( + net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() + .setWorldSlug("demo") + .setWorldDisplayName("Demo World") + .setRealmSlug("production") + .setRealmDisplayName("Private Realm") + .setTenantId("7") + .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(false) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build()); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); AuthenticationException exception = assertThrows( AuthenticationException.class, - () -> service.verifyEmailLoginOtp("unknown@example.com", "123456")); + () -> + service.listBootstrapCharacters( + bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); - assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, exception.getCode()); - verifyNoInteractions(accountEmailLoginChallengeRepository, sessionService); + assertEquals("NON_PUBLIC_ENROLLMENT_REQUIRED", exception.getCode()); + assertEquals( + "Existing game membership is required for this non-public realm", exception.getMessage()); + verifyNoInteractions(entityManagementClient); } @Test - void emailLoginOtpVerificationLocksChallengeBeforeConsumingIt() { + void listBootstrapCharactersRejectsAmbiguousRealmBeforeAdmissionFiltering() { Account account = new Account(); - account.setId(9L); + account.setId(11L); setPersistedAuthenticationIdentity(account); - account.setEmail("verified@example.com"); - account.setRole("player"); - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = - new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); - challenge.setId(5L); - challenge.setAccountId(9L); - challenge.setCodeHash(hash("123456")); - challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(10)); - challenge.setInvalidAttemptCount(0); - when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); - when(accountEmailLoginChallengeRepository.findByAccountId(9L)) - .thenReturn(Optional.of(challenge)); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + var visibleRealm = + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("production") + .setDisplayName("Live Realm") + .setTenantId("7") + .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build(); + var hiddenDuplicate = + visibleRealm.toBuilder().setVisible(false).setPublicProductionRealm(false).build(); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn(java.util.List.of(visibleRealm, hiddenDuplicate)); + + AuthenticationException ex = + assertThrows( + AuthenticationException.class, + () -> + service.listBootstrapCharacters( + bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); - AuthenticationResult result = service.verifyEmailLoginOtp("verified@example.com", "123456"); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", ex.getCode()); + verifyNoInteractions(entityManagementClient); + } - assertEquals(account.getAccountUuid().toString(), result.accountId()); - var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); - assertEquals("account-service", claims.getAudience().iterator().next()); - assertEquals(account.getAccountUuid().toString(), claims.getSubject()); - assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); - org.mockito.InOrder inOrder = org.mockito.Mockito.inOrder(accountEmailLoginChallengeRepository); - inOrder.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(9L); - inOrder.verify(accountEmailLoginChallengeRepository).findByAccountId(9L); - inOrder.verify(accountEmailLoginChallengeRepository).delete(challenge); + @Test + void listBootstrapCharactersSkipsMalformedUnrelatedRealm() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + var visibleRealm = + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("production") + .setDisplayName("Live Realm") + .setTenantId("7") + .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build(); + var malformedUnrelatedRealm = + visibleRealm.toBuilder().setRealmSlug("broken").setTenantId("bad").build(); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn(java.util.List.of(malformedUnrelatedRealm, visibleRealm)); + + var characters = + service.listBootstrapCharacters( + bootstrap.bootstrapToken(), "demo", "production", connectScopeId); + + assertTrue(characters.isEmpty()); } @Test - void authenticateReturnsControlUiTokenWithoutGameplayMembership() { + void listBootstrapRealmsIncludesRealmStatePolicy() { Account account = new Account(); - account.setId(1L); + account.setId(11L); setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); - AuthenticationResult result = service.authenticate("demo", "password"); + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - assertNotNull(result.authToken()); - assertEquals(account.getAccountUuid().toString(), result.accountId()); - var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); - assertEquals("control-ui", claims.getAudience().iterator().next()); - assertEquals(account.getAccountUuid().toString(), claims.getSubject()); - assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); - assertEquals(java.util.List.of(), claims.get("globalRoles")); - assertNotNull(claims.get("jti")); - assertFalse(claims.containsKey("tenantId")); - org.mockito.Mockito.verify(sessionService) - .storeAccountSession(1L, result.authToken(), 3600000L); - verifyNoInteractions(accountTenantMembershipRepository); + var realms = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); + + assertEquals(1, realms.size()); + assertEquals(REALM_ID, realms.getFirst().realmId()); + var scopeClaims = + new JwtUtil(JWT_SECRET, 300000L) + .parseToken(realms.getFirst().connectScopeId()) + .getPayload(); + assertEquals(account.getAccountUuid().toString(), scopeClaims.getSubject()); + assertEquals(account.getAccountUuid().toString(), scopeClaims.get("accountId", String.class)); + assertEquals( + REALM_ID, + new JwtUtil(JWT_SECRET, 300000L) + .parseToken(realms.getFirst().connectScopeId()) + .getPayload() + .get("realmId")); + assertEquals("SHARED", realms.getFirst().stateScope()); + assertEquals(23L, realms.getFirst().catalogRevision()); + assertEquals(PLAYABLE_STATE_NAMESPACE_ID, realms.getFirst().playableStateNamespaceId()); + assertEquals("PLAYABLE_STATE_SCOPE_SHARED", realms.getFirst().playableStateScope()); + assertEquals("ALLOW_NEW", realms.getFirst().characterCreationPolicy()); } @ParameterizedTest - @CsvSource({ - "SECURITY_LOCKED, AUTH_ACCOUNT_LOCKED", - "DEACTIVATED_PENDING_DELETE, AUTH_INVALID_CREDENTIALS", - "DELETED, AUTH_INVALID_CREDENTIALS" - }) - void authenticateRejectsIneligibleLifecycleState( - AccountLifecycleState lifecycleState, String expectedCode) { + @ValueSource( + strings = { + "shared-live", + "C6ED6A44-C7E7-4F18-81FC-078A74E67C07", + "c6ed6a44c7e74f1881fc078a74e67c07" + }) + void listBootstrapRealmsRejectsNoncanonicalPlayableStateNamespaceIdFromReachableRealm( + String namespaceId) { Account account = new Account(); - account.setId(1L); + account.setId(11L); setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); - account.setLifecycleState(lifecycleState); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("production") + .setDisplayName("Live Realm") + .setTenantId("7") + .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(namespaceId) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); AuthenticationException exception = - assertThrows(AuthenticationException.class, () -> service.authenticate("demo", "password")); + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); - assertEquals(expectedCode, exception.getCode()); - verifyNoInteractions(sessionService); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); + verifyNoInteractions(accountConnectScopeRepository); } @Test - void authenticateForGameplayReturnsTokenWhenPasswordMatches() { + void listBootstrapRealmsReadsFreshEntitlementsAndReusesVerifiedAccountIdentity() { Account account = new Account(); - account.setId(1L); + account.setId(11L); setPersistedAuthenticationIdentity(account); - account.setEmail("demo@example.com"); + account.setUsername("demo"); account.setPasswordHash(hash("password")); - when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); - jwtAuthProperties.setJwtSecret(null); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("production") + .setDisplayName("Live Realm") + .setTenantId("7") + .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build(), + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("preview") + .setDisplayName("Private Preview Realm") + .setTenantId("7") + .setGameInstanceId("45") + .setRealmId("ce814357-64ad-44e8-b004-828a9ae37c13") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(18L) + .setVisible(true) + .setPublicProductionRealm(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( + 11L, 7L, "demo", "preview")) + .thenReturn(true); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "preview")) + .thenReturn( + net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() + .setWorldSlug("demo") + .setWorldDisplayName("Demo World") + .setRealmSlug("preview") + .setRealmDisplayName("Private Preview Realm") + .setTenantId("7") + .setGameInstanceId("45") + .setRealmId("ce814357-64ad-44e8-b004-828a9ae37c13") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(18L) + .setVisible(true) + .setPublicProductionRealm(false) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build()); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + var firstCall = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(1)) + .findByTenantId(7L); + org.mockito.Mockito.clearInvocations(accountRepository); + var secondCall = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); + + assertEquals(2, firstCall.size()); + assertEquals(2, secondCall.size()); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) + .findByTenantId(7L); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.times(1 + secondCall.size())) + .findByAccountUuid(account.getAccountUuid()); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()).findById(11L); + JwtUtil tokenReader = new JwtUtil(JWT_SECRET, 3600000L); + for (var realm : secondCall) { + var claims = tokenReader.parseToken(realm.connectScopeId()).getPayload(); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); + } + } - AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "password"); + @Test + void listBootstrapWorldsReadsFreshEntitlementsOncePerTenantPerInvocation() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(gameSessionClient.listGameplayWorlds()) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() + .setWorldSlug("demo") + .setDisplayName("Demo World") + .build(), + net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() + .setWorldSlug("sandbox") + .setDisplayName("Sandbox World") + .build())); + when(gameSessionClient.listGameplayRealms("sandbox")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("sandbox") + .setRealmSlug("production") + .setDisplayName("Sandbox Realm") + .setTenantId("7") + .setGameInstanceId("45") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(18L) + .setVisible(true) + .setPublicProductionRealm(true) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + var firstCall = service.listBootstrapWorlds(bootstrap.bootstrapToken()); + var secondCall = service.listBootstrapWorlds(bootstrap.bootstrapToken()); + + assertEquals(2, firstCall.size()); + assertEquals(2, secondCall.size()); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) + .findByTenantId(7L); + } - assertNotNull(result.authToken()); - assertEquals(account.getAccountUuid().toString(), result.accountId()); - var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); - assertEquals("account-service", claims.getAudience().iterator().next()); - assertEquals(account.getAccountUuid().toString(), claims.getSubject()); - assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); - assertEquals(java.util.List.of(), claims.get("globalRoles")); - assertNotNull(claims.get("jti")); - org.mockito.Mockito.verify(sessionService) - .storeAccountSession(1L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); - verifyNoInteractions(accountTenantMembershipRepository); + @Test + void listBootstrapWorldsOmitsCanceledTenantAndFailsWhenEntitlementIsUnavailable() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + Subscription activeDemo = new Subscription(); + activeDemo.setId(1L); + activeDemo.setTenantId(7L); + activeDemo.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(activeDemo)); + when(gameSessionClient.listGameplayWorlds()) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() + .setWorldSlug("demo") + .setDisplayName("Demo World") + .build(), + net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() + .setWorldSlug("sandbox") + .setDisplayName("Sandbox World") + .build())); + when(gameSessionClient.listGameplayRealms("sandbox")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("sandbox") + .setRealmSlug("production") + .setDisplayName("Sandbox Realm") + .setTenantId("8") + .setGameInstanceId("45") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID_TENANT_8) + .setCatalogRevision(23L) + .setPointerVersion(18L) + .setVisible(true) + .setPublicProductionRealm(true) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + Subscription canceledSandbox = new Subscription(); + canceledSandbox.setId(2L); + canceledSandbox.setTenantId(8L); + canceledSandbox.setStatus("canceled"); + when(subscriptionRepository.findByTenantId(8L)).thenReturn(java.util.List.of(canceledSandbox)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + var worldsWithCanceledTenant = service.listBootstrapWorlds(bootstrap.bootstrapToken()); + + assertEquals( + java.util.List.of("demo"), + worldsWithCanceledTenant.stream().map(world -> world.worldSlug()).toList()); + + when(subscriptionRepository.findByTenantId(8L)).thenReturn(java.util.List.of()); + AuthenticationException unavailableSandbox = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapWorlds(bootstrap.bootstrapToken())); + + assertEquals("ENTITLEMENT_UNAVAILABLE", unavailableSandbox.getCode()); + + Subscription activeSandbox = new Subscription(); + activeSandbox.setId(3L); + activeSandbox.setTenantId(8L); + activeSandbox.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of()); + when(subscriptionRepository.findByTenantId(8L)).thenReturn(java.util.List.of(activeSandbox)); + + AuthenticationException unavailable = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapWorlds(bootstrap.bootstrapToken())); + + assertEquals("ENTITLEMENT_UNAVAILABLE", unavailable.getCode()); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(3)) + .findByTenantId(7L); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) + .findByTenantId(8L); } @Test - void issuePlayerBootstrapReturnsShortLivedToken() { + void listBootstrapRealmsPropagatesUnavailableEntitlements() { Account account = new Account(); - account.setId(7L); + account.setId(11L); setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); - account.setLoginAuthModes("PASSWORD"); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - jwtAuthProperties.setJwtSecret(null); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of()); - PlayerBootstrapResult result = service.issuePlayerBootstrap("demo", "password"); + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - assertEquals(account.getAccountUuid().toString(), result.accountId()); - assertNotNull(result.bootstrapToken()); - assertNotNull(result.issuedAt()); - assertNotNull(result.expiresAt()); - org.mockito.Mockito.verify(sessionService) - .storeAccountSession( - org.mockito.ArgumentMatchers.eq(7L), - org.mockito.ArgumentMatchers.eq(result.bootstrapToken()), - org.mockito.ArgumentMatchers.eq(300000L)); - var claims = new JwtUtil(JWT_SECRET, 300000L).parseToken(result.bootstrapToken()).getPayload(); - assertEquals("player-bootstrap", claims.getAudience().iterator().next()); - assertEquals(account.getAccountUuid().toString(), claims.getSubject()); - assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); - assertFalse(claims.containsKey("tenantId")); - assertEquals(300000L, claims.getExpiration().getTime() - claims.getIssuedAt().getTime()); - org.mockito.Mockito.verify(accountRepository).findByAccountUuid(account.getAccountUuid()); - org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) - .isAccountSessionActive( - org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyString()); - verifyNoInteractions(accountEmailLoginChallengeRepository); + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + + assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); } - @ParameterizedTest - @EnumSource(InvalidAuthenticationIdentity.class) - void issuePlayerBootstrapRejectsUnprovedIdentityBeforeConsumingOtpOrMinting( - InvalidAuthenticationIdentity invalidIdentity) { + @Test + void listBootstrapWorldsFailsInsteadOfReturningIncompleteWorldDiscovery() { Account account = new Account(); - account.setId(50L); + account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); - account.setLoginAuthModes("EMAIL_OTP"); - assignInvalidAuthenticationIdentity(account, invalidIdentity); - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = - new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); - challenge.setAccountId(50L); - challenge.setCodeHash(hash("123456")); - challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); + account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountEmailLoginChallengeRepository.findByAccountId(50L)) - .thenReturn(Optional.of(challenge)); + when(gameSessionClient.listGameplayWorlds()) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() + .setWorldSlug("demo") + .setDisplayName("Demo World") + .build(), + net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() + .setWorldSlug("sandbox") + .setDisplayName("Sandbox World") + .build())); + when(gameSessionClient.listGameplayRealms("sandbox")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("sandbox") + .setRealmSlug("production") + .setDisplayName("Sandbox Realm") + .setTenantId("8") + .setGameInstanceId("45") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID_TENANT_8) + .setCatalogRevision(23L) + .setPointerVersion(18L) + .setVisible(true) + .setPublicProductionRealm(true) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of()); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); AuthenticationException unavailable = assertThrows( - AuthenticationException.class, () -> service.issuePlayerBootstrap("demo", "123456")); - assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); + AuthenticationException.class, + () -> service.listBootstrapWorlds(bootstrap.bootstrapToken())); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(50L); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).findByAccountId(50L); - org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) - .delete(challenge); - verifyNoInteractions(sessionService); + assertEquals("ENTITLEMENT_UNAVAILABLE", unavailable.getCode()); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(1)) + .findByTenantId(7L); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.never()) + .findByTenantId(8L); + } + + @Test + void listBootstrapRealmsRethrowsOtherAuthenticationErrors() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("preview") + .setDisplayName("Private Preview Realm") + .setTenantId("7") + .setGameInstanceId("45") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(18L) + .setVisible(true) + .setPublicProductionRealm(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + AuthenticationException authorityError = + new AuthenticationException("AUTH_UNAVAILABLE", "Membership authority is unavailable"); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenThrow(authorityError); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + + assertEquals("AUTH_UNAVAILABLE", exception.getCode()); } @Test - void issuePlayerBootstrapPrefersEmailLookupOverCollidingUsername() { - Account emailAccount = new Account(); - emailAccount.setId(7L); - setPersistedAuthenticationIdentity(emailAccount); - emailAccount.setUsername("email-owner"); - emailAccount.setEmail("player@example.com"); - emailAccount.setPasswordHash(hash("password")); - emailAccount.setLoginAuthModes("PASSWORD"); - when(accountRepository.findByEmail("player@example.com")).thenReturn(Optional.of(emailAccount)); + void listBootstrapRealmsRejectsRealmWithMalformedTenantId() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("broken") + .setDisplayName("Broken Realm") + .setTenantId("bad") + .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build(), + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("production") + .setDisplayName("Live Realm") + .setTenantId("7") + .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - PlayerBootstrapResult result = - service.issuePlayerBootstrap(" PLAYER@EXAMPLE.COM ", "password"); + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); - assertEquals(emailAccount.getAccountUuid().toString(), result.accountId()); - org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) - .findByUsername(org.mockito.ArgumentMatchers.anyString()); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); } @Test - void issuePlayerBootstrapAcceptsAndConsumesEmailLoginOtp() { + void listBootstrapRealmsRejectsRealmWithUnknownStateScope() { Account account = new Account(); - account.setId(7L); + account.setId(11L); setPersistedAuthenticationIdentity(account); account.setUsername("demo"); - account.setEmail("demo@example.com"); - account.setLoginAuthModes("EMAIL_OTP"); - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = - new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); - challenge.setAccountId(7L); - challenge.setCodeHash(hash("123456")); - challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); + account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - when(accountEmailLoginChallengeRepository.findByAccountId(7L)) - .thenReturn(Optional.of(challenge)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("production") + .setDisplayName("Live Realm") + .setTenantId("7") + .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setRequiresCharacterSelection(false) + .setStateScope("UNKNOWN") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - PlayerBootstrapResult result = service.issuePlayerBootstrap("demo", "123456"); + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); - assertEquals(account.getAccountUuid().toString(), result.accountId()); - org.mockito.InOrder inOrder = org.mockito.Mockito.inOrder(accountEmailLoginChallengeRepository); - inOrder.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(7L); - inOrder.verify(accountEmailLoginChallengeRepository).findByAccountId(7L); - inOrder.verify(accountEmailLoginChallengeRepository).delete(challenge); - org.mockito.Mockito.verify(sessionService) - .storeAccountSession(7L, result.bootstrapToken(), 300000L); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); } @Test - void authenticateForGameplayUsesNormalizedEmailLookup() { + void listBootstrapCharactersUsesIsolatedRealmRoster() { Account account = new Account(); - account.setId(1L); + account.setId(11L); setPersistedAuthenticationIdentity(account); account.setUsername("demo"); - account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); - when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); - - AuthenticationResult result = - service.authenticateForGameplay(" DEMO@example.com ", "password"); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); - assertNotNull(result.authToken()); - assertEquals(account.getAccountUuid().toString(), result.accountId()); - org.mockito.Mockito.verify(sessionService) - .storeAccountSession(1L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); - verifyNoInteractions(accountTenantMembershipRepository); - org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) - .findByUsername(org.mockito.ArgumentMatchers.anyString()); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("production") + .setDisplayName("Live Realm") + .setTenantId("7") + .setGameInstanceId("91") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setRequiresCharacterSelection(false) + .setStateScope("ISOLATED") + .setCharacterCreationPolicy("COPIED_ONLY") + .build())); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) + .thenReturn( + net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() + .setWorldSlug("demo") + .setWorldDisplayName("Demo World") + .setRealmSlug("production") + .setRealmDisplayName("Live Realm") + .setTenantId("7") + .setGameInstanceId("91") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setRequiresCharacterSelection(false) + .setStateScope("ISOLATED") + .setCharacterCreationPolicy("COPIED_ONLY") + .build()); + net.firedevops.firemud.entitymanagement.v1.Character character = + net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() + .setId("char-iso-1") + .setName("ForkMara") + .setLevel(4) + .build(); + when(entityManagementClient.listCharactersByAccount( + 7L, account.getAccountUuid(), 91L, PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) + .thenReturn(java.util.List.of(character)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + + var characters = + service.listBootstrapCharacters( + bootstrap.bootstrapToken(), "demo", "production", connectScopeId); + + assertEquals(1, characters.size()); + assertEquals("char-iso-1", characters.getFirst().characterId()); + assertEquals("ForkMara", characters.getFirst().characterName()); + assertEquals("ISOLATED", characters.getFirst().stateScope()); + assertEquals("COPIED_ONLY", characters.getFirst().characterCreationPolicy()); } @Test - void authenticateThrowsWhenInvalid() { - when(accountRepository.findByEmail("demo")).thenReturn(Optional.empty()); - AuthenticationException exception = + void listBootstrapCharactersRejectsAdmissionPointerWithMalformedGameInstanceId() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) + .thenReturn( + admissionPointer( + 7L, "demo", "production", "44", 17L, true, true, "SHARED", "ALLOW_NEW"), + net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() + .setWorldSlug("demo") + .setWorldDisplayName("Demo World") + .setRealmSlug("production") + .setRealmDisplayName("Live Realm") + .setTenantId("7") + .setGameInstanceId("bad") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build()); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + + AuthenticationException ex = assertThrows( - AuthenticationException.class, () -> service.authenticateForGameplay("demo", "bad")); - assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, exception.getCode()); + AuthenticationException.class, + () -> + service.listBootstrapCharacters( + bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", ex.getCode()); + org.mockito.Mockito.verifyNoInteractions(entityManagementClient); } @Test - void authenticateDoesNotUseGlobalAccountFallback() { - when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.empty()); + void listBootstrapCharactersRejectsAdmissionPointerWithUnknownStateScope() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) + .thenReturn( + admissionPointer( + 7L, "demo", "production", "44", 17L, true, true, "SHARED", "ALLOW_NEW"), + net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() + .setWorldSlug("demo") + .setWorldDisplayName("Demo World") + .setRealmSlug("production") + .setRealmDisplayName("Live Realm") + .setTenantId("7") + .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setRequiresCharacterSelection(false) + .setStateScope("UNKNOWN") + .setCharacterCreationPolicy("ALLOW_NEW") + .build()); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); AuthenticationException exception = assertThrows( AuthenticationException.class, - () -> service.authenticateForGameplay("demo@example.com", "password")); + () -> + service.listBootstrapCharacters( + bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); - assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, exception.getCode()); - org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) - .findByUsername(org.mockito.ArgumentMatchers.anyString()); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); + verifyNoInteractions(entityManagementClient); } @Test - void authenticateAllowsGlobalIdentityWithoutTenantMembership() { + void listBootstrapCharactersUsesWorldQualifiedPointerLookupWhenRealmSlugDuplicatesAcrossWorlds() { Account account = new Account(); - account.setId(7L); + account.setId(11L); setPersistedAuthenticationIdentity(account); - account.setEmail("demo@example.com"); + account.setUsername("demo"); account.setPasswordHash(hash("password")); - when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); - AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "password"); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); - assertEquals(account.getAccountUuid().toString(), result.accountId()); - assertNotNull(result.authToken()); - org.mockito.Mockito.verify(sessionService) - .storeAccountSession(7L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); - verifyNoInteractions(accountTenantMembershipRepository); + when(gameSessionClient.listGameplayRealms("sandbox")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("sandbox") + .setRealmSlug("production") + .setDisplayName("Live Realm") + .setTenantId("7") + .setGameInstanceId("91") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setRequiresCharacterSelection(false) + .setStateScope("ISOLATED") + .setCharacterCreationPolicy("COPIED_ONLY") + .build())); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) + .thenReturn( + net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() + .setWorldSlug("demo") + .setWorldDisplayName("Demo World") + .setRealmSlug("production") + .setRealmDisplayName("Live Realm") + .setTenantId("7") + .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build()); + when(gameSessionClient.getAdmissionPointer(7L, "sandbox", "production")) + .thenReturn( + net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() + .setWorldSlug("sandbox") + .setWorldDisplayName("Builder Sandbox") + .setRealmSlug("production") + .setRealmDisplayName("Live Realm") + .setTenantId("7") + .setGameInstanceId("91") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setRequiresCharacterSelection(false) + .setStateScope("ISOLATED") + .setCharacterCreationPolicy("COPIED_ONLY") + .build()); + net.firedevops.firemud.entitymanagement.v1.Character character = + net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() + .setId("char-sandbox-1") + .setName("BuilderMara") + .setLevel(9) + .build(); + when(entityManagementClient.listCharactersByAccount( + 7L, account.getAccountUuid(), 91L, PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) + .thenReturn(java.util.List.of(character)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service + .listBootstrapRealms(bootstrap.bootstrapToken(), "sandbox") + .getFirst() + .connectScopeId(); + + var characters = + service.listBootstrapCharacters( + bootstrap.bootstrapToken(), "sandbox", "production", connectScopeId); + + assertEquals(1, characters.size()); + assertEquals("char-sandbox-1", characters.getFirst().characterId()); + assertEquals("BuilderMara", characters.getFirst().characterName()); + assertEquals("ISOLATED", characters.getFirst().stateScope()); + org.mockito.Mockito.verify(gameSessionClient, org.mockito.Mockito.times(2)) + .getAdmissionPointer(7L, "sandbox", "production"); } @Test - void getTenantMembershipForRuntimeReturnsAdmissionAllowedForExistingAccount() { + void listBootstrapCharactersUsesSignedScopeToDisambiguateTenantIdentity() { Account account = new Account(); account.setId(11L); setPersistedAuthenticationIdentity(account); account.setUsername("demo"); - account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); - AccountTenantMembership activeMembership = membership(account, 7L); - activeMembership.setMembershipVersion(17L); - activeMembership.setMembershipAuthorityGeneration(29L); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyLong())) + .thenReturn(Optional.of(membership(account, 7L))); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("production") + .setDisplayName("Tenant Seven") + .setTenantId("7") + .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build(), + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("production") + .setDisplayName("Tenant Eight") + .setTenantId("8") + .setGameInstanceId("45") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID_TENANT_8) + .setCatalogRevision(23L) + .setPointerVersion(18L) + .setVisible(true) + .setPublicProductionRealm(true) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) + .thenReturn( + admissionPointer( + 7L, "demo", "production", "44", 17L, true, true, "SHARED", "ALLOW_NEW")); + when(gameSessionClient.getAdmissionPointer(8L, "demo", "production")) + .thenReturn( + admissionPointer( + 8L, "demo", "production", "45", 18L, true, true, "SHARED", "ALLOW_NEW")); + when(entityManagementClient.listCharactersByAccount( + 7L, account.getAccountUuid(), 44L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn(java.util.List.of()); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").stream() + .filter(realm -> realm.tenantId() == 7L) + .findFirst() + .orElseThrow() + .connectScopeId(); + + var characters = + service.listBootstrapCharacters( + bootstrap.bootstrapToken(), "demo", "production", connectScopeId); + + assertTrue(characters.isEmpty()); + org.mockito.Mockito.verify(gameSessionClient, org.mockito.Mockito.times(2)) + .getAdmissionPointer(7L, "demo", "production"); + org.mockito.Mockito.verify(gameSessionClient).getAdmissionPointer(8L, "demo", "production"); + } + + @Test + void listBootstrapCharactersRejectsPathThatDoesNotMatchSignedScope() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(activeMembership)); + .thenReturn(Optional.of(membership(account, 7L))); - var dto = service.getTenantMembershipForRuntime(11L, 7L, "req-1"); + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); - assertEquals(11L, dto.accountId()); - assertEquals(7L, dto.tenantId()); - assertTrue(dto.membershipExists()); - assertTrue(dto.gameplayAdmissionAllowed()); - assertEquals(17L, dto.membershipVersion()); - assertEquals("ACTIVE", dto.membershipLifecycleState()); - assertEquals(29L, dto.membershipAuthorityGeneration()); - assertNotNull(dto.evaluatedAt()); + AuthenticationException ex = + assertThrows( + AuthenticationException.class, + () -> + service.listBootstrapCharacters( + bootstrap.bootstrapToken(), "sandbox", "production", connectScopeId)); + + assertEquals("CONNECT_SCOPE_MISMATCH", ex.getCode()); + verifyNoInteractions(entityManagementClient); } @Test - void getTenantMembershipForRuntimeReturnsCoherentMissingMembershipForExistingAccount() { + void listBootstrapCharactersRejectsChangedCanonicalRealmId() { Account account = new Account(); account.setId(11L); setPersistedAuthenticationIdentity(account); account.setUsername("demo"); - account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.empty()); - - var dto = service.getTenantMembershipForRuntime(11L, 7L, "req-1"); + .thenReturn(Optional.of(membership(account, 7L))); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + net.firedevops.firemud.gamesession.v1.GameplayRealm changedRealm = + gameSessionClient.listGameplayRealms("demo").getFirst().toBuilder() + .setRealmId("57c58f36-c5ea-4aa8-8ef7-91a45e407f01") + .build(); + when(gameSessionClient.listGameplayRealms("demo")).thenReturn(java.util.List.of(changedRealm)); + net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer changedAdmissionPointer = + gameSessionClient.getAdmissionPointer(7L, "demo", "production").toBuilder() + .setRealmId("57c58f36-c5ea-4aa8-8ef7-91a45e407f01") + .build(); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) + .thenReturn(changedAdmissionPointer); + + AuthenticationException ex = + assertThrows( + AuthenticationException.class, + () -> + service.listBootstrapCharacters( + bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); - assertEquals(11L, dto.accountId()); - assertEquals(7L, dto.tenantId()); - assertFalse(dto.membershipExists()); - assertFalse(dto.gameplayAdmissionAllowed()); - assertEquals(0L, dto.membershipVersion()); - assertEquals("MISSING", dto.membershipLifecycleState()); - assertEquals(0L, dto.membershipAuthorityGeneration()); - assertNotNull(dto.evaluatedAt()); + assertEquals("CONNECT_SCOPE_MISMATCH", ex.getCode()); + verifyNoInteractions(entityManagementClient); } @Test - void getTenantMembershipForRuntimeReturnsInactiveMembershipWithIndependentGenerations() { + void listBootstrapRealmsExcludesNonPublicRealmWithoutGrant() { Account account = new Account(); account.setId(11L); setPersistedAuthenticationIdentity(account); account.setUsername("demo"); - account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); - AccountTenantMembership inactiveMembership = membership(account, 7L); - inactiveMembership.setGameplayAdmissionAllowed(false); - inactiveMembership.setLifecycleState("INACTIVE"); - inactiveMembership.setMembershipVersion(23L); - inactiveMembership.setMembershipAuthorityGeneration(41L); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(inactiveMembership)); + .thenReturn(Optional.empty()); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("preview") + .setDisplayName("Preview Realm") + .setTenantId("7") + .setGameInstanceId("55") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(19L) + .setVisible(false) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "preview")) + .thenReturn( + admissionPointer( + 7L, "demo", "preview", "55", 19L, false, false, "SHARED", "ALLOW_NEW")); - var dto = service.getTenantMembershipForRuntime(11L, 7L, "req-1"); + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - assertEquals(11L, dto.accountId()); - assertEquals(7L, dto.tenantId()); - assertTrue(dto.membershipExists()); - assertFalse(dto.gameplayAdmissionAllowed()); - assertEquals(23L, dto.membershipVersion()); - assertEquals("INACTIVE", dto.membershipLifecycleState()); - assertEquals(41L, dto.membershipAuthorityGeneration()); - assertNotNull(dto.evaluatedAt()); + var realms = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); + + assertEquals(0, realms.size()); } - @Test - void getTenantMembershipForRuntimeRejectsMissingAccount() { - when(accountRepository.findById(11L)).thenReturn(Optional.empty()); + @ParameterizedTest + @CsvSource({"true, false", "false, true"}) + void listBootstrapRealmsExcludesNonPublicRealmWithoutMembershipEvenWithGrant( + boolean visible, boolean publicProductionRealm) { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.empty()); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("preview") + .setDisplayName("Preview Realm") + .setTenantId("7") + .setGameInstanceId("55") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(19L) + .setVisible(visible) + .setPublicProductionRealm(publicProductionRealm) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "preview")) + .thenReturn( + net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() + .setWorldSlug("demo") + .setWorldDisplayName("Demo World") + .setRealmSlug("preview") + .setRealmDisplayName("Preview Realm") + .setTenantId("7") + .setGameInstanceId("55") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(19L) + .setVisible(visible) + .setPublicProductionRealm(publicProductionRealm) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build()); + when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( + 11L, 7L, "demo", "preview")) + .thenReturn(true); - assertThrows( - IllegalArgumentException.class, - () -> service.getTenantMembershipForRuntime(11L, 7L, "req-1")); + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + assertTrue(service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").isEmpty()); } - @Test - void getTenantEntitlementsForRuntimeFailsClosedBeforeReadingLegacyEvidence() { - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.getTenantEntitlementsForRuntime(7L, "req-current-entitlement")); + @ParameterizedTest + @CsvSource({"true, false", "false, true"}) + void listBootstrapRealmsIncludesNonPublicRealmWhenMembershipAndGrantPresent( + boolean visible, boolean publicProductionRealm) { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("preview") + .setDisplayName("Preview Realm") + .setTenantId("7") + .setGameInstanceId("55") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(23L) + .setPointerVersion(19L) + .setVisible(visible) + .setPublicProductionRealm(publicProductionRealm) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "preview")) + .thenReturn( + admissionPointer( + 7L, + "demo", + "preview", + "55", + 19L, + visible, + publicProductionRealm, + "SHARED", + "ALLOW_NEW")); + when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( + 11L, 7L, "demo", "preview")) + .thenReturn(true); - assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); - verifyNoInteractions(retainedSubscriptionEvidenceRepository); + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + var realms = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); + + assertEquals(1, realms.size()); + assertEquals("preview", realms.getFirst().realmSlug()); + assertFalse(realms.getFirst().connectScopeId().isBlank()); } @Test @@ -1722,37 +6262,29 @@ void exportTenantDataUsesPublicAccountUuidAndRetainsTenantLocalFields() { void deleteAccountRefusesNonterminalSubscription() { Account account = new Account(); account.setId(2L); - RetainedSubscriptionEvidence subscription = - new RetainedSubscriptionEvidence( - 91L, 2L, "unqualified", "active", null, null, 7L, 19L, UUID.randomUUID()); + Subscription subscription = new Subscription(); + subscription.setStatus("active"); + subscription.setAccount(account); + subscription.setTenantId(7L); when(accountRepository.findById(2L)).thenReturn(Optional.of(account)); - when(retainedSubscriptionEvidenceRepository.findHistoryByAccountId(2L)) - .thenReturn(java.util.List.of(subscription)); + when(subscriptionRepository.findByAccountId(2L)).thenReturn(java.util.List.of(subscription)); AccountLifecycleException ex = assertThrows(AccountLifecycleException.class, () -> service.deleteAccount(2L)); assertEquals("ACCOUNT_DELETE_ACTIVE_BILLING_OWNER", ex.getCode()); - org.mockito.Mockito.verify(retainedSubscriptionEvidenceRepository).findHistoryByAccountId(2L); } @Test void deleteAccountRemainsUnavailableAfterTerminalSubscriptionsWithoutChildWrites() { Account account = new Account(); account.setId(2L); - RetainedSubscriptionEvidence subscription = - new RetainedSubscriptionEvidence( - 91L, - 2L, - "unqualified", - "canceled", - null, - java.time.LocalDateTime.now(), - 7L, - 19L, - UUID.randomUUID()); + Subscription subscription = new Subscription(); + subscription.setStatus("canceled"); + subscription.setEndedAt(java.time.LocalDateTime.now()); + subscription.setAccount(account); + subscription.setTenantId(7L); when(accountRepository.findById(2L)).thenReturn(Optional.of(account)); - when(retainedSubscriptionEvidenceRepository.findHistoryByAccountId(2L)) - .thenReturn(java.util.List.of(subscription)); + when(subscriptionRepository.findByAccountId(2L)).thenReturn(java.util.List.of(subscription)); AccountLifecycleException ex = assertThrows(AccountLifecycleException.class, () -> service.deleteAccount(2L)); @@ -1766,7 +6298,9 @@ void deleteAccountRemainsUnavailableAfterTerminalSubscriptionsWithoutChildWrites paymentTransactionRepository, profileRepository, accountTenantMembershipRepository); - org.mockito.Mockito.verify(retainedSubscriptionEvidenceRepository).findHistoryByAccountId(2L); + org.mockito.Mockito.verify(subscriptionRepository).findByAccountId(2L); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.never()) + .deleteByAccountId(2L); org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()).delete(account); } @@ -2380,6 +6914,14 @@ void updateLoginAuthModesFailsClosedBeforeReadingOrPersistingAccount() { org.mockito.Mockito.verifyNoInteractions(accountRepository); } + private Account directTextAccount() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + return account; + } + private void setPersistedAuthenticationIdentity(Account account) { setPersistedAuthenticationIdentity( account, AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); @@ -2415,6 +6957,31 @@ private enum InvalidAuthenticationIdentity { CONTRADICTORY_SOURCE_ROW } + private static DirectTextCallerContext directTextCaller() { + return new DirectTextCallerContext( + 11L, + 7L, + UUID.fromString(REALM_ID), + PLAYABLE_STATE_NAMESPACE_ID, + "SHARED", + 44L, + "session-1", + "direct-text-request-1"); + } + + private static DirectTextJoinTarget directTextTarget() { + return new DirectTextJoinTarget( + 7L, + UUID.fromString(REALM_ID), + "demo", + "production", + PLAYABLE_STATE_NAMESPACE_ID, + "SHARED", + 44L, + 23L, + 17L); + } + private static String hash(String password) { Argon2 argon2 = Argon2Factory.create(); char[] chars = password.toCharArray(); @@ -2425,6 +6992,47 @@ private static String hash(String password) { } } + private static net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer admissionPointer( + long tenantId, + String worldSlug, + String realmSlug, + String gameInstanceId, + long pointerVersion, + boolean visible, + boolean publicProductionRealm, + String stateScope, + String characterCreationPolicy) { + return net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() + .setWorldSlug(worldSlug) + .setWorldDisplayName("demo".equals(worldSlug) ? "Demo World" : "Builder Sandbox") + .setRealmSlug(realmSlug) + .setRealmDisplayName("production".equals(realmSlug) ? "Live Realm" : "Preview Realm") + .setTenantId(Long.toString(tenantId)) + .setGameInstanceId(gameInstanceId) + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(playableStateNamespaceIdForTenant(tenantId)) + .setCatalogRevision(23L) + .setPointerVersion(pointerVersion) + .setVisible(visible) + .setPublicProductionRealm(publicProductionRealm) + .setRequiresCharacterSelection(false) + .setStateScope(stateScope) + .setCharacterCreationPolicy(characterCreationPolicy) + .build(); + } + + private static String playableStateNamespaceIdForTenant(long tenantId) { + return switch ((int) tenantId) { + case 7 -> PLAYABLE_STATE_NAMESPACE_ID; + case 8 -> PLAYABLE_STATE_NAMESPACE_ID_TENANT_8; + default -> + UUID.nameUUIDFromBytes( + ("playable-state-namespace-" + tenantId) + .getBytes(java.nio.charset.StandardCharsets.UTF_8)) + .toString(); + }; + } + private static AccountTenantMembership membership(Account account, long tenantId) { AccountTenantMembership membership = new AccountTenantMembership(); membership.setId(tenantId * 100 + (account.getId() == null ? 0L : account.getId())); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/LegacySubscriptionContainmentTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/LegacySubscriptionContainmentTest.java deleted file mode 100644 index a7236525c6..0000000000 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/LegacySubscriptionContainmentTest.java +++ /dev/null @@ -1,175 +0,0 @@ -package net.firedevops.firemud.accountservice.service.impl; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; - -import io.grpc.Context; -import io.grpc.stub.StreamObserver; -import java.lang.reflect.Modifier; -import java.time.LocalDateTime; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicReference; -import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeRequest; -import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; -import net.firedevops.firemud.accountservice.entity.Account; -import net.firedevops.firemud.accountservice.entity.RetainedSubscriptionEvidence; -import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; -import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; -import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; -import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; -import net.firedevops.firemud.accountservice.repository.AccountRepository; -import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; -import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; -import net.firedevops.firemud.accountservice.service.exception.AccountLifecycleException; -import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.CsvSource; -import org.junit.jupiter.params.provider.ValueSource; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.springframework.transaction.PlatformTransactionManager; - -/** - * Local containment only; canonical positive producer and admission remain separate obligations. - */ -class LegacySubscriptionContainmentTest { - @Mock private AccountRepository accounts; - @Mock private AccountJoinOperationRepository joins; - @Mock private RetainedSubscriptionEvidenceRepository retained; - @Mock private AccountAuthorityOutboxRepository outbox; - @Mock private AccountPasswordResetOperationRepository resets; - @Mock private AccountLogoutAllOperationRepository logouts; - @Mock private AccountSecurityStateOperationRepository security; - @Mock private PlatformTransactionManager transactions; - @InjectMocks private AccountServiceImpl service; - private AutoCloseable mocks; - - @BeforeEach - void setUp() { - mocks = MockitoAnnotations.openMocks(this); - } - - @AfterEach - void tearDown() throws Exception { - mocks.close(); - } - - @ParameterizedTest - @ValueSource(strings = {"active", "trialing", "past_due", "grace", "canceled"}) - void retainedStatusAndCountersCannotProduceAPositiveServiceOrRuntimeRpc(String status) { - when(retained.findHistoryByAccountId(2L)).thenReturn(List.of(evidence(status, null))); - - AuthenticationException denied = - assertThrows( - AuthenticationException.class, - () -> service.getTenantEntitlementsForRuntime(7L, "retained-is-not-authority")); - assertThat(denied.getCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); - - AccountGrpcService rpc = new AccountGrpcService(null, service, null, "test"); - AtomicReference response = new AtomicReference<>(); - var observer = - new StreamObserver() { - @Override - public void onNext(GetTenantEntitlementsForRuntimeResponse value) { - response.set(value); - } - - @Override - public void onError(Throwable failure) { - throw new AssertionError( - "Expected the existing response-level unavailable outcome", failure); - } - - @Override - public void onCompleted() {} - }; - for (String workload : List.of("game-session-service", "world-management-service")) { - Context context = - Context.ROOT.withValue( - GrpcPeerIdentity.CONTEXT_KEY, - new GrpcPeerIdentity("spiffe://firemud/ns/test/sa/" + workload, "test", workload)); - context.run( - () -> - rpc.getTenantEntitlementsForRuntime( - GetTenantEntitlementsForRuntimeRequest.newBuilder() - .setTenantId("7") - .setRequestId("retained-is-not-authority") - .build(), - observer)); - assertThat(response.get()).isNotNull(); - assertThat(response.get().getError().getCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); - assertThat(response.get().getGameplayAvailable()).isFalse(); - assertThat(response.get().getAllowPublicJoin()).isFalse(); - assertThat(response.get().getEntitlementVersion()).isZero(); - assertThat(response.get().getTenantBillingSequence()).isZero(); - assertThat(response.get().getEvaluatedAt()).isEmpty(); - } - verifyNoInteractions( - retained, accounts, joins, outbox, resets, logouts, security, transactions); - } - - @ParameterizedTest - @CsvSource({ - "active,false,ACCOUNT_DELETE_ACTIVE_BILLING_OWNER", - "canceled,false,ACCOUNT_DELETE_ACTIVE_BILLING_OWNER", - "canceled,true,ACCOUNT_DELETE_UNAVAILABLE", - "expired,true,ACCOUNT_DELETE_UNAVAILABLE" - }) - void deletionStillReadsHistoricalBlockersAndNeverGainsErasureAuthority( - String status, boolean ended, String expectedCode) { - Account account = new Account(); - account.setId(2L); - when(accounts.findById(2L)).thenReturn(Optional.of(account)); - when(retained.findHistoryByAccountId(2L)) - .thenReturn(List.of(evidence(status, ended ? LocalDateTime.of(2025, 1, 2, 3, 4) : null))); - - AccountLifecycleException denied = - assertThrows(AccountLifecycleException.class, () -> service.deleteAccount(2L)); - - assertThat(denied.getCode()).isEqualTo(expectedCode); - verify(retained).findHistoryByAccountId(2L); - verify(joins).hasRetainedOperation(2L); - verifyNoInteractions(outbox, resets, logouts, security, transactions); - } - - @Test - void retainedJoinReceiptKeepsItsEarlierDeletionDenialBeforeHistoricalBillingReads() { - Account account = new Account(); - account.setId(2L); - when(accounts.findById(2L)).thenReturn(Optional.of(account)); - when(joins.hasRetainedOperation(2L)).thenReturn(true); - - AccountLifecycleException denied = - assertThrows(AccountLifecycleException.class, () -> service.deleteAccount(2L)); - - assertThat(denied.getCode()).isEqualTo("ACCOUNT_DELETE_JOIN_RECEIPT_RETAINED"); - verifyNoInteractions(retained, outbox, resets, logouts, security, transactions); - } - - @Test - void historicalOwnerHasNoGenericMutationOrCurrentTenantAuthorityApi() { - assertThat(RetainedSubscriptionEvidence.class.isRecord()).isTrue(); - assertThat( - Arrays.stream(RetainedSubscriptionEvidenceRepository.class.getDeclaredMethods()) - .filter(method -> Modifier.isPublic(method.getModifiers())) - .map(method -> method.getName()) - .toList()) - .containsExactly("findHistoryByAccountId"); - } - - private static RetainedSubscriptionEvidence evidence(String status, LocalDateTime ended) { - return new RetainedSubscriptionEvidence( - 91L, 2L, "unqualified", status, null, ended, 7L, 19L, UUID.randomUUID()); - } -} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierTest.java index 86c606f8ee..cde168fd95 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierTest.java @@ -39,7 +39,6 @@ import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.GameplayLoginReplayState; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; import net.firedevops.firemud.accountservice.repository.AccountRepository; -import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.accountservice.service.session.AccountGameplayCanonicalLoginOwner; @@ -108,6 +107,8 @@ class AccountGameplayPrimaryCredentialVerifierTest { net.firedevops.firemud.accountservice.service .AccountPasswordResetDraftSourceChangeRepository.class), mock(net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository.class), + mock( + net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository.class), mock( net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository .class), @@ -123,7 +124,7 @@ class AccountGameplayPrimaryCredentialVerifierTest { mock(net.firedevops.firemud.accountservice.repository.ProfileRepository.class), mock(net.firedevops.firemud.accountservice.mapper.ProfileMapper.class), mock(net.firedevops.firemud.accountservice.repository.PaymentTransactionRepository.class), - org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), + mock(net.firedevops.firemud.accountservice.repository.SubscriptionRepository.class), mock(net.firedevops.firemud.accountservice.repository.ExternalAccountRepository.class), mock(net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository.class), mock( @@ -134,6 +135,8 @@ class AccountGameplayPrimaryCredentialVerifierTest { mock(net.firedevops.firemud.accountservice.config.MailProperties.class), mock(net.firedevops.firemud.accountservice.config.AccountTokenProperties.class), mock(net.firedevops.firemud.common.security.JwtAuthProperties.class), + mock(net.firedevops.firemud.accountservice.client.GameSessionClient.class), + mock(net.firedevops.firemud.accountservice.client.EntityManagementClient.class), jwt, sessions, transactions); diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java index 14e01a13bd..34194c27cf 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java @@ -27,6 +27,7 @@ import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; /** * Genuine Account owner mutations. Fresh creator/legal sources and signer platform evidence are @@ -100,6 +101,35 @@ public AccountControlUiOriginalOrderFixture( ownedCompositionConnections); } + /** + * Test-only composition with one preselected Game Design provenance tuple shared by Account and + * World. It is imported during construction, never substituted onto existing associations. + */ + public AccountControlUiOriginalOrderFixture( + String jdbcUrl, + String username, + String password, + String redisHost, + int redisPort, + Path temporary, + FreshTenantCreationEvidence creationEvidence, + boolean ownedCompositionConnections) + throws Exception { + this( + jdbcUrl, + username, + password, + redisHost, + redisPort, + temporary, + Objects.requireNonNull(creationEvidence, "creationEvidence").canonicalTenantId(), + Clock.systemUTC(), + null, + Clock.systemUTC(), + ownedCompositionConnections, + creationEvidence); + } + /** Actor clock is injectable for genuine signed-credential expiry recovery proof. */ public AccountControlUiOriginalOrderFixture( String jdbcUrl, @@ -193,6 +223,35 @@ private AccountControlUiOriginalOrderFixture( Clock serviceClock, boolean ownedCompositionConnections) throws Exception { + this( + jdbcUrl, + username, + password, + redisHost, + redisPort, + temporary, + gameDesignTenant, + actorClock, + migrationTarget, + serviceClock, + ownedCompositionConnections, + AccountControlUiOwnerSourcesFixture.defaultCreation(gameDesignTenant)); + } + + private AccountControlUiOriginalOrderFixture( + String jdbcUrl, + String username, + String password, + String redisHost, + int redisPort, + Path temporary, + UUID gameDesignTenant, + Clock actorClock, + String migrationTarget, + Clock serviceClock, + boolean ownedCompositionConnections, + FreshTenantCreationEvidence creationEvidence) + throws Exception { this.temporary = temporary; Objects.requireNonNull(actorClock, "actorClock"); Objects.requireNonNull(serviceClock, "serviceClock"); @@ -205,7 +264,8 @@ private AccountControlUiOriginalOrderFixture( false, gameDesignTenant, migrationTarget, - ownedCompositionConnections); + ownedCompositionConnections, + creationEvidence); RedisClient allocatedClient = null; try { signerFixture = new AccountControlUiSignerFixture(f, temporary, serviceClock); @@ -235,6 +295,8 @@ private AccountControlUiOriginalOrderFixture( .on() .addPassword(PASSWORD) .keyPattern("session:auth:token:*") + .keyPattern("session:auth:generation:issuer:*") + .keyPattern("session:auth:generation:account:*") .addCommand(io.lettuce.core.protocol.CommandType.HELLO) .addCommand(io.lettuce.core.protocol.CommandType.PING) .addCommand( @@ -250,6 +312,8 @@ private AccountControlUiOriginalOrderFixture( .addCommand(io.lettuce.core.protocol.CommandType.GET) .addCommand(io.lettuce.core.protocol.CommandType.SET) .addCommand(io.lettuce.core.protocol.CommandType.PEXPIRETIME) + .addCommand(io.lettuce.core.protocol.CommandType.PTTL) + .addCommand(io.lettuce.core.protocol.CommandType.TYPE) .addCommand(io.lettuce.core.protocol.CommandType.TIME)); connection .sync() @@ -335,6 +399,16 @@ public UUID tenantId() { return f.tenant; } + /** The exact immutable source tuple imported at construction for cross-owner composition. */ + public FreshTenantCreationEvidence creationEvidence() { + return f.creationEvidence; + } + + /** Reuse the same physical test-only Account writer without resetting its ACL or credentials. */ + AccountCoordinationPinnedConnectionProvider gameplayConnectionProvider() { + return () -> accountClient.connect(ByteArrayCodec.INSTANCE); + } + /** * Real Account-owned selected Game Logic source reads over this fixture's SQL and Coordination * Redis owners; callers choose the clock and target namespace for their composition. @@ -390,29 +464,6 @@ record IssuedCreator( CapturedEnvironmentBoundary environment, AccountControlUiOwnerSourcesFixture sources) {} - /** Same-package reuse of genuine certified ACCOUNT issuance, separate from tenant creation. */ - IssuedAccount issueCertifiedAccount(String password) { - var account = f.createCertifiedGlobalAccount(password); - var request = - new AccountControlUiIssuanceService.AccountSignInRequest( - UUID.randomUUID(), account.getEmail(), password, UUID.randomUUID()); - String compact; - try (var peer = - AccountControlUiOwnerSourcesFixture.withPeer( - AccountControlUiOwnerSourcesFixture.CALLER); - var issued = issuance.issueAccount(request)) { - compact = new String(issued.compactBytes(), StandardCharsets.US_ASCII); - } - assertThat(actors.authenticateAccount(compact).accountId()).isEqualTo(account.getAccountUuid()); - return new IssuedAccount(account, compact, actors, f); - } - - record IssuedAccount( - net.firedevops.firemud.accountservice.entity.Account account, - String compact, - AccountControlUiActorService actors, - AccountControlUiOwnerSourcesFixture sources) {} - // These fixture entry points use actual Account owners with test-only creator/legal, // environment, signer-platform and Redis inputs. They confer no production authority. public net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderGrpcCodec.Request diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java index 4d33bbc4bc..db2d28a421 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java @@ -56,7 +56,6 @@ import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; -import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountCreatorMembershipSourceReader; import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapAuthorizationSource; import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapService; @@ -99,6 +98,7 @@ final class AccountControlUiOwnerSourcesFixture { final Account account; final AccountRepository accounts; final UUID tenant; + final FreshTenantCreationEvidence creationEvidence; final UUID request = UUID.randomUUID(), callerContext = UUID.randomUUID(); final AtomicReference boundary = new AtomicReference<>(testBoundary("test-production")); @@ -162,6 +162,35 @@ final class AccountControlUiOwnerSourcesFixture { String migrationTarget, boolean ownedCompositionConnections) throws Exception { + this( + jdbcUrl, + username, + password, + root, + installNegativeIssuer, + tenant, + migrationTarget, + ownedCompositionConnections, + defaultCreation(tenant)); + } + + /** Shared immutable provenance must be supplied before any Account association is created. */ + AccountControlUiOwnerSourcesFixture( + String jdbcUrl, + String username, + String password, + Path root, + boolean installNegativeIssuer, + UUID tenant, + String migrationTarget, + boolean ownedCompositionConnections, + FreshTenantCreationEvidence creationEvidence) + throws Exception { + this.creationEvidence = Objects.requireNonNull(creationEvidence, "creationEvidence"); + if (!creationEvidence.canonicalTenantId().equals(tenant)) { + throw new IllegalArgumentException( + "Shared creation evidence must identify the Account tenant"); + } if (migrationTarget != null && !HISTORICAL_MIGRATION_TARGETS.contains(migrationTarget)) { throw new IllegalArgumentException( "Only the preserved 160.1 source-retention, 1006 parent, 1007 preliminary source-read, 1009 selected-owner predecessor, or 1010 selected-publication closure predecessor is supported"); @@ -207,8 +236,9 @@ final class AccountControlUiOwnerSourcesFixture { candidate.setLoginAuthModes("EMAIL_OTP"); return accounts.save(candidate); }); - var creator = testCreation(account.getAccountUuid(), tenant); - var fresh = new FreshTenantIdentityAssociationRepository(dsl, NAMESPACE); + var creator = testCreation(account.getAccountUuid(), creationEvidence); + var fresh = + new FreshTenantIdentityAssociationRepository(dsl, creationEvidence.targetNamespace()); tx( () -> { fresh.importVerified(creator.creationEvidence()); @@ -376,6 +406,9 @@ final class AccountControlUiOwnerSourcesFixture { net.firedevops.firemud.accountservice.service .AccountPasswordResetDraftSourceChangeRepository.class), mock(AccountAuditOutboxRepository.class), + mock( + net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository + .class), mock(AccountJoinOperationRepository.class), challenges, null, // Realm grants are not used by primary authentication. @@ -384,8 +417,7 @@ final class AccountControlUiOwnerSourcesFixture { null, // Profiles are not used by primary authentication. null, // Profile mapper is not used by primary authentication. null, // Payment transactions are not used by primary authentication. - // Retained evidence is not read by primary authentication. - org.mockito.Mockito.mock(RetainedSubscriptionEvidenceRepository.class), + null, // Subscriptions are not used by primary authentication. null, // External identities are not used by primary authentication. null, // Password reset tokens are not used by primary authentication. null, // Email verification tokens are not used by primary authentication. @@ -394,6 +426,8 @@ final class AccountControlUiOwnerSourcesFixture { null, // Mail properties are not used by primary authentication. null, // Token properties are not used by primary authentication. null, // JWT auth properties are not used by primary authentication. + null, // Game Session client is not used by primary authentication. + null, // Entity Management client is not used by primary authentication. null, // JWT utility is not used by primary authentication. null, // Session service is not used by primary authentication. manager); @@ -669,26 +703,28 @@ void assertNoIssuance() { assertThat(coordinationCalls).hasValue(0); } - private static FreshTenantCreatorEvidence testCreation(UUID account, UUID tenant) { - UUID request = UUID.randomUUID(), - operation = UUID.randomUUID(), - authorization = UUID.randomUUID(); + static FreshTenantCreationEvidence defaultCreation(UUID tenant) { + UUID request = UUID.randomUUID(), operation = UUID.randomUUID(); String key = "test-only-game-row-17"; String digest = GameTenantCreationDigest.requestDigest(NAMESPACE, request, key, "Test game", null); - var creation = - new FreshTenantCreationEvidence( - 1, - NAMESPACE, - request, - operation, - digest, - tenant, - 17L, - key, - "NEW_GAME_ROW", - GameTenantCreationDigest.evidenceDigest( - NAMESPACE, request, operation, digest, tenant, 17L, key, "NEW_GAME_ROW")); + return new FreshTenantCreationEvidence( + 1, + NAMESPACE, + request, + operation, + digest, + tenant, + 17L, + key, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + NAMESPACE, request, operation, digest, tenant, 17L, key, "NEW_GAME_ROW")); + } + + private static FreshTenantCreatorEvidence testCreation( + UUID account, FreshTenantCreationEvidence creation) { + UUID authorization = UUID.randomUUID(); String authorizationDigest = "sha256:" + "8".repeat(64); return new FreshTenantCreatorEvidence( 1, diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java new file mode 100644 index 0000000000..ad28fb69a8 --- /dev/null +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java @@ -0,0 +1,523 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collection; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CopyOnWriteArrayList; +import javax.crypto.spec.SecretKeySpec; +import net.firedevops.firemud.account.v1.AuthenticateRequest; +import net.firedevops.firemud.account.v1.GameplayLoginSourceContext; +import net.firedevops.firemud.account.v1.GameplayLoginTransportClass; +import net.firedevops.firemud.accountservice.dto.CanonicalGameplayLoginRequest; +import net.firedevops.firemud.accountservice.dto.GameplayCredentialSourceContext; +import net.firedevops.firemud.accountservice.dto.InitialGameplayLoginResult; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountAuthEvidenceBundleRepository; +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.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.GameplayLoginReplayState; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountInitialGameplayLoginDisposalRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.AccountGenerationProjectionRedisScriptContribution; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCredentialRequestDigestKeySource.CredentialDigestKey; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import org.springframework.aop.framework.ProxyFactory; +import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource; +import org.springframework.transaction.interceptor.TransactionInterceptor; +import tools.jackson.databind.json.JsonMapper; + +/** + * Shared-source Account LOGIN composition for the original creator or a separate global player. SQL + * owners, primary verification, signer correspondence, encrypted response recovery, and physical + * Redis registration/projection are real; upstream creator/legal/platform evidence, key custody, + * the newly stored OTP, and the verified caller argument remain controlled inputs. + * + *

This helper borrows the original fixture's connections and does not activate runtime wiring. + * Its ACTIVE tenantAdmin creator membership remains non-admitting. LOGIN establishes global + * identity only; no positive membership, entitlement, connect scope, or PLAY authority is made. + */ +public final class AccountPlayerAdmissionSharedOwnerFixture { + private static final SecureRandom RANDOM = new SecureRandom(); + private static final int REGISTRY_BYTES = + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES; + private static final long REGISTRY_CLEANUP_MILLIS = 30_000L; + private final AccountControlUiOwnerSourcesFixture sources; + private final Account account; + private final AccountJwtJwksTrustedSource publicSource; + private final Clock clock; + private final AccountCoordinationPinnedConnectionProvider connections; + private final AccountGameplayDelegationIssuanceRepository issuance; + private final AccountAuthoritySourceEvidenceRepository authoritySources; + private final AccountGameplayDelegationAuthorityProjection projection; + private final AccountGameplayCanonicalLoginOwner login; + private final AccountGameplayPrimaryCredentialVerifier verifier; + private final AccountGameplayDelegationCommittedIssuanceOwner committedOwner; + private final AccountInitialGameplayLoginDisposalOwner disposal; + private final List ownerObservations = new CopyOnWriteArrayList<>(); + private final String otp = "shared-login-" + UUID.randomUUID(); + + public AccountPlayerAdmissionSharedOwnerFixture( + AccountControlUiOriginalOrderFixture original, Path temporary) throws Exception { + this(original, temporary, Clock.systemUTC()); + } + + public AccountPlayerAdmissionSharedOwnerFixture( + AccountControlUiOriginalOrderFixture original, Path temporary, Clock clock) throws Exception { + this(original, temporary, clock, false); + } + + static AccountPlayerAdmissionSharedOwnerFixture freshGlobalPlayer( + AccountControlUiOriginalOrderFixture original, Path temporary, Clock clock) throws Exception { + return new AccountPlayerAdmissionSharedOwnerFixture(original, temporary, clock, true); + } + + private AccountPlayerAdmissionSharedOwnerFixture( + AccountControlUiOriginalOrderFixture original, + Path temporary, + Clock clock, + boolean separateGlobalPlayer) + throws Exception { + Objects.requireNonNull(original, "Original Account owner fixture is required"); + this.clock = Objects.requireNonNull(clock, "Clock is required"); + sources = original.preparedOriginalCreator().sources(); + account = + separateGlobalPlayer + ? sources.createGlobalAccount("shared-player-" + UUID.randomUUID()) + : sources.account; + publicSource = original.publicSource; + connections = original.gameplayConnectionProvider(); + assertCreatorRemainsNonAdmitting(); + assertThat(sources.challenges.findByAccountId(account.getId())).isEmpty(); + + var generations = new AccountAuthorityGenerationRepository(sources.dsl); + var outbox = new AccountAuthorityOutboxRepository(sources.dsl); + authoritySources = + new AccountAuthoritySourceEvidenceRepository(sources.dsl, generations, outbox); + sources.tx( + () -> { + authoritySources.initializeIssuerIfAbsent(GameSessionAccountDelegationProfile.ISSUER); + return null; + }); + var bundles = new AccountAuthEvidenceBundleRepository(sources.dsl, generations, outbox); + var issuanceTarget = + new AccountGameplayDelegationIssuanceRepository(sources.dsl, authoritySources, bundles); + // Preserve MANDATORY writes and independent REQUIRES_NEW committed-proof readbacks. + var issuanceProxy = new ProxyFactory(issuanceTarget); + issuanceProxy.setProxyTargetClass(true); + issuanceProxy.addAdvice( + new TransactionInterceptor(sources.manager, new AnnotationTransactionAttributeSource())); + issuance = + observed( + AccountGameplayDelegationIssuanceRepository.class, + (AccountGameplayDelegationIssuanceRepository) + issuanceProxy.getProxy( + AccountGameplayDelegationIssuanceRepository.class.getClassLoader())); + var cryptography = + new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring(writeResponseKeyring(temporary).toString())); + var envelopes = + new AccountGameplayDelegationResponseEnvelopeRepository( + sources.dsl, authoritySources, bundles, issuance, cryptography); + var lifecycle = original.signerFixture; + var signer = + observed( + AccountGameplayDelegationSigner.class, + new AccountGameplayDelegationSigner( + issuance, + lifecycle.desired, + lifecycle.trust, + lifecycle.api, + original.publicSource, + new AccountGameplayDelegationResponseEnvelopeService(envelopes), + sources.manager, + clock, + lifecycle.privateRoot, + Path.of("current.key"), + lifecycle.publicRoot, + Path.of("jwks.json"))); + var redis = + observed( + AccountGameplayDelegationRedisClient.class, + new AccountGameplayDelegationRedisClient( + connections, + loginScriptCatalog(), + new AcknowledgementRequirements(1, 1, 5_000), + clock, + REGISTRY_BYTES, + AccountPlayerAdmissionSharedOwnerFixture.class.getClassLoader())); + projection = + observed( + AccountGameplayDelegationAuthorityProjection.class, + new AccountGameplayDelegationAuthorityProjection( + authoritySources, sources.manager, redis)); + var registry = + observed( + AccountGameplayDelegationTokenRegistry.class, + new AccountGameplayDelegationTokenRegistry( + issuance, sources.manager, redis, clock, REGISTRY_BYTES, REGISTRY_CLEANUP_MILLIS)); + disposal = + observed( + AccountInitialGameplayLoginDisposalOwner.class, + new AccountInitialGameplayLoginDisposalOwner( + observed( + AccountInitialGameplayLoginDisposalRepository.class, + new AccountInitialGameplayLoginDisposalRepository(sources.dsl)), + registry, + sources.manager)); + var commit = + observed( + AccountGameplayDelegationIssuanceCommitService.class, + new AccountGameplayDelegationIssuanceCommitService( + signer, registry, projection, issuance, sources.manager, clock)); + committedOwner = + observed( + AccountGameplayDelegationCommittedIssuanceOwner.class, + new AccountGameplayDelegationCommittedIssuanceOwner( + issuance, signer, registry, sources.manager, clock)); + var recovery = + observed( + AccountGameplayDelegationResponseRecoveryOwner.class, + new AccountGameplayDelegationResponseRecoveryOwner( + envelopes, committedOwner, sources.manager)); + verifier = + observed( + AccountGameplayPrimaryCredentialVerifier.class, + new AccountGameplayPrimaryCredentialVerifier(sources.primary)); + login = + observed( + AccountGameplayCanonicalLoginOwner.class, + new AccountGameplayCanonicalLoginOwner( + sources.accounts, + issuance, + digestKeys(clock), + commit, + recovery, + sources.manager, + clock)); + // Control-UI consumed the original challenge. Never resurrect or reuse that consumed row. + sources.installGlobalOtp(account, otp); + } + + /** Bounded stage names only; no invocation arguments, results, SQL or token material. */ + public List ownerObservations() { + return List.copyOf(ownerObservations); + } + + private T observed(Class type, T actual) { + return org.mockito.Mockito.mock( + type, + invocation -> { + String operation = type.getSimpleName() + "." + invocation.getMethod().getName(); + ownerObservations.add(operation + ":ENTER"); + try { + Object result = invocation.getMethod().invoke(actual, invocation.getArguments()); + ownerObservations.add(operation + ":OK"); + return result; + } catch (InvocationTargetException wrapped) { + Throwable failure = wrapped.getCause(); + String sqlState = + failure instanceof org.jooq.exception.DataAccessException sql + ? sql.sqlState() + : "none"; + ownerObservations.add( + operation + ":" + failure.getClass().getSimpleName() + ":" + sqlState); + throw failure; + } + }); + } + + public UUID accountId() { + return account.getAccountUuid(); + } + + public FreshTenantCreationEvidence creationEvidence() { + return sources.creationEvidence; + } + + /** The test supplies caller coordinates; the actual owner binds and consumes the fresh OTP. */ + public CanonicalGameplayLoginRequest loginRequest( + UUID requestId, GameplayCredentialSourceContext context) { + return new CanonicalGameplayLoginRequest(requestId, account.getEmail(), otp, context); + } + + /** + * Real stored OTP input for the canonical receiver; source/socket custody is caller-controlled. + */ + public AuthenticateRequest wireLoginRequest( + UUID requestId, GameplayCredentialSourceContext context) { + var request = loginRequest(requestId, context); + if (!"trusted_tcp_proxy".equals(context.transportClass())) { + throw new IllegalArgumentException("Canonical receiver requires trusted TCP Proxy context"); + } + return AuthenticateRequest.newBuilder() + .setRequestId(request.requestId().toString()) + .setEmail(account.getEmail()) + .setPassword(otp) + .setSourceContext( + GameplayLoginSourceContext.newBuilder() + .setCallerContextId(context.contextId().toString()) + .setCanonicalClientAddress(context.canonicalClientAddress()) + .setTransportClass( + GameplayLoginTransportClass.GAMEPLAY_LOGIN_TRANSPORT_CLASS_TRUSTED_TCP_PROXY)) + .build(); + } + + /** + * The caller must install the real TLS peer interceptor on its private mTLS server. Known-token + * retirement uses the same SQL/Redis owners; unqualified no-binding disposal remains PENDING. + */ + public AccountGameplayAuthenticateReceiver authenticateReceiver(String namespace) { + if (!creationEvidence().targetNamespace().equals(namespace)) { + throw new IllegalArgumentException("Receiver namespace must match the shared tenant source"); + } + return new AccountGameplayAuthenticateReceiver(login, verifier, namespace, disposal); + } + + /** Actual receipt-backed public source, not a replacement JWKS document. */ + public AccountJwtJwksTrustedSource trustedJwksSource() { + return publicSource; + } + + AccountGameplayAdmissionCallerVerifier admissionCallerVerifier() { + return new AccountGameplayAdmissionCallerVerifier(publicSource, committedOwner, clock); + } + + AccountGameplayDelegationIssuanceRepository issuanceRepository() { + return issuance; + } + + /** Direct owner invocation, not evidence of an authenticated transport or deployed caller. */ + public InitialGameplayLoginResult authenticate( + CanonicalGameplayLoginRequest request, String verifiedGameSessionWorkload) { + return login.authenticate(request, verifiedGameSessionWorkload, verifier); + } + + /** Exact SQL, active Redis, and projection readback; identity remains distinct from admission. */ + public void assertCommittedNonAdmittingLogin(InitialGameplayLoginResult result) { + assertThat(result.accountId()).isEqualTo(accountId()); + assertThat(result.profile()).isEqualTo(GameSessionAccountDelegationProfile.PROFILE); + assertCommittedNonAdmittingLogin( + result.requestId(), + result.callerContextId(), + result.tokenJti(), + result.tokenSha256(), + result.expiresAtEpochSecond()); + } + + /** Compares nonsecret receiving-client evidence to actual SQL, Redis and current sources. */ + public void assertCommittedNonAdmittingLogin( + UUID requestId, + UUID callerContextId, + UUID tokenJti, + String tokenSha256, + long expiresAtEpochSecond) { + assertThat(sources.challenges.findByAccountId(account.getId())).isEmpty(); + var replay = sources.tx(() -> issuance.readCurrentGameplayLoginReplay(requestId).orElseThrow()); + assertThat(replay.state()).isEqualTo(GameplayLoginReplayState.COMMITTED); + var committed = sources.tx(() -> issuance.readCurrentCommittedCandidate(requestId)); + assertThat(committed.identity()).isEqualTo(replay.identity()); + assertThat(committed.identity().accountId()).isEqualTo(accountId()); + assertThat(committed.identity().callerContextId()).isEqualTo(callerContextId); + assertThat(committed.identity().tokenJti()).isEqualTo(tokenJti); + assertThat(committed.tokenSha256()).isEqualTo(tokenSha256); + assertThat(committed.commitProofSha256()).isNotBlank(); + assertThat(committed.registrationLocalAofCount()).isGreaterThanOrEqualTo(1L); + assertThat(committed.registrationReplicaAofCount()).isGreaterThanOrEqualTo(1L); + assertThat(committed.registryAbsoluteExpiryMillis()) + .isEqualTo( + Math.addExact( + Math.multiplyExact(expiresAtEpochSecond, 1_000L), REGISTRY_CLEANUP_MILLIS)); + var snapshot = + sources.tx( + () -> + authoritySources.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, accountId())); + byte[][] expected = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(snapshot); + var observation = projection.observeCurrent(accountId()); + assertThat(observation.issuerGeneration()).isEqualTo(snapshot.issuer().generation()); + assertThat(observation.accountGeneration()).isEqualTo(snapshot.account().generation()); + try (var connection = connections.openPinnedConnection()) { + var commands = connection.sync(); + assertThat(commands.aclWhoami()) + .isEqualTo(AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY); + byte[] tokenKey = ascii(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX + tokenSha256); + var active = + GameSessionAccountDelegationRegistryRecord.decode(commands.get(tokenKey), REGISTRY_BYTES); + assertThat(active.state()).isEqualTo("active"); + assertThat(active.tokenHash()).isEqualTo(tokenSha256); + assertThat(active.requestId()).isEqualTo(requestId.toString()); + assertThat(commands.pexpiretime(tokenKey)) + .isEqualTo(committed.registryAbsoluteExpiryMillis()); + assertThat( + commands.get( + ascii( + AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + + GameSessionAccountDelegationProfile.ISSUER))) + .containsExactly(expected[0]); + assertThat( + commands.get( + ascii( + AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + + accountId()))) + .containsExactly(expected[1]); + } + assertCreatorRemainsNonAdmitting(); + if (!accountId().equals(sources.account.getAccountUuid())) { + sources.tx( + () -> { + var fresh = + new FreshTenantIdentityAssociationRepository( + sources.dsl, creationEvidence().targetNamespace()); + var memberships = + new AccountTenantMembershipRepository( + sources.dsl, + sources.accounts, + fresh, + new AccountMembershipPairAuthorityRepository(sources.dsl)); + assertThat(memberships.findFreshMembership(accountId(), sources.tenant)).isEmpty(); + return null; + }); + } + } + + /** Real canonical membership and role readback, with the original source tuple unchanged. */ + public void assertCreatorRemainsNonAdmitting() { + UUID creatorId = sources.account.getAccountUuid(); + sources.tx( + () -> { + var fresh = + new FreshTenantIdentityAssociationRepository( + sources.dsl, creationEvidence().targetNamespace()); + assertThat(fresh.read(sources.tenant)).contains(creationEvidence()); + var pairs = new AccountMembershipPairAuthorityRepository(sources.dsl); + var memberships = + new AccountTenantMembershipRepository(sources.dsl, sources.accounts, fresh, pairs); + var membership = memberships.findFreshMembership(creatorId, sources.tenant).orElseThrow(); + assertThat(membership.getLifecycleState()).isEqualTo("ACTIVE"); + assertThat(membership.getAuthorityProvenance()).isEqualTo("TENANT_CREATION"); + assertThat(membership.isGameplayAdmissionAllowed()).isFalse(); + var pair = pairs.readPositive(creatorId, sources.tenant).orElseThrow(); + var roles = + new AccountTenantMembershipRoleSnapshotRepository(sources.dsl) + .findForCanonicalUpdate( + creatorId, + sources.tenant, + pair.provenance(), + membership.getId(), + membership.getMembershipVersion()) + .orElseThrow(); + assertThat(roles.roles()).containsExactly("tenantAdmin"); + return null; + }); + } + + private static Path writeResponseKeyring(Path temporary) throws IOException { + Path root = + Files.createTempDirectory(Files.createDirectories(temporary), "shared-login-keyring-") + .toAbsolutePath(); + byte[] key = new byte[32]; + RANDOM.nextBytes(key); + try { + Files.writeString( + root.resolve("keyring"), + "firemud-account-response-envelope-keyring-v1\nactive shared-login " + + Base64.getUrlEncoder().withoutPadding().encodeToString(key) + + "\n", + StandardCharsets.US_ASCII); + } finally { + Arrays.fill(key, (byte) 0); + } + return root; + } + + private static AccountGameplayCredentialRequestDigestKeySource digestKeys(Clock clock) { + byte[] key = new byte[32]; + RANDOM.nextBytes(key); + CredentialDigestKey digest; + try { + digest = + new CredentialDigestKey( + "shared-login", + new SecretKeySpec(key, "HmacSHA256"), + Instant.now(clock).plusSeconds(3_600)); + } finally { + Arrays.fill(key, (byte) 0); + } + return new AccountGameplayCredentialRequestDigestKeySource() { + @Override + public CredentialDigestKey currentKey() { + return digest; + } + + @Override + public CredentialDigestKey requireKey(String keyId) { + if (!digest.keyId().equals(keyId)) { + throw new IllegalStateException("Unknown test-only LOGIN digest key"); + } + return digest; + } + }; + } + + private static RedisScriptCatalog loginScriptCatalog() throws IOException { + List descriptors = new ArrayList<>(); + var json = JsonMapper.builder().build(); + for (String resource : + List.of( + "/redis/scripts/account-game-session-delegation-pending-register.json", + "/redis/scripts/account-game-session-delegation-activate-committed.json", + "/redis/scripts/account-game-session-delegation-authority-project-issuer.json", + "/redis/scripts/account-initial-gameplay-login-dispose.json")) { + try (var input = + AccountPlayerAdmissionSharedOwnerFixture.class.getResourceAsStream(resource)) { + if (input == null) throw new IllegalStateException("Account LOGIN descriptor is absent"); + descriptors.add(json.readValue(input, RedisScriptDescriptor.class)); + } + } + return RedisScriptCatalog.fromContributions( + List.of( + new AccountGenerationProjectionRedisScriptContribution(), + new RedisScriptContribution() { + @Override + public String ownerId() { + return "account-service"; + } + + @Override + public Collection descriptors() { + return List.copyOf(descriptors); + } + })); + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java new file mode 100644 index 0000000000..ced10986f5 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java @@ -0,0 +1,588 @@ +package net.firedevops.firemud.common.account.authority; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadConstraints; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.json.JsonFactory; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Account's PUBLIC_PRODUCTION SHARED PRESEEDED PLAYER_ADMISSION variant of the existing runtime + * evidence contract. Content validation is not source authentication or an admission grant. + * + *

The owner must derive this value from its final Account transaction and protected target read. + * Target source references name that complete read; they hold no World lock through later use. + * Decoding validates content only and cannot promote caller-supplied data to source authority. + */ +public final class RuntimePlayerAdmissionEntitlementEvidence { + public static final String SCHEMA = RuntimeTenantOperationEntitlementEvidence.SCHEMA; + public static final String VARIANT = "PLAYER_ADMISSION"; + public static final int MAX_CANONICAL_BYTES = 256 * 1024; + public static final int MAX_CONNECT_SCOPE_CHARS = 16384; + private static final JsonMapper JSON = + JsonMapper.builder( + JsonFactory.builder() + .streamReadConstraints( + StreamReadConstraints.builder() + .maxNestingDepth(16) + .maxStringLength(65536) + .maxNumberLength(19) + .build()) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final Set TARGET_FIELDS = + Set.of( + "targetClass", + "characterCreationPolicy", + "targetNamespace", + "tenantId", + "tenantSlug", + "worldSlug", + "realmId", + "realmSlug", + "playableStateNamespaceId", + "playableStateScope", + "gameInstanceId", + "canonicalVersionId", + "catalogRevision", + "pointerVersion", + "activeWorldEpoch", + "evaluatedAt", + "connectScopeExpiresAt"); + private static final Set FACT_FIELDS = + Set.of( + "sourceKind", + "subscriptionStatus", + "provisioningStatus", + "gameplayAvailable", + "allowPublicJoin", + "allowNewGameplayBindings", + "allowNewInstanceStarts", + "quotas", + "entitlementVersion", + "tenantBillingSequence", + "tenantAuthorityGeneration"); + private static final Set SOURCE_FIELDS = + Set.of( + "callerTokenJti", + "callerTokenExpiresAt", + "paidReceiptValidUntil", + "callerTokenSha256", + "callerRegistryRecordSha256", + "callerCommitProofSha256", + "callerContextId", + "callerOperationId", + "scopeDigest", + "entitlementSourceDigest", + "admissionPointerSnapshotDigest", + "gameSessionOwnerProofDigest", + "publishedPolicySetDigest", + "worldLifecycleDigest", + "worldCaptureId", + "worldRowVersion"); + private final Snapshot membership; + private final byte[] canonicalBytes; + + private RuntimePlayerAdmissionEntitlementEvidence(Snapshot membership, byte[] canonicalBytes) { + this.membership = membership; + this.canonicalBytes = canonicalBytes.clone(); + } + + /** Content-only construction; production source provenance belongs to the Account owner. */ + public static RuntimePlayerAdmissionEntitlementEvidence fromOwnerEvaluation( + UUID requestId, + String callerWorkload, + String verifiedConnectScopeId, + Snapshot membership, + Map target, + Map facts, + Map source, + Instant evaluatedAt) { + Objects.requireNonNull(membership); + RuntimeMembershipAuthorityEvidenceValidator.validate(membership); + requireUuid(membership.accountId()); + requireUuid(membership.tenantId()); + if (!membership.authorityTuple().privateRealmGrantVersions().isEmpty()) + throw invalid("Public player evidence cannot carry private grant authority"); + if (!"firemud-account-service".equals(membership.issuerId())) + throw invalid("Canonical Account issuer required"); + requireUuid(requestId.toString()); + var peer = + GrpcPeerIdentity.parseUri(callerWorkload) + .filter( + value -> + value.uri().equals(callerWorkload) + && "game-session-service".equals(value.service())) + .orElseThrow(() -> invalid("Exact Game Session caller required")); + if (verifiedConnectScopeId == null + || verifiedConnectScopeId.isBlank() + || verifiedConnectScopeId.length() > MAX_CONNECT_SCOPE_CHARS) + throw invalid("Verified connect scope required"); + exact(target, TARGET_FIELDS); + exact(facts, FACT_FIELDS); + exact(source, SOURCE_FIELDS); + if (!"PUBLIC_PRODUCTION".equals(target.get("targetClass")) + || !"PRESEEDED_ONLY".equals(target.get("characterCreationPolicy")) + || !peer.namespace().equals(target.get("targetNamespace")) + || !membership.tenantId().equals(target.get("tenantId")) + || !"SHARED".equals(target.get("playableStateScope"))) + throw invalid("Exact public SHARED tenant target required"); + for (String key : + List.of( + "tenantId", + "realmId", + "playableStateNamespaceId", + "gameInstanceId", + "canonicalVersionId")) requireUuid(text(target.get(key))); + for (String key : List.of("tenantSlug", "worldSlug", "realmSlug")) + if (!text(target.get(key)).matches("[a-z0-9]+(?:-[a-z0-9]+)*")) + throw invalid("Canonical slug required"); + for (String key : List.of("catalogRevision", "pointerVersion", "activeWorldEpoch")) + positive(target.get(key)); + Instant scopeTime = instant(target.get("evaluatedAt")); + Instant scopeExpiry = instant(target.get("connectScopeExpiresAt")); + if (!evaluatedAt.isAfter(Instant.EPOCH) + || evaluatedAt.isBefore(scopeTime) + || !evaluatedAt.isBefore(scopeExpiry)) throw invalid("Scope is not current at evaluation"); + validateFacts(facts, membership); + for (String key : + List.of("callerTokenJti", "callerContextId", "callerOperationId", "worldCaptureId")) + requireUuid(text(source.get(key))); + for (String key : + List.of("callerTokenSha256", "callerRegistryRecordSha256", "callerCommitProofSha256")) + if (!text(source.get(key)).matches("[0-9a-f]{64}")) throw invalid("Source SHA-256 required"); + for (String key : + List.of( + "scopeDigest", + "entitlementSourceDigest", + "worldLifecycleDigest", + "publishedPolicySetDigest", + "gameSessionOwnerProofDigest")) + if (!text(source.get(key)).matches("sha256:[0-9a-f]{64}")) + throw invalid("Source digest required"); + for (String key : List.of("admissionPointerSnapshotDigest")) + if (!text(source.get(key)).matches("[0-9a-f]{64}")) + throw invalid("Canonical target source digest required"); + if (!text(source.get("worldRowVersion")).matches("0|[1-9][0-9]{0,18}") + || Long.parseLong(text(source.get("worldRowVersion"))) < 0) + throw invalid("World row version required"); + Instant validUntil = instant(source.get("callerTokenExpiresAt")); + if (scopeExpiry.isBefore(validUntil)) validUntil = scopeExpiry; + if ("PAID_HOSTING".equals(facts.get("sourceKind"))) { + Instant providerDeadline = instant(source.get("paidReceiptValidUntil")); + if (providerDeadline.isBefore(validUntil)) validUntil = providerDeadline; + } else if (source.get("paidReceiptValidUntil") != null) { + throw invalid("Demo evidence cannot assert a paid receipt deadline"); + } + if (!evaluatedAt.isBefore(validUntil)) throw invalid("Player source validity expired"); + Map fields = new LinkedHashMap<>(); + fields.put("schema", SCHEMA); + fields.put("variant", VARIANT); + fields.put("bundleVersion", "1"); + fields.put("authorityAvailability", "AVAILABLE"); + fields.put("issuer", membership.issuerId()); + fields.put("tenantId", membership.tenantId()); + fields.put("callerAccountId", membership.accountId()); + fields.put("callerWorkload", callerWorkload); + fields.put("verifiedConnectScopeId", verifiedConnectScopeId); + fields.put("target", target); + fields.putAll(facts); + fields.put("membershipExists", membership.membershipExists()); + fields.put("membershipLifecycleState", membership.membershipLifecycleState()); + fields.put("gameplayAdmissionAllowed", membership.gameplayAdmissionAllowed()); + fields.put("membershipVersion", membership.membershipVersion()); + fields.put("membershipAuthorityGeneration", membership.membershipAuthorityGeneration()); + fields.put("roles", membership.roles()); + fields.put("issuanceFence", membership.issuanceFence()); + fields.put("authorityTuple", tuple(membership)); + fields.put( + "outboxCheckpoints", + membership.checkpoints().stream() + .map( + checkpoint -> { + Map entry = new LinkedHashMap<>(); + entry.put("outboxStreamKey", checkpoint.outboxStreamKey()); + entry.put("outboxSequence", checkpoint.outboxSequence()); + membership.sourceEvidence().stream() + .filter(event -> event.outboxStreamKey().equals(checkpoint.outboxStreamKey())) + .findFirst() + .ifPresent( + event -> { + entry.put("sourceEventId", event.eventId()); + entry.put("sourceEventDigest", event.eventDigest()); + }); + return entry; + }) + .toList()); + fields.put("authoritySourceEvidence", membership.sourceEvidence()); + fields.put("sourceReferences", source); + fields.put("validUntil", validUntil.toString()); + // The committed-input identity excludes the request and evaluation time. Source references + // include the actual caller issuance, retained scope, billing and protected target captures. + String snapshotIdentity = digest(fields); + fields.put("snapshotIdentity", snapshotIdentity); + fields.put("requestId", requestId.toString()); + fields.put("evaluatedAt", evaluatedAt.toString()); + fields.put( + "evaluationIdentity", + digest( + Map.of( + "snapshotIdentity", + snapshotIdentity, + "requestId", + requestId.toString(), + "callerWorkload", + callerWorkload, + "evaluatedAt", + evaluatedAt.toString()))); + byte[] bytes = canonical(fields); + if (bytes.length > MAX_CANONICAL_BYTES) throw invalid("Player evidence exceeds size bound"); + return new RuntimePlayerAdmissionEntitlementEvidence(membership, bytes); + } + + /** Strict content decoder only; authenticated transport and Account sources remain mandatory. */ + public static RuntimePlayerAdmissionEntitlementEvidence parseCanonical(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_CANONICAL_BYTES) + throw invalid("Player evidence is absent or exceeds size bound"); + try { + String json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + Map fields = JSON.readValue(json, new TypeReference<>() {}); + Map authority = object(fields.get("authorityTuple")); + Set requiredTuple = + Set.of( + "issuerAuthGeneration", + "accountAuthorityGeneration", + "tenantAuthorityGeneration", + "membershipAuthorityGeneration", + "privateRealmGrantVersions"); + if (!authority.keySet().containsAll(requiredTuple) + || authority.keySet().stream() + .anyMatch( + k -> + !requiredTuple.contains(k) + && !Set.of("accountSecurityCutoff", "tenantBillingCutoff").contains(k)) + || !list(authority.get("privateRealmGrantVersions")).isEmpty()) + throw invalid("Closed public authority tuple required"); + Optional accountCutoff = + Optional.empty(); + if (authority.containsKey("accountSecurityCutoff")) { + var cutoff = object(authority.get("accountSecurityCutoff")); + exact(cutoff, Set.of("accountAuthorityGeneration", "outboxStreamKey", "outboxSequence")); + accountCutoff = + Optional.of( + new MembershipAuthorityEventV1Codec.AccountSecurityCutoff( + text(cutoff.get("accountAuthorityGeneration")), + text(cutoff.get("outboxStreamKey")), + text(cutoff.get("outboxSequence")))); + } + Map tenantCutoffs = + new LinkedHashMap<>(); + object(authority.get("tenantBillingCutoff")) + .forEach( + (tenant, raw) -> { + var cutoff = object(raw); + exact( + cutoff, + Set.of( + "tenantAuthorityGeneration", + "tenantBillingSequence", + "outboxStreamKey", + "outboxSequence")); + tenantCutoffs.put( + tenant, + new MembershipAuthorityEventV1Codec.TenantBillingCutoff( + text(cutoff.get("tenantAuthorityGeneration")), + text(cutoff.get("tenantBillingSequence")), + text(cutoff.get("outboxStreamKey")), text(cutoff.get("outboxSequence")))); + }); + var tuple = + new MembershipAuthorityEventV1Codec.AuthorityTuple( + text(authority.get("issuerAuthGeneration")), + text(authority.get("accountAuthorityGeneration")), + strings(authority.get("tenantAuthorityGeneration")), + strings(authority.get("membershipAuthorityGeneration")), + List.of(), + accountCutoff, + Optional.of(tenantCutoffs)); + var checkpoints = + list(fields.get("outboxCheckpoints")).stream() + .map( + raw -> { + var checkpoint = object(raw); + String stream = text(checkpoint.get("outboxStreamKey")); + String sequence = text(checkpoint.get("outboxSequence")); + return new RuntimeMembershipAuthorityEvidenceValidator.Checkpoint( + stream, sequence); + }) + .toList(); + var events = + list(fields.get("authoritySourceEvidence")).stream() + .map( + raw -> { + var event = object(raw); + exact( + event, + Set.of( + "outboxStreamKey", + "outboxSequence", + "eventId", + "eventDigest", + "canonicalEventJson")); + return new RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence( + text(event.get("outboxStreamKey")), + text(event.get("outboxSequence")), + text(event.get("eventId")), + text(event.get("eventDigest")), + text(event.get("canonicalEventJson"))); + }) + .toList(); + Snapshot membership = + new Snapshot( + text(fields.get("issuer")), + text(fields.get("callerAccountId")), + text(fields.get("tenantId")), + bool(fields.get("membershipExists")), + text(fields.get("membershipLifecycleState")), + bool(fields.get("gameplayAdmissionAllowed")), + strings(fields.get("membershipVersion")), + text(fields.get("membershipAuthorityGeneration")), + list(fields.get("roles")).stream() + .map(RuntimePlayerAdmissionEntitlementEvidence::text) + .toList(), + tuple, + text(fields.get("issuanceFence")), + checkpoints, + events); + Map facts = new LinkedHashMap<>(); + FACT_FIELDS.forEach(key -> facts.put(key, fields.get(key))); + var rebuilt = + fromOwnerEvaluation( + UUID.fromString(text(fields.get("requestId"))), + text(fields.get("callerWorkload")), + text(fields.get("verifiedConnectScopeId")), + membership, + object(fields.get("target")), + facts, + object(fields.get("sourceReferences")), + instant(fields.get("evaluatedAt"))); + if (!Arrays.equals(bytes, rebuilt.canonicalBytes)) + throw invalid("Player evidence must be the exact closed canonical value"); + return rebuilt; + } catch (CharacterCodingException failure) { + throw invalid("Player evidence requires strict UTF-8"); + } catch (RuntimeException failure) { + throw invalid("Invalid canonical player evidence"); + } + } + + private static Map object(Object value) { + if (!(value instanceof Map map)) throw invalid("Object required"); + Map result = new LinkedHashMap<>(); + map.forEach((key, member) -> result.put(text(key), member)); + return result; + } + + private static Map strings(Object value) { + Map result = new LinkedHashMap<>(); + object(value).forEach((key, member) -> result.put(key, text(member))); + return result; + } + + private static List list(Object value) { + if (!(value instanceof List list) || list.size() > 16) + throw invalid("Bounded list required"); + return list; + } + + private static boolean bool(Object value) { + if (!(value instanceof Boolean flag)) throw invalid("Boolean required"); + return flag; + } + + private static Instant instant(Object value) { + String text = text(value); + Instant instant = Instant.parse(text); + if (!instant.toString().equals(text)) throw invalid("Canonical timestamp required"); + return instant; + } + + private static void validateFacts(Map facts, Snapshot membership) { + String kind = text(facts.get("sourceKind")); + if (!Set.of("PAID_HOSTING", "NON_PAID_DEMO").contains(kind) + || facts.get("provisioningStatus") != null) + throw invalid("Current explicit source required"); + Object status = facts.get("subscriptionStatus"); + if ("NON_PAID_DEMO".equals(kind) + ? status != null + : !(status instanceof String) + || !Set.of("trialing", "active", "past_due", "grace", "suspended", "canceled") + .contains(status)) throw invalid("Source subscription status differs"); + for (String key : + List.of( + "gameplayAvailable", + "allowPublicJoin", + "allowNewGameplayBindings", + "allowNewInstanceStarts")) + if (!(facts.get(key) instanceof Boolean)) + throw invalid("Explicit entitlement booleans required"); + positive(facts.get("entitlementVersion")); + positive(facts.get("tenantBillingSequence")); + positive(facts.get("tenantAuthorityGeneration")); + var tuple = membership.authorityTuple(); + var cutoff = + tuple + .tenantBillingCutoff() + .orElseThrow(() -> invalid("Billing cutoff required")) + .get(membership.tenantId()); + if (!Objects.equals( + tuple.tenantAuthorityGeneration().get(membership.tenantId()), + facts.get("tenantAuthorityGeneration")) + || cutoff == null + || !Objects.equals(cutoff.tenantBillingSequence(), facts.get("tenantBillingSequence"))) + throw invalid("Facts differ from current tenant authority"); + if (!(facts.get("quotas") instanceof Map quotas) + || !quotas + .keySet() + .equals(Set.of("maxActiveSessions", "maxConcurrentGameInstances", "maxStorageBytes"))) + throw invalid("Complete quotas required"); + quotas + .values() + .forEach( + value -> { + if (!text(value).matches("0|[1-9][0-9]{0,18}") || Long.parseLong(text(value)) < 0) + throw invalid("Nonnegative quota required"); + }); + } + + private static Map tuple(Snapshot membership) { + var supplied = membership.authorityTuple(); + Map result = new LinkedHashMap<>(); + result.put("issuerAuthGeneration", supplied.issuerAuthGeneration()); + result.put("accountAuthorityGeneration", supplied.accountAuthorityGeneration()); + result.put("tenantAuthorityGeneration", supplied.tenantAuthorityGeneration()); + result.put("membershipAuthorityGeneration", supplied.membershipAuthorityGeneration()); + result.put("privateRealmGrantVersions", supplied.privateRealmGrantVersions()); + supplied.accountSecurityCutoff().ifPresent(value -> result.put("accountSecurityCutoff", value)); + supplied.tenantBillingCutoff().ifPresent(value -> result.put("tenantBillingCutoff", value)); + return result; + } + + private static void exact(Map fields, Set expected) { + if (fields == null || !fields.keySet().equals(expected)) + throw invalid("Missing or extra scoped fields"); + } + + private static String text(Object value) { + if (!(value instanceof String text) || text.isBlank()) throw invalid("Required text absent"); + return text; + } + + private static void requireUuid(String value) { + if (!UUID.fromString(value).toString().equals(value) || new UUID(0, 0).toString().equals(value)) + throw invalid("Canonical UUID required"); + } + + private static void positive(Object value) { + if (!text(value).matches("[1-9][0-9]{0,18}") || Long.parseLong(text(value)) <= 0) + throw invalid("Positive owner counter required"); + } + + private static byte[] canonical(Map value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException failure) { + throw invalid("Cannot encode canonical player evidence"); + } + } + + public static String digest(Map preimage) { + return digestBytes(canonical(preimage)); + } + + public static String digestBytes(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 unavailable", impossible); + } + } + + public Instant evaluatedAt() { + return instant(fields().get("evaluatedAt")); + } + + public Instant validUntil() { + return instant(fields().get("validUntil")); + } + + /** Applies actual source time bounds only; this never establishes a current World hold. */ + public void requireCurrentAt(Instant now) { + Objects.requireNonNull(now); + if (now.isBefore(evaluatedAt()) || !now.isBefore(validUntil())) + throw invalid("Player entitlement source observation expired"); + } + + public Snapshot membershipSource() { + return membership; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + /** A detached copy; editing it cannot alter this value. */ + public Map fields() { + return JSON.readValue( + new String(canonicalBytes, StandardCharsets.UTF_8), new TypeReference<>() {}); + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + @Override + public boolean equals(Object other) { + return other instanceof RuntimePlayerAdmissionEntitlementEvidence value + && Arrays.equals(canonicalBytes, value.canonicalBytes); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes); + } + + @Override + public String toString() { + return "RuntimePlayerAdmissionEntitlementEvidence[PLAYER_ADMISSION, redacted]"; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java new file mode 100644 index 0000000000..32ca98404d --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java @@ -0,0 +1,298 @@ +package net.firedevops.firemud.common.account.authority; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Checkpoint; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.junit.jupiter.api.Test; + +/** Controlled content fixtures, not source authentication, transport or owner execution. */ +class RuntimePlayerAdmissionEntitlementEvidenceTest { + private static final UUID ACCOUNT = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID REQUEST = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final String PEER = "spiffe://firemud/ns/prod/sa/game-session-service"; + private static final String HASH = "a".repeat(64); + private static final Instant NOW = Instant.parse("2026-11-02T00:00:00Z"); + + @Test + void canonicalVariantRetainsExplicitAbsenceAndCompleteApplicableAuthority() { + var value = capture(target(), facts(), sources(), NOW); + assertThat(value.fields()) + .containsEntry("variant", "PLAYER_ADMISSION") + .containsEntry("authorityAvailability", "AVAILABLE") + .containsEntry("callerAccountId", ACCOUNT.toString()) + .containsEntry("verifiedConnectScopeId", "controlled-scope") + .containsEntry("membershipExists", false) + .containsEntry("membershipLifecycleState", "MISSING"); + assertThat(value.membershipSource().membershipAuthorityGeneration()).isEqualTo("1"); + assertThat(value.membershipSource().checkpoints()).hasSize(4); + assertThat(value.membershipSource().sourceEvidence()).hasSize(1); + byte[] copy = value.canonicalBytes(); + copy[0] = 0; + value.fields().put("callerAccountId", TENANT.toString()); + assertThat(value.fields()).containsEntry("callerAccountId", ACCOUNT.toString()); + assertThat(value.toString()).doesNotContain("controlled-scope"); + assertThatThrownBy( + () -> RuntimeTenantOperationEntitlementEvidence.parseCanonical(value.canonicalBytes())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void identitiesBindActualInputsAndSeparateSnapshotFromEvaluation() { + var first = capture(target(), facts(), sources(), NOW); + var later = capture(target(), facts(), sources(), NOW.plusSeconds(1)); + assertThat(first.fields().get("snapshotIdentity")) + .isEqualTo(later.fields().get("snapshotIdentity")); + assertThat(first.fields().get("evaluationIdentity")) + .isNotEqualTo(later.fields().get("evaluationIdentity")); + var changed = sources(); + changed.put("worldLifecycleDigest", "sha256:" + "b".repeat(64)); + assertThat(capture(target(), facts(), changed, NOW).fields().get("snapshotIdentity")) + .isNotEqualTo(first.fields().get("snapshotIdentity")); + } + + @Test + void incompleteOrConflictingTargetFactsAndSourcesNeverProduceAValue() { + for (String field : List.of("activeWorldEpoch", "canonicalVersionId", "targetClass")) { + var target = target(); + target.remove(field); + assertThatThrownBy(() -> capture(target, facts(), sources(), NOW)) + .isInstanceOf(IllegalArgumentException.class); + } + for (String field : List.of("tenantAuthorityGeneration", "tenantBillingSequence")) { + var facts = facts(); + facts.put(field, "9"); + assertThatThrownBy(() -> capture(target(), facts, sources(), NOW)) + .isInstanceOf(IllegalArgumentException.class); + } + var unframedScopeSource = sources(); + unframedScopeSource.put("scopeDigest", HASH); + assertThatThrownBy(() -> capture(target(), facts(), unframedScopeSource, NOW)) + .isInstanceOf(IllegalArgumentException.class); + var target = target(); + target.put("characterCreationPolicy", "PLAYER_CREATED"); + assertThatThrownBy(() -> capture(target, facts(), sources(), NOW)) + .isInstanceOf(IllegalArgumentException.class); + var source = sources(); + source.put("callerGeneration", "1"); + assertThatThrownBy(() -> capture(target(), facts(), source, NOW)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> capture(target(), facts(), sources(), NOW.plusSeconds(120))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void strictDecoderRoundTripsAndRejectsNoncanonicalUnknownOrConflictingContent() { + var value = capture(target(), facts(), sources(), NOW); + assertThat(RuntimePlayerAdmissionEntitlementEvidence.parseCanonical(value.canonicalBytes())) + .isEqualTo(value); + String json = new String(value.canonicalBytes(), StandardCharsets.UTF_8); + for (byte[] malformed : + List.of( + (" " + json).getBytes(StandardCharsets.UTF_8), + json.replace("\"variant\":\"PLAYER_ADMISSION\"", "\"variant\":\"TENANT_OPERATION\"") + .getBytes(StandardCharsets.UTF_8), + (json.substring(0, json.length() - 1) + ",\"unknown\":true}") + .getBytes(StandardCharsets.UTF_8), + (json.substring(0, json.length() - 1) + ",\"variant\":\"PLAYER_ADMISSION\"}") + .getBytes(StandardCharsets.UTF_8), + json.replace("\"membershipExists\":false", "\"membershipExists\":true") + .getBytes(StandardCharsets.UTF_8), + json.replace("\"pointerVersion\":\"3\"", "\"pointerVersion\":\"4\"") + .getBytes(StandardCharsets.UTF_8), + new byte[] {(byte) 0xc3, (byte) 0x28}, + new byte[RuntimePlayerAdmissionEntitlementEvidence.MAX_CANONICAL_BYTES + 1])) { + assertThatThrownBy(() -> RuntimePlayerAdmissionEntitlementEvidence.parseCanonical(malformed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void validityIsMinimumOfActualScopeCallerAndPaidReceiptBounds() { + var source = sources(); + var demo = capture(target(), facts(), source, NOW); + assertThat(demo.validUntil()).isEqualTo(NOW.plusSeconds(90)); + demo.requireCurrentAt(NOW.plusSeconds(89)); + assertThatThrownBy(() -> demo.requireCurrentAt(NOW.plusSeconds(90))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> demo.requireCurrentAt(NOW.minusSeconds(1))) + .isInstanceOf(IllegalArgumentException.class); + var paid = facts(); + paid.put("sourceKind", "PAID_HOSTING"); + paid.put("subscriptionStatus", "active"); + source.put("paidReceiptValidUntil", NOW.plusSeconds(4).toString()); + var value = capture(target(), paid, source, NOW); + assertThat(value.validUntil()).isEqualTo(NOW.plusSeconds(4)); + assertThat(RuntimePlayerAdmissionEntitlementEvidence.parseCanonical(value.canonicalBytes())) + .isEqualTo(value); + source.put("paidReceiptValidUntil", NOW.toString()); + assertThatThrownBy(() -> capture(target(), paid, source, NOW)) + .isInstanceOf(IllegalArgumentException.class); + source.put("paidReceiptValidUntil", null); + assertThatThrownBy(() -> capture(target(), paid, source, NOW)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static RuntimePlayerAdmissionEntitlementEvidence capture( + Map target, + Map facts, + Map source, + Instant at) { + return RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( + REQUEST, PEER, "controlled-scope", membership(), target, facts, source, at); + } + + private static Map target() { + Map target = new LinkedHashMap<>(); + target.put("targetClass", "PUBLIC_PRODUCTION"); + target.put("characterCreationPolicy", "PRESEEDED_ONLY"); + target.put("targetNamespace", "prod"); + target.put("tenantId", TENANT.toString()); + target.put("tenantSlug", "tenant"); + target.put("worldSlug", "world"); + target.put("realmId", REQUEST.toString()); + target.put("realmSlug", "production"); + target.put("playableStateNamespaceId", REQUEST.toString()); + target.put("playableStateScope", "SHARED"); + target.put("gameInstanceId", REQUEST.toString()); + target.put("canonicalVersionId", REQUEST.toString()); + target.put("catalogRevision", "7"); + target.put("pointerVersion", "3"); + target.put("activeWorldEpoch", "5"); + target.put("evaluatedAt", NOW.minusSeconds(20).toString()); + target.put("connectScopeExpiresAt", NOW.plusSeconds(120).toString()); + return target; + } + + private static Map facts() { + Map facts = new LinkedHashMap<>(); + facts.put("sourceKind", "NON_PAID_DEMO"); + facts.put("subscriptionStatus", null); + facts.put("provisioningStatus", null); + for (String flag : + List.of( + "gameplayAvailable", + "allowPublicJoin", + "allowNewGameplayBindings", + "allowNewInstanceStarts")) facts.put(flag, true); + facts.put( + "quotas", + Map.of( + "maxActiveSessions", + "3", + "maxConcurrentGameInstances", + "2", + "maxStorageBytes", + "4096")); + facts.put("entitlementVersion", "1"); + facts.put("tenantBillingSequence", "1"); + facts.put("tenantAuthorityGeneration", "2"); + return facts; + } + + private static Map sources() { + Map source = new LinkedHashMap<>(); + source.put("callerTokenExpiresAt", NOW.plusSeconds(90).toString()); + source.put("paidReceiptValidUntil", null); + for (String key : + List.of("callerTokenJti", "callerContextId", "callerOperationId", "worldCaptureId")) + source.put(key, REQUEST.toString()); + for (String key : + List.of( + "callerTokenSha256", + "callerRegistryRecordSha256", + "callerCommitProofSha256", + "admissionPointerSnapshotDigest")) source.put(key, HASH); + for (String key : + List.of( + "scopeDigest", + "entitlementSourceDigest", + "gameSessionOwnerProofDigest", + "publishedPolicySetDigest", + "worldLifecycleDigest")) source.put(key, "sha256:" + HASH); + source.put("worldRowVersion", "0"); + return source; + } + + private static Snapshot membership() { + String requestDigest = + GameTenantCreationDigest.requestDigest("prod", REQUEST, "world", "World", null); + var source = + new FreshTenantCreationEvidence( + 1, + "prod", + REQUEST, + REQUEST, + requestDigest, + TENANT, + 17, + "world", + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "prod", REQUEST, REQUEST, requestDigest, TENANT, 17, "world", "NEW_GAME_ROW")); + var request = + new TenantAuthorityEventV1Codec.AuthorityRequest( + REQUEST, "sha256:" + HASH, TENANT, source.creationRequestId(), source.requestDigest()); + var billing = + new TenantAuthorityEventV1Codec.BillingReceipt( + TENANT, + REQUEST, + "sha256:" + HASH, + TenantAuthorityEventV1Codec.tenantBillingStreamKey(TENANT), + 1, + TenantAuthorityEventV1Codec.tenantBillingEventId(REQUEST), + "sha256:" + HASH); + var event = TenantAuthorityEventV1Codec.seal(request, source, 2, 2, 1, billing); + String prefix = MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX; + var tuple = + new AuthorityTuple( + "1", + "1", + Map.of(TENANT.toString(), "2"), + Map.of(TENANT.toString(), "1"), + List.of(), + Optional.empty(), + Optional.of( + Map.of( + TENANT.toString(), + new TenantBillingCutoff("2", "1", event.outboxStreamKey(), "1")))); + return new Snapshot( + "firemud-account-service", + ACCOUNT.toString(), + TENANT.toString(), + false, + "MISSING", + false, + Map.of(TENANT.toString(), "1"), + "1", + List.of(), + tuple, + "1", + List.of( + new Checkpoint(prefix + "account/" + ACCOUNT, "0"), + new Checkpoint(prefix + "issuer/firemud-account-service", "0"), + new Checkpoint(prefix + "membership/" + ACCOUNT + "/" + TENANT, "0"), + new Checkpoint(event.outboxStreamKey(), "1")), + List.of( + new SourceEvidence( + event.outboxStreamKey(), + "1", + event.eventId().toString(), + event.eventDigest(), + new String(event.payload(), StandardCharsets.UTF_8)))); + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodec.java new file mode 100644 index 0000000000..4ef24c0535 --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodec.java @@ -0,0 +1,161 @@ +package net.firedevops.firemud.common.account.authority; + +import com.google.protobuf.ByteString; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import net.firedevops.firemud.account.v1.PlayerAdmissionEntitlementReadSelectors; +import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementRequest; +import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementResponse; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; + +/** Closed comparison and content mapping; this codec authenticates neither callers nor sources. */ +public final class RuntimePlayerAdmissionEntitlementGrpcCodec { + public static final int MAX_REQUEST_WIRE_BYTES = 40 * 1024; + public static final int MAX_RESPONSE_WIRE_BYTES = + RuntimePlayerAdmissionEntitlementEvidence.MAX_CANONICAL_BYTES + MAX_REQUEST_WIRE_BYTES + 32; + public static final long CALL_DEADLINE_SECONDS = 45L; + + private RuntimePlayerAdmissionEntitlementGrpcCodec() {} + + public record Request(RetainedTargetSelector target, String connectScopeId) { + public Request { + Objects.requireNonNull(target, "Exact retained target selectors required"); + if (connectScopeId == null + || connectScopeId.isBlank() + || connectScopeId.length() + > RuntimePlayerAdmissionEntitlementEvidence.MAX_CONNECT_SCOPE_CHARS) throw invalid(); + } + + public String expectedGameSessionWorkload() { + return "spiffe://firemud/ns/" + target.targetNamespace() + "/sa/game-session-service"; + } + + @Override + public String toString() { + return "PlayerAdmissionEntitlementSelectors[redacted]"; + } + } + + /** Process-local credential carrier only; never include in logs or a persisted operation. */ + public record PresentedRequest(Request request, String initialLoginJwt) { + public PresentedRequest { + Objects.requireNonNull(request); + if (initialLoginJwt == null + || initialLoginJwt.isBlank() + || initialLoginJwt.length() > GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES + || !initialLoginJwt.matches("[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+")) + throw invalid(); + } + + @Override + public String toString() { + return "PlayerAdmissionEntitlementCredential[redacted]"; + } + } + + public static ReadPlayerAdmissionEntitlementRequest toRequest( + Request request, String initialLoginJwt) { + new PresentedRequest(request, initialLoginJwt); + var wire = + ReadPlayerAdmissionEntitlementRequest.newBuilder() + .addSelectors(selectors(request)) + .addInitialLoginJwt(initialLoginJwt) + .build(); + if (wire.getSerializedSize() > MAX_REQUEST_WIRE_BYTES) throw invalid(); + return wire; + } + + public static PresentedRequest parseRequest(ReadPlayerAdmissionEntitlementRequest wire) { + if (wire == null + || wire.getSerializedSize() > MAX_REQUEST_WIRE_BYTES + || !wire.getUnknownFields().asMap().isEmpty()) throw invalid(); + return new PresentedRequest( + parseSelectors(one(wire.getSelectorsList())), one(wire.getInitialLoginJwtList())); + } + + public static ReadPlayerAdmissionEntitlementResponse toResponse( + Request request, RuntimePlayerAdmissionEntitlementEvidence evidence) { + requireBinding(request, evidence); + var wire = + ReadPlayerAdmissionEntitlementResponse.newBuilder() + .addRequest(selectors(request)) + .addCanonicalEvidence(ByteString.copyFrom(evidence.canonicalBytes())) + .build(); + if (wire.getSerializedSize() > MAX_RESPONSE_WIRE_BYTES) throw invalid(); + return wire; + } + + public static RuntimePlayerAdmissionEntitlementEvidence requireResponse( + Request expected, ReadPlayerAdmissionEntitlementResponse wire) { + Objects.requireNonNull(expected); + if (wire == null + || wire.getSerializedSize() > MAX_RESPONSE_WIRE_BYTES + || !wire.getUnknownFields().asMap().isEmpty() + || !expected.equals(parseSelectors(one(wire.getRequestList())))) throw invalid(); + var evidence = + RuntimePlayerAdmissionEntitlementEvidence.parseCanonical( + one(wire.getCanonicalEvidenceList()).toByteArray()); + requireBinding(expected, evidence); + return evidence; + } + + private static PlayerAdmissionEntitlementReadSelectors selectors(Request request) { + return PlayerAdmissionEntitlementReadSelectors.newBuilder() + .addSchemaVersion(1) + .addTarget( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionRequest( + request.target())) + .addConnectScopeId(request.connectScopeId()) + .build(); + } + + private static Request parseSelectors(PlayerAdmissionEntitlementReadSelectors wire) { + if (wire.getSerializedSize() > MAX_REQUEST_WIRE_BYTES + || !wire.getUnknownFields().asMap().isEmpty() + || one(wire.getSchemaVersionList()) != 1) throw invalid(); + return new Request( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseTargetResolutionRequest( + one(wire.getTargetList())), + one(wire.getConnectScopeIdList())); + } + + private static void requireBinding( + Request request, RuntimePlayerAdmissionEntitlementEvidence evidence) { + Map fields = Objects.requireNonNull(evidence).fields(); + var target = request.target(); + if (!target.accountId().toString().equals(fields.get("callerAccountId")) + || !target.tenantId().toString().equals(fields.get("tenantId")) + || !target.readRequestId().toString().equals(fields.get("requestId")) + || !request.expectedGameSessionWorkload().equals(fields.get("callerWorkload")) + || !request.connectScopeId().equals(fields.get("verifiedConnectScopeId"))) throw invalid(); + if (!(fields.get("target") instanceof Map actual) + || !target.targetNamespace().equals(actual.get("targetNamespace")) + || !target.tenantId().toString().equals(actual.get("tenantId")) + || !target.tenantSlug().equals(actual.get("tenantSlug")) + || !target.worldSlug().equals(actual.get("worldSlug")) + || !target.realmId().toString().equals(actual.get("realmId")) + || !target.realmSlug().equals(actual.get("realmSlug")) + || !target + .playableStateNamespaceId() + .toString() + .equals(actual.get("playableStateNamespaceId")) + || !target.playableStateScope().equals(actual.get("playableStateScope")) + || !target.gameInstanceId().toString().equals(actual.get("gameInstanceId")) + || !Long.toString(target.catalogRevision()).equals(actual.get("catalogRevision")) + || !Long.toString(target.pointerVersion()).equals(actual.get("pointerVersion"))) + throw invalid(); + } + + private static T one(List values) { + if (values.size() != 1) throw invalid(); + return values.getFirst(); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException( + "Exact bounded player-admission entitlement evidence required"); + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameplayAdmissionDecisionReadGrpcCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameplayAdmissionDecisionReadGrpcCodec.java index 5d382dce16..22bc86bd2b 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameplayAdmissionDecisionReadGrpcCodec.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameplayAdmissionDecisionReadGrpcCodec.java @@ -188,14 +188,15 @@ public static VisiblePublicProductionTargets fromDiscoveryResponse( Target target = parseTargetEvidence(wire); if (!expected.targetNamespace().equals(target.targetNamespace()) || !"SHARED".equals(target.playableStateScope()) - || !"PRESEEDED_ONLY".equals(target.characterCreationPolicy()) + || !("PRESEEDED_ONLY".equals(target.characterCreationPolicy()) + || "PLAYER_CREATED".equals(target.characterCreationPolicy())) || target.ownerProofOutcome() != OwnerProofOutcome.COMMITTED || target.positiveDurableAbort() || !tenants.add(target.canonicalTenantId()) || !tenantSlugs.add(target.tenantSlug()) || !realms.add(target.realmId())) { throw invalid( - "Discovery requires unique current public SHARED PRESEEDED owner targets"); + "Discovery requires unique current public SHARED owner targets with a supported creation policy"); } return target; }) diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/CanonicalGameplayAdmissionDecisionReadGrpcCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/CanonicalGameplayAdmissionDecisionReadGrpcCodecTest.java index 2d1298723e..48491eb874 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/CanonicalGameplayAdmissionDecisionReadGrpcCodecTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/CanonicalGameplayAdmissionDecisionReadGrpcCodecTest.java @@ -96,6 +96,24 @@ void discoveryRoundTripsCompleteOwnerTargetsAndAuthenticatedEmptyCollection() { .isEmpty(); } + @Test + void discoveryCarriesBothSupportedPublicCreationPoliciesWithoutChangingTargetEvidence() { + for (String policy : List.of("PRESEEDED_ONLY", "PLAYER_CREATED")) { + var current = target(lease(), policy); + var request = + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.DiscoveryRequest( + DECISION_ID, current.targetNamespace()); + var response = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( + request, List.of(current)); + assertThat( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + request, response) + .targets()) + .containsExactly(current); + } + } + @Test void discoveryRejectsOpenRequestShapeAndChangedResponseCorrelation() { var request = @@ -168,8 +186,7 @@ void discoveryRejectsDuplicateTenantAuthorityAndUnsupportedOrIncompleteTargets() .setCurrentTargets(0, wire.toBuilder().setPlayableStateScope(0, "ISOLATED")) .build(), response.toBuilder() - .setCurrentTargets( - 0, wire.toBuilder().setCharacterCreationPolicy(0, "PLAYER_CREATED")) + .setCurrentTargets(0, wire.toBuilder().setCharacterCreationPolicy(0, "UNSUPPORTED")) .build(), response.toBuilder() .setCurrentTargets(0, wire.toBuilder().clearCanonicalGameInstanceUuid()) diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodecTest.java new file mode 100644 index 0000000000..7d19d96322 --- /dev/null +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodecTest.java @@ -0,0 +1,279 @@ +package net.firedevops.firemud.common.account.authority; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Checkpoint; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.junit.jupiter.api.Test; + +/** Controlled content and wire fixtures only; no source authentication or owner execution. */ +class RuntimePlayerAdmissionEntitlementGrpcCodecTest { + private static final UUID ACCOUNT = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID REQUEST = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final String PEER = "spiffe://firemud/ns/prod/sa/game-session-service"; + private static final String HASH = "a".repeat(64); + private static final Instant NOW = Instant.parse("2026-11-02T00:00:00Z"); + private static final String TOKEN = "controlled.initial.jwt"; + + private static RuntimePlayerAdmissionEntitlementGrpcCodec.Request request( + UUID account, UUID requestId) { + return new RuntimePlayerAdmissionEntitlementGrpcCodec.Request( + new RetainedTargetSelector( + requestId, + account, + "prod", + TENANT, + "tenant", + "world", + REQUEST, + "production", + REQUEST, + "SHARED", + REQUEST, + 7, + 3), + "controlled-scope"); + } + + @Test + void exactRoundTripPreservesSelectorsAndNeverEchoesCredential() { + var request = request(ACCOUNT, REQUEST); + var wire = RuntimePlayerAdmissionEntitlementGrpcCodec.toRequest(request, TOKEN); + var presented = RuntimePlayerAdmissionEntitlementGrpcCodec.parseRequest(wire); + assertThat(presented.request()).isEqualTo(request); + assertThat(presented.initialLoginJwt()).isEqualTo(TOKEN); + assertThat(presented.toString()).doesNotContain(TOKEN, "controlled-scope"); + assertThat(request.toString()).doesNotContain("controlled-scope"); + var value = capture(target(), facts(), sources(), NOW); + var response = RuntimePlayerAdmissionEntitlementGrpcCodec.toResponse(request, value); + assertThat(RuntimePlayerAdmissionEntitlementGrpcCodec.requireResponse(request, response)) + .isEqualTo(value); + assertThat(response.toByteString().toStringUtf8()).doesNotContain(TOKEN); + } + + @Test + void missingDuplicateUnknownAndOversizedMembersAreRejected() { + var request = request(ACCOUNT, REQUEST); + var wire = RuntimePlayerAdmissionEntitlementGrpcCodec.toRequest(request, TOKEN); + var unknown = + com.google.protobuf.UnknownFieldSet.newBuilder() + .addField( + 99, com.google.protobuf.UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + for (var malformed : + List.of( + wire.getDefaultInstanceForType(), + wire.toBuilder().addSelectors(wire.getSelectors(0)).build(), + wire.toBuilder().addInitialLoginJwt(TOKEN).build(), + wire.toBuilder().setUnknownFields(unknown).build(), + wire.toBuilder() + .setSelectors(0, wire.getSelectors(0).toBuilder().addSchemaVersion(1)) + .build(), + wire.toBuilder() + .setSelectors(0, wire.getSelectors(0).toBuilder().setUnknownFields(unknown)) + .build(), + wire.toBuilder().setInitialLoginJwt(0, "a".repeat(45000)).build())) { + assertThatThrownBy(() -> RuntimePlayerAdmissionEntitlementGrpcCodec.parseRequest(malformed)) + .isInstanceOf(IllegalArgumentException.class); + } + var response = + RuntimePlayerAdmissionEntitlementGrpcCodec.toResponse( + request, capture(target(), facts(), sources(), NOW)); + for (var malformed : + List.of( + response.getDefaultInstanceForType(), + response.toBuilder().addRequest(response.getRequest(0)).build(), + response.toBuilder().addCanonicalEvidence(response.getCanonicalEvidence(0)).build(), + response.toBuilder().setUnknownFields(unknown).build(), + response.toBuilder() + .setCanonicalEvidence(0, com.google.protobuf.ByteString.copyFromUtf8("{}")) + .build())) { + assertThatThrownBy( + () -> RuntimePlayerAdmissionEntitlementGrpcCodec.requireResponse(request, malformed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void changedCallerRequestOrScopeCannotBeReturnedAsCorrelatedEvidence() { + var request = request(ACCOUNT, REQUEST); + var value = capture(target(), facts(), sources(), NOW); + var response = RuntimePlayerAdmissionEntitlementGrpcCodec.toResponse(request, value); + for (var other : + List.of( + request(UUID.randomUUID(), REQUEST), + request(ACCOUNT, UUID.randomUUID()), + new RuntimePlayerAdmissionEntitlementGrpcCodec.Request( + request.target(), "another-scope"))) { + assertThatThrownBy(() -> RuntimePlayerAdmissionEntitlementGrpcCodec.toResponse(other, value)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> RuntimePlayerAdmissionEntitlementGrpcCodec.requireResponse(other, response)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + private static RuntimePlayerAdmissionEntitlementEvidence capture( + Map target, + Map facts, + Map source, + Instant at) { + return RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( + REQUEST, PEER, "controlled-scope", membership(), target, facts, source, at); + } + + private static Map target() { + Map target = new LinkedHashMap<>(); + target.put("targetClass", "PUBLIC_PRODUCTION"); + target.put("characterCreationPolicy", "PRESEEDED_ONLY"); + target.put("targetNamespace", "prod"); + target.put("tenantId", TENANT.toString()); + target.put("tenantSlug", "tenant"); + target.put("worldSlug", "world"); + target.put("realmId", REQUEST.toString()); + target.put("realmSlug", "production"); + target.put("playableStateNamespaceId", REQUEST.toString()); + target.put("playableStateScope", "SHARED"); + target.put("gameInstanceId", REQUEST.toString()); + target.put("canonicalVersionId", REQUEST.toString()); + target.put("catalogRevision", "7"); + target.put("pointerVersion", "3"); + target.put("activeWorldEpoch", "5"); + target.put("evaluatedAt", NOW.minusSeconds(20).toString()); + target.put("connectScopeExpiresAt", NOW.plusSeconds(120).toString()); + return target; + } + + private static Map facts() { + Map facts = new LinkedHashMap<>(); + facts.put("sourceKind", "NON_PAID_DEMO"); + facts.put("subscriptionStatus", null); + facts.put("provisioningStatus", null); + for (String flag : + List.of( + "gameplayAvailable", + "allowPublicJoin", + "allowNewGameplayBindings", + "allowNewInstanceStarts")) facts.put(flag, true); + facts.put( + "quotas", + Map.of( + "maxActiveSessions", + "3", + "maxConcurrentGameInstances", + "2", + "maxStorageBytes", + "4096")); + facts.put("entitlementVersion", "1"); + facts.put("tenantBillingSequence", "1"); + facts.put("tenantAuthorityGeneration", "2"); + return facts; + } + + private static Map sources() { + Map source = new LinkedHashMap<>(); + source.put("callerTokenExpiresAt", NOW.plusSeconds(90).toString()); + source.put("paidReceiptValidUntil", null); + for (String key : + List.of("callerTokenJti", "callerContextId", "callerOperationId", "worldCaptureId")) + source.put(key, REQUEST.toString()); + for (String key : + List.of( + "callerTokenSha256", + "callerRegistryRecordSha256", + "callerCommitProofSha256", + "admissionPointerSnapshotDigest")) source.put(key, HASH); + for (String key : + List.of( + "scopeDigest", + "entitlementSourceDigest", + "gameSessionOwnerProofDigest", + "publishedPolicySetDigest", + "worldLifecycleDigest")) source.put(key, "sha256:" + HASH); + source.put("worldRowVersion", "0"); + return source; + } + + private static Snapshot membership() { + String requestDigest = + GameTenantCreationDigest.requestDigest("prod", REQUEST, "world", "World", null); + var source = + new FreshTenantCreationEvidence( + 1, + "prod", + REQUEST, + REQUEST, + requestDigest, + TENANT, + 17, + "world", + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "prod", REQUEST, REQUEST, requestDigest, TENANT, 17, "world", "NEW_GAME_ROW")); + var request = + new TenantAuthorityEventV1Codec.AuthorityRequest( + REQUEST, "sha256:" + HASH, TENANT, source.creationRequestId(), source.requestDigest()); + var billing = + new TenantAuthorityEventV1Codec.BillingReceipt( + TENANT, + REQUEST, + "sha256:" + HASH, + TenantAuthorityEventV1Codec.tenantBillingStreamKey(TENANT), + 1, + TenantAuthorityEventV1Codec.tenantBillingEventId(REQUEST), + "sha256:" + HASH); + var event = TenantAuthorityEventV1Codec.seal(request, source, 2, 2, 1, billing); + String prefix = MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX; + var tuple = + new AuthorityTuple( + "1", + "1", + Map.of(TENANT.toString(), "2"), + Map.of(TENANT.toString(), "1"), + List.of(), + Optional.empty(), + Optional.of( + Map.of( + TENANT.toString(), + new TenantBillingCutoff("2", "1", event.outboxStreamKey(), "1")))); + return new Snapshot( + "firemud-account-service", + ACCOUNT.toString(), + TENANT.toString(), + false, + "MISSING", + false, + Map.of(TENANT.toString(), "1"), + "1", + List.of(), + tuple, + "1", + List.of( + new Checkpoint(prefix + "account/" + ACCOUNT, "0"), + new Checkpoint(prefix + "issuer/firemud-account-service", "0"), + new Checkpoint(prefix + "membership/" + ACCOUNT + "/" + TENANT, "0"), + new Checkpoint(event.outboxStreamKey(), "1")), + List.of( + new SourceEvidence( + event.outboxStreamKey(), + "1", + event.eventId().toString(), + event.eventDigest(), + new String(event.payload(), StandardCharsets.UTF_8)))); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterActorProjection.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterActorProjection.java new file mode 100644 index 0000000000..2d7373ca81 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterActorProjection.java @@ -0,0 +1,13 @@ +package net.firedevops.firemud.entitymanagement.bootstrap; + +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterActor; + +/** Exact same-row persisted discovery fields; zero is a legitimate stored level. */ +public record AccountBootstrapRosterActorProjection( + UUID characterUuid, String displayName, int level) { + public AccountBootstrapRosterActorProjection { + new CanonicalGameplayRosterActor(characterUuid, displayName); + if (level < 0) throw new IllegalArgumentException("Persisted actor level is invalid"); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPeerInterceptor.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPeerInterceptor.java new file mode 100644 index 0000000000..94513fde0b --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPeerInterceptor.java @@ -0,0 +1,71 @@ +package net.firedevops.firemud.entitymanagement.bootstrap; + +import io.grpc.Context; +import io.grpc.Contexts; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.Status; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; + +/** + * Purpose-specific certificate guard runs before protobuf decoding; no canonical GS allowlist + * change. + */ +public final class AccountBootstrapRosterPeerInterceptor implements ServerInterceptor { + public static final String METHOD_NAME = + "entity_management.v1.AccountBootstrapRosterReadService/ReadAccountBootstrapRoster"; + private static final Context.Key VERIFIED_ACCOUNT = + Context.key("firemud-account-bootstrap-roster-peer"); + private final String namespace; + + public AccountBootstrapRosterPeerInterceptor(String namespace) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Fixed workload namespace required"); + } + this.namespace = namespace; + } + + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + if (!METHOD_NAME.equals(call.getMethodDescriptor().getFullMethodName())) { + return next.startCall(call, headers); + } + var peer = + GrpcPeerIdentity.fromSslSession(call.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION)) + .orElse(null); + if (peer == null) { + call.close( + Status.UNAUTHENTICATED.withDescription("Authenticated Account workload required"), + new Metadata()); + return new ServerCall.Listener<>() {}; + } + if (!trusted(peer, namespace) + || SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService()) { + call.close( + Status.PERMISSION_DENIED.withDescription("Exact Account workload required"), + new Metadata()); + return new ServerCall.Listener<>() {}; + } + return Contexts.interceptCall( + Context.current() + .withValue(VERIFIED_ACCOUNT, peer) + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer), + call, + headers, + next); + } + + static boolean trusted(GrpcPeerIdentity peer, String namespace) { + return peer != null && peer.isService("account-service") && peer.isInNamespace(namespace); + } + + static GrpcPeerIdentity currentVerifiedPeer() { + return VERIFIED_ACCOUNT.get(); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadContract.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadContract.java new file mode 100644 index 0000000000..ff9f783dfa --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadContract.java @@ -0,0 +1,79 @@ +package net.firedevops.firemud.entitymanagement.bootstrap; + +import java.util.HashSet; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterActor; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadRequest; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadResponse; +import net.firedevops.firemud.entitymanagement.validation.CanonicalEntitySourceValues; + +/** Closed, bounded transient discovery contract. No original-selection or retention identities. */ +public final class AccountBootstrapRosterReadContract { + public static final int MAX_REQUEST_BYTES = 4096; + public static final int MAX_RESPONSE_BYTES = 64 * 1024; + public static final int MAX_ACTORS = 100; + + private AccountBootstrapRosterReadContract() {} + + public static CanonicalGameplayRosterTarget requireRequest( + AccountBootstrapRosterReadRequest wire) { + if (wire == null + || wire.getSerializedSize() > MAX_REQUEST_BYTES + || !wire.getUnknownFields().asMap().isEmpty() + || !wire.hasExpectedTarget() + || !wire.getExpectedTarget().getUnknownFields().asMap().isEmpty() + || !GrpcPeerIdentity.isValidNamespace(wire.getTargetNamespace())) { + throw new IllegalArgumentException("Complete closed bootstrap roster request required"); + } + uuid(wire.getRequestUuid()); + uuid(wire.getCanonicalAccountUuid()); + var target = wire.getExpectedTarget(); + uuid(target.getTenantUuid()); + uuid(target.getRealmUuid()); + uuid(target.getGameInstanceUuid()); + uuid(target.getCanonicalVersionUuid()); + uuid(target.getPlayableStateNamespaceUuid()); + var parsed = CanonicalGameplayRosterTarget.fromWire(target); + if (!parsed.toWire().equals(target)) { + throw new IllegalArgumentException("Canonical exact target required"); + } + return parsed; + } + + public static AccountBootstrapRosterReadResponse requireResponse( + AccountBootstrapRosterReadRequest request, AccountBootstrapRosterReadResponse response) { + requireRequest(request); + if (response == null + || response.getSerializedSize() > MAX_RESPONSE_BYTES + || !response.getUnknownFields().asMap().isEmpty() + || !response.hasRequest() + || !request.equals(response.getRequest()) + || response.getActorsCount() > MAX_ACTORS) { + throw new IllegalArgumentException("Bounded exact bootstrap roster response required"); + } + String previous = null; + var seen = new HashSet(); + for (var actor : response.getActorsList()) { + if (!actor.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Closed actor projection required"); + } + UUID actorUuid = uuid(actor.getCharacterUuid()); + new CanonicalGameplayRosterActor(actorUuid, actor.getDisplayName()); + if (!actor.hasLevel() || actor.getLevel() < 0) { + throw new IllegalArgumentException("Actual persisted actor level required"); + } + if (!seen.add(actorUuid) + || (previous != null && previous.compareTo(actor.getCharacterUuid()) >= 0)) { + throw new IllegalArgumentException("Unique UUID-ordered actor projection required"); + } + previous = actor.getCharacterUuid(); + } + return response; + } + + public static UUID uuid(String value) { + return CanonicalEntitySourceValues.parseCanonicalNonNilUuid(value); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadGrpcService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadGrpcService.java new file mode 100644 index 0000000000..0a2d385803 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadGrpcService.java @@ -0,0 +1,76 @@ +package net.firedevops.firemud.entitymanagement.bootstrap; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterOwnerEvidencePort.OwnerEvidenceUnavailableException; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadRequest; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadResponse; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadServiceGrpc; + +/** Unregistered receiver. Install its dedicated peer interceptor in every manual composition. */ +public final class AccountBootstrapRosterReadGrpcService + extends AccountBootstrapRosterReadServiceGrpc.AccountBootstrapRosterReadServiceImplBase { + private final AccountBootstrapRosterReadService service; + private final String namespace; + + public AccountBootstrapRosterReadGrpcService( + AccountBootstrapRosterReadService service, String namespace) { + this.service = Objects.requireNonNull(service, "service"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Fixed workload namespace required"); + } + this.namespace = namespace; + } + + @Override + public void readAccountBootstrapRoster( + AccountBootstrapRosterReadRequest request, + StreamObserver observer) { + var peer = AccountBootstrapRosterPeerInterceptor.currentVerifiedPeer(); + if (peer == null) { + refuse(observer, Status.UNAUTHENTICATED); + return; + } + if (!AccountBootstrapRosterPeerInterceptor.trusted(peer, namespace) + || SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService()) { + refuse(observer, Status.PERMISSION_DENIED); + return; + } + AccountBootstrapRosterReadResponse response; + try { + AccountBootstrapRosterReadService.requireNoAmbientTransaction(); + AccountBootstrapRosterReadContract.requireRequest(request); + if (!namespace.equals(request.getTargetNamespace())) { + refuse(observer, Status.PERMISSION_DENIED); + return; + } + response = service.read(request); + } catch (OwnerEvidenceUnavailableException + | org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException + | org.springframework.transaction.CannotCreateTransactionException unavailable) { + refuse(observer, Status.UNAVAILABLE); + return; + } catch (UnsupportedOperationException | IllegalStateException precondition) { + refuse(observer, Status.FAILED_PRECONDITION); + return; + } catch (IllegalArgumentException invalid) { + refuse(observer, Status.INVALID_ARGUMENT); + return; + } catch (RuntimeException unexpected) { + refuse(observer, Status.INTERNAL); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private static void refuse(StreamObserver observer, Status status) { + observer.onError( + status.withDescription("Account bootstrap roster read refused").asRuntimeException()); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadService.java new file mode 100644 index 0000000000..a4e104cfcc --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadService.java @@ -0,0 +1,95 @@ +package net.firedevops.firemud.entitymanagement.bootstrap; + +import java.util.Objects; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterEntryPolicy; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.service.impl.GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterActor; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadRequest; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadResponse; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Manually composed and unregistered Account discovery; no actor or receipt writes. */ +public final class AccountBootstrapRosterReadService { + private final GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter owner; + private final CharacterRepository characters; + private final TransactionTemplate reads; + + public AccountBootstrapRosterReadService( + GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter owner, + CharacterRepository characters, + PlatformTransactionManager transactionManager) { + this.owner = Objects.requireNonNull(owner, "owner"); + this.characters = Objects.requireNonNull(characters, "characters"); + reads = + new TransactionTemplate(Objects.requireNonNull(transactionManager, "transactionManager")); + reads.setReadOnly(true); + reads.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + reads.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + reads.setTimeout(5); + } + + public AccountBootstrapRosterReadResponse read(AccountBootstrapRosterReadRequest request) { + requireNoAmbientTransaction(); + CanonicalGameplayRosterTarget target = + AccountBootstrapRosterReadContract.requireRequest(request); + if (target.playableStateScope() != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED + || target.entryPolicy() != CanonicalGameplayRosterEntryPolicy.PRESEEDED_ONLY) { + throw new UnsupportedOperationException("Unsupported bootstrap roster target"); + } + requireCurrent(request, target); + var actors = + Objects.requireNonNull( + reads.execute( + ignored -> + characters.readAccountBootstrapRoster( + AccountBootstrapRosterReadContract.uuid(request.getCanonicalAccountUuid()), + target))); + // Source RPCs run outside SQL. This detects source movement over the local projection; + // it does not claim a distributed hold or protect a later admission/selection. + requireCurrent(request, target); + var response = AccountBootstrapRosterReadResponse.newBuilder().setRequest(request); + for (var actor : actors) { + response.addActors( + AccountBootstrapRosterActor.newBuilder() + .setCharacterUuid(actor.characterUuid().toString()) + .setDisplayName(actor.displayName()) + .setLevel(actor.level())); + } + return AccountBootstrapRosterReadContract.requireResponse(request, response.build()); + } + + private void requireCurrent( + AccountBootstrapRosterReadRequest request, CanonicalGameplayRosterTarget target) { + requireNoAmbientTransaction(); + var current = + owner.resolveCurrentTarget( + AccountBootstrapRosterReadContract.uuid(request.getRequestUuid()), + AccountBootstrapRosterReadContract.uuid(request.getCanonicalAccountUuid()), + target); + if (current == null + || !current.requestUuid().toString().equals(request.getRequestUuid()) + || !current.canonicalAccountUuid().toString().equals(request.getCanonicalAccountUuid()) + || !target.equals(current.target())) { + throw new TargetChangedException(); + } + } + + public static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new TargetChangedException(); + } + } + + public static final class TargetChangedException extends IllegalStateException { + public TargetChangedException() { + super("Bootstrap roster target precondition failed"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java index 8d34f302f3..72feec9c3b 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java @@ -1217,26 +1217,64 @@ private void lockCanonicalRosterNamespace(CanonicalGameplayRosterTarget target) } } + /** + * Transient Account discovery only: reads existing canonical actor rows without enrolling a + * namespace, capturing a snapshot or creating an original-selection/retention receipt. The caller + * supplies a short owner read transaction after independently resolving current sources. + */ + public List< + net.firedevops.firemud.entitymanagement.bootstrap.AccountBootstrapRosterActorProjection> + readAccountBootstrapRoster(UUID canonicalAccountUuid, CanonicalGameplayRosterTarget target) { + Objects.requireNonNull(canonicalAccountUuid, "canonicalAccountUuid"); + Objects.requireNonNull(target, "target"); + if (!org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) { + throw new IllegalStateException("Account bootstrap discovery requires owner transaction"); + } + if (target.playableStateScope() + != net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_SHARED + || target.entryPolicy() + != net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterEntryPolicy + .PRESEEDED_ONLY) { + throw new UnsupportedOperationException("Account bootstrap target is unsupported"); + } + String enrolledScope = + dsl.select(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_SCOPE) + .from(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES) + .where( + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES + .TENANT_UUID + .eq(target.tenantUuid()) + .and( + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_NAMESPACE_ID.eq( + target.playableStateNamespaceId()))) + .fetchOne(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_SCOPE); + // A namespace with no rows may legitimately have no enrollment yet. Absence does not create + // enrollment or authority; the complete independently current owner target supplies scope. + if (enrolledScope != null && !target.playableStateScope().name().equals(enrolledScope)) { + throw new IllegalStateException("CANONICAL_GAMEPLAY_ROSTER_NAMESPACE_SCOPE_MISMATCH"); + } + var rows = + canonicalRosterQuery(canonicalAccountUuid, target) + .fetch( + row -> + new net.firedevops.firemud.entitymanagement.bootstrap + .AccountBootstrapRosterActorProjection( + row.get(CHARACTERS.CHARACTER_UUID), + row.get(CHARACTERS.NAME), + row.get(CHARACTERS.LEVEL))); + if (rows.size() > CanonicalGameplayRosterSnapshotDigest.MAX_ROSTER_SIZE) { + throw new IllegalStateException("CANONICAL_GAMEPLAY_ROSTER_LIMIT_EXCEEDED"); + } + return rows; + } + private List readCurrentCanonicalRoster( UUID canonicalAccountUuid, CanonicalGameplayRosterTarget target) { + var query = canonicalRosterQuery(canonicalAccountUuid, target); List actors = - dsl.select(CHARACTERS.CHARACTER_UUID, CHARACTERS.NAME) - .from(CHARACTERS) - .where( - CHARACTERS - .ACCOUNT_UUID - .eq(canonicalAccountUuid) - .and(CHARACTERS.TENANT_UUID.eq(target.tenantUuid())) - .and( - CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID.eq( - target.playableStateNamespaceId())) - .and(CHARACTERS.PLAYABLE_STATE_SCOPE.eq(target.playableStateScope().name())) - .and( - CHARACTERS.ACTOR_IDENTITY_STATUS.eq( - ActorIdentityStatus.OWNER_RESOLVED.name())) - .and(CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON.isNull())) - .orderBy(CHARACTERS.CHARACTER_UUID.asc()) - .limit(CanonicalGameplayRosterSnapshotDigest.MAX_ROSTER_SIZE + 1) + query .forShare() .fetch( row -> @@ -1248,6 +1286,23 @@ private List readCurrentCanonicalRoster( return actors; } + private org.jooq.SelectLimitPercentStep> + canonicalRosterQuery(UUID canonicalAccountUuid, CanonicalGameplayRosterTarget target) { + return dsl.select(CHARACTERS.CHARACTER_UUID, CHARACTERS.NAME, CHARACTERS.LEVEL) + .from(CHARACTERS) + .where( + CHARACTERS + .ACCOUNT_UUID + .eq(canonicalAccountUuid) + .and(CHARACTERS.TENANT_UUID.eq(target.tenantUuid())) + .and(CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID.eq(target.playableStateNamespaceId())) + .and(CHARACTERS.PLAYABLE_STATE_SCOPE.eq(target.playableStateScope().name())) + .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq(ActorIdentityStatus.OWNER_RESOLVED.name())) + .and(CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON.isNull())) + .orderBy(CHARACTERS.CHARACTER_UUID.asc()) + .limit(CanonicalGameplayRosterSnapshotDigest.MAX_ROSTER_SIZE + 1); + } + private CanonicalGameplayRosterSnapshot readBackCanonicalGameplayRosterSnapshot( UUID canonicalAccountUuid, CanonicalGameplayRosterTarget expectedTarget, diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter.java index 6f2889e011..422512e04d 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter.java @@ -60,7 +60,18 @@ public GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter( public CanonicalGameplayRosterOwnerEvidence resolveCurrentTarget( CanonicalGameplayRosterReadRequest request) { Objects.requireNonNull(request, "request"); - CanonicalGameplayRosterTarget expected = request.expectedTarget(); + return resolveCurrentTarget( + request.requestUuid(), request.canonicalAccountUuid(), request.expectedTarget()); + } + + /** Non-admitting current source read, without inventing an original selection or session. */ + public CanonicalGameplayRosterOwnerEvidence resolveCurrentTarget( + java.util.UUID requestUuid, + java.util.UUID canonicalAccountUuid, + CanonicalGameplayRosterTarget expected) { + Objects.requireNonNull(requestUuid, "requestUuid"); + Objects.requireNonNull(canonicalAccountUuid, "canonicalAccountUuid"); + Objects.requireNonNull(expected, "expected"); if (expected.playableStateScope() != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED || expected.entryPolicy() != CanonicalGameplayRosterEntryPolicy.PRESEEDED_ONLY) { throw new UnsupportedOperationException( @@ -69,8 +80,8 @@ public CanonicalGameplayRosterOwnerEvidence resolveCurrentTarget( CanonicalGameplayRosterOwnerReadEvidence.Request ownerReadRequest = new CanonicalGameplayRosterOwnerReadEvidence.Request( - request.requestUuid(), - request.canonicalAccountUuid(), + requestUuid, + canonicalAccountUuid, workloadNamespace, expected.tenantUuid(), expected.worldSlug(), @@ -95,7 +106,7 @@ public CanonicalGameplayRosterOwnerEvidence resolveCurrentTarget( } try { - return mapCompleteEvidence(request, ownerReadRequest, evidence); + return mapCompleteEvidence(ownerReadRequest, evidence); } catch (RuntimeException invalid) { if (invalid instanceof OwnerEvidenceUnavailableException unavailable) { throw unavailable; @@ -105,11 +116,9 @@ public CanonicalGameplayRosterOwnerEvidence resolveCurrentTarget( } private CanonicalGameplayRosterOwnerEvidence mapCompleteEvidence( - CanonicalGameplayRosterReadRequest request, CanonicalGameplayRosterOwnerReadEvidence.Request ownerReadRequest, CanonicalGameplayRosterOwnerReadEvidence evidence) { - if (!request.requestUuid().equals(evidence.request().requestUuid()) - || !request.canonicalAccountUuid().equals(evidence.request().canonicalAccountUuid())) { + if (!ownerReadRequest.equals(evidence.request())) { throw new IllegalArgumentException("Game Session evidence changed request/account binding"); } GameSessionCanonicalInitialAdmissionOwnerProof proof = evidence.gameSessionOwnerProof(); diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPostgresMtlsIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPostgresMtlsIntegrationTest.java new file mode 100644 index 0000000000..02b847b8b9 --- /dev/null +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPostgresMtlsIntegrationTest.java @@ -0,0 +1,488 @@ +package net.firedevops.firemud.entitymanagement.bootstrap; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.ManagedChannel; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.net.InetSocketAddress; +import java.nio.file.Path; +import java.time.Instant; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.account.RuntimeAccountIdentityEvidence; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +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.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadGrpcCodec; +import net.firedevops.firemud.entitymanagement.client.GameSessionCanonicalGameplayRosterOwnerReadClient; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentExpectedTarget; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentOwnerEvidence; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentRequest; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentResult; +import net.firedevops.firemud.entitymanagement.service.PreseededActorCorePayload; +import net.firedevops.firemud.entitymanagement.service.impl.GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadRequest; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadResponse; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterOwnerReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadResponse; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import net.firedevops.firemud.test.LoopbackMtlsTestPki.IdentitySpec; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Actual Entity/Saga migrations, assignment writer, read-only repository and two socket mTLS hops. + * Upstream COMMITTED target/published-policy bytes and assignment eligibility are controlled input; + * this does not execute Game Session/World/publication owner stores or prove production custody. + */ +@Testcontainers +@Timeout(value = 3, unit = TimeUnit.MINUTES) +@SuppressWarnings("resource") +class AccountBootstrapRosterPostgresMtlsIntegrationTest { + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @TempDir static Path directory; + private static LoopbackMtlsTestPki.Pki pki; + + @BeforeAll + static void certificates() throws Exception { + pki = + LoopbackMtlsTestPki.create( + directory, + "Account bootstrap roster test CA", + new IdentitySpec( + "entity-server", "spiffe://firemud/ns/test/sa/entity-management-service", true), + new IdentitySpec("gs-server", "spiffe://firemud/ns/test/sa/game-session-service", true), + new IdentitySpec( + "entity-client", "spiffe://firemud/ns/test/sa/entity-management-service", false), + new IdentitySpec("account", "spiffe://firemud/ns/test/sa/account-service", false), + new IdentitySpec( + "foreign-account", "spiffe://firemud/ns/other/sa/account-service", false), + new IdentitySpec( + "gs-client", "spiffe://firemud/ns/test/sa/game-session-service", false)); + } + + @Test + void persistedZeroOneAndAccountNamespaceIsolationHaveNoDiscoveryWrites() throws Exception { + try (var f = fixture()) { + var request = f.source.request(); + var before = f.rows(); + assertThat(f.read("account", request).getActorsList()).isEmpty(); + assertThat(f.rows()).isEqualTo(before); // valid empty does not enroll the namespace + UUID account = UUID.fromString(request.getCanonicalAccountUuid()); + UUID first = f.assign(account, f.source.target(), 101L, "Persisted Ship"); + f.dsl.execute("UPDATE characters SET level=7 WHERE character_uuid=?", first); + var one = f.read("account", request); + assertThat(one.getRequest()).isEqualTo(request); + assertThat(one.getActorsCount()).isEqualTo(1); + assertThat(one.getActors(0).getCharacterUuid()).isEqualTo(first.toString()); + assertThat(one.getActors(0).getDisplayName()).isEqualTo("Persisted Ship"); + assertThat(one.getActors(0).hasLevel()).isTrue(); + assertThat(one.getActors(0).getLevel()).isEqualTo(7); + // The current assignment writer/partial unique index permits one OWNER_RESOLVED actor per + // account namespace. This read does not widen that writer invariant to fabricate a many + // fixture. + UUID otherAccount = UUID.randomUUID(); + UUID zeroLevelActor = f.assign(otherAccount, f.source.target(), 102L, "Other Account"); + var otherNamespace = + request.getExpectedTarget().toBuilder() + .setPlayableStateNamespaceUuid(UUID.randomUUID().toString()) + .build(); + f.assign( + account, CanonicalGameplayRosterTarget.fromWire(otherNamespace), 101L, "Other Namespace"); + f.dsl.execute( + "INSERT INTO characters (account_id,account_uuid,name,tenant_id,playable_state_key) VALUES (101,?,'Quarantined',1,'shared-live')", + account); + before = f.rows(); + var isolated = f.read("account", request); + assertThat(isolated.getActorsList().stream().map(actor -> actor.getCharacterUuid()).toList()) + .containsExactly(first.toString()); + assertThat(isolated.getActors(0).getLevel()).isEqualTo(7); + var storedZero = + f.read( + "account", + request.toBuilder().setCanonicalAccountUuid(otherAccount.toString()).build()); + assertThat(storedZero.getActors(0).getCharacterUuid()).isEqualTo(zeroLevelActor.toString()); + assertThat(storedZero.getActors(0).hasLevel()).isTrue(); + assertThat(storedZero.getActors(0).getLevel()).isZero(); + assertThat( + f.read( + "account", + request.toBuilder() + .setCanonicalAccountUuid(UUID.randomUUID().toString()) + .build()) + .getActorsList()) + .isEmpty(); + assertThat(f.rows()).isEqualTo(before); + assertThat(f.ownerReads.get()).isEqualTo(10); + } + } + + @Test + void workloadGuardPrecedesMalformedDecodeAndUnsupportedScopeOrNamespaceNeverQueriesSource() + throws Exception { + try (var f = fixture()) { + var malformed = + f.source.request().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + f.refuses("foreign-account", malformed, Status.Code.PERMISSION_DENIED); + f.refuses("gs-client", malformed, Status.Code.PERMISSION_DENIED); + f.refuses("account", malformed, Status.Code.INVALID_ARGUMENT); + f.refuses( + "account", + f.source.request().toBuilder().setTargetNamespace("other").build(), + Status.Code.PERMISSION_DENIED); + f.refuses( + "account", + f.source.request().toBuilder() + .setExpectedTarget( + f.source.request().getExpectedTarget().toBuilder() + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) + .build(), + Status.Code.FAILED_PRECONDITION); + f.refuses( + "account", + f.source.request().toBuilder() + .setExpectedTarget( + f.source.request().getExpectedTarget().toBuilder() + .setEntryPolicy( + net.firedevops.firemud.entitymanagement.v1 + .CanonicalGameplayRosterEntryPolicy + .CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED)) + .build(), + Status.Code.FAILED_PRECONDITION); + assertThat(f.ownerReads.get()).isZero(); + } + } + + @Test + void unavailableChangedDigestAndSourceMovementAcrossSqlRefuseWithoutEmptySuccess() + throws Exception { + try (var f = fixture()) { + var before = f.rows(); + f.unavailable = true; + f.refuses("account", f.source.request(), Status.Code.UNAVAILABLE); + f.unavailable = false; + f.pointerDigest.set("f".repeat(64)); + f.refuses("account", f.source.request(), Status.Code.FAILED_PRECONDITION); + f.pointerDigest.set(f.source.target().admissionPointerSnapshotDigest()); + f.changeAfterNextSourceRead = true; + f.refuses("account", f.source.request(), Status.Code.FAILED_PRECONDITION); + assertThat(f.rows()).isEqualTo(before); + } + } + + private static Fixture fixture() throws Exception { + String schema = "entity_bootstrap_" + UUID.randomUUID().toString().replace("-", ""); + var ds = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + ds.setSchema(schema); + var migration = + Flyway.configure() + .dataSource(ds) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_entity_management_service") + .locations( + "filesystem:" + + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(), + "classpath:db/migration/saga") + .placeholders(Map.of("serviceSchema", schema)); + migration + .getConfigurationExtension(PostgreSQLConfigurationExtension.class) + .setTransactionalLock(false); + migration.load().migrate(); + return new Fixture( + schema, + DSL.using(new TransactionAwareDataSourceProxy(ds), SQLDialect.POSTGRES), + new DataSourceTransactionManager(ds)); + } + + private static final class Fixture implements AutoCloseable { + final String schema; + final DSLContext dsl; + final DataSourceTransactionManager manager; + final CharacterRepository characters; + final AccountBootstrapRosterFixture.Fixture source; + final AtomicInteger ownerReads = new AtomicInteger(); + final AtomicReference pointerDigest; + volatile boolean unavailable; + volatile boolean changeAfterNextSourceRead; + final Server sourceServer; + final Server entityServer; + final GameSessionCanonicalGameplayRosterOwnerReadClient client; + final List channels = new ArrayList<>(); + + Fixture(String schema, DSLContext dsl, DataSourceTransactionManager manager) throws Exception { + this.schema = schema; + this.dsl = dsl; + this.manager = manager; + characters = new CharacterRepository(dsl); + source = AccountBootstrapRosterFixture.create(); + pointerDigest = new AtomicReference<>(source.target().admissionPointerSnapshotDigest()); + sourceServer = + server( + "gs-server", + new CanonicalGameplayRosterOwnerReadServiceGrpc + .CanonicalGameplayRosterOwnerReadServiceImplBase() { + @Override + public void getCanonicalGameplayRosterOwnerRead( + GetCanonicalGameplayRosterOwnerReadRequest wire, + StreamObserver observer) { + var peer = GrpcPeerIdentity.current(); + if (peer == null + || !peer.isService("entity-management-service") + || !peer.isInNamespace("test")) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + ownerReads.incrementAndGet(); + if (unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + return; + } + var request = CanonicalGameplayRosterOwnerReadGrpcCodec.fromRequest(wire); + var base = source.evidence().request(); + var rebound = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + request.requestUuid(), + request.canonicalAccountUuid(), + base.targetNamespace(), + base.canonicalTenantUuid(), + base.worldSlug(), + base.realmUuid(), + base.realmSlug(), + base.playableStateNamespaceUuid(), + base.playableStateScope(), + base.canonicalGameInstanceUuid(), + base.canonicalVersionUuid(), + base.expectedCatalogRevision(), + base.expectedPointerVersion(), + base.expectedActiveWorldEpoch()); + if (!request.equals(rebound)) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + return; + } + var evidence = + new CanonicalGameplayRosterOwnerReadEvidence( + request, + pointerDigest.get(), + source.evidence().gameSessionOwnerProof(), + source.evidence().publishedPolicySetEvidence()); + if (changeAfterNextSourceRead) { + pointerDigest.set("f".repeat(64)); + changeAfterNextSourceRead = false; + } + observer.onNext( + CanonicalGameplayRosterOwnerReadGrpcCodec.toResponse(request, evidence)); + observer.onCompleted(); + } + }, + new GrpcPeerIdentityInterceptor()); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameSessionService("127.0.0.1:" + sourceServer.getPort()); + client = + new GameSessionCanonicalGameplayRosterOwnerReadClient( + endpoints, + pki.clientProperties(directory, pki.identity("entity-client")), + new GrpcChannelFactory(), + "test"); + client.init(); + var service = + new AccountBootstrapRosterReadService( + new GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter(client, "test"), + characters, + manager); + entityServer = + server( + "entity-server", + new AccountBootstrapRosterReadGrpcService(service, "test"), + new AccountBootstrapRosterPeerInterceptor("test")); + } + + AccountBootstrapRosterReadResponse read(String alias, AccountBootstrapRosterReadRequest request) + throws Exception { + var identity = pki.identity(alias); + var channel = + NettyChannelBuilder.forAddress("127.0.0.1", entityServer.getPort()) + .sslContext( + GrpcSslContexts.forClient() + .trustManager(pki.caCertificate()) + .keyManager( + identity.privateKey(), identity.certificate(), pki.caCertificate()) + .build()) + .intercept( + new GrpcServerPeerIdentityClientInterceptor( + "spiffe://firemud/ns/test/sa/entity-management-service")) + .maxInboundMessageSize(AccountBootstrapRosterReadContract.MAX_RESPONSE_BYTES) + .build(); + channels.add(channel); + return AccountBootstrapRosterReadServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(10, TimeUnit.SECONDS) + .readAccountBootstrapRoster(request); + } + + void refuses(String alias, AccountBootstrapRosterReadRequest request, Status.Code expected) { + assertThatThrownBy(() -> read(alias, request)) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + UUID assign(UUID account, CanonicalGameplayRosterTarget target, long rowId, String name) { + UUID operation = UUID.randomUUID(); + var evidence = + new PreseededActorAssignmentOwnerEvidence( + operation, + account, + PreseededActorAssignmentOwnerEvidence.Eligibility.ELIGIBLE, + Instant.parse("2026-10-04T00:00:00Z"), + 4L, + "1".repeat(64), + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid().toString(), + target.catalogRevision(), + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.playableStateNamespaceId(), + target.playableStateScope(), + PreseededActorAssignmentOwnerEvidence.PublishedEntryPolicy.PRESEEDED_ONLY, + PreseededActorAssignmentOwnerEvidence.AccountPurpose.PRESEEDED_ACTOR_STAGING, + PreseededActorAssignmentOwnerEvidence.AccountCurrentness.CURRENT_AT_REVALIDATION, + "2".repeat(64), + target.publishedOwnerProofDigest(), + target.publishedReleaseBundleRef()); + var request = + new PreseededActorAssignmentRequest( + operation, + account, + new PreseededActorCorePayload(PreseededActorCorePayload.ActorKind.PLAYER, name), + new PreseededActorAssignmentExpectedTarget( + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid().toString(), + target.catalogRevision(), + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.playableStateNamespaceId(), + target.publishedReleaseBundleRef(), + target.playableStateScope())); + var result = + new TransactionTemplate(manager) + .execute( + ignored -> + characters.assignPreseededActor( + request, + evidence, + new RuntimeAccountIdentityEvidence( + 1, "test", operation, account, rowId, "ACCOUNT_DATABASE_INSERT"), + request.mutationIntentDigest())); + assertThat(result.outcome()).isEqualTo(PreseededActorAssignmentResult.Outcome.ASSIGNED); + return result.characterUuid(); + } + + Map> rows() { + var rows = new LinkedHashMap>(); + for (String table : + List.of( + "characters", + "entity_playable_state_namespace_scopes", + "entity_preseeded_actor_assignment_operations", + "entity_canonical_gameplay_roster_snapshots", + "entity_canonical_gameplay_roster_snapshot_actors", + "entity_canonical_roster_original_selections", + "entity_canonical_roster_admissions", + "entity_canonical_roster_retention_references")) { + rows.put( + table, + dsl.fetch( + "SELECT to_jsonb(t)::text||':'||xmin::text AS value FROM " + + table + + " t ORDER BY value") + .getValues(0, String.class)); + } + return rows; + } + + @Override + public void close() throws Exception { + for (var channel : channels) { + channel.shutdownNow(); + assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + entityServer.shutdownNow(); + assertThat(entityServer.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + client.close(); + sourceServer.shutdownNow(); + assertThat(sourceServer.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + dsl.execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + + private static Server server( + String alias, io.grpc.BindableService service, io.grpc.ServerInterceptor interceptor) + throws Exception { + var identity = pki.identity(alias); + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .maxInboundMessageSize(AccountBootstrapRosterReadContract.MAX_REQUEST_BYTES) + .addService(ServerInterceptors.intercept(service, interceptor)) + .build() + .start(); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPeerInterceptorTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPeerInterceptorTest.java new file mode 100644 index 0000000000..deac9277d9 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPeerInterceptorTest.java @@ -0,0 +1,108 @@ +package unit.net.firedevops.firemud.entitymanagement.bootstrap; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.*; + +import io.grpc.Attributes; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.Status; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.List; +import java.util.Map; +import javax.net.ssl.SSLSession; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.entitymanagement.bootstrap.AccountBootstrapRosterPeerInterceptor; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +class AccountBootstrapRosterPeerInterceptorTest { + @AfterEach + void clear() { + SessionContext.clear(); + } + + @Test + void exactAccountCertificateIsAvailableBeforeMessageHandling() throws Exception { + var call = call("spiffe://firemud/ns/test/sa/account-service"); + ServerCallHandler next = mock(ServerCallHandler.class); + when(next.startCall(any(), any())) + .thenAnswer( + ignored -> { + assertThat(GrpcPeerIdentity.current().isService("account-service")).isTrue(); + assertThat(GrpcPeerIdentity.current().isInNamespace("test")).isTrue(); + return new ServerCall.Listener() {}; + }); + new AccountBootstrapRosterPeerInterceptor("test").interceptCall(call, new Metadata(), next); + verify(next).startCall(any(), any()); + } + + @Test + void absentWrongNamespaceAndGameSessionPeersNeverStartMessageDecoding() throws Exception { + for (String identity : + new String[] { + null, + "spiffe://firemud/ns/other/sa/account-service", + "spiffe://firemud/ns/test/sa/game-session-service" + }) { + var call = call(identity); + ServerCallHandler next = mock(ServerCallHandler.class); + new AccountBootstrapRosterPeerInterceptor("test").interceptCall(call, new Metadata(), next); + verify(next, never()).startCall(any(), any()); + verify(call) + .close( + argThat( + status -> + status.getCode() + == (identity == null + ? Status.Code.UNAUTHENTICATED + : Status.Code.PERMISSION_DENIED)), + any()); + } + } + + @Test + void callerRoleAndInternalServiceContextsCannotSupplyDiscoveryAuthority() throws Exception { + for (boolean internal : List.of(false, true)) { + SessionContext.setContext( + internal ? null : "11111111-1111-4111-8111-111111111111", + internal ? List.of() : List.of("platformAdmin"), + Map.of(), + internal, + "account-service", + "instance"); + var call = call("spiffe://firemud/ns/test/sa/account-service"); + ServerCallHandler next = mock(ServerCallHandler.class); + new AccountBootstrapRosterPeerInterceptor("test").interceptCall(call, new Metadata(), next); + verify(next, never()).startCall(any(), any()); + verify(call) + .close(argThat(status -> status.getCode() == Status.Code.PERMISSION_DENIED), any()); + SessionContext.clear(); + } + } + + private static ServerCall call(String identity) throws Exception { + ServerCall call = mock(ServerCall.class); + MethodDescriptor descriptor = mock(MethodDescriptor.class); + when(descriptor.getFullMethodName()) + .thenReturn(AccountBootstrapRosterPeerInterceptor.METHOD_NAME); + when(call.getMethodDescriptor()).thenReturn(descriptor); + var attributes = Attributes.EMPTY; + if (identity != null) { + X509Certificate leaf = mock(X509Certificate.class); + when(leaf.getSubjectAlternativeNames()).thenReturn(List.of(List.of(6, identity))); + SSLSession session = mock(SSLSession.class); + when(session.getPeerCertificates()).thenReturn(new Certificate[] {leaf}); + attributes = Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, session).build(); + } + when(call.getAttributes()).thenReturn(attributes); + return call; + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadServiceTest.java new file mode 100644 index 0000000000..2b46dfa4b1 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadServiceTest.java @@ -0,0 +1,219 @@ +package unit.net.firedevops.firemud.entitymanagement.bootstrap; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.*; + +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.entitymanagement.bootstrap.AccountBootstrapRosterActorProjection; +import net.firedevops.firemud.entitymanagement.bootstrap.AccountBootstrapRosterFixture; +import net.firedevops.firemud.entitymanagement.bootstrap.AccountBootstrapRosterReadContract; +import net.firedevops.firemud.entitymanagement.bootstrap.AccountBootstrapRosterReadService; +import net.firedevops.firemud.entitymanagement.client.GameSessionCanonicalGameplayRosterOwnerReadClient; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterOwnerEvidencePort.OwnerEvidenceUnavailableException; +import net.firedevops.firemud.entitymanagement.service.impl.GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterActor; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadResponse; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +class AccountBootstrapRosterReadServiceTest { + @Test + void realAdapterReadsCurrentSourceBeforeAndAfterShortLocalProjectionIncludingEmpty() + throws Exception { + var f = AccountBootstrapRosterFixture.create(); + var client = mock(GameSessionCanonicalGameplayRosterOwnerReadClient.class); + var repository = mock(CharacterRepository.class); + when(client.getCanonicalGameplayRosterOwnerRead(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat( + invocation.getArgument( + 0, CanonicalGameplayRosterOwnerReadEvidence.Request.class)) + .isEqualTo(f.evidence().request()); + return f.evidence(); + }); + UUID actor = UUID.randomUUID(); + when(repository.readAccountBootstrapRoster(any(), eq(f.target()))) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isTrue(); + return List.of( + new AccountBootstrapRosterActorProjection(actor, "Persisted Actor", 7)); + }) + .thenReturn(List.of()); + var service = service(client, repository); + assertThat(service.read(f.request()).getActorsList()) + .containsExactly( + AccountBootstrapRosterActor.newBuilder() + .setCharacterUuid(actor.toString()) + .setDisplayName("Persisted Actor") + .setLevel(7) + .build()); + assertThat(service.read(f.request()).getActorsList()).isEmpty(); + verify(client, times(4)).getCanonicalGameplayRosterOwnerRead(f.evidence().request()); + verify(repository, times(2)) + .readAccountBootstrapRoster( + UUID.fromString(f.request().getCanonicalAccountUuid()), f.target()); + verifyNoMoreInteractions(client, repository); + } + + @Test + void sourceChangedBeforeSqlOrDuringProjectionNeverReturnsEmptySuccess() throws Exception { + var f = AccountBootstrapRosterFixture.create(); + var changed = + new CanonicalGameplayRosterOwnerReadEvidence( + f.evidence().request(), + "f".repeat(64), + f.evidence().gameSessionOwnerProof(), + f.evidence().publishedPolicySetEvidence()); + var client = mock(GameSessionCanonicalGameplayRosterOwnerReadClient.class); + var repository = mock(CharacterRepository.class); + var service = service(client, repository); + when(client.getCanonicalGameplayRosterOwnerRead(any())).thenReturn(changed); + assertThatThrownBy(() -> service.read(f.request())) + .isInstanceOf(AccountBootstrapRosterReadService.TargetChangedException.class); + verifyNoInteractions(repository); + when(client.getCanonicalGameplayRosterOwnerRead(any())).thenReturn(f.evidence(), changed); + when(repository.readAccountBootstrapRoster(any(), any())).thenReturn(List.of()); + assertThatThrownBy(() -> service.read(f.request())) + .isInstanceOf(AccountBootstrapRosterReadService.TargetChangedException.class); + verify(repository).readAccountBootstrapRoster(any(), any()); + } + + @Test + void unavailableOrWrongAccountSourceCannotBeAnEmptyRoster() throws Exception { + var f = AccountBootstrapRosterFixture.create(); + var client = mock(GameSessionCanonicalGameplayRosterOwnerReadClient.class); + var repository = mock(CharacterRepository.class); + var service = service(client, repository); + when(client.getCanonicalGameplayRosterOwnerRead(any())) + .thenThrow(new IllegalStateException("offline")); + assertThatThrownBy(() -> service.read(f.request())) + .isInstanceOf(OwnerEvidenceUnavailableException.class); + org.mockito.Mockito.doReturn(f.evidence()) + .when(client) + .getCanonicalGameplayRosterOwnerRead(any()); + var changedAccount = + f.request().toBuilder().setCanonicalAccountUuid(UUID.randomUUID().toString()).build(); + assertThatThrownBy(() -> service.read(changedAccount)) + .isInstanceOf(OwnerEvidenceUnavailableException.class); + verifyNoInteractions(repository); + } + + @Test + void malformedUnsupportedAndAmbientTransactionRefuseBeforeAnySourceOrSql() throws Exception { + var f = AccountBootstrapRosterFixture.create(); + var client = mock(GameSessionCanonicalGameplayRosterOwnerReadClient.class); + var repository = mock(CharacterRepository.class); + var service = service(client, repository); + assertThatThrownBy( + () -> service.read(f.request().toBuilder().setCanonicalAccountUuid("12").build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.read( + f.request().toBuilder() + .setExpectedTarget( + f.request().getExpectedTarget().toBuilder() + .setPlayableStateScope( + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) + .build())) + .isInstanceOf(UnsupportedOperationException.class); + var unknown = + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + assertThatThrownBy( + () -> service.read(f.request().toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class); + new TransactionTemplate(new LocalTransactions()) + .executeWithoutResult( + ignored -> { + assertThatThrownBy(() -> service.read(f.request())) + .isInstanceOf(AccountBootstrapRosterReadService.TargetChangedException.class); + }); + verifyNoInteractions(client, repository); + } + + @Test + void exactEchoClosedActorBoundsCanonicalIdsAndDeterministicOrderAreRequired() throws Exception { + var f = AccountBootstrapRosterFixture.create(); + var first = + AccountBootstrapRosterActor.newBuilder() + .setCharacterUuid("11111111-1111-4111-8111-111111111111") + .setDisplayName("First") + .setLevel(0) + .build(); + var second = first.toBuilder().setCharacterUuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa").build(); + var valid = + AccountBootstrapRosterReadResponse.newBuilder() + .setRequest(f.request()) + .addActors(first) + .addActors(second) + .build(); + assertThat(AccountBootstrapRosterReadContract.requireResponse(f.request(), valid)) + .isEqualTo(valid); + for (var invalid : + List.of( + valid.toBuilder() + .setRequest(f.request().toBuilder().setRequestUuid(UUID.randomUUID().toString())) + .build(), + valid.toBuilder().addActors(second).build(), + valid.toBuilder().clearActors().addActors(second).addActors(first).build(), + valid.toBuilder() + .clearActors() + .addActors(first.toBuilder().setCharacterUuid("1")) + .build(), + valid.toBuilder() + .clearActors() + .addActors(first.toBuilder().setDisplayName(" First")) + .build(), + valid.toBuilder().clearActors().addActors(first.toBuilder().clearLevel()).build(), + valid.toBuilder().clearActors().addActors(first.toBuilder().setLevel(-1)).build(), + valid.toBuilder().addAllActors(java.util.Collections.nCopies(100, second)).build())) { + assertThatThrownBy( + () -> AccountBootstrapRosterReadContract.requireResponse(f.request(), invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + private static AccountBootstrapRosterReadService service( + GameSessionCanonicalGameplayRosterOwnerReadClient client, CharacterRepository repository) { + return new AccountBootstrapRosterReadService( + new GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter( + client, AccountBootstrapRosterFixture.NAMESPACE), + repository, + new LocalTransactions()); + } + + private static final class LocalTransactions extends AbstractPlatformTransactionManager { + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected void doBegin(Object tx, TransactionDefinition definition) {} + + @Override + protected void doCommit(DefaultTransactionStatus status) {} + + @Override + protected void doRollback(DefaultTransactionStatus status) {} + } +} diff --git a/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterFixture.java b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterFixture.java new file mode 100644 index 0000000000..febbbd1d8d --- /dev/null +++ b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterFixture.java @@ -0,0 +1,272 @@ +package net.firedevops.firemud.entitymanagement.bootstrap; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.testing.AuthoringFixtures; +import net.firedevops.firemud.common.testing.PlayerCreatedPublishedPolicyFixtures; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterEntryPolicy; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadRequest; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.test.IsolatedWorldPublicationInventoryFixtures; +import tools.jackson.databind.json.JsonMapper; + +/** + * Complete closed upstream bytes are controlled test input, not executed publication/World custody. + */ +public final class AccountBootstrapRosterFixture { + public static final String NAMESPACE = "test"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private AccountBootstrapRosterFixture() {} + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "The retained generated protobuf request message is immutable.") + public record Fixture( + AccountBootstrapRosterReadRequest request, + CanonicalGameplayRosterTarget target, + CanonicalGameplayRosterOwnerReadEvidence evidence) { + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The retained generated protobuf request message is immutable.") + public Fixture {} + } + + public static Fixture create() throws Exception { + var account = AuthoringFixtures.freshGraphRequest().accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); + var prepared = PlayerCreatedPublishedPolicyFixtures.prepare(draft); + var operation = + new GameDesignPublicationOperationBinding( + prepared.account(), + prepared.world(), + IsolatedWorldPublicationInventoryFixtures.stipulated( + prepared.account(), prepared.world())); + var world = prepared.world().request(); + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new GameDesignPublicationTerminalEvidence.Participant( + owner, + Long.toString(draft.target().gameDesignVersionRowId()), + null, + world.appliedCommitId(), + owner.equals("WORLD_MANAGEMENT") ? world.contentDigest() : "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + owner.equals("GAME_LOGIC") ? "sha256:" + "a".repeat(64) : null, + null, + null)) + .toList(); + var release = + new GameDesignPublicationTerminalEvidence.ReleaseContent( + world.canonicalTenantId(), + world.canonicalVersionId(), + "bundle:bootstrap-test", + 3, + "v2", + world.publishWorkflowId(), + "sha256:" + "a".repeat(64), + 1, + List.of(), + List.of(), + participants, + List.of("LOOK"), + "generation-1", + prepared.world()); + var terminal = + new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), + GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED, + release, + 6L); + var policy = + RealmEntryPolicy.parse( + """ + {"schemaVersion":1,"worldSlug":"earth","worldDisplayName":"Earth", + "realmSlug":"main","realmDisplayName":"Main","visible":true, + "publicProduction":true,"stateScope":"SHARED","entryPolicy":"PRESEEDED_ONLY"} + """, + JSON); + UUID policyId = UUID.randomUUID(); + UUID revisionId = UUID.randomUUID(); + String logical = "realm-policy/earth/main"; + var selected = + new PublishedRealmEntryPolicyEvidence( + policyId, + draft.commitId(), + revisionId, + logical, + policy, + PublishedRealmEntryPolicyEvidence.calculateDigest( + policyId, + draft.target(), + 3, + release.publishedReleaseBundleRef(), + release.contentDigest(), + world.publishWorkflowId(), + release.manifestHash(), + draft.commitId(), + revisionId, + logical, + policy)); + var snapshot = + Map.of( + "schema", + PublishedRealmEntryPolicySetEvidence.SNAPSHOT_SCHEMA, + "bindingJson", + draft.canonicalJson(), + "bindingDigest", + draft.digest(), + "sourceEpoch", + "1", + "policies", + List.of( + Map.of( + "commitId", + draft.commitId().toString(), + "revisionId", + revisionId.toString(), + "logicalRevisionId", + logical, + "policy", + JSON.readTree(policy.canonicalJson())))); + var capture = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + capture, PublishedRealmEntryPolicySetEvidence.CAPTURE_SCHEMA); + DraftAuthorizationFenceBinding.frame(capture, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame( + capture, Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(snapshot))); + var policies = List.of(selected); + String digest = + PublishedRealmEntryPolicySetEvidence.calculatePolicySetDigest( + draft.target(), + 3, + draft.commitId(), + "1", + release.publishedReleaseBundleRef(), + release.contentDigest(), + world.publishWorkflowId(), + release.manifestHash(), + 6L, + operation.canonicalBytes(), + capture.toByteArray(), + terminal.canonicalBytes(), + policies); + var policySet = + new PublishedRealmEntryPolicySetEvidence( + draft.target(), + 3, + draft.commitId(), + "1", + release.publishedReleaseBundleRef(), + release.contentDigest(), + world.publishWorkflowId(), + release.manifestHash(), + 6L, + operation.canonicalBytes(), + capture.toByteArray(), + terminal.canonicalBytes(), + 1, + digest, + policies); + UUID realm = UUID.randomUUID(); + UUID namespace = UUID.randomUUID(); + UUID instance = UUID.randomUUID(); + var hold = + new WorldCanonicalInitialAdmissionHold.HoldIdentity( + new WorldCanonicalInitialAdmissionHold.Request( + NAMESPACE, + draft.target().canonicalTenantId(), + "earth", + realm, + namespace, + "SHARED", + instance, + draft.target().canonicalVersionId(), + 82L, + "controlled-initial-target", + "d".repeat(64), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + 71L, + null), + UUID.randomUUID(), + UUID.randomUUID()); + var proof = + new GameSessionCanonicalInitialAdmissionOwnerProof( + hold, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + 73L, + 91L, + "sha256:" + "b".repeat(64), + false, + Instant.parse("2026-10-08T03:04:05Z")); + var target = + new CanonicalGameplayRosterTarget( + draft.target().canonicalTenantId(), + realm, + "earth", + "main", + instance, + 71L, + 73L, + 82L, + draft.target().canonicalVersionId(), + selected.policyDigest().substring(7), + release.publishedReleaseBundleRef(), + "a".repeat(64), + "b".repeat(64), + namespace, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + CanonicalGameplayRosterEntryPolicy.PRESEEDED_ONLY); + var request = + AccountBootstrapRosterReadRequest.newBuilder() + .setRequestUuid(UUID.randomUUID().toString()) + .setCanonicalAccountUuid(UUID.randomUUID().toString()) + .setTargetNamespace(NAMESPACE) + .setExpectedTarget(target.toWire()) + .build(); + var ownerRequest = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + UUID.fromString(request.getRequestUuid()), + UUID.fromString(request.getCanonicalAccountUuid()), + NAMESPACE, + target.tenantUuid(), + "earth", + realm, + "main", + namespace, + "SHARED", + instance, + target.canonicalVersionUuid(), + 71L, + 73L, + 82L); + return new Fixture( + request, + target, + new CanonicalGameplayRosterOwnerReadEvidence( + ownerRequest, target.admissionPointerSnapshotDigest(), proof, policySet)); + } +} diff --git a/services/game-session-service/build.gradle.kts b/services/game-session-service/build.gradle.kts index ab2b77fa28..c2bd44fa92 100644 --- a/services/game-session-service/build.gradle.kts +++ b/services/game-session-service/build.gradle.kts @@ -187,10 +187,14 @@ val gameSessionClassesProofJar by tasks.registering(Jar::class) { include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture*.class") include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture*.class") include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture*.class") + include("net/firedevops/firemud/gamesession/repository/CanonicalPublishedAdmissionActualOwnerCompositionFixture*.class") include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayControlledInitialObservationFixture*.class") include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionTestFixture*.class") + include("net/firedevops/firemud/gamesession/service/InitialGameplayLoginPhysicalCompositionFixture*.class") } from("src/main/resources") { + include("redis/lua/game-session-initial-context-cas.lua") + include("redis/scripts/game-session-initial-context-cas.json") include("redis/lua/game-session-issuer-bootstrap-partition-build.lua") include("redis/scripts/game-session-issuer-bootstrap-partition-build.json") include("redis/lua/game-session-issuer-binding-local-add.lua") diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClient.java new file mode 100644 index 0000000000..7d88cf4ae2 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClient.java @@ -0,0 +1,393 @@ +package net.firedevops.firemud.gamesession.client; + +import io.grpc.Context; +import io.grpc.Deadline; +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Clock; +import java.time.Instant; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; +import java.util.function.Supplier; +import net.firedevops.firemud.account.v1.AccountPlayerAdmissionEntitlementReadServiceGrpc; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementGrpcCodec; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +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.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyScope; + +/** + * Manually composed Account PLAYER_ADMISSION read. The caller supplies an owned canonical scope and + * live LOGIN custody; this client contributes no admission decision or hold. + */ +public final class AccountPlayerAdmissionEntitlementClient + extends AbstractReloadingBlockingGrpcClient< + AccountPlayerAdmissionEntitlementReadServiceGrpc + .AccountPlayerAdmissionEntitlementReadServiceBlockingStub> { + private final String namespace; + private final String expectedAccountPeer; + private final Clock clock; + + public AccountPlayerAdmissionEntitlementClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + String workloadNamespace, + Clock clock) { + super( + endpoints, + requireFileBackedMtls(tls, "Player-admission entitlement read"), + channels, + AccountPlayerAdmissionEntitlementClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Fixed Game Session workload namespace required"); + } + this.namespace = workloadNamespace; + this.expectedAccountPeer = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + this.clock = Objects.requireNonNull(clock, "Clock required"); + } + + /** Initializes this workflow-owned client outside any ambient SQL transaction. */ + public void init() throws IOException { + requireNoAmbientSql( + "Player-admission entitlement client initialization requires no ambient SQL"); + initOnce("Player-admission entitlement client is closed", "Account read unavailable"); + } + + /** + * Reads the exact current Account value for one verified first-party scope and LOGIN result. The + * token is disclosed only by the generated request after exact same-namespace Account mTLS peer + * verification. This read supplies no World hold and never persists LOGIN custody. + */ + public RuntimePlayerAdmissionEntitlementEvidence read( + FirstPartyConnectContext verifiedContext, + UUID readRequestId, + CanonicalGameplayLoginResult loginCustody, + BooleanSupplier loginCustodyCurrent) { + return read( + readRequestId, + loginCustody, + loginCustodyCurrent, + () -> request(verifiedContext, readRequestId), + () -> request(verifiedContext, readRequestId), + evidence -> + requireTargetBinding( + evidence, + verifiedContext.resolvedTarget(), + Instant.ofEpochMilli(verifiedContext.claims().expiresAtMillis()).toString())); + } + + /** + * Borrows an Account-issued direct-text lobby scope inside its owner's current custody callback. + * Retaining or decoding the scope never establishes that custody; this read installs no context. + */ + public RuntimePlayerAdmissionEntitlementEvidence read( + DirectTextAuthenticatedLobbyScope scope, + InitialGameplayLoginAttemptCoordinates original, + ObservedDirectTextTransport transport, + UUID readRequestId, + CanonicalGameplayLoginResult loginCustody, + BooleanSupplier loginCustodyCurrent) { + return read( + readRequestId, + loginCustody, + loginCustodyCurrent, + () -> { + if (scope == null) throw invalid(); + scope.requireCurrent(original, loginCustody, transport, clock); + }, + () -> + request( + scope.publicTarget(), + scope.evidence().accountId(), + scope.issued().connectScopeId(), + readRequestId), + evidence -> + requireTargetBinding( + evidence, scope.publicTarget(), scope.issued().connectScopeExpiresAt())); + } + + private RuntimePlayerAdmissionEntitlementEvidence read( + UUID readRequestId, + CanonicalGameplayLoginResult loginCustody, + BooleanSupplier loginCustodyCurrent, + Runnable requireScopeCurrent, + Supplier requestSource, + Consumer requireResponseTarget) { + requireNoAmbientSql("Player-admission entitlement RPC requires no ambient SQL"); + Deadline overall = + Deadline.after( + RuntimePlayerAdmissionEntitlementGrpcCodec.CALL_DEADLINE_SECONDS, TimeUnit.SECONDS); + if (Context.current().getDeadline() != null) { + overall = overall.minimum(Context.current().getDeadline()); + } + if (!v4(readRequestId)) { + throw invalid(); + } + requireCurrent(loginCustodyCurrent, requireScopeCurrent); + if (overall.isExpired()) { + throw failure(Status.Code.DEADLINE_EXCEEDED); + } + + var request = requestSource.get(); + var login = requireLiveLogin(loginCustody, request.target().accountId()); + byte[] compactJwt = null; + try { + compactJwt = loginCustody.compactJwtBytes(); + requireCurrent(loginCustodyCurrent, requireScopeCurrent); + if (overall.isExpired()) { + throw failure(Status.Code.DEADLINE_EXCEEDED); + } + if (!isBoundedAsciiJwt(compactJwt) || !matchesSha256(compactJwt, login.tokenSha256())) { + throw invalid(); + } + String compact = new String(compactJwt, StandardCharsets.US_ASCII); + var wireRequest = RuntimePlayerAdmissionEntitlementGrpcCodec.toRequest(request, compact); + var stub = + requireInitializedStub("Account player-admission entitlement client is unavailable") + .withDeadline(overall) + .withMaxOutboundMessageSize( + RuntimePlayerAdmissionEntitlementGrpcCodec.MAX_REQUEST_WIRE_BYTES) + .withMaxInboundMessageSize( + RuntimePlayerAdmissionEntitlementGrpcCodec.MAX_RESPONSE_WIRE_BYTES); + // Recheck immediately before invoking gRPC; the call credentials independently gate body + // release on the exact authenticated Account peer. + requireCurrent(loginCustodyCurrent, requireScopeCurrent); + if (overall.isExpired()) { + throw failure(Status.Code.DEADLINE_EXCEEDED); + } + var response = stub.readPlayerAdmissionEntitlement(wireRequest); + requireCurrent(loginCustodyCurrent, requireScopeCurrent); + requireLiveLogin(loginCustody, request.target().accountId()); + var evidence = RuntimePlayerAdmissionEntitlementGrpcCodec.requireResponse(request, response); + requireResponseTarget.accept(evidence); + requireLoginBinding(evidence, login); + requireCurrent(loginCustodyCurrent, requireScopeCurrent); + requireLiveLogin(loginCustody, request.target().accountId()); + evidence.requireCurrentAt(clock.instant()); + return evidence; + } catch (StatusRuntimeException transport) { + throw failure(transport.getStatus().getCode()); + } finally { + if (compactJwt != null) { + Arrays.fill(compactJwt, (byte) 0); + } + } + } + + private RuntimePlayerAdmissionEntitlementGrpcCodec.Request request( + FirstPartyConnectContext context, UUID readRequestId) { + try { + if (context == null || !context.hasCompleteRoutingScope()) { + throw invalid(); + } + var claims = context.claims(); + UUID accountId = UUID.fromString(context.accountId()); + if (!v4(accountId) + || claims.expiresAtMillis() <= clock.millis() + || context.connectScopeId() == null + || context.connectScopeId().isBlank()) { + throw invalid(); + } + return request(context.resolvedTarget(), accountId, context.connectScopeId(), readRequestId); + } catch (RuntimeException invalidContext) { + throw invalid(); + } + } + + private RuntimePlayerAdmissionEntitlementGrpcCodec.Request request( + CanonicalPlayableTarget target, UUID accountId, String connectScopeId, UUID readRequestId) { + if (target == null + || !namespace.equals(target.targetNamespace()) + || !"SHARED".equals(target.playableStateScope()) + || !"PRESEEDED_ONLY".equals(target.characterCreationPolicy()) + || target.positiveDurableAbort() + || !v4(accountId)) throw invalid(); + var selector = + new RetainedTargetSelector( + readRequestId, + accountId, + target.targetNamespace(), + target.canonicalTenantId(), + target.tenantSlug(), + target.worldSlug(), + target.realmId(), + target.realmSlug(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + target.catalogRevision(), + target.pointerVersion()); + return new RuntimePlayerAdmissionEntitlementGrpcCodec.Request(selector, connectScopeId); + } + + private CanonicalGameplayLoginResult.NonSecretEvidence requireLiveLogin( + CanonicalGameplayLoginResult custody, UUID expectedAccount) { + try { + if (custody == null) { + throw invalid(); + } + var evidence = custody.evidence(); + long now = clock.instant().getEpochSecond(); + if (evidence == null + || !expectedAccount.equals(evidence.accountId()) + || !GameSessionAccountDelegationProfile.PROFILE.equals(evidence.tokenProfile()) + || evidence.issuedAtEpochSecond() > now + || evidence.notBeforeEpochSecond() > now + || evidence.expiresAtEpochSecond() <= now) { + throw invalid(); + } + return evidence; + } catch (RuntimeException invalidCustody) { + throw invalid(); + } + } + + private static void requireLoginBinding( + RuntimePlayerAdmissionEntitlementEvidence evidence, + CanonicalGameplayLoginResult.NonSecretEvidence login) { + Object rawSources = evidence.fields().get("sourceReferences"); + if (!(rawSources instanceof Map sources) + || !login.tokenJti().toString().equals(sources.get("callerTokenJti")) + || !login.tokenSha256().equals(sources.get("callerTokenSha256")) + || !login.callerContextId().toString().equals(sources.get("callerContextId"))) { + throw invalid(); + } + } + + private static void requireTargetBinding( + RuntimePlayerAdmissionEntitlementEvidence evidence, + CanonicalPlayableTarget target, + String connectScopeExpiresAt) { + Object rawTarget = evidence.fields().get("target"); + Object rawSources = evidence.fields().get("sourceReferences"); + if (!(rawTarget instanceof Map actual) + || !(rawSources instanceof Map sources) + || !"PUBLIC_PRODUCTION".equals(actual.get("targetClass")) + || !"PRESEEDED_ONLY".equals(actual.get("characterCreationPolicy")) + || !target.targetNamespace().equals(actual.get("targetNamespace")) + || !target.canonicalTenantId().toString().equals(actual.get("tenantId")) + || !target.tenantSlug().equals(actual.get("tenantSlug")) + || !target.worldSlug().equals(actual.get("worldSlug")) + || !target.realmId().toString().equals(actual.get("realmId")) + || !target.realmSlug().equals(actual.get("realmSlug")) + || !target + .playableStateNamespaceId() + .toString() + .equals(actual.get("playableStateNamespaceId")) + || !target.playableStateScope().equals(actual.get("playableStateScope")) + || !target.canonicalGameInstanceId().toString().equals(actual.get("gameInstanceId")) + || !target.canonicalVersionId().toString().equals(actual.get("canonicalVersionId")) + || !Long.toString(target.catalogRevision()).equals(actual.get("catalogRevision")) + || !Long.toString(target.pointerVersion()).equals(actual.get("pointerVersion")) + || !Long.toString(target.activeWorldEpoch()).equals(actual.get("activeWorldEpoch")) + || !connectScopeExpiresAt.equals(actual.get("connectScopeExpiresAt")) + || !target + .admissionPointerSnapshotDigest() + .equals(sources.get("admissionPointerSnapshotDigest")) + || !target.ownerProofDigest().equals(sources.get("gameSessionOwnerProofDigest"))) { + throw invalid(); + } + } + + private boolean isBoundedAsciiJwt(byte[] bytes) { + if (bytes == null + || bytes.length == 0 + || bytes.length > GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES) { + return false; + } + for (byte value : bytes) { + if (value < 0x21 || value > 0x7e) { + return false; + } + } + return true; + } + + private static boolean matchesSha256(byte[] value, String expected) { + byte[] digest = null; + try { + digest = MessageDigest.getInstance("SHA-256").digest(value); + return HexFormat.of().formatHex(digest).equals(expected); + } catch (NoSuchAlgorithmException unavailable) { + return false; + } finally { + if (digest != null) { + Arrays.fill(digest, (byte) 0); + } + } + } + + private static boolean current(BooleanSupplier custodyCurrent) { + try { + return custodyCurrent != null && custodyCurrent.getAsBoolean(); + } catch (RuntimeException unavailable) { + return false; + } + } + + private static void requireCurrent(BooleanSupplier custodyCurrent, Runnable requireScopeCurrent) { + if (!current(custodyCurrent) || Context.current().isCancelled()) { + throw failure(Status.Code.CANCELLED); + } + requireScopeCurrent.run(); + } + + private static boolean v4(UUID value) { + return value != null && value.version() == 4 && value.variant() == 2; + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountPlayerAdmissionEntitlementReadServiceGrpc + .AccountPlayerAdmissionEntitlementReadServiceBlockingStub + buildStub(ManagedChannel channel) { + return AccountPlayerAdmissionEntitlementReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedAccountPeer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedAccountPeer)) + .withCompression("gzip"); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException( + "Exact live LOGIN custody and verified player-admission scope required"); + } + + private static StatusRuntimeException failure(Status.Code code) { + return Status.fromCode(code) + .withDescription("Account player-admission entitlement read did not complete") + .asRuntimeException(); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java index d450e1041f..5a9188b515 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java @@ -131,10 +131,10 @@ public void listVisiblePublicProductionAdmissionTargets( } final ListVisiblePublicProductionAdmissionTargetsResponse response; try { - var before = readPreseededDiscoveryTargets(); + var before = readDiscoveryTargets(); // Validate the complete first read before treating it as an expected collection. CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse(parsed, before); - var after = readPreseededDiscoveryTargets(); + var after = readDiscoveryTargets(); response = CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse(parsed, after); if (!new HashSet<>(before).equals(new HashSet<>(after))) { fail(observer, Status.FAILED_PRECONDITION); @@ -196,13 +196,13 @@ public void resolvePublishedRealmAdmissionTarget( sendSource(observer, response); } - private List readPreseededDiscoveryTargets() { + private List readDiscoveryTargets() { var selected = new ArrayList(); var tenants = new HashSet(); var tenantSlugs = new HashSet(); var realms = new HashSet(); for (var route : routeReader.readVisiblePublicProductionTargets()) { - // Qualify every source before filtering, so an excluded policy cannot hide bad authority. + // Qualify the complete collection before returning either supported discovery policy. var target = CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseTargetEvidence( CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetEvidence(toTarget(route))); @@ -215,11 +215,11 @@ private List readPreseededDiscoveryTargets() { || !realms.add(target.realmId())) { throw new IllegalArgumentException("Discovery source has invalid or duplicate authority"); } - if ("PRESEEDED_ONLY".equals(target.characterCreationPolicy())) { - selected.add(target); - } else if (!"PLAYER_CREATED".equals(target.characterCreationPolicy())) { + if (!"PRESEEDED_ONLY".equals(target.characterCreationPolicy()) + && !"PLAYER_CREATED".equals(target.characterCreationPolicy())) { throw new IllegalArgumentException("Discovery source has unsupported character policy"); } + selected.add(target); } return List.copyOf(selected); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalPublishedAdmissionActualOwnerCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalPublishedAdmissionActualOwnerCompositionFixture.java new file mode 100644 index 0000000000..7ec6ed0f27 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalPublishedAdmissionActualOwnerCompositionFixture.java @@ -0,0 +1,51 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.grpc.BindableService; +import io.grpc.ServerInterceptors; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; +import net.firedevops.firemud.gamesession.client.GameDesignPublishedRealmPolicyClient; +import net.firedevops.firemud.gamesession.security.CanonicalGameplayAdmissionDecisionReadWorkloadGuard; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.impl.CanonicalGameplayAdmissionDecisionReadGrpcService; +import org.jooq.DSLContext; + +/** + * Assembles actual current Game Session source readers over caller-owned PostgreSQL state. The + * caller owns source provenance, authenticated clients, socket identity and cleanup. This fixture + * creates no rows, changes no registration and does not authorize gameplay admission. + */ +public final class CanonicalPublishedAdmissionActualOwnerCompositionFixture { + private CanonicalPublishedAdmissionActualOwnerCompositionFixture() {} + + public static BindableService receiver( + DSLContext dsl, + String namespace, + GameDesignPublishedRealmPolicyClient policies, + WorldCanonicalInstanceLifecycleClient world) { + var catalogs = new GameSessionCanonicalRealmCatalogRepository(dsl); + var admissions = + new CanonicalInitialAdmissionRepository( + dsl, + catalogs, + new GameSessionCanonicalAdmissionPointerRepository( + dsl, catalogs, new GameplayAdmissionPointerEventRepository(dsl))); + var launches = new CanonicalGameInstanceLaunchAssociationRepository(dsl, namespace); + var routes = new CanonicalPlayerRouteReadService(namespace, catalogs, admissions, launches); + var published = + new CanonicalPublishedPlayerRouteReadService( + namespace, routes, catalogs, launches, policies); + var guard = new CanonicalGameplayAdmissionDecisionReadWorkloadGuard(namespace); + var receiver = + new CanonicalGameplayAdmissionDecisionReadGrpcService( + new CanonicalGameplayBindingInventoryRepository(dsl), + guard, + namespace, + null, + routes, + published, + launches, + world); + return () -> ServerInterceptors.intercept(receiver, guard); + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginPhysicalCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginPhysicalCompositionFixture.java new file mode 100644 index 0000000000..0c778a8049 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginPhysicalCompositionFixture.java @@ -0,0 +1,410 @@ +package net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.output.StatusOutput; +import io.lettuce.core.protocol.CommandArgs; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; +import io.lettuce.core.protocol.ProtocolVersion; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.InitialGameplayLoginTokenWitness; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayLoginAccountClient; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding.AcknowledgementPolicy; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding.Profile; +import org.jooq.DSLContext; +import org.springframework.transaction.PlatformTransactionManager; + +/** + * Actual original journal, PENDING, Account client and INSTALLED composition over borrowed physical + * stores. Credential delivery and external Redis qualification remain controlled. The caller must + * finish earlier users of the GS Redis principal before opening this fixture; no active sibling + * connections are reset. The decoded readback is historical evidence, not receiving custody, + * current token authority, gameplay admission or a production qualification provider. + */ +@SuppressWarnings("resource") +public final class InitialGameplayLoginPhysicalCompositionFixture implements AutoCloseable { + private static final String PRINCIPAL = InitialGameplayLoginRedisBinding.PRINCIPAL; + private static final String BINDING = "controlled-physical-initial-login-primary"; + private final InitialGameplayLoginCoordinationJournalRepository journal; + private final RedisClient writer; + private final List mutations = new ArrayList<>(); + private final List journalObservations = new ArrayList<>(); + private InitialGameplayLoginOwner.Outcome outcome; + private CanonicalGameplayLoginResult loginResult; + private InitialGameplayLoginContextState installedReadback; + private boolean closed; + + /** + * Transfers the mutable OTP buffer, but borrows the already migrated SQL owners, initialized + * actual Account client and test-owned AOF primary/replica. No listener or runtime bean is added. + */ + public static InitialGameplayLoginPhysicalCompositionFixture open( + DSLContext gs, + PlatformTransactionManager transactionManager, + String redisHost, + int redisPort, + CanonicalGameplayLoginAccountClient account, + String email, + String canonicalClientAddress, + char[] ownedOtp) { + Objects.requireNonNull(ownedOtp, "Owned credential buffer required"); + InitialGameplayLoginPhysicalCompositionFixture fixture = null; + try (var credentials = + new InitialGameplayLoginCredentialPresentation(email, canonicalClientAddress, ownedOtp)) { + fixture = new InitialGameplayLoginPhysicalCompositionFixture(gs, redisHost, redisPort); + fixture.receive(transactionManager, account, credentials); + assertThat(Arrays.equals(ownedOtp, new char[ownedOtp.length])).isTrue(); + return fixture; + } catch (RuntimeException | Error failure) { + if (fixture != null) { + try { + fixture.close(); + } catch (RuntimeException | Error cleanup) { + failure.addSuppressed(cleanup); + } + } + throw failure; + } finally { + Arrays.fill(ownedOtp, '\0'); + } + } + + private InitialGameplayLoginPhysicalCompositionFixture( + DSLContext gs, String redisHost, int redisPort) { + var actualJournal = new InitialGameplayLoginCoordinationJournalRepository(gs); + // Observation only: every method delegates to the unchanged real SQL owner. + journal = + org.mockito.Mockito.mock( + InitialGameplayLoginCoordinationJournalRepository.class, + invocation -> { + String operation = invocation.getMethod().getName(); + try { + Object result = + invoke(actualJournal, invocation.getMethod(), invocation.getArguments()); + journalObservations.add(operation + ":OK"); + return result; + } catch (Throwable failure) { + String sqlState = + failure instanceof org.jooq.exception.DataAccessException sql + ? sql.sqlState() + : "none"; + journalObservations.add( + operation + ":" + failure.getClass().getSimpleName() + ":" + sqlState); + throw failure; + } + }); + String password = UUID.randomUUID().toString(); + configureOwnedPrincipal(redisHost, redisPort, password); + writer = redis(redisHost, redisPort, PRINCIPAL, password); + } + + private void receive( + PlatformTransactionManager transactionManager, + CanonicalGameplayLoginAccountClient account, + InitialGameplayLoginCredentialPresentation credentials) { + var contexts = + new InitialGameplayLoginContextRedisClient( + new InitialGameplayLoginRedisBinding( + BINDING, + this::observedConnection, + new AcknowledgementPolicy(Profile.REPLICATED, 1, 1, 5_000)), + RedisScriptCatalog.fromContributions( + List.of(new InitialGameplayLoginRedisScriptContribution())), + new ControlledQualification()); + var cleanup = + new InitialGameplayLoginCleanupOwner( + journal, + new InitialGameplayLoginRedisAttemptClosure(contexts), + account, + transactionManager); + outcome = new InitialGameplayLoginOwner(contexts, cleanup, account).receive(credentials); + assertThat(outcome.status()) + .as( + "Initial LOGIN failureCode=%s journal=%s mutations=%s", + outcome.failureCode(), journalObservations, mutations) + .isEqualTo(InitialGameplayLoginOwner.Status.INSTALLED_NON_ADMITTING); + loginResult = outcome.takePrivateResult().orElseThrow(); + assertThat(mutations).containsExactly("CREATE_PENDING", "INSTALL"); + installedReadback = physicalReadback(); + assertThat(installedReadback.state()) + .isEqualTo(InitialGameplayLoginContextState.State.INSTALLED); + assertThat(installedReadback.evidence()).isEqualTo(loginResult.evidence()); + var retained = journal.readCommitted(coordinates()).orElseThrow(); + assertThat(retained.abandoned()).isFalse(); + assertThat(retained.verifiedWitness()).contains(witness(installedReadback)); + assertThat(retained.frozenRetirementRequest()).isEmpty(); + byte[] compact = loginResult.compactJwtBytes(); + try { + assertThat(containsSequence(installedReadback.encode(), compact)).isFalse(); + } finally { + Arrays.fill(compact, (byte) 0); + } + } + + public InitialGameplayLoginAttemptCoordinates coordinates() { + return outcome.coordinates(); + } + + /** The actual owner outcome, retained for explicit pre-admission custody-loss cleanup. */ + public InitialGameplayLoginOwner.Outcome outcome() { + return outcome; + } + + /** Borrow the actual transferred result; the fixture retains its cleanup responsibility. */ + public CanonicalGameplayLoginResult loginResult() { + return loginResult; + } + + /** Historical physical installation evidence only; this does not authenticate current custody. */ + public InitialGameplayLoginContextState installedReadback() { + return installedReadback; + } + + /** + * Call before shutting down Account transport; known-token disposal uses that actual receiver. + */ + public InitialGameplayLoginCleanupOwner.CleanupObservation abandonOriginalAfterCustodyLoss() { + var observation = outcome.abandonOriginalAfterCustodyLoss(); + assertThat(physicalReadback().state()).isEqualTo(InitialGameplayLoginContextState.State.CLOSED); + var retained = journal.readCommitted(coordinates()).orElseThrow(); + assertThat(retained.abandoned()).isTrue(); + assertThat(retained.frozenRetirementRequest()).isPresent(); + assertThat(retained.frozenRetirementRequest().orElseThrow().getTokenWitness()) + .isEqualTo(witness(installedReadback)); + assertThatThrownBy(loginResult::compactJwtBytes).isInstanceOf(IllegalStateException.class); + return observation; + } + + private InitialGameplayLoginContextState physicalReadback() { + try (var connection = writer.connect(ByteArrayCodec.INSTANCE)) { + var commands = connection.sync(); + assertThat(commands.aclWhoami()).isEqualTo(PRINCIPAL); + byte[] key = key(coordinates()); + var decoded = InitialGameplayLoginContextState.decode(commands.get(key)); + assertThat(decoded.coordinates()).isEqualTo(coordinates()); + assertThat(commands.pttl(key)).isEqualTo(-1L); + return decoded; + } + } + + /** Every command still delegates to the real pinned physical connection. */ + @SuppressWarnings("unchecked") + private StatefulRedisConnection observedConnection() { + var connection = writer.connect(ByteArrayCodec.INSTANCE); + return (StatefulRedisConnection) + Proxy.newProxyInstance( + StatefulRedisConnection.class.getClassLoader(), + new Class[] {StatefulRedisConnection.class}, + (proxy, method, args) -> { + if (!method.getName().equals("sync")) return invoke(connection, method, args); + var commands = connection.sync(); + return Proxy.newProxyInstance( + RedisCommands.class.getClassLoader(), + new Class[] {RedisCommands.class}, + (commandProxy, command, arguments) -> { + if (command.getName().equals("evalsha")) { + beforeMutation(commands, (byte[][]) arguments[2], (byte[][]) arguments[3]); + } + return invoke(commands, command, arguments); + }); + }); + } + + private void beforeMutation( + RedisCommands commands, byte[][] keys, byte[][] args) { + require(keys.length == 1 && args.length == 3); + String operation = new String(args[0], StandardCharsets.US_ASCII); + var desired = InitialGameplayLoginContextState.decode(args[2]); + var original = desired.coordinates(); + require(Arrays.equals(keys[0], key(original))); + var committed = journal.readCommitted(original).orElseThrow(); + require(original.expectedAttemptFence() == 1); + require(!original.requestId().equals(original.callerContextId())); + if ("CREATE_PENDING".equals(operation)) { + require(mutations.isEmpty()); + require(!committed.abandoned() && committed.verifiedWitness().isEmpty()); + // Observation only: the actual Lua absence check remains the create authority. + require(commands.get(keys[0]) == null); + } else if ("INSTALL".equals(operation)) { + require(mutations.equals(List.of("CREATE_PENDING"))); + require(!committed.abandoned()); + require(committed.verifiedWitness().filter(witness(desired)::equals).isPresent()); + var pending = InitialGameplayLoginContextState.decode(commands.get(keys[0])); + require(pending.coordinates().equals(original)); + require(pending.state() == InitialGameplayLoginContextState.State.PENDING); + } else { + require("CLOSE".equals(operation) && committed.abandoned()); + } + mutations.add(operation); + } + + private static InitialGameplayLoginTokenWitness witness(InitialGameplayLoginContextState state) { + var evidence = state.evidence(); + return InitialGameplayLoginTokenWitness.newBuilder() + .setTokenJti(evidence.tokenJti().toString()) + .setTokenSha256(evidence.tokenSha256()) + .setTokenGeneration(Long.parseLong(evidence.tokenGeneration())) + .setIssuanceFence(Long.parseLong(evidence.issuanceFence())) + .build(); + } + + private static Object invoke(Object target, Method method, Object[] arguments) throws Throwable { + try { + return method.invoke(target, arguments); + } catch (InvocationTargetException failure) { + throw failure.getCause(); + } + } + + private static void configureOwnedPrincipal(String host, int port, String password) { + var administrator = redis(host, port, null, null); + try (var connection = administrator.connect(ByteArrayCodec.INSTANCE)) { + var commands = connection.sync(); + require( + commands + .clientList() + .lines() + .noneMatch(line -> line.contains(" user=" + PRINCIPAL + " "))); + commands.aclSetuser( + PRINCIPAL, + new AclSetuserArgs() + .reset() + .on() + .addPassword(password) + .keyPattern(InitialGameplayLoginContextRedisKeys.FAMILY_SCOPE + "*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.GET) + .addCommand(CommandType.SET) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.PEXPIRETIME)); + commands.dispatch( + CommandType.ACL, + new StatusOutput<>(ByteArrayCodec.INSTANCE), + new CommandArgs<>(ByteArrayCodec.INSTANCE).add("SETUSER").add(PRINCIPAL).add("+waitaof")); + } finally { + administrator.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } + + private static RedisClient redis(String host, int port, String username, String password) { + var builder = RedisURI.Builder.redis(host, port); + if (username != null) builder.withAuthentication(username, password); + var uri = builder.build(); + uri.setTimeout(Duration.ofSeconds(10)); + var client = RedisClient.create(uri); + client.setOptions( + ClientOptions.builder() + .autoReconnect(false) + .protocolVersion(ProtocolVersion.RESP2) + .build()); + return client; + } + + private static byte[] key(InitialGameplayLoginAttemptCoordinates coordinates) { + return InitialGameplayLoginContextRedisKeys.contextKey(coordinates.callerContextId()) + .getBytes(StandardCharsets.US_ASCII); + } + + private static boolean containsSequence(byte[] haystack, byte[] needle) { + for (int offset = 0; offset <= haystack.length - needle.length; offset++) { + if (Arrays.equals(haystack, offset, offset + needle.length, needle, 0, needle.length)) { + return true; + } + } + return false; + } + + private static void require(boolean condition) { + if (!condition) + throw new IllegalStateException("Physical initial LOGIN fixture precondition failed"); + } + + /** Stipulated test authority only, never a production recovery or transport-custody producer. */ + private static final class ControlledQualification + implements InitialGameplayLoginCoordinationQualification { + @Override + public Optional acquire(String scope, String binding) { + require(InitialGameplayLoginContextRedisKeys.FAMILY_SCOPE.equals(scope)); + require(BINDING.equals(binding)); + return Optional.of( + new Lease() { + private boolean closed; + + @Override + public String scope() { + return scope; + } + + @Override + public String protectedBindingId() { + return binding; + } + + @Override + public long fence() { + return 37; + } + + @Override + public void requireCurrent() { + require(!closed); + } + + @Override + public void close() { + closed = true; + } + }); + } + } + + /** + * Ends pre-admission private custody before closing owned Redis clients. Retained SQL rows and + * Redis markers stay with the enclosing disposable physical fixture, without a retention bypass. + */ + @Override + public void close() { + if (closed) return; + closed = true; + try { + if (outcome != null + && outcome.status() == InitialGameplayLoginOwner.Status.INSTALLED_NON_ADMITTING + && outcome.custodyLossCleanup().isEmpty()) { + outcome.abandonOriginalAfterCustodyLoss(); + } + } finally { + if (loginResult != null) loginResult.close(); + if (outcome != null) outcome.close(); + writer.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java new file mode 100644 index 0000000000..6ca0218ecb --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java @@ -0,0 +1,783 @@ +package net.firedevops.firemud.gamesession.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +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.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BiConsumer; +import java.util.function.BooleanSupplier; +import net.firedevops.firemud.account.v1.AccountPlayerAdmissionEntitlementReadServiceGrpc; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; +import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementRequest; +import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementResponse; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Checkpoint; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementGrpcCodec; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +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.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginContextState; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyScope; +import net.firedevops.firemud.gamesession.support.FirstPartyReceivingFixture; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** Controlled Account peer proof for credential release and canonical response binding. */ +@Timeout(90) +class AccountPlayerAdmissionEntitlementClientMtlsTest { + private static final String NAMESPACE = "firemud-test"; + private static final String GS_PEER = + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service"; + private static final String ACCOUNT_PEER = + "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service"; + private static final String JWT = "a.b.c"; + private static final UUID LOGIN_REQUEST = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID LOGIN_CONTEXT = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID LOGIN_JTI = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID READ_REQUEST = UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final Instant NOW = Instant.ofEpochMilli(FirstPartyReceivingFixture.NOW + 1_000L); + private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC); + private static final InitialGameplayLoginAttemptCoordinates ORIGINAL = + new InitialGameplayLoginAttemptCoordinates(LOGIN_REQUEST, LOGIN_CONTEXT, 1); + private static final ObservedDirectTextTransport TRANSPORT = + new ObservedDirectTextTransport( + "00042", UUID.fromString("99999999-9999-4999-8999-999999999999")); + private static final Instant DIRECT_SCOPE_EXPIRY = NOW.plusSeconds(25); + @TempDir static Path directory; + private static LoopbackMtlsTestPki.Pki pki; + + @BeforeAll + static void certificates() throws Exception { + pki = + LoopbackMtlsTestPki.create( + directory, + "Player admission entitlement client test CA", + new LoopbackMtlsTestPki.IdentitySpec("client", GS_PEER, false), + new LoopbackMtlsTestPki.IdentitySpec("account", ACCOUNT_PEER, true), + new LoopbackMtlsTestPki.IdentitySpec( + "wrong-service", + "spiffe://firemud/ns/" + NAMESPACE + "/sa/world-management-service", + true), + new LoopbackMtlsTestPki.IdentitySpec( + "wrong-namespace", "spiffe://firemud/ns/other/sa/account-service", true)); + } + + @Test + void exactAccountPeerReceivesCurrentLoginCredentialAndReturnsBoundCanonicalEvidence() + throws Exception { + var context = context(); + var login = loginCustody(); + var calls = new AtomicInteger(); + var observedJwt = new AtomicReference(); + var observedPeer = new AtomicReference(); + Server server = server("account", calls, observedJwt, observedPeer, context, login.evidence()); + try (var client = client(server)) { + client.init(); + var result = client.read(context, READ_REQUEST, login, () -> true); + assertThat(result.fields()) + .containsEntry("variant", "PLAYER_ADMISSION") + .containsEntry("sourceKind", "NON_PAID_DEMO") + .containsEntry("membershipExists", false); + assertThat(calls).hasValue(1); + assertThat(observedJwt).hasValue(JWT); + assertThat(observedPeer).hasValue(GS_PEER); + assertThat(new String(result.canonicalBytes(), StandardCharsets.UTF_8)).doesNotContain(JWT); + } finally { + stop(server); + } + } + + @Test + void sameCaWrongServiceAndNamespaceReceiveNoRequestCredential() throws Exception { + for (String identity : List.of("wrong-service", "wrong-namespace")) { + var context = context(); + var login = loginCustody(); + var calls = new AtomicInteger(); + var observedJwt = new AtomicReference(); + var observedPeer = new AtomicReference(); + Server server = server(identity, calls, observedJwt, observedPeer, context, login.evidence()); + try (var client = client(server)) { + client.init(); + assertThatThrownBy(() -> client.read(context, READ_REQUEST, login, () -> true)) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(calls).hasValue(0); + assertThat(observedJwt).hasValue(null); + assertThat(observedPeer).hasValue(null); + } finally { + stop(server); + } + } + } + + @Test + void staleLoginCustodyDoesNotStartRpc() throws Exception { + var context = context(); + var login = loginCustody(); + var calls = new AtomicInteger(); + var observedJwt = new AtomicReference(); + var observedPeer = new AtomicReference(); + Server server = server("account", calls, observedJwt, observedPeer, context, login.evidence()); + try (var client = client(server)) { + client.init(); + assertThatThrownBy(() -> client.read(context, READ_REQUEST, login, () -> false)) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.CANCELLED)); + assertThat(calls).hasValue(0); + assertThat(observedJwt).hasValue(null); + } finally { + stop(server); + } + } + + @Test + void directTextOwnedScopeUsesExactAccountExpiryAndCurrentLoginWithoutFirstPartyContext() + throws Exception { + var target = context().resolvedTarget(); + var borrowed = new ArrayList(); + var login = loginCustody(borrowed); + var scope = directTextScope(target, login, DIRECT_SCOPE_EXPIRY); + var calls = new AtomicInteger(); + var observedJwt = new AtomicReference(); + var observedPeer = new AtomicReference(); + Server server = + server( + "account", + calls, + observedJwt, + observedPeer, + target, + DIRECT_SCOPE_EXPIRY, + login.evidence(), + (value, sources) -> {}, + () -> {}); + try (var client = client(server)) { + client.init(); + var result = client.read(scope, ORIGINAL, TRANSPORT, READ_REQUEST, login, () -> true); + assertThat(result.fields()) + .containsEntry("verifiedConnectScopeId", "direct-text-owned-scope"); + assertThat(((Map) result.fields().get("target")).get("connectScopeExpiresAt")) + .isEqualTo(DIRECT_SCOPE_EXPIRY.toString()); + assertThat(calls).hasValue(1); + assertThat(observedJwt).hasValue(JWT); + assertThat(observedPeer).hasValue(GS_PEER); + assertThat(new String(result.canonicalBytes(), StandardCharsets.UTF_8)).doesNotContain(JWT); + assertThat(borrowed) + .isNotEmpty() + .allSatisfy(bytes -> assertThat(bytes).containsOnly((byte) 0)); + } finally { + stop(server); + } + } + + @ParameterizedTest + @ValueSource( + strings = { + "original-request", + "original-context", + "attempt-fence", + "transport-session", + "transport-proxy", + "stale-custody", + "throwing-custody", + "null-custody", + "custody-lost-before-rpc", + "closed-login", + "expired-login", + "expired-scope", + "wrong-namespace", + "private-scope", + "created-policy", + "durable-abort", + "read-correlation" + }) + void directTextInvalidOrStaleInputsDiscloseNoCredential(String change) throws Exception { + var target = context().resolvedTarget(); + switch (change) { + case "wrong-namespace" -> doReturn("other").when(target).targetNamespace(); + case "private-scope" -> doReturn("ISOLATED").when(target).playableStateScope(); + case "created-policy" -> doReturn("PLAYER_CREATED").when(target).characterCreationPolicy(); + case "durable-abort" -> doReturn(true).when(target).positiveDurableAbort(); + default -> {} + } + var login = loginCustody(); + var expiry = "expired-login".equals(change) ? NOW.plusSeconds(90) : DIRECT_SCOPE_EXPIRY; + var scope = directTextScope(target, login, expiry); + var original = + switch (change) { + case "original-request" -> + new InitialGameplayLoginAttemptCoordinates(UUID.randomUUID(), LOGIN_CONTEXT, 1); + case "original-context" -> + new InitialGameplayLoginAttemptCoordinates(LOGIN_REQUEST, UUID.randomUUID(), 1); + case "attempt-fence" -> + new InitialGameplayLoginAttemptCoordinates(LOGIN_REQUEST, LOGIN_CONTEXT, 2); + default -> ORIGINAL; + }; + var transport = + switch (change) { + case "transport-session" -> + new ObservedDirectTextTransport("42", TRANSPORT.proxyConnectionId()); + case "transport-proxy" -> new ObservedDirectTextTransport("00042", UUID.randomUUID()); + default -> TRANSPORT; + }; + var checks = new AtomicInteger(); + BooleanSupplier current = + switch (change) { + case "stale-custody" -> () -> false; + case "throwing-custody" -> + () -> { + throw new IllegalStateException("Controlled custody lost"); + }; + case "null-custody" -> null; + case "custody-lost-before-rpc" -> () -> checks.incrementAndGet() < 3; + default -> () -> true; + }; + if ("closed-login".equals(change)) { + when(login.compactJwtBytes()).thenThrow(new IllegalStateException("Controlled closed LOGIN")); + } + Clock clientClock = + switch (change) { + case "expired-login" -> Clock.fixed(NOW.plusSeconds(60), ZoneOffset.UTC); + case "expired-scope" -> Clock.fixed(DIRECT_SCOPE_EXPIRY, ZoneOffset.UTC); + default -> CLOCK; + }; + UUID selectedReadId = "read-correlation".equals(change) ? new UUID(0, 0) : READ_REQUEST; + var calls = new AtomicInteger(); + var observedJwt = new AtomicReference(); + var observedPeer = new AtomicReference(); + Server server = + server("account", calls, observedJwt, observedPeer, context(), login.evidence()); + try (var client = client(server, clientClock)) { + client.init(); + assertThatThrownBy( + () -> client.read(scope, original, transport, selectedReadId, login, current)) + .isInstanceOf(RuntimeException.class); + assertThat(calls).hasValue(0); + assertThat(observedJwt).hasValue(null); + assertThat(observedPeer).hasValue(null); + } finally { + stop(server); + } + } + + @ParameterizedTest + @ValueSource(strings = {"wrong-service", "wrong-namespace"}) + void directTextWrongAccountPeerReceivesNoCredential(String identity) throws Exception { + var context = context(); + var login = loginCustody(); + var scope = directTextScope(context.resolvedTarget(), login, DIRECT_SCOPE_EXPIRY); + var calls = new AtomicInteger(); + var observedJwt = new AtomicReference(); + var observedPeer = new AtomicReference(); + Server server = server(identity, calls, observedJwt, observedPeer, context, login.evidence()); + try (var client = client(server)) { + client.init(); + assertThatThrownBy( + () -> client.read(scope, ORIGINAL, TRANSPORT, READ_REQUEST, login, () -> true)) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(calls).hasValue(0); + assertThat(observedJwt).hasValue(null); + } finally { + stop(server); + } + } + + @ParameterizedTest + @ValueSource( + strings = { + "version", + "owner-proof", + "pointer-digest", + "scope-expiry", + "login-jti", + "login-hash", + "login-context" + }) + void directTextRejectsAuthenticatedResponseBindingDrift(String change) throws Exception { + var target = context().resolvedTarget(); + var login = loginCustody(); + var scope = directTextScope(target, login, DIRECT_SCOPE_EXPIRY); + var calls = new AtomicInteger(); + var observedJwt = new AtomicReference(); + var observedPeer = new AtomicReference(); + BiConsumer, Map> drift = + (value, sources) -> { + switch (change) { + case "version" -> value.put("canonicalVersionId", UUID.randomUUID().toString()); + case "owner-proof" -> + sources.put("gameSessionOwnerProofDigest", "sha256:" + "9".repeat(64)); + case "pointer-digest" -> sources.put("admissionPointerSnapshotDigest", "9".repeat(64)); + case "scope-expiry" -> + value.put("connectScopeExpiresAt", DIRECT_SCOPE_EXPIRY.plusSeconds(1).toString()); + case "login-jti" -> sources.put("callerTokenJti", UUID.randomUUID().toString()); + case "login-hash" -> sources.put("callerTokenSha256", "9".repeat(64)); + case "login-context" -> sources.put("callerContextId", UUID.randomUUID().toString()); + default -> throw new IllegalArgumentException(change); + } + }; + Server server = + server( + "account", + calls, + observedJwt, + observedPeer, + target, + DIRECT_SCOPE_EXPIRY, + login.evidence(), + drift, + () -> {}); + try (var client = client(server)) { + client.init(); + assertThatThrownBy( + () -> client.read(scope, ORIGINAL, TRANSPORT, READ_REQUEST, login, () -> true)) + .isInstanceOf(IllegalArgumentException.class); + assertThat(calls).hasValue(1); + assertThat(observedJwt).hasValue(JWT); + } finally { + stop(server); + } + } + + @ParameterizedTest + @ValueSource(strings = {"custody", "scope-expiry", "login-expiry", "closed-login"}) + void directTextRechecksLiveInputsAfterRpc(String change) throws Exception { + var target = context().resolvedTarget(); + var login = loginCustody(); + var expiry = "login-expiry".equals(change) ? NOW.plusSeconds(90) : DIRECT_SCOPE_EXPIRY; + var scope = directTextScope(target, login, expiry); + var current = new AtomicBoolean(true); + var clockTime = new AtomicReference<>(NOW); + Clock movingClock = mock(Clock.class); + when(movingClock.instant()).thenAnswer(invocation -> clockTime.get()); + var calls = new AtomicInteger(); + var observedJwt = new AtomicReference(); + var observedPeer = new AtomicReference(); + Runnable afterRead = + () -> { + switch (change) { + case "custody" -> current.set(false); + case "scope-expiry" -> clockTime.set(DIRECT_SCOPE_EXPIRY); + case "login-expiry" -> clockTime.set(NOW.plusSeconds(60)); + case "closed-login" -> + when(login.compactJwtBytes()).thenThrow(new IllegalStateException("Closed LOGIN")); + default -> throw new IllegalArgumentException(change); + } + }; + Server server = + server( + "account", + calls, + observedJwt, + observedPeer, + target, + expiry, + login.evidence(), + (value, sources) -> {}, + afterRead); + try (var client = client(server, movingClock)) { + client.init(); + assertThatThrownBy( + () -> client.read(scope, ORIGINAL, TRANSPORT, READ_REQUEST, login, current::get)) + .isInstanceOf(RuntimeException.class); + assertThat(calls).hasValue(1); + } finally { + stop(server); + } + } + + private static DirectTextAuthenticatedLobbyScope directTextScope( + CanonicalPlayableTarget target, CanonicalGameplayLoginResult login, Instant expiry) { + return new DirectTextAuthenticatedLobbyScope( + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + InitialGameplayLoginContextState.installed(ORIGINAL, login), + TRANSPORT, + target, + DirectTextIssuedConnectScope.fromAccountResponse( + FirstPartyReceivingFixture.ACCOUNT.toString(), + DirectTextAuthenticatedLobbyScope.targetFor(target), + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("direct-text-owned-scope") + .setEvaluatedAt(NOW.minusSeconds(10).toString()) + .setConnectScopeExpiresAt(expiry.toString()) + .build(), + CLOCK)); + } + + private static AccountPlayerAdmissionEntitlementClient client(Server server) throws Exception { + return client(server, CLOCK); + } + + private static AccountPlayerAdmissionEntitlementClient client(Server server, Clock clock) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + server.getPort()); + return new AccountPlayerAdmissionEntitlementClient( + endpoints, + pki.clientProperties(directory, pki.identity("client")), + new GrpcChannelFactory(), + NAMESPACE, + clock); + } + + private static Server server( + String identity, + AtomicInteger calls, + AtomicReference observedJwt, + AtomicReference observedPeer, + FirstPartyConnectContext context, + CanonicalGameplayLoginResult.NonSecretEvidence login) + throws Exception { + return server( + identity, + calls, + observedJwt, + observedPeer, + context.resolvedTarget(), + Instant.ofEpochMilli(context.claims().expiresAtMillis()), + login, + (value, sources) -> {}, + () -> {}); + } + + private static Server server( + String identity, + AtomicInteger calls, + AtomicReference observedJwt, + AtomicReference observedPeer, + CanonicalPlayableTarget target, + Instant scopeExpiry, + CanonicalGameplayLoginResult.NonSecretEvidence login, + BiConsumer, Map> drift, + Runnable afterRead) + throws Exception { + var service = + new AccountPlayerAdmissionEntitlementReadServiceGrpc + .AccountPlayerAdmissionEntitlementReadServiceImplBase() { + @Override + public void readPlayerAdmissionEntitlement( + ReadPlayerAdmissionEntitlementRequest request, + StreamObserver observer) { + calls.incrementAndGet(); + var peer = GrpcPeerIdentity.current(); + observedPeer.set(peer == null ? null : peer.uri()); + try { + var presented = RuntimePlayerAdmissionEntitlementGrpcCodec.parseRequest(request); + observedJwt.set(presented.initialLoginJwt()); + var evidence = evidence(presented.request(), target, scopeExpiry, login, drift); + afterRead.run(); + observer.onNext( + RuntimePlayerAdmissionEntitlementGrpcCodec.toResponse( + presented.request(), evidence)); + observer.onCompleted(); + } catch (Exception malformed) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Controlled Account fixture rejected request") + .asRuntimeException()); + } + } + }; + var serverIdentity = pki.identity(identity); + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverIdentity.privateKey(), serverIdentity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private static void stop(Server server) throws InterruptedException { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + + private static FirstPartyConnectContext context() { + var fixture = new FirstPartyReceivingFixture(); + CanonicalPlayableTarget target = org.mockito.Mockito.spy(fixture.target()); + doReturn("PRESEEDED_ONLY").when(target).characterCreationPolicy(); + when(fixture.routes.readCurrentTarget(FirstPartyReceivingFixture.TENANT)).thenReturn(target); + return fixture.service.parse(fixture.token()).orElseThrow(); + } + + private static CanonicalGameplayLoginResult loginCustody() throws Exception { + return loginCustody(new ArrayList<>()); + } + + private static CanonicalGameplayLoginResult loginCustody(List borrowed) throws Exception { + var login = mock(CanonicalGameplayLoginResult.class); + String jwtSha256 = + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(JWT.getBytes(StandardCharsets.US_ASCII))); + var evidence = + new CanonicalGameplayLoginResult.NonSecretEvidence( + FirstPartyReceivingFixture.ACCOUNT, + LOGIN_REQUEST, + LOGIN_CONTEXT, + LOGIN_JTI, + jwtSha256, + GameSessionAccountDelegationProfile.PROFILE, + NOW.minusSeconds(10).getEpochSecond(), + NOW.minusSeconds(10).getEpochSecond(), + NOW.plusSeconds(60).getEpochSecond(), + "1", + "1", + canonical(GameSessionAccountDelegationProfile.authorityTuple(1, 1)), + canonical( + List.of( + Map.of( + "outboxStreamKey", + "account:auth-authority:v1:account/" + FirstPartyReceivingFixture.ACCOUNT, + "outboxSequence", + "0"), + Map.of( + "outboxStreamKey", + "account:auth-authority:v1:issuer/firemud-account-service", + "outboxSequence", + "0"))), + canonical(List.of())); + when(login.evidence()).thenReturn(evidence); + when(login.compactJwtBytes()) + .thenAnswer( + invocation -> { + byte[] bytes = JWT.getBytes(StandardCharsets.US_ASCII); + borrowed.add(bytes); + return bytes; + }); + return login; + } + + private static ByteString canonical(Object value) throws Exception { + return ByteString.copyFrom( + Rfc8785CanonicalJson.canonicalizeUtf8( + tools.jackson.databind.json.JsonMapper.builder().build().writeValueAsString(value))); + } + + private static RuntimePlayerAdmissionEntitlementEvidence evidence( + RuntimePlayerAdmissionEntitlementGrpcCodec.Request request, + CanonicalPlayableTarget retained, + Instant scopeExpiry, + CanonicalGameplayLoginResult.NonSecretEvidence login, + BiConsumer, Map> drift) + throws Exception { + Instant scopeStarted = NOW.minusSeconds(10); + Map target = new LinkedHashMap<>(); + target.put("targetClass", "PUBLIC_PRODUCTION"); + target.put("characterCreationPolicy", "PRESEEDED_ONLY"); + target.put("targetNamespace", retained.targetNamespace()); + target.put("tenantId", retained.canonicalTenantId().toString()); + target.put("tenantSlug", retained.tenantSlug()); + target.put("worldSlug", retained.worldSlug()); + target.put("realmId", retained.realmId().toString()); + target.put("realmSlug", retained.realmSlug()); + target.put("playableStateNamespaceId", retained.playableStateNamespaceId().toString()); + target.put("playableStateScope", retained.playableStateScope()); + target.put("gameInstanceId", retained.canonicalGameInstanceId().toString()); + target.put("canonicalVersionId", retained.canonicalVersionId().toString()); + target.put("catalogRevision", Long.toString(retained.catalogRevision())); + target.put("pointerVersion", Long.toString(retained.pointerVersion())); + target.put("activeWorldEpoch", Long.toString(retained.activeWorldEpoch())); + target.put("evaluatedAt", scopeStarted.toString()); + target.put("connectScopeExpiresAt", scopeExpiry.toString()); + + Map facts = new LinkedHashMap<>(); + facts.put("sourceKind", "NON_PAID_DEMO"); + facts.put("subscriptionStatus", null); + facts.put("provisioningStatus", null); + for (String field : + List.of( + "gameplayAvailable", + "allowPublicJoin", + "allowNewGameplayBindings", + "allowNewInstanceStarts")) { + facts.put(field, true); + } + facts.put( + "quotas", + Map.of( + "maxActiveSessions", "3", + "maxConcurrentGameInstances", "2", + "maxStorageBytes", "4096")); + facts.put("entitlementVersion", "1"); + facts.put("tenantBillingSequence", "1"); + facts.put("tenantAuthorityGeneration", "2"); + + Map sources = new LinkedHashMap<>(); + sources.put("callerTokenJti", login.tokenJti().toString()); + sources.put("callerTokenSha256", login.tokenSha256()); + sources.put("callerRegistryRecordSha256", "a".repeat(64)); + sources.put("callerCommitProofSha256", "b".repeat(64)); + sources.put("callerContextId", login.callerContextId().toString()); + sources.put("callerOperationId", LOGIN_REQUEST.toString()); + sources.put( + "callerTokenExpiresAt", Instant.ofEpochSecond(login.expiresAtEpochSecond()).toString()); + sources.put("paidReceiptValidUntil", null); + sources.put("scopeDigest", "sha256:" + "c".repeat(64)); + sources.put("entitlementSourceDigest", "sha256:" + "d".repeat(64)); + sources.put("admissionPointerSnapshotDigest", retained.admissionPointerSnapshotDigest()); + sources.put("gameSessionOwnerProofDigest", retained.ownerProofDigest()); + sources.put("publishedPolicySetDigest", "sha256:" + "e".repeat(64)); + sources.put("worldLifecycleDigest", "sha256:" + "f".repeat(64)); + sources.put("worldCaptureId", "77777777-7777-4777-8777-777777777777"); + sources.put("worldRowVersion", "0"); + drift.accept(target, sources); + + return RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( + request.target().readRequestId(), + request.expectedGameSessionWorkload(), + request.connectScopeId(), + membership(request.target().accountId(), request.target().tenantId(), retained), + target, + facts, + sources, + NOW); + } + + private static Snapshot membership(UUID account, UUID tenant, CanonicalPlayableTarget target) + throws Exception { + UUID sourceRequest = UUID.fromString("88888888-8888-4888-8888-888888888888"); + String hash = "a".repeat(64); + String requestDigest = + GameTenantCreationDigest.requestDigest( + target.targetNamespace(), sourceRequest, target.worldSlug(), "World", null); + var freshTenant = + new FreshTenantCreationEvidence( + 1, + target.targetNamespace(), + sourceRequest, + sourceRequest, + requestDigest, + tenant, + 17, + target.worldSlug(), + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + target.targetNamespace(), + sourceRequest, + sourceRequest, + requestDigest, + tenant, + 17, + target.worldSlug(), + "NEW_GAME_ROW")); + var authorityRequest = + new TenantAuthorityEventV1Codec.AuthorityRequest( + sourceRequest, + "sha256:" + hash, + tenant, + freshTenant.creationRequestId(), + freshTenant.requestDigest()); + var billing = + new TenantAuthorityEventV1Codec.BillingReceipt( + tenant, + sourceRequest, + "sha256:" + hash, + TenantAuthorityEventV1Codec.tenantBillingStreamKey(tenant), + 1, + TenantAuthorityEventV1Codec.tenantBillingEventId(sourceRequest), + "sha256:" + hash); + var event = TenantAuthorityEventV1Codec.seal(authorityRequest, freshTenant, 2, 2, 1, billing); + String prefix = MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX; + var tuple = + new AuthorityTuple( + "1", + "1", + Map.of(tenant.toString(), "2"), + Map.of(tenant.toString(), "1"), + List.of(), + Optional.empty(), + Optional.of( + Map.of( + tenant.toString(), + new TenantBillingCutoff("2", "1", event.outboxStreamKey(), "1")))); + return new Snapshot( + "firemud-account-service", + account.toString(), + tenant.toString(), + false, + "MISSING", + false, + Map.of(tenant.toString(), "1"), + "1", + List.of(), + tuple, + "1", + List.of( + new Checkpoint(prefix + "account/" + account, "0"), + new Checkpoint(prefix + "issuer/firemud-account-service", "0"), + new Checkpoint(prefix + "membership/" + account + "/" + tenant, "0"), + new Checkpoint(event.outboxStreamKey(), "1")), + List.of( + new SourceEvidence( + event.outboxStreamKey(), + "1", + event.eventId().toString(), + event.eventDigest(), + new String(event.payload(), StandardCharsets.UTF_8)))); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java index 391e6129fe..f68d7b3e45 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java @@ -100,7 +100,7 @@ void discoveryReturnsOnlyCompleteUnchangedOwnerCollectionRegardlessOfIterationOr } @Test - void discoveryExcludesValidPlayerCreatedTargetsOnBothReads() { + void discoveryReturnsCompletePlayerCreatedAndMixedPolicyCollectionsOnBothReads() { var preseeded = discoveryTarget("first", "First world"); var created = discoveryTarget("second", "Created world", "PLAYER_CREATED"); for (var initial : List.of(List.of(preseeded, created), List.of(created))) { @@ -121,9 +121,15 @@ void discoveryExcludesValidPlayerCreatedTargetsOnBothReads() { CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseDiscoveryRequest( discoveryRequest()), captured.getValue()); - assertThat(result.targets()).hasSize(initial.size() - 1); + assertThat(result.targets()).hasSize(initial.size()); assertThat(result.targets()) - .allMatch(target -> target.characterCreationPolicy().equals("PRESEEDED_ONLY")); + .extracting( + target -> target.canonicalTenantId(), target -> target.characterCreationPolicy()) + .containsExactlyInAnyOrderElementsOf( + initial.stream() + .map( + target -> tuple(target.canonicalTenantId(), target.characterCreationPolicy())) + .toList()); verify(routes, times(2)).readVisiblePublicProductionTargets(); } } @@ -352,12 +358,37 @@ private static void assertDiscoveryFailure( verify(observer, never()).onCompleted(); } + @Test + void discoveryReturnsCompleteMixedPolicyTargetsWithStableIndependentReread() { + var seeded = discoveryTarget("seeded", "Seeded world"); + var created = discoveryTarget("created", "Created world", "PLAYER_CREATED"); + var routes = mock(CanonicalPlayerRouteReadService.class); + when(routes.readVisiblePublicProductionTargets()) + .thenReturn(List.of(seeded, created), List.of(created, seeded)); + var observer = discoveryObserver(); + discoveryService(routes, mock(CanonicalGameplayAdmissionDecisionReadWorkloadGuard.class)) + .listVisiblePublicProductionAdmissionTargets(discoveryRequest(), observer); + var captured = + ArgumentCaptor.forClass(ListVisiblePublicProductionAdmissionTargetsResponse.class); + verify(observer).onNext(captured.capture()); + var request = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseDiscoveryRequest(discoveryRequest()); + assertThat( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + request, captured.getValue()) + .targets()) + .extracting(target -> target.characterCreationPolicy()) + .containsExactly("PLAYER_CREATED", "PRESEEDED_ONLY"); + verify(routes, times(2)).readVisiblePublicProductionTargets(); + verify(observer).onCompleted(); + } + private static CanonicalPlayableTarget discoveryTarget(String slug, String displayName) { return discoveryTarget(slug, displayName, "PRESEEDED_ONLY"); } private static CanonicalPlayableTarget discoveryTarget( - String slug, String displayName, String policy) { + String slug, String displayName, String creationPolicy) { UUID tenant = UUID.nameUUIDFromBytes(("tenant-" + slug).getBytes(StandardCharsets.UTF_8)); UUID realm = UUID.nameUUIDFromBytes(("realm-" + slug).getBytes(StandardCharsets.UTF_8)); UUID namespace = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); @@ -417,7 +448,7 @@ private static CanonicalPlayableTarget discoveryTarget( CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, false, Instant.parse("2026-10-25T00:00:00Z"), - policy); + creationPolicy); } @Test 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 448b954fd5..bf74dc929e 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,7 +7,6 @@ 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; @@ -592,8 +591,7 @@ private void compose( REDIS.getHost(), REDIS.getMappedPort(6379), proofDirectory.resolve("account"), - tenant, - true); + tenant); var world = database(WORLD, "world-management-service", true); var gs = database(GS, "game-session-service", true)) { var issuer = @@ -2338,9 +2336,7 @@ private static javax.sql.DataSource dataSource(DSLContext dsl) { var provider = (org.jooq.impl.DataSourceConnectionProvider) dsl.configuration().connectionProvider(); var proxy = (TransactionAwareDataSourceProxy) provider.dataSource(); - 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; + return Objects.requireNonNull(proxy.getTargetDataSource()); } private static SQLException findSqlException(Throwable failure) { @@ -4775,73 +4771,47 @@ private static Database database(PostgreSQLContainer postgres, String service .getConfigurationExtension(PostgreSQLConfigurationExtension.class) .setTransactionalLock(false); } - 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; + 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; - @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(); - } - 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; + @Override + public void close() { + closed = true; + } + }); + installation.register(); } + return new Database(schema, dsl, manager, write, installation); } private static WorldRuntimeInstallationRegistry.Registration advanceInstallationRegistry( @@ -4941,14 +4911,11 @@ private record Database( DSLContext dsl, DataSourceTransactionManager manager, TransactionTemplate write, - WorldRuntimeInstallationRegistry installationRegistry, - HikariDataSource pool) + WorldRuntimeInstallationRegistry installationRegistry) implements AutoCloseable { @Override public void close() { - try (HikariDataSource ownedPool = pool) { - dsl.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); - } + dsl.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); } } From c15507cc8fef45e4719dd2ed4ba74cd3c8f570df Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 7 Nov 2026 16:42:21 +1300 Subject: [PATCH 13/23] Carry mandatory Entity PostgreSQL proof contract with foundation Retain the existing exact two-path Testcontainers classification. Java proof sources remain unchanged and PostgreSQL execution is not silently skipped. --- dev-tools/tests/testcontainers-disabled-contract.sh | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/dev-tools/tests/testcontainers-disabled-contract.sh b/dev-tools/tests/testcontainers-disabled-contract.sh index 51159513ab..f7f21be261 100644 --- a/dev-tools/tests/testcontainers-disabled-contract.sh +++ b/dev-tools/tests/testcontainers-disabled-contract.sh @@ -4,6 +4,7 @@ set -euo pipefail ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" SAGA_TEST="$ROOT_DIR/services/common-saga/src/test/java/integration/net/firedevops/firemud/common/saga/persistence/SagaPersistenceRepositoryIntegrationTest.java" IN_PROCESS_TEST="services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionCrossServiceIntegrationTest.java" +POSTGRES_MTLS_TEST="services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPostgresMtlsIntegrationTest.java" grep -Eq '^@Testcontainers\(disabledWithoutDocker = true\)$' "$SAGA_TEST" if grep -Eq 'POSTGRES\.(start|stop)\(' "$SAGA_TEST"; then @@ -17,7 +18,10 @@ while IFS= read -r -d '' java_file; do bare_annotations+=("${java_file#"$ROOT_DIR/"}") fi done < <(find "$ROOT_DIR/services" -type f -name '*.java' -print0) -if ((${#bare_annotations[@]} != 1)) || [[ "${bare_annotations[0]}" != "$IN_PROCESS_TEST" ]]; then +expected_bare_annotations=("$IN_PROCESS_TEST" "$POSTGRES_MTLS_TEST") +if ! diff -u \ + <(printf '%s\n' "${expected_bare_annotations[@]}" | LC_ALL=C sort) \ + <(printf '%s\n' "${bare_annotations[@]}" | LC_ALL=C sort); then printf 'unexpected bare @Testcontainers annotation(s):\n' >&2 printf ' %s\n' "${bare_annotations[@]}" >&2 exit 1 From 415e5a5373886c3e9c9b390865027e574cbb5760 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 7 Nov 2026 18:02:45 +1300 Subject: [PATCH 14/23] Keep hosting creation in its canonical receiver and tighten Account source contracts --- .../player-access-and-session.md | 14 +- .../StripeHostingSubscriptionProvisioner.java | 202 --------- ...ostingSubscriptionLifecycleRepository.java | 37 +- ...ostingSubscriptionProvisioningService.java | 125 ------ ...ccountPlayerAdmissionEntitlementOwner.java | 31 +- ...PlayerAdmissionEntitlementGrpcService.java | 33 +- ...ipeHostingSubscriptionProvisionerTest.java | 391 ------------------ ...ngSubscriptionProvisioningServiceTest.java | 154 ------- ...ntPlayerAdmissionEntitlementOwnerTest.java | 133 ++++-- ...erAdmissionEntitlementGrpcServiceTest.java | 286 ++++++++++++- 10 files changed, 454 insertions(+), 952 deletions(-) delete mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisioner.java delete mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java delete mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisionerTest.java delete mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 7f291b0114..4617feca46 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -14,11 +14,13 @@ The local reconstruction based on `6b86f46f3fd0a76729b27f99b1e573bbac649838` car The #3389 source includes the private [`TENANT_OPERATION` proto](../../../protos/account/v1/tenant_operation_entitlement_read.proto), [strict common evidence codec](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementGrpcCodec.java), [Account source owner](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwner.java), [workload guard](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantOperationEntitlementWorkloadGuard.java), [gRPC receiver](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantOperationEntitlementGrpcService.java), and [World client](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClient.java). They prepare an explicit paid-or-DEMO eligibility read for the exact same-namespace World workload without source fallback, capacity commitment or player admission. They remain manually composed and unregistered; the paid branch still depends on the missing canonical subscription schema. The [controlled mTLS transport test source](../../../services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClientMtlsTest.java) uses a controlled Account source owner and does not establish physical paid entitlement authority. -Held hosting sources include 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), [lifecycle repository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java), and [same-owner terminal-resolution composition](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionService.java), with their focused unit sources. Retained dispatch/readback and fresh Account primary-authentication guards do not enable `CreateSubscription`, a provider worker, cancellation recovery, or a production billing route. Their required canonical intent, provisioning, lifecycle, dispatch and terminal-resolution storage is not installed in this candidate; the dependent physical billing/retention proofs are not carried as candidate qualification. +Held hosting sources here include the [lifecycle repository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java) and [same-owner terminal-resolution composition](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionService.java), with their focused unit sources. Retained dispatch/readback and fresh Account primary-authentication guards do not enable `CreateSubscription`, a provider worker, cancellation recovery, or a production billing route. Their required canonical intent, provisioning, lifecycle, dispatch and terminal-resolution storage is not installed in this candidate; the dependent physical billing/retention proofs are not carried as candidate qualification. + +Initial provider creation is carried by [#3390](https://github.com/benhook1013/FireMUD/pull/3390), alongside its canonical storage and dispatch physical proof. The [Stripe provisioner](https://github.com/benhook1013/FireMUD/blob/d327e67c51637592637b6a349e59aa74aaf74f55/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisioner.java), [provisioning composition](https://github.com/benhook1013/FireMUD/blob/d327e67c51637592637b6a349e59aa74aaf74f55/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java) and both focused unit suites are absent from this front boundary and preserved in that receiver. The paid first-invoice confirmation finding remains open there: `default_incomplete` creation and subscription polling do not complete payment, and controlled active-subscription inputs are not paid-checkout proof. Account/provider-hosted checkout completion after confirmed provider linkage and its proof remain required under [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). This ownership transfer enables no provider worker, runtime registration, automatic charging or activation. The #3390 source adds the unregistered [Entity bootstrap-roster proto](../../../protos/entity-management/v1/account_bootstrap_roster_read.proto), [Entity persisted reader](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadService.java), [Account client](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClient.java), and [signed V2 scope reader](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReader.java). Discovery is bounded to independently current public-production `SHARED`/`PRESEEDED_ONLY` targets and actual persisted eligible actors, including their stored level and valid empty rosters; it creates no selection, actor, retained roster, session or admission authority. Target reads surrounding Entity SQL detect source movement but supply no distributed hold. The scope reader compares the signed selector with retained Account evidence and requires an externally authenticated Account identity. Neither reader is consumed by the existing public facade. [`CanonicalJoinScopeV2`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CanonicalJoinScopeV2.java) also redacts its bearer scope in `toString()`. -Focused unit and controlled physical proof sources are retained, including the [Entity PostgreSQL/mTLS roster tests](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPostgresMtlsIntegrationTest.java), [Account roster-client mTLS tests](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClientMtlsTest.java), and [V2 scope-reader units](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReaderTest.java). The expanded candidate passes 523 selected cases: 403 Account, eight Entity, 73 Game Session, fourteen Common Platform Core, 21 Common Security and four World client mTLS cases, with no failures, errors or skips. The first expanded run passed 524 cases plus affected integration/cross-service source compilation in 13m16s; removing the previously adjudicated duplicate membership test preserved its richer proof, and the final Account rerun plus affected enabled Checkstyle, SpotBugs, formatting and documentation checks passed in 9m26s. These local units and controlled transports do not establish physical PostgreSQL or source-built runtime Smoke; fresh exact-comparison CI and positive Smoke remain required before this earlier boundary is ready. +Focused unit and controlled physical proof sources are retained, including the [Entity PostgreSQL/mTLS roster tests](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPostgresMtlsIntegrationTest.java), [Account roster-client mTLS tests](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClientMtlsTest.java), and [V2 scope-reader units](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReaderTest.java). Before the provider-write source transfer, the expanded candidate passed 523 selected cases: 403 Account, eight Entity, 73 Game Session, fourteen Common Platform Core, 21 Common Security and four World client mTLS cases, with no failures, errors or skips. The first expanded run passed 524 cases plus affected integration/cross-service source compilation in 13m16s; removing the previously adjudicated duplicate membership test preserved its richer proof, and the final Account rerun plus affected enabled Checkstyle, SpotBugs, formatting and documentation checks passed in 9m26s. Those historical units and controlled transports do not qualify the reduced boundary or establish physical PostgreSQL or source-built runtime Smoke. After the transfer, affected production/unit/integration compilation, all 51 selected Account owner/handler/lifecycle/workload-guard cases, and enabled Account Checkstyle, SpotBugs and Java formatting pass. Physical integration execution is unrun locally; exact-comparison CI and positive Smoke remain required before this earlier boundary is ready. The V1028-and-later subscription UUID transition, immutable retained archive, numeric-authority retirement, production denial stubs, canonical public facade and live `PLAYER_ADMISSION` integration are outside this preparation. Schema retirement and a functioning canonical UUID admission replacement must arrive together at one downstream receiving boundary, preserving retained-data safety without a new numeric bridge or dual authority. No entitlement-receiver registration, production custody, canonical player admission, activation or physical proof success is claimed, and the capability ratings below remain unchanged. @@ -28,7 +30,7 @@ The local candidate now retains the [Account player-admission owner](../../../se Three Account physical proof sources are present: the [current-source PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java), [entitlement-owner PostgreSQL/mTLS suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java), and [committed-LOGIN composition](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java). They prepare DEMO, absent/joined membership, exact scope and committed LOGIN checks on the existing schema; shared owner/context fixture and resource integration must preserve the existing constructors and numeric runtime dependencies. The owner suite controls caller/current issuance and protected Game Session/World inputs; the committed-LOGIN case replaces Account caller doubles with actual committed issuance and recovery while retaining controlled signing, initial delivery and protected targets. None establishes paid billing composition. The four-file World/shared positive composition cohort remains downstream because it requires the canonical UUID direct-text scope DTOs and producer; genuine LOGIN/World positive composition remains an explicit receiving obligation, not dropped scope. -Historical #3390 proof324 (22 owner and five shared cases), proof335 (three Account PostgreSQL cases) and proof352 (34 client mTLS cases) remain donor-source results. Earlier locally skipped physical aggregates remain skipped; none of these results qualifies this expanded reconstruction. Fresh selected unit/mTLS, affected source compilation and enabled static checks are recorded in the foundation proof above; physical execution remains outstanding here. Production mTLS/custody and Redis qualification, complete authenticated target provenance, a World hold through later commitment, paid schema/provider composition, runtime registration and functional admission remain open; point-in-time evidence is not a capacity or admission decision. +Historical #3390 proof324 (22 owner and five shared cases), proof335 (three Account PostgreSQL cases) and proof352 (34 client mTLS cases) remain donor-source results. Earlier locally skipped physical aggregates remain skipped; none of these results qualifies this expanded reconstruction. The selected unit/mTLS, affected source compilation and enabled static checks recorded in the foundation proof above retain their pre-transfer comparison; physical execution remains outstanding here. Production mTLS/custody and Redis qualification, complete authenticated target provenance, a World hold through later commitment, paid schema/provider composition, runtime registration and functional admission remain open; point-in-time evidence is not a capacity or admission decision. ### Lifecycle-bound private realm-grant source preparation @@ -56,7 +58,7 @@ The source owner refuses ambient Account SQL and requires a workload-only `Sessi Earlier component proof is bounded by the [Account discovery-owner tests](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java), [entitlement-owner tests](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwnerTest.java), [Account target-client tests](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClientTest.java), [Game Session collection-read tests](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java), and [workload-guard tests](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayAdmissionDecisionReadWorkloadGuardTest.java). The prior affected regression run passed 76 selected Account and Game Session cases without failures, errors or skips, plus enabled affected static analysis, formatting and documentation checks. It covers concurrent requests across separate owners, unchanged target projection and sanitized dependency failures, not the local mixed-policy addition. Retained physical proof passed all 10 [Account DEMO discovery and scope PostgreSQL cases](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java), including deterministic filtering, source-head drift, expiry refusal and immutable rows. Earlier broader unit, loopback-mTLS and final-admission composition runs overlap this coverage and are not additive or a current whole-system qualification. The PostgreSQL discovery tests use controlled Game Session responses; client mTLS tests use a controlled Game Session server, and final-admission composition uses a controlled World capture. These proofs do not establish the complete authenticated cross-owner source chain, deployment custody, paid discovery activation or production capacity. -The existing [`AccountServiceImpl.listBootstrapWorlds`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java) and its positive tests remain on the legacy path in this source slice. The local [`AccountCanonicalPublicRealmScopeOwner`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java) separately issues and retains signed canonical UUID V2 public selector scopes; its focused and pre-V1028 PostgreSQL proof remains component-only. That scope owner and the newly retained [V2 reader](#local-source-foundation-preparation) are not consumed by the existing facade. Unregistered hosting observer, intent, lifecycle, provisioning and plan implementations and focused units are present; they do not establish paid discovery against this source slice’s legacy schema. Subscription schema retirement and functioning canonical UUID facade/admission consumers remain one downstream receiving boundary, including the V1028 retained archive, V1029 canonical table and dependent lifecycle/dispatch/terminal-resolution storage. No numeric fallback or second subscription table is introduced. Private `REALMS`, registered browser/direct scope consumption, live [player-admission entitlement integration](#player-admission-entitlement-source-preparation), JOIN consumer migration, default registration and gameplay admission remain gaps. +The existing [`AccountServiceImpl.listBootstrapWorlds`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java) and its positive tests remain on the legacy path in this source slice. The local [`AccountCanonicalPublicRealmScopeOwner`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java) separately issues and retains signed canonical UUID V2 public selector scopes; its focused and pre-V1028 PostgreSQL proof remains component-only. That scope owner and the newly retained [V2 reader](#local-source-foundation-preparation) are not consumed by the existing facade. Unregistered hosting observer, intent, lifecycle and plan implementations and focused units are present; they do not establish paid discovery against this source slice’s legacy schema. Subscription schema retirement and functioning canonical UUID facade/admission consumers remain one downstream receiving boundary, including the V1028 retained archive, V1029 canonical table and dependent lifecycle/dispatch/terminal-resolution storage. No numeric fallback or second subscription table is introduced. Private `REALMS`, registered browser/direct scope consumption, live [player-admission entitlement integration](#player-admission-entitlement-source-preparation), JOIN consumer migration, default registration and gameplay admission remain gaps. The local [`AccountCanonicalPublicRealmScopeOwner`](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java) adds an actual public selector-scope producer over the same complete target and current Account source owners. It preserves genuine membership absence without enrolling a pair, returns current ACTIVE/INACTIVE facts without treating closed enrollment as loss of public visibility, and persists signed canonical UUID V2 scope preimages through the existing Account scope repository. Focused signing and orchestration cases use real local signing and bootstrap verification with controlled source and transaction inputs. The retained pre-V1028 PostgreSQL scope cases preserve exact signed UUID/V2 hash, digest and provenance bytes without membership, pair, JOIN or event writes, refuse a real DEMO source-head change, and roll back a real PostgreSQL insert refusal. No facade/default registration, private lifecycle completion, JOIN or admission is established. Current-head CI remains required after source changes. @@ -543,7 +545,7 @@ Account connect-token issuance retains its existing bootstrap and scope authenti | `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; tenant IDs remain numeric and 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. Current connect-token issuance returns `AUTH_UNAVAILABLE` before replay-cache or fresh pointer/visibility/membership reads while the canonical producer is unavailable; target current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `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); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml); [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. Their canonical UUID schema prerequisites V1028/V1029 and existing facade convergence are carried by [#3389](https://github.com/benhook1013/FireMUD/pull/3389) and [#3390](https://github.com/benhook1013/FireMUD/pull/3390). This source carrier still retains the legacy numeric schema; `CreateSubscription` still fails closed before mutation. Subscription lifecycle processing, reconciliation, entitlement/availability enforcement, caller-stable creation identity, active-subscription deletion guards, per-subscription binding, 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.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); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml); [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. Their canonical UUID schema prerequisites V1028/V1029, existing facade convergence and initial provider-write source are carried by [#3390](https://github.com/benhook1013/FireMUD/pull/3390); paid first-invoice checkout completion remains open there. This source carrier still retains the legacy numeric schema; `CreateSubscription` still fails closed before mutation. Subscription lifecycle processing, reconciliation, entitlement/availability enforcement, caller-stable creation identity, active-subscription deletion guards, per-subscription binding, 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 local reader refuses null, missing, ambiguous or nonpositive-version subscription evidence. Classified storage outages preserve `ENTITLEMENT_UNAVAILABLE`; JOIN diagnostic persistence follows rollback, and terminal-outage reads preserve the complete original receipt. The focused current-source qualification is recorded below. Legacy gRPC still carries unavailable outcomes in its error field, an explicit transport-classification gap. Current connect-token issuance returns `AUTH_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. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | | `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [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` validates existing bootstrap and scope, then returns `AUTH_UNAVAILABLE` before 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. | @@ -782,7 +784,7 @@ R1419 passes 70 fresh selected cases (49 Logging units, fifteen application/Post ## Validation and Proof -The [local source-foundation preparation](#local-source-foundation-preparation) records fresh selected unit/mTLS, affected source compilation and enabled static/format proof for the reconstructed source. Historical #3389, #3390 and #3403 results retain their original comparisons. Physical PostgreSQL qualification and fresh positive runtime Smoke remain receiving obligations; the independently supported parent runtime is preserved, not requalified by source-only checks. +The [local source-foundation preparation](#local-source-foundation-preparation) records selected unit/mTLS, affected source compilation and enabled static/format proof for the reconstructed source before the provider-write transfer. Those results and historical #3389, #3390 and #3403 results retain their original comparisons; the reduced boundary now has the affected compilation and 51-case focused Account proof recorded above, not a repeated whole-foundation qualification. Physical PostgreSQL qualification and fresh positive runtime Smoke remain receiving obligations; the independently supported parent runtime is preserved, not requalified by source-only checks. The prepared region owner has a scope-local liveness limit when `beginInitialTimeline` commits `INITIALIZING` but the Redis initialization call never executes. The retained phase, initialization operation and source do not grant a second creation permission; absent keys cannot distinguish that cut from metadata loss, so repeated owner retries refuse without a lease or runtime owner installation. No shipped in-place automatic recovery, dedicated alert or operator repair is claimed. The operator recovery boundary is recorded by [Game Session operations](../../architecture/microservices/game-session-service/operations.md#initial-region-timeline-recovery-boundary). 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 deleted file mode 100644 index c6de43e0a2..0000000000 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisioner.java +++ /dev/null @@ -1,202 +0,0 @@ -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.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 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()) { - return new Pending("PROVIDER_LOOKUP_UNRESOLVED", null); - } - 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 4d1095a061..ae02b181a4 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 @@ -246,23 +246,26 @@ public TransitionResult applyTerminalResolution( utc(prepared.capturedAt), utc(prepared.deadline), utc(actor.authenticatedAt())); - dsl.execute( - "INSERT INTO subscription_lifecycle_operations (request_id, creation_request_id, subscription_id, tenant_id, expected_row_version, " - + "reserved_row_version, provider_subscription_id, provisioning_attempt_id, request_payload, request_digest, state, row_version, " - + "max_attempts, max_stalled_attempts, lease_millis, backoff_millis, observation_age_millis, warning_millis, grace_millis, deadline_at, retry_at, created_at) " - + "SELECT ?, creation_request_id, subscription_id, tenant_id, ?, ?, provider_subscription_id, provisioning_attempt_id, ?, ?, 'PENDING', 1, " - + "1, 1, lease_millis, backoff_millis, observation_age_millis, warning_millis, grace_millis, ?::timestamptz, ?::timestamptz, ?::timestamptz " - + "FROM subscription_lifecycle_operations WHERE request_id = ? AND state = 'BILLING_RECONCILIATION_TERMINAL_FAILURE' AND row_version = ?", - request.resolutionRequestId(), - request.expectedSubscriptionVersion(), - request.expectedSubscriptionVersion() + 1, - request.payload(), - request.digest(), - utc(prepared.deadline), - utc(prepared.capturedAt), - utc(prepared.capturedAt), - request.failedRequestId(), - request.expectedFailedOperationVersion()); + if (dsl.execute( + "INSERT INTO subscription_lifecycle_operations (request_id, creation_request_id, subscription_id, tenant_id, expected_row_version, " + + "reserved_row_version, provider_subscription_id, provisioning_attempt_id, request_payload, request_digest, state, row_version, " + + "max_attempts, max_stalled_attempts, lease_millis, backoff_millis, observation_age_millis, warning_millis, grace_millis, deadline_at, retry_at, created_at) " + + "SELECT ?, creation_request_id, subscription_id, tenant_id, ?, ?, provider_subscription_id, provisioning_attempt_id, ?, ?, 'PENDING', 1, " + + "1, 1, lease_millis, backoff_millis, observation_age_millis, warning_millis, grace_millis, ?::timestamptz, ?::timestamptz, ?::timestamptz " + + "FROM subscription_lifecycle_operations WHERE request_id = ? AND state = 'BILLING_RECONCILIATION_TERMINAL_FAILURE' AND row_version = ?", + request.resolutionRequestId(), + request.expectedSubscriptionVersion(), + request.expectedSubscriptionVersion() + 1, + request.payload(), + request.digest(), + utc(prepared.deadline), + utc(prepared.capturedAt), + utc(prepared.capturedAt), + request.failedRequestId(), + request.expectedFailedOperationVersion()) + != 1) { + throw new FenceRejectedException("Terminal resolution exact failed-operation copy rejected"); + } if (dsl.execute( "UPDATE subscription SET lifecycle_inflight_request_id = ?, row_version = row_version + 1 " + "WHERE subscription_id = ? AND row_version = ? AND lifecycle_inflight_request_id = ? AND superseded_at IS NULL", 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 deleted file mode 100644 index 1cc49b0b19..0000000000 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java +++ /dev/null @@ -1,125 +0,0 @@ -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.ProvisioningClaim; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.TransitionResult; -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(); - var prepared = - Objects.requireNonNull( - transaction.execute(status -> repository.prepareProviderDispatch(claim, dispatchId))); - var dispatch = - Objects.requireNonNull( - transaction.execute(status -> repository.readProviderDispatch(prepared))); - 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 = - lifecycle.readCurrent(claim.creation().tenantId()); - 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, Committed {} - - public record Pending( - Disposition disposition, StripeHostingSubscriptionProvisioner.Result providerResult) - implements Result {} - - public record Reconciling(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/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java index fc705d2d1b..90bf77d531 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java @@ -133,7 +133,12 @@ public RuntimePlayerAdmissionEntitlementEvidence evaluate( case PAID_HOSTING -> capturePaidSources(request, caller, prepared); case NON_PAID_DEMO -> captureDemoSources(request, caller, prepared); }; - evidence.requireCurrentAt(now()); + try { + evidence.requireCurrentAt(now()); + } catch (IllegalArgumentException expired) { + // This final post-commit check only rejects an expired or future source observation. + throw unavailable(); + } return evidence; } @@ -333,6 +338,7 @@ private CurrentPlayer readCurrentPlayer(Request request, VerifiedCaller caller) .findCanonicalEvidenceByTokenHash(AccountJoinDigest.tokenHash(request.connectScopeId())) .orElseThrow(AccountPlayerAdmissionEntitlementOwner::unavailable); if (!"PUBLIC_PRODUCTION".equals(scope.targetClass()) + || !"SHARED".equals(scope.playableStateScope()) || scope.tenantProvenance().kind() != TenantProvenanceKind.FRESH_GAME_DESIGN || scope.tenantProvenance().legacyTenantId() != null || !accountId.equals(scope.accountUuid()) @@ -435,9 +441,15 @@ private static void requireNoAmbientTransaction() { || TransactionSynchronizationManager.isSynchronizationActive()) throw unavailable(); } - private static IllegalStateException unavailable() { - return new IllegalStateException( - "ENTITLEMENT_UNAVAILABLE: current player source evidence is unavailable"); + private static SourceUnavailableException unavailable() { + return new SourceUnavailableException(); + } + + /** Current owner evidence cannot be supplied; not a configuration or codec failure. */ + public static final class SourceUnavailableException extends IllegalStateException { + public SourceUnavailableException() { + super("ENTITLEMENT_UNAVAILABLE: current player source evidence is unavailable"); + } } private void requireSameHead(Request request, SourceSelection selected) { @@ -500,15 +512,23 @@ private PublishedRealmEvidence readProtectedTarget( var selector = selector(request, scope); var resolved = Objects.requireNonNull(targets.resolvePublishedRealmAdmissionTarget(selector)); if (!selector.equals(resolved.selector())) throw unavailable(); + requireSupportedTarget(resolved.currentTarget()); CanonicalGameplayAdmissionDecisionReadGrpcCodec.requireRetainedTargetMatches( selector, resolved.currentTarget()); var result = Objects.requireNonNull(targets.readPublishedRealmAdmissionOwner(resolved.strictSelector())); if (!resolved.strictSelector().equals(result.selector()) || !resolved.currentTarget().equals(result.currentTarget())) throw unavailable(); + requireSupportedTarget(result.currentTarget()); return result; } + private static void requireSupportedTarget( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target target) { + if (!"SHARED".equals(target.playableStateScope()) + || !"PRESEEDED_ONLY".equals(target.characterCreationPolicy())) throw unavailable(); + } + private static RuntimePlayerAdmissionEntitlementEvidence capture( Request request, CurrentPlayer player, @@ -519,9 +539,10 @@ private static RuntimePlayerAdmissionEntitlementEvidence capture( Instant paidReceiptValidUntil) { var scope = player.scope(); var current = target.currentTarget(); + requireSupportedTarget(current); Map binding = new LinkedHashMap<>(); binding.put("targetClass", "PUBLIC_PRODUCTION"); - binding.put("characterCreationPolicy", "PRESEEDED_ONLY"); + binding.put("characterCreationPolicy", current.characterCreationPolicy()); binding.put("targetNamespace", current.targetNamespace()); binding.put("tenantId", scope.tenantUuid().toString()); binding.put("tenantSlug", scope.tenantSlug()); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java index 2ddf42719a..c939580312 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java @@ -1,10 +1,12 @@ package net.firedevops.firemud.accountservice.service.impl; +import com.google.protobuf.Any; import io.grpc.Server; import io.grpc.ServerInterceptors; import io.grpc.Status; import io.grpc.StatusRuntimeException; import io.grpc.TlsServerCredentials; +import io.grpc.protobuf.StatusProto; import io.grpc.stub.StreamObserver; import java.util.List; import java.util.Objects; @@ -14,10 +16,13 @@ import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementRequest; import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementResponse; import net.firedevops.firemud.accountservice.security.AccountPlayerAdmissionEntitlementWorkloadGuard; +import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionLifecycleService; import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner; +import net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException; import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementGrpcCodec; import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; +import net.firedevops.firemud.shared.v1.ErrorDetail; import org.springframework.transaction.support.TransactionSynchronizationManager; /** @@ -96,11 +101,18 @@ public void readPlayerAdmissionEntitlement( request.target(), request.connectScopeId(), authenticatedCaller); var evidence = owner.evaluate(sourceRequest, presented.initialLoginJwt()); response = RuntimePlayerAdmissionEntitlementGrpcCodec.toResponse(request, evidence); - } catch (RuntimeException unavailableSource) { - // No positive evidence, alternate source, or exception details escape an unavailable - // evaluation. + } catch (AccountPlayerAdmissionEntitlementOwner.SourceUnavailableException + | AccountHostingSubscriptionLifecycleService.EntitlementUnavailableException + | DemoTenantEntitlementException + | org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException + | org.springframework.transaction.TransactionException unavailableSource) { fail(observer, Status.UNAVAILABLE); return; + } catch (RuntimeException internalFailure) { + // Unexpected, configuration and codec faults are not retryable source outages. + fail(observer, Status.INTERNAL); + return; } try { observer.onNext(response); @@ -112,9 +124,18 @@ public void readPlayerAdmissionEntitlement( } private static void fail(StreamObserver observer, Status status) { + String message = "Player-admission entitlement evidence is unavailable"; observer.onError( - Status.fromCode(status.getCode()) - .withDescription("Player-admission entitlement evidence is unavailable") - .asRuntimeException()); + StatusProto.toStatusRuntimeException( + com.google.rpc.Status.newBuilder() + .setCode(status.getCode().value()) + .setMessage(message) + .addDetails( + Any.pack( + ErrorDetail.newBuilder() + .setCode(status.getCode().name()) + .setMessage(message) + .build())) + .build())); } } 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 deleted file mode 100644 index a64ef32f6d..0000000000 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisionerTest.java +++ /dev/null @@ -1,391 +0,0 @@ -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("")); - 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"); - assertThat(missing.methods) - .containsExactly(RequestMethod.GET, RequestMethod.GET, RequestMethod.GET); - 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 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 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/service/AccountHostingSubscriptionProvisioningServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java deleted file mode 100644 index 32e14ef03f..0000000000 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java +++ /dev/null @@ -1,154 +0,0 @@ -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.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 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); - } - - @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/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java index 9e3654d9da..c32648c446 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java @@ -73,6 +73,8 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; @@ -121,6 +123,8 @@ void missingMembershipRemainsAnExplicitNonadmittingBaselineWithActualCallerAndTa var binding = (Map) value.fields().get("target"); assertThat(binding.get("realmId")).isEqualTo(f.scope.realmId().toString()); assertThat(binding.get("pointerVersion")).isEqualTo("3"); + assertThat(binding.get("playableStateScope")).isEqualTo("SHARED"); + assertThat(binding.get("characterCreationPolicy")).isEqualTo("PRESEEDED_ONLY"); assertThat(value.toString()).doesNotContain("controlled-token", f.scope.connectScopeId()); assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "commit"); verifyNoInteractions(f.hosting, f.observer); @@ -204,7 +208,8 @@ void scopeDeadlineReachedDuringFinalCommitReturnsNoValue() throws Exception { Fixture f = new Fixture(false); f.transactions.afterSecondCommit = () -> f.time.set(NOW.plusSeconds(60)); assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) - .hasMessageContaining("expired"); + .isExactlyInstanceOf( + AccountPlayerAdmissionEntitlementOwner.SourceUnavailableException.class); assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "commit"); } @@ -412,6 +417,58 @@ void changedOwnerPointerFailsExactRetainedTargetComparison() throws Exception { verifyNoInteractions(f.demos, f.hosting, f.observer); } + @ParameterizedTest + @NullSource + @ValueSource(strings = {"PLAYER_CREATED", "unknown", ""}) + void unsupportedCurrentPolicyCannotBecomePreseededPlayerEvidence(String policy) throws Exception { + Fixture f = new Fixture(false); + var resolved = f.targets.resolvePublishedRealmAdmissionTarget(f.request.target()); + when(resolved.currentTarget().characterCreationPolicy()).thenReturn(policy); + doReturn(resolved).when(f.targets).resolvePublishedRealmAdmissionTarget(f.request.target()); + + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .isExactlyInstanceOf( + AccountPlayerAdmissionEntitlementOwner.SourceUnavailableException.class); + + org.mockito.Mockito.verify(f.targets, org.mockito.Mockito.never()) + .readPublishedRealmAdmissionOwner(any()); + verifyNoInteractions(f.demos, f.hosting, f.observer); + assertThat(f.transactions.events).containsExactly("begin", "commit"); + } + + @Test + void isolatedRetainedScopeFailsBeforeProtectedTargetOrEntitlementCapture() throws Exception { + Fixture f = new Fixture(false, "ISOLATED"); + + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .isExactlyInstanceOf( + AccountPlayerAdmissionEntitlementOwner.SourceUnavailableException.class); + + verifyNoInteractions(f.targets, f.sources, f.demos, f.hosting, f.observer); + assertThat(f.transactions.events).containsExactly("begin", "rollback"); + } + + @Test + void protectedReadCannotReplaceSupportedPolicyBeforeEvidenceCapture() throws Exception { + Fixture f = new Fixture(false); + var resolved = f.targets.resolvePublishedRealmAdmissionTarget(f.request.target()); + var original = f.targets.readPublishedRealmAdmissionOwner(resolved.strictSelector()); + doReturn(resolved).when(f.targets).resolvePublishedRealmAdmissionTarget(f.request.target()); + when(f.targets.readPublishedRealmAdmissionOwner(resolved.strictSelector())) + .thenAnswer( + invocation -> { + when(original.currentTarget().characterCreationPolicy()).thenReturn("PLAYER_CREATED"); + return original; + }); + + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .isExactlyInstanceOf( + AccountPlayerAdmissionEntitlementOwner.SourceUnavailableException.class); + + verifyNoInteractions(f.demos, f.hosting, f.observer); + assertThat(f.transactions.events).containsExactly("begin", "commit"); + } + @Test void scopeChangedDuringProtectedTargetReadCannotBindFinalAccountEvidence() throws Exception { Fixture f = new Fixture(false); @@ -568,22 +625,7 @@ private static final class Fixture { new java.util.concurrent.atomic.AtomicReference<>(NOW); private final FreshTenantCreationEvidence source = source(); private final TenantAuthorityEventV1Codec.Event tenantEvent = tenantEvent(source); - private final CanonicalJoinScopeV2 scope = - new CanonicalJoinScopeV2( - "private-bearer-" + UUID.randomUUID(), - ACCOUNT, - TENANT, - UUID.randomUUID(), - "tenant", - "world", - "production", - UUID.randomUUID(), - "SHARED", - UUID.randomUUID(), - 7, - 3, - NOW.minusSeconds(20).toString(), - NOW.plusSeconds(60).toString()); + private final CanonicalJoinScopeV2 scope; private final AccountGameplayDelegationPendingIdentity identity = new AccountGameplayDelegationPendingIdentity( UUID.randomUUID(), @@ -622,27 +664,48 @@ private static final class Fixture { 1, tenantEvent.eventId(), tenantEvent.eventDigest()); - private final Request request = - new Request( - new CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector( - UUID.randomUUID(), - ACCOUNT, - "prod", - TENANT, - scope.tenantSlug(), - scope.worldSlug(), - scope.realmId(), - scope.realmSlug(), - scope.playableStateNamespaceId(), - scope.playableStateScope(), - scope.gameInstanceId(), - scope.catalogRevision(), - scope.pointerVersion()), - scope.connectScopeId(), - PEER); + private final Request request; private final AccountPlayerAdmissionEntitlementOwner owner; private Fixture(boolean exists) throws Exception { + this(exists, "SHARED"); + } + + private Fixture(boolean exists, String stateScope) throws Exception { + scope = + new CanonicalJoinScopeV2( + "private-bearer-" + UUID.randomUUID(), + ACCOUNT, + TENANT, + UUID.randomUUID(), + "tenant", + "world", + "production", + UUID.randomUUID(), + stateScope, + UUID.randomUUID(), + 7, + 3, + NOW.minusSeconds(20).toString(), + NOW.plusSeconds(60).toString()); + request = + new Request( + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector( + UUID.randomUUID(), + ACCOUNT, + "prod", + TENANT, + scope.tenantSlug(), + scope.worldSlug(), + scope.realmId(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + "SHARED", + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion()), + scope.connectScopeId(), + PEER); controlledTarget(targets); var dsl = mock(DSLContext.class); var connection = mock(Connection.class); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java index ce61e144dd..8d4335e452 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java @@ -2,24 +2,59 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; import io.grpc.Status; +import io.grpc.protobuf.StatusProto; import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Stream; import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementRequest; import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementResponse; +import net.firedevops.firemud.accountservice.security.AccountPlayerAdmissionEntitlementWorkloadGuard; +import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionLifecycleService; import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner; +import net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.ArgumentCaptor; +import org.mockito.MockedConstruction; +import org.springframework.transaction.support.TransactionSynchronizationManager; -/** Direct method calls cannot install the receiver's TLS-derived private peer assertion. */ +/** Handler classifications use a controlled guard, not a claim of authenticated TLS custody. */ class AccountPlayerAdmissionEntitlementGrpcServiceTest { + private static final String PEER = "spiffe://firemud/ns/prod/sa/game-session-service"; + private static final String JWT = "private-token.payload.signature"; + private static final String SCOPE = "private-scope"; + private static final String SECRET = "private-source-internal-identifier"; + private static final String MESSAGE = "Player-admission entitlement evidence is unavailable"; + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + @Test @SuppressWarnings("unchecked") - void authenticationPrecedesEvenNullMalformedAndOversizedCredentialParsing() { + void authenticationPrecedesEvenNullMalformedAndOversizedCredentialParsing() throws Exception { var owner = mock(AccountPlayerAdmissionEntitlementOwner.class); var service = new AccountPlayerAdmissionEntitlementGrpcService(owner, "prod"); for (var request : @@ -31,17 +66,246 @@ void authenticationPrecedesEvenNullMalformedAndOversizedCredentialParsing() { .build() }) { StreamObserver observer = mock(StreamObserver.class); - service.readPlayerAdmissionEntitlement(request, observer); - - var failure = ArgumentCaptor.forClass(Throwable.class); - verify(observer).onError(failure.capture()); - assertThat(Status.fromThrowable(failure.getValue()).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED); - assertThat(failure.getValue().getMessage()).doesNotContain("private-token"); - verify(observer, never()).onNext(any()); - verify(observer, never()).onCompleted(); + assertRefusal(observer, Status.Code.UNAUTHENTICATED); } verifyNoInteractions(owner); } + + @ParameterizedTest + @MethodSource("ownerFailures") + void ownerFailuresRetainExactAvailabilityClassificationWithoutSourceDetails( + RuntimeException cause, Status.Code expected) throws Exception { + try (var f = new AuthenticatedFixture()) { + when(f.owner.evaluate(any(), any())).thenThrow(cause); + f.service.readPlayerAdmissionEntitlement(wire("prod"), f.observer); + assertRefusal(f.observer, expected); + verify(f.owner).evaluate(sourceRequest("prod"), JWT); + } + } + + private static Stream ownerFailures() { + return Stream.of( + org.junit.jupiter.params.provider.Arguments.of( + new AccountPlayerAdmissionEntitlementOwner.SourceUnavailableException(), + Status.Code.UNAVAILABLE), + org.junit.jupiter.params.provider.Arguments.of( + new AccountHostingSubscriptionLifecycleService.EntitlementUnavailableException( + new IllegalStateException(SECRET)), + Status.Code.UNAVAILABLE), + org.junit.jupiter.params.provider.Arguments.of( + new DemoTenantEntitlementException( + DemoTenantEntitlementException.Code.ENTITLEMENT_UNAVAILABLE, SECRET), + Status.Code.UNAVAILABLE), + org.junit.jupiter.params.provider.Arguments.of( + new org.jooq.exception.DataAccessException(SECRET), Status.Code.UNAVAILABLE), + org.junit.jupiter.params.provider.Arguments.of( + new org.springframework.dao.DataAccessResourceFailureException(SECRET), + Status.Code.UNAVAILABLE), + org.junit.jupiter.params.provider.Arguments.of( + new org.springframework.transaction.CannotCreateTransactionException(SECRET), + Status.Code.UNAVAILABLE), + org.junit.jupiter.params.provider.Arguments.of( + new IllegalStateException("ENTITLEMENT_UNAVAILABLE: " + SECRET), Status.Code.INTERNAL), + org.junit.jupiter.params.provider.Arguments.of( + new IllegalArgumentException(SECRET), Status.Code.INTERNAL), + org.junit.jupiter.params.provider.Arguments.of( + new NullPointerException(SECRET), Status.Code.INTERNAL)); + } + + @Test + void authenticatedMalformedAndWrongNamespaceRequestsNeverReachOwner() throws Exception { + try (var f = new AuthenticatedFixture()) { + f.service.readPlayerAdmissionEntitlement(null, f.observer); + assertRefusal(f.observer, Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(f.owner); + } + try (var f = new AuthenticatedFixture()) { + f.service.readPlayerAdmissionEntitlement( + ReadPlayerAdmissionEntitlementRequest.getDefaultInstance(), f.observer); + assertRefusal(f.observer, Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(f.owner); + } + try (var f = new AuthenticatedFixture()) { + f.service.readPlayerAdmissionEntitlement(wire("other"), f.observer); + assertRefusal(f.observer, Status.Code.PERMISSION_DENIED); + verifyNoInteractions(f.owner); + } + } + + @Test + void ambientTransactionAndSynchronizationRefuseBeforeOwnerOrParsing() throws Exception { + try (var f = new AuthenticatedFixture()) { + TransactionSynchronizationManager.setActualTransactionActive(true); + f.service.readPlayerAdmissionEntitlement(null, f.observer); + assertRefusal(f.observer, Status.Code.FAILED_PRECONDITION); + verifyNoInteractions(f.owner); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + try (var f = new AuthenticatedFixture()) { + TransactionSynchronizationManager.initSynchronization(); + f.service.readPlayerAdmissionEntitlement(null, f.observer); + assertRefusal(f.observer, Status.Code.FAILED_PRECONDITION); + verifyNoInteractions(f.owner); + } + } + + @Test + void successfulOwnerValueUsesExactCallerCredentialAndClosedResponseBinding() throws Exception { + try (var f = new AuthenticatedFixture()) { + var evidence = evidence(); + when(f.owner.evaluate(any(), any())).thenReturn(evidence); + f.service.readPlayerAdmissionEntitlement(wire("prod"), f.observer); + var response = ArgumentCaptor.forClass(ReadPlayerAdmissionEntitlementResponse.class); + verify(f.observer).onNext(response.capture()); + assertThat(response.getValue()) + .isEqualTo( + RuntimePlayerAdmissionEntitlementGrpcCodec.toResponse(request("prod"), evidence)); + assertThat(response.getValue().toString()).doesNotContain(JWT); + verify(f.owner).evaluate(sourceRequest("prod"), JWT); + verify(f.observer).onCompleted(); + verify(f.observer, never()).onError(any()); + } + } + + @Test + void responseBindingOrCodecFaultIsInternalAndNeverEmitsEvidence() throws Exception { + try (var f = new AuthenticatedFixture()) { + var evidence = evidence(); + when(evidence.fields()).thenReturn(Map.of()); + when(f.owner.evaluate(any(), any())).thenReturn(evidence); + f.service.readPlayerAdmissionEntitlement(wire("prod"), f.observer); + assertRefusal(f.observer, Status.Code.INTERNAL); + } + } + + @Test + void responseCallbackFaultIsInternalWithoutCompletionOrPrivateDetails() throws Exception { + try (var f = new AuthenticatedFixture()) { + var evidence = evidence(); + when(f.owner.evaluate(any(), any())).thenReturn(evidence); + doThrow(new IllegalStateException(SECRET)).when(f.observer).onNext(any()); + f.service.readPlayerAdmissionEntitlement(wire("prod"), f.observer); + assertStructuredFailure(f.observer, Status.Code.INTERNAL); + verify(f.observer, never()).onCompleted(); + } + } + + private static void assertRefusal( + StreamObserver observer, Status.Code expected) + throws Exception { + assertStructuredFailure(observer, expected); + verify(observer, never()).onNext(any()); + verify(observer, never()).onCompleted(); + } + + private static void assertStructuredFailure( + StreamObserver observer, Status.Code expected) + throws Exception { + var failure = ArgumentCaptor.forClass(Throwable.class); + verify(observer).onError(failure.capture()); + assertThat(Status.fromThrowable(failure.getValue()).getCode()).isEqualTo(expected); + var status = StatusProto.fromThrowable(failure.getValue()); + assertThat(status).isNotNull(); + assertThat(status.getCode()).isEqualTo(expected.value()); + assertThat(status.getMessage()).isEqualTo(MESSAGE); + assertThat(status.getDetailsCount()).isOne(); + var detail = status.getDetails(0).unpack(ErrorDetail.class); + assertThat(detail) + .isEqualTo(ErrorDetail.newBuilder().setCode(expected.name()).setMessage(MESSAGE).build()); + assertThat(status.getSerializedSize()).isLessThan(256); + assertThat(status.toString()).doesNotContain(JWT, SCOPE, SECRET, "private-token"); + assertThat(failure.getValue().getCause()).isNull(); + } + + private static RuntimePlayerAdmissionEntitlementGrpcCodec.Request request(String namespace) { + return new RuntimePlayerAdmissionEntitlementGrpcCodec.Request( + new RetainedTargetSelector( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + namespace, + UUID.fromString("33333333-3333-4333-8333-333333333333"), + "tenant", + "world", + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "production", + UUID.fromString("55555555-5555-4555-8555-555555555555"), + "SHARED", + UUID.fromString("66666666-6666-4666-8666-666666666666"), + 7, + 3), + SCOPE); + } + + private static ReadPlayerAdmissionEntitlementRequest wire(String namespace) { + return RuntimePlayerAdmissionEntitlementGrpcCodec.toRequest(request(namespace), JWT); + } + + private static AccountPlayerAdmissionEntitlementOwner.Request sourceRequest(String namespace) { + return new AccountPlayerAdmissionEntitlementOwner.Request( + request(namespace).target(), SCOPE, PEER); + } + + /** The owner unit tests prove canonical content; this double isolates response forwarding. */ + private static RuntimePlayerAdmissionEntitlementEvidence evidence() { + var request = request("prod"); + var target = request.target(); + Map binding = new LinkedHashMap<>(); + binding.put("targetNamespace", "prod"); + binding.put("tenantId", target.tenantId().toString()); + binding.put("tenantSlug", target.tenantSlug()); + binding.put("worldSlug", target.worldSlug()); + binding.put("realmId", target.realmId().toString()); + binding.put("realmSlug", target.realmSlug()); + binding.put("playableStateNamespaceId", target.playableStateNamespaceId().toString()); + binding.put("playableStateScope", target.playableStateScope()); + binding.put("gameInstanceId", target.gameInstanceId().toString()); + binding.put("catalogRevision", "7"); + binding.put("pointerVersion", "3"); + var evidence = mock(RuntimePlayerAdmissionEntitlementEvidence.class); + when(evidence.fields()) + .thenReturn( + Map.of( + "callerAccountId", + target.accountId().toString(), + "tenantId", + target.tenantId().toString(), + "requestId", + target.readRequestId().toString(), + "callerWorkload", + PEER, + "verifiedConnectScopeId", + SCOPE, + "target", + binding)); + when(evidence.canonicalBytes()) + .thenReturn("controlled-owner-value".getBytes(StandardCharsets.UTF_8)); + return evidence; + } + + private static final class AuthenticatedFixture implements AutoCloseable { + private final MockedConstruction guards; + private final AccountPlayerAdmissionEntitlementOwner owner = + mock(AccountPlayerAdmissionEntitlementOwner.class); + private final AccountPlayerAdmissionEntitlementGrpcService service; + + @SuppressWarnings("unchecked") + private final StreamObserver observer = + mock(StreamObserver.class); + + private AuthenticatedFixture() { + guards = + mockConstruction( + AccountPlayerAdmissionEntitlementWorkloadGuard.class, + (guard, context) -> + when(guard.requireAuthenticatedGameSessionCaller()).thenReturn(PEER)); + service = new AccountPlayerAdmissionEntitlementGrpcService(owner, "prod"); + } + + @Override + public void close() { + guards.close(); + } + } } From 57eec1ebb152582bf0d722c7792678a4b638b5e7 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 7 Nov 2026 18:25:29 +1300 Subject: [PATCH 15/23] fix(account): classify malformed bootstrap roster actors as source errors --- .../AccountBootstrapRosterReadClient.java | 11 +- ...ountBootstrapRosterReadClientMtlsTest.java | 130 +++++++++++++++++- 2 files changed, 138 insertions(+), 3 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClient.java index 605fa05d04..f65a0db6b1 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClient.java @@ -96,14 +96,21 @@ public List read(UUID requestId, UUID accountId, PublishedRealmEvidence p List actors = new ArrayList<>(response.getActorsCount()); String previous = null; for (var actor : response.getActorsList()) { - UUID id = parseUuid(actor.getCharacterUuid()); if (!actor.getUnknownFields().asMap().isEmpty() || !actor.hasLevel() || (previous != null && previous.compareTo(actor.getCharacterUuid()) >= 0)) { throw new IllegalStateException( "Entity bootstrap discovery actors are duplicated or unordered"); } - actors.add(new Actor(id, actor.getDisplayName(), actor.getLevel())); + Actor decoded; + try { + decoded = + new Actor( + parseUuid(actor.getCharacterUuid()), actor.getDisplayName(), actor.getLevel()); + } catch (IllegalArgumentException invalidActor) { + throw new IllegalStateException("Entity bootstrap discovery actor is malformed"); + } + actors.add(decoded); previous = actor.getCharacterUuid(); } return List.copyOf(actors); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClientMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClientMtlsTest.java index 728fa4a612..4d0801bf57 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClientMtlsTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClientMtlsTest.java @@ -5,6 +5,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.google.protobuf.UnknownFieldSet; import io.grpc.Context; import io.grpc.Server; import io.grpc.ServerInterceptors; @@ -55,6 +56,7 @@ class AccountBootstrapRosterReadClientMtlsTest { private static final UUID INSTANCE = UUID.fromString("55555555-5555-4555-8555-555555555555"); private static final UUID VERSION = UUID.fromString("66666666-6666-4666-8666-666666666666"); private static final UUID ACTOR = UUID.fromString("77777777-7777-4777-8777-777777777777"); + private static final UUID SECOND_ACTOR = UUID.fromString("88888888-8888-4888-8888-888888888888"); @TempDir static Path directory; private static LoopbackMtlsTestPki.Pki pki; @@ -87,6 +89,7 @@ void exactEntityPeerPreservesRequestNamespaceAndActualLevelIncludingZero() throw AccountBootstrapRosterReadResponse.newBuilder() .setRequest(request) .addActors(actor().setLevel(0)) + .addActors(actor().setCharacterUuid(SECOND_ACTOR.toString()).setLevel(4)) .build(); try (var server = server("entity", service); var client = client(server.port())) { @@ -94,7 +97,9 @@ void exactEntityPeerPreservesRequestNamespaceAndActualLevelIncludingZero() throw UUID requestId = UUID.randomUUID(); var actors = client.read(requestId, ACCOUNT, published()); assertThat(actors) - .containsExactly(new AccountBootstrapRosterReadClient.Actor(ACTOR, "Mara", 0)); + .containsExactly( + new AccountBootstrapRosterReadClient.Actor(ACTOR, "Mara", 0), + new AccountBootstrapRosterReadClient.Actor(SECOND_ACTOR, "Mara", 4)); assertThat(service.request.get().getRequestUuid()).isEqualTo(requestId.toString()); assertThat(service.request.get().getCanonicalAccountUuid()).isEqualTo(ACCOUNT.toString()); assertThat(service.request.get().getExpectedTarget().getPlayableStateNamespaceUuid()) @@ -170,6 +175,129 @@ void mismatchedDuplicateAndMissingLevelResponsesNeverBecomeAnEmptySuccess() thro } } + @Test + void malformedActorFieldsRemainBoundedSourceFailures() throws Exception { + var invalidActors = + List.of( + actor().setLevel(1).setCharacterUuid("source-payload-not-a-uuid").build(), + actor().setLevel(1).clearCharacterUuid().build(), + actor().setLevel(1).setCharacterUuid(new UUID(0L, 0L).toString()).build(), + actor().setLevel(1).clearDisplayName().build(), + actor().setLevel(1).setDisplayName(" ").build(), + actor().setLevel(1).setDisplayName(" Mara").build(), + actor().setLevel(1).setDisplayName("Mara ").build(), + actor().setLevel(1).setDisplayName("M".repeat(101)).build(), + actor().setLevel(1).setDisplayName("Mara\u0007").build(), + actor().setLevel(-1).build()); + Probe service = new Probe(); + try (var server = server("entity", service); + var client = client(server.port())) { + client.init(); + for (var invalid : invalidActors) { + service.respond = + request -> + AccountBootstrapRosterReadResponse.newBuilder() + .setRequest(request) + .addActors(invalid) + .build(); + assertThatThrownBy(() -> client.read(UUID.randomUUID(), ACCOUNT, published())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Entity bootstrap discovery actor is malformed") + .hasNoCause(); + } + assertThat(service.calls.get()).isEqualTo(invalidActors.size()); + } + } + + @Test + void actorShapeAndOrderingAreCheckedBeforeSourceUuidParsing() throws Exception { + var unknownFields = + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + var invalidActorLists = + List.of( + List.of(actor().setCharacterUuid("source-payload-not-a-uuid").build()), + List.of(actor().setLevel(1).setUnknownFields(unknownFields).build()), + List.of( + actor() + .setLevel(1) + .setCharacterUuid("source-payload-not-a-uuid") + .setUnknownFields(unknownFields) + .build()), + List.of(actor().setLevel(1).build(), actor().setLevel(1).build()), + List.of( + actor().setLevel(1).setCharacterUuid(SECOND_ACTOR.toString()).build(), + actor().setLevel(1).build()), + List.of( + actor().setLevel(1).build(), + actor().setLevel(1).setCharacterUuid("0-source-payload-not-a-uuid").build())); + Probe service = new Probe(); + try (var server = server("entity", service); + var client = client(server.port())) { + client.init(); + for (var invalid : invalidActorLists) { + service.respond = + request -> + AccountBootstrapRosterReadResponse.newBuilder() + .setRequest(request) + .addAllActors(invalid) + .build(); + assertThatThrownBy(() -> client.read(UUID.randomUUID(), ACCOUNT, published())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Entity bootstrap discovery actors are duplicated or unordered") + .hasNoCause(); + } + assertThat(service.calls.get()).isEqualTo(invalidActorLists.size()); + } + } + + @Test + void noncanonicalActorUuidRemainsASourceFailure() throws Exception { + Probe service = new Probe(); + try (var server = server("entity", service); + var client = client(server.port())) { + client.init(); + for (String noncanonical : List.of("AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA", "7-7-4-8-7")) { + service.respond = + request -> + AccountBootstrapRosterReadResponse.newBuilder() + .setRequest(request) + .addActors(actor().setCharacterUuid(noncanonical).setLevel(1)) + .build(); + assertThatThrownBy(() -> client.read(UUID.randomUUID(), ACCOUNT, published())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Canonical actor UUID required") + .hasNoCause(); + } + assertThat(service.calls.get()).isEqualTo(2); + } + } + + @Test + void callerInputFailuresRemainArgumentErrorsBeforeTheEntityRead() throws Exception { + Probe service = new Probe(); + try (var server = server("entity", service); + var client = client(server.port())) { + client.init(); + for (UUID invalid : new UUID[] {null, new UUID(0L, 0L)}) { + assertThatThrownBy(() -> client.read(invalid, ACCOUNT, published())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> client.read(UUID.randomUUID(), invalid, published())) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy(() -> client.read(UUID.randomUUID(), TENANT, published())) + .isInstanceOf(IllegalArgumentException.class); + var unsupported = published(); + when(unsupported.currentTarget().playableStateScope()).thenReturn("ISOLATED"); + assertThatThrownBy(() -> client.read(UUID.randomUUID(), ACCOUNT, unsupported)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new AccountBootstrapRosterReadClient.Actor(ACTOR, " ", 1)) + .isInstanceOf(IllegalArgumentException.class); + assertThat(service.calls.get()).isZero(); + } + } + @Test void ambientSqlRefusesBeforeTheEntityRead() throws Exception { Probe service = new Probe(); From ab249aa4f93929fbdf2ccc8bc7c8aa3cacc2d70c Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 7 Nov 2026 19:18:08 +1300 Subject: [PATCH 16/23] fix(account): close entitlement and roster review findings Clarify the private entitlement contract and receipt-owned dispatch permission, reject nullable roster levels, preserve exact cross-host expiry, and strengthen owner-shaped proofs. Move six complete source-owner paths into the foundation. --- .../account-service/api-contracts.md | 12 +- .../api-contracts.md | 8 + .../runtime-and-data.md | 6 + .../gameplay-rules-entities-and-effects.md | 6 + ...ostingSubscriptionLifecycleRepository.java | 8 +- ...emoWorldsOwnerPostgresIntegrationTest.java | 161 +++++++++++++++++- .../repository/CharacterRepository.java | 26 +-- ...haracterRepositoryBootstrapRosterTest.java | 127 ++++++++++++++ ...countPlayerAdmissionEntitlementClient.java | 6 +- ...alGameplayTenantGameplayTagRepository.java | 4 + ...ssionBarrierRepositoryIntegrationTest.java | 89 +++++++--- ...yerAdmissionEntitlementClientMtlsTest.java | 66 +++++++ ...antOperationEntitlementClientMtlsTest.java | 13 +- 13 files changed, 488 insertions(+), 44 deletions(-) create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/CharacterRepositoryBootstrapRosterTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index bd0a587ab9..e240d5d39a 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -127,7 +127,7 @@ Fresh-enrollment certification is internal Account owner work, not a public regi The public bootstrap WORLDS source is prepared as an unregistered Account owner and is not yet wired into the existing `ListBootstrapWorlds` facade. Its current schema-backed source is the canonical Account DEMO entitlement; paid-hosting discovery remains unavailable until the subscription schema and retained facade consumers migrate together. Current source and proof status are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#public-bootstrap-worlds-source-preparation). -Additional unregistered source prepares separate World Management `TENANT_OPERATION` and Game Session [player-admission entitlement reads](#private-player-admission-entitlement-read), held hosting provisioning and terminal-resolution owners, a signed canonical V2 scope reader, and an Account client for Entity-owned persisted bootstrap-roster discovery. These sources do not replace the existing public discovery/JOIN facade or runtime entitlement RPC, register a receiver, or enable player admission. The scope reader verifies an existing selector rather than authenticating its caller; the roster read supplies transient persisted discovery rather than a selection, actor allocation, session, or admission result. Exact source boundaries and pending proof are recorded in [local source-foundation preparation](../../../project-management/implementation-tracking/player-access-and-session.md#local-source-foundation-preparation). +Additional unregistered source prepares separate World Management [`TENANT_OPERATION` entitlement reads](#private-tenant-operation-entitlement-read) and Game Session [player-admission entitlement reads](#private-player-admission-entitlement-read), held hosting provisioning and terminal-resolution owners, a signed canonical V2 scope reader, and an Account client for Entity-owned persisted bootstrap-roster discovery. These sources do not replace the existing public discovery/JOIN facade or runtime entitlement RPC, register a receiver, or enable player admission. The scope reader verifies an existing selector rather than authenticating its caller; the roster read supplies transient persisted discovery rather than a selection, actor allocation, session, or admission result. Exact source boundaries and pending proof are recorded in [local source-foundation preparation](../../../project-management/implementation-tracking/player-access-and-session.md#local-source-foundation-preparation). The opaque `bootstrap-connect-scope` artifact uses canonical non-nil Account UUID subject/claim equality. Both browser discovery and the existing direct-text Account producer obtain that identity from Account persistence; the dedicated reader resolves it back to Account-local storage before existing binding checks. Numeric scopes have no compatibility parser: clients obtain fresh scope evidence through bounded rediscovery, while retained rows/receipts are not rewritten and existing retained-replay guards remain. Caller authentication, public-join policy and the held connect-token issuer are unchanged. Detailed receiving proof belongs to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#bootstrap-connect-scope-uuid-artifact). @@ -247,11 +247,19 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - `AddCurrency` – deferred virtual-currency substrate; unavailable as a supported v1 monetization API and not entitlement authority. - `SpendCurrency` – deferred virtual-currency substrate; unavailable as a supported v1 monetization API and not entitlement authority. +### Private tenant-operation entitlement read + +`AccountTenantOperationEntitlementReadService/ReadTenantOperationEntitlement` is a distinct private `TENANT_OPERATION` evidence read defined by the [purpose-specific protobuf](../../../../protos/account/v1/tenant_operation_entitlement_read.proto). Only the exact same-namespace World Management workload may call it over mTLS; method authorization precedes request decoding, and bearer tokens, ambient caller context and caller-supplied workload values cannot replace transport identity. Account derives the evidence's `callerWorkload` from the authenticated peer, never request data. + +The request carries schema version 1, `targetNamespace` matching Account's configured workload namespace, canonical non-nil `tenantId` and `requestId` UUIDs, and an explicit `sourceKind` of exactly `PAID_HOSTING` or `NON_PAID_DEMO`. There is no default, inference or fallback between sources. The paid branch requires a fresh current Account hosting receipt for the exact tenant and matching current tenant-authority evidence; the DEMO branch reads Account's canonical current DEMO entitlement. Account captures complete entitlement facts, tenant-authority/billing-cutoff evidence and outbox checkpoints in the selected owner source transaction. Missing, stale, mismatched or unavailable selected-source authority supplies no success evidence. The response echoes the exact request and carries strict canonical evidence bound to its tenant, request, source kind and authenticated World workload. Repeated transport members each require exactly one value, and unknown fields fail closed. The [closed codec](../../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementGrpcCodec.java) owns the 1 KiB request bound, response wire allowance of 64 KiB + 1 KiB + 32 bytes, five-second deadline and exact response comparisons; the [evidence codec](../../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementEvidence.java) owns the 64 KiB canonical content bound. + +This held source preparation supplies point-in-time eligibility evidence, not capacity commitment, durable evaluation replay, player admission or runtime activation. The receiver and World client remain manually composed and unregistered, and the owner of a later lifecycle action must enforce currentness at use. Source dependencies and proof limits belong to the [local source-foundation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#local-source-foundation-preparation). + ### Private player-admission entitlement read `AccountPlayerAdmissionEntitlementReadService/ReadPlayerAdmissionEntitlement` is a distinct private `PLAYER_ADMISSION` evidence read defined by the [purpose-specific protobuf](../../../../protos/account/v1/player_admission_entitlement_read.proto). Only the exact same-namespace Game Session workload may call it over mTLS; method authorization precedes request decoding, and ambient bearer or caller-supplied workload context cannot replace transport identity. The request carries schema version 1, the complete retained canonical target selector, Account-issued connect scope and explicit initial `game-session-account-delegation` credential. Repeated transport members each require exactly one value, and unknown fields fail closed. The credential is disclosed only to the verified Account peer on this method and must never be logged or persisted as request evidence. -Account verifies the credential subject and current committed issuance, retained scope, current membership including explicit absence, and Account-selected paid-or-DEMO source. Callers cannot select a source family or convert missing paid authority into DEMO. The response echoes only the closed selectors and carries exact canonical `PLAYER_ADMISSION` evidence, never the credential. The [closed codec](../../../../services/common-security/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodec.java) owns wire bounds, the call deadline and exact response comparisons; the [evidence codec](../../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java) owns the canonical content. `scopeDigest` preserves the retained V2 `sha256:`-prefixed digest, distinct from raw-hex token/registry hashes. Unavailable, changed or expired authority produces no positive or empty-success evidence. +Account verifies the credential subject and current committed issuance, retained scope, current membership including explicit absence, and Account-selected paid-or-DEMO source. Callers cannot select a source family or convert missing paid authority into DEMO. The response echoes only the closed selectors and carries exact canonical `PLAYER_ADMISSION` evidence, never the credential. The [closed codec](../../../../services/common-security/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodec.java) owns wire bounds, the call deadline and exact response comparisons; the [evidence codec](../../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java) owns the canonical content. `scopeDigest` preserves the retained V2 `sha256:`-prefixed digest, distinct from raw-hex token/registry hashes. Unavailable, changed or expired authority produces no positive or empty-success evidence. Account validates `evaluatedAt` against its own source and scope ordering. The receiving Game Session clock independently requires `now < validUntil`; it does not treat Account's evaluation timestamp as a cross-host not-before bound. No numerical skew allowance or expiry extension is applied. This read supports only public-production `SHARED`/`PRESEEDED_ONLY` targets. Broader WORLDS discovery does not widen that restriction. It supplies point-in-time evidence, not membership repair, actor selection, capacity commitment, a World hold through Account commit or later admission, or gameplay admission. The receiver and Game Session client remain manually composed and unregistered; genuine scope/LOGIN custody, runtime integration and proof limits belong to the [player-admission source tracker](../../../project-management/implementation-tracking/player-access-and-session.md#player-admission-entitlement-source-preparation). diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 5dd85c3b74..ec2afba336 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -291,3 +291,11 @@ The current contract still leaves player command orchestration, authored stat/co - **Live:** The seeded `firemud.look.rooms` entries provide the visible entities for the demo rooms, `ListRoomEntities` is wired into Game Logic's `ResolveLook`, and the resulting instrumentation is captured in [`look-instrumentation.md`](../../../project-management/slice-support/look-instrumentation.md). - **Stubbed:** Real-time behaviors such as item respawns, stealth/aura-driven visibility, and inventory states still rely on static fixtures so regression tests remain reproducible. - **Deferred:** Future slices may consume read-only location metadata from the target `character_location` and `npc_location` tables, which are World Management-owned and currently absent; Entity Management is not the location authority and must not create competing tables or fields. Those slices will support multi-instance visibility rules and surface richer context hints (combat alerts, quest markers) while keeping the public DTO focused on display data. + +## Account bootstrap persisted actor discovery + +`AccountBootstrapRosterReadService.ReadAccountBootstrapRoster` in [account_bootstrap_roster_read.proto](../../../../protos/entity-management/v1/account_bootstrap_roster_read.proto) is a distinct manually composed, unregistered, non-admitting Account discovery boundary. Its purpose-specific certificate interceptor authenticates only the exact same-workload-namespace `account-service` mTLS peer before message decoding. Missing identity is `UNAUTHENTICATED`; another workload/namespace, ambient caller/role or internal-service context, and a request namespace differing from the configured workload namespace are `PERMISSION_DENIED`. The existing canonical roster methods remain Game Session-only and unchanged; ordinary `ListCharactersByAccount` is not a substitute. + +The closed request contains canonical non-nil request and Account UUIDs, the configured workload namespace and the complete existing `CanonicalGameplayRosterTarget`, including every source digest, release reference and positive owner counter. It carries no bootstrap credential, `PlayerExecutionContext`, Game Session session, original selection or retained roster reference. The request bound is 4 KiB; unknown fields, noncanonical UUIDs and incomplete targets are invalid. The response echoes the exact entire request and contains at most 100 unique actors ordered by canonical UUID text within 64 KiB. Each actor has its persisted UUID, trimmed control-free display name of at most 100 Unicode code points, and explicit nonnegative `level` sourced from the same eligible `characters` row. The optional wire field must be present even when the actual persisted level is zero; absence is never normalized to zero. + +Entity independently reads the complete current Game Session, sealed publication and World target through its existing Entity-only `GetCanonicalGameplayRosterOwnerRead` client and codec before querying persisted rows, compares the exact reconstructed target with the caller's expected target, and rereads that owner target after the short local projection transaction. Only current visible public-production `SHARED` / `PRESEEDED_ONLY` is supported. A valid supported target may return zero eligible actors; unsupported private, isolated, `PLAYER_CREATED` and `AUTO_PROVISIONED` paths remain explicit obligations and cannot return a fabricated empty success. Malformed input is `INVALID_ARGUMENT`, unsupported or changed preconditions are `FAILED_PRECONDITION`, and unavailable owner or storage reads are `UNAVAILABLE`; failures return no partial projection. This read allocates no actor, selection, snapshot, admission nonce or retention reference and supplies no admission authority or distributed source hold. See [runtime/data limitations](./runtime-and-data.md#account-bootstrap-transient-projection) and the [proof tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#account-bootstrap-persisted-discovery). diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index 3ef2440b85..9fb8f7cfce 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -554,3 +554,9 @@ If you change Redis usage for this service, you must read and apply: - [Redis Cache & Rate Limiting](../../system-architecture-redis-cache.md) - [FireMUD Redis Lua Patterns](../../system-architecture-redis-lua-patterns.md) - [Redis Operations & Migrations](../../system-architecture-redis-operations.md) + +### Account bootstrap transient projection + +The [Account bootstrap read](./api-contracts.md#account-bootstrap-persisted-actor-discovery) uses one independent five-second read-only repeatable-read owner transaction between two independently authenticated current-target reads. It refuses ambient SQL transactions or synchronization before source access. Both source RPCs run outside SQL; the transaction selects only the exact Account UUID, tenant UUID, playable-state namespace and scope with `OWNER_RESOLVED` identity and no quarantine reason. UUID, name and the existing Entity-owned `characters.level` come from the same selected row; this projection does not introduce mandatory authored RPG state. A missing local namespace enrollment may yield a valid empty roster only after the complete supported current owner target is independently established; the read never inserts enrollment. An existing contradictory enrollment refuses. + +This transient projection shares the canonical actor predicates and bounded UUID ordering with sealed roster reads, while creating no sealed payload or receipt. The post-projection current-target read detects source movement across the local read; it does not hold remote sources or protect a later selection, token issuance or gameplay commit. Account remains responsible for its caller eligibility and future admission revalidation. Current preseeded assignment storage permits one owner-resolved actor per account/tenant/namespace; the read does not widen that write invariant. The finite wire list preserves deterministic handling for any future supported multiple-actor writer. Private, player-created, auto-provisioned and isolated discovery remain unsupported by this local branch, and their target-state obligations remain under [persisted actor and realm-entry identity](#persisted-actor-and-realm-entry-identity). Source and proof status is in the [implementation tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#account-bootstrap-persisted-discovery). diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index 6b8e888f4c..355b387de8 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -312,3 +312,9 @@ The focused [Ordinary Account UUID copy-carrier test](../../../services/entity-m | Social Groups | Durable communication mutation persistence and duplicate-delivery convergence | Communication persistence and fanout contracts | | Account and Common Security | Account identity, caller scope, gameplay attestation, and authorization inputs | Auth/session and gameplay-attestation helpers | | Automation Scripting | Future effect-producing automation; it is not the authority for item, actor, or communication mutation | Script/event handoff contracts | + +### Account bootstrap persisted discovery + +The manually composed, unregistered Account bootstrap discovery source now has a distinct purpose proto, exact Account workload guard, current-source adapter overload without a fabricated Game Session session, and a read-only persisted projection. It rereads the complete actual Game Session owner target before and after local SQL and preserves actual same-row UUID/name/level. Its contract and currentness limits are owned by [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#account-bootstrap-persisted-actor-discovery) and [runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md#account-bootstrap-transient-projection). + +Focused unit and combined PostgreSQL/socket-mTLS test sources cover real typed client/codec/adapter composition, actual Entity/Saga migrations and assignment writer, persisted zero/one actor reads, same-row nonzero and zero levels, account/namespace isolation, quarantine exclusion, unchanged actor/selection/snapshot/retention storage, workload/context refusal, closure/bounds, unsupported scope/policy, unavailable source and source-digest drift across SQL. Upstream Game Session/World/publication bytes and assignment eligibility remain controlled fixtures rather than executed upstream owner stores or production custody. Existing preseeded writer uniqueness prevents a physical many-actor fixture; bounded ordered multiple-response validation is unit source coverage only. Preserved source proof309 passes eight focused units and three combined PostgreSQL/socket-mTLS cases. Actual public receiving compilation342 now passes; focused receiving execution and documentation checks remain pending. These executions retain their source attribution and do not establish a complete upstream chain. This source addition does not qualify production registration, Account consumer settlement, private/player-created/auto-provisioned discovery, admission or activation. 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 ae02b181a4..8733895de8 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 @@ -1666,7 +1666,9 @@ public enum Disposition { public record ClaimResult(Disposition disposition, ProvisioningClaim claim) {} /** - * Private construction prevents mistaking caller-supplied status/version booleans for a claim. + * Private construction prevents mistaking caller-supplied status/version booleans for a claim. A + * claim's attempt number never grants or denies provider creation. Only an independently read + * ProviderDispatch carries initial-call permission from the retained first-dispatch receipt. */ public static final class ProvisioningClaim { private final AccountSubscriptionCreationRecord creation; @@ -1714,10 +1716,6 @@ public Instant claimedAt() { public Instant expiresAt() { return expiresAt; } - - public boolean reconciliationRequiredBeforeCreate() { - return attemptNumber > 1; - } } /** Frozen into durable work on its first claim; later configuration cannot widen its budget. */ diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java index 5422151555..c17b6a2360 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java @@ -10,6 +10,7 @@ import static org.mockito.Mockito.when; import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import java.sql.Connection; import java.sql.SQLException; import java.sql.Timestamp; import java.time.Clock; @@ -22,6 +23,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Properties; import java.util.Set; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; @@ -32,6 +34,7 @@ import net.firedevops.firemud.accountservice.config.AccountTokenProperties; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.BootstrapWorldDto; +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; @@ -85,9 +88,11 @@ * Bootstrap JWT signing uses a local test key and the actual caller verifier/persisted Account; the * active-session registry and complete Game Session collection are controlled inputs. Fresh Game * Design evidence is imported as a fixture, not obtained from an authenticated owner call. The - * canonical public-scope cases additionally use real membership/pair and V2 scope persistence. This - * proves neither paid hosting, issuer custody, workload provenance, a World hold, private support - * nor gameplay admission; a retained selector is not PLAYER entitlement or JOIN permission. + * canonical public-scope cases additionally use real membership/pair, V2 scope persistence and + * retained-selector reads. Expected reader Account UUIDs are comparison inputs from this fixture, + * not caller authentication performed by the reader. This proves neither paid hosting, issuer + * custody, workload provenance, a World hold, private support nor gameplay admission; a retained + * selector is not PLAYER entitlement or JOIN permission. */ class AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest { private static final String NAMESPACE = "demo-worlds-proof"; @@ -350,6 +355,143 @@ void absentMembershipAndClosedEnrollmentPersistOnlyTheExactCanonicalPublicSelect .get(0, Long.class)) .isEqualTo(1L); f.assertNoMembershipPairJoinOrPaidReads(); + SessionContext.setContext( + f.account.getAccountUuid().toString(), + List.of("player"), + Map.of(tenant.tenantId().toString(), List.of("player"))); + + assertThat(f.scopeReader.read(f.account.getAccountUuid(), scope.connectScopeId())) + .isEqualTo(scope); + assertThat(f.scopeReader.read(f.account.getAccountUuid(), scope.connectScopeId())) + .isEqualTo(scope); + + assertThat(SessionContext.getAccountId()).isEqualTo(f.account.getAccountUuid().toString()); + assertThat(SessionContext.getScopedRoles(tenant.tenantId().toString())) + .containsExactly("player"); + assertThat(f.snapshot()).isEqualTo(after); + assertThat( + f.inTransaction( + () -> f.scopes.findCanonicalEvidenceByTokenHash(tokenHash).orElseThrow())) + .isEqualTo(evidence); + f.assertNoMembershipPairJoinOrPaidReads(); + verify(f.targets, times(2)).listVisiblePublicProductionAdmissionTargets(any()); + } + + @Test + void actualRetainedScopeRefusesAnotherPersistedExpectedAccountWithoutChangingCallerContext() { + Fixture f = fixture(); + CanonicalJoinScopeV2 scope = f.issueScope("scope-wrong-account"); + Account other = new Account(); + other.setUsername("other-scope-reader"); + other.setEmail("other-scope-reader@example.test"); + other.setPasswordHash("controlled-unused-password-verifier"); + other.setRole("player"); + Account expected = f.inTransaction(() -> f.accounts.save(other)); + SessionContext.setContext(expected.getAccountUuid().toString(), List.of("player"), Map.of()); + Map before = f.snapshot(); + + assertCode( + "CONNECT_SCOPE_INVALID", + () -> f.scopeReader.read(expected.getAccountUuid(), scope.connectScopeId())); + + assertThat(SessionContext.getAccountId()).isEqualTo(expected.getAccountUuid().toString()); + assertThat(f.scopeReader.read(f.account.getAccountUuid(), scope.connectScopeId())) + .isEqualTo(scope); + // The UUID argument is comparison data supplied by the outer owner; ambient roles/identity + // are neither accepted as source authority nor cleared to make this read succeed. + assertThat(SessionContext.getAccountId()).isEqualTo(expected.getAccountUuid().toString()); + assertThat(f.snapshot()).isEqualTo(before); + f.assertNoMembershipPairJoinOrPaidReads(); + verify(f.targets, times(2)).listVisiblePublicProductionAdmissionTargets(any()); + } + + @Test + void actualIssuedScopeExpiryRefusesWithoutRestampingItsRetainedSelector() { + Fixture f = fixture(); + CanonicalJoinScopeV2 scope = f.issueScope("scope-reader-expiry"); + Map before = f.snapshot(); + f.clock.offset.set( + Duration.between(f.clock.instant(), Instant.parse(scope.connectScopeExpiresAt())) + .plusSeconds(1)); + + assertCode( + "CONNECT_SCOPE_INVALID", + () -> f.scopeReader.read(f.account.getAccountUuid(), scope.connectScopeId())); + + assertThat(f.snapshot()).isEqualTo(before); + assertThat(f.inTransaction(() -> f.scopes.findCanonical(scope.connectScopeId()).orElseThrow())) + .isEqualTo(scope); + f.assertNoMembershipPairJoinOrPaidReads(); + verify(f.targets, times(2)).listVisiblePublicProductionAdmissionTargets(any()); + } + + @Test + void actualImmutableScopeGuardRejectsEvidenceMutationAndReaderReturnsOriginalPreimage() { + Fixture f = fixture(); + CanonicalJoinScopeV2 scope = f.issueScope("scope-immutable"); + Map before = f.snapshot(); + String tokenHash = AccountJoinDigest.tokenHash(scope.connectScopeId()); + + org.jooq.exception.DataAccessException failure = + org.junit.jupiter.api.Assertions.assertThrows( + org.jooq.exception.DataAccessException.class, + () -> + f.dsl.execute( + "UPDATE account_connect_scope_records SET world_slug = ? WHERE scope_token_hash = ?", + "different-world", + tokenHash)); + + SQLException sql = Objects.requireNonNull(sqlFailure(failure)); + assertThat(sql.getSQLState()).isEqualTo("23514"); + assertThat(sql.getMessage()).contains("Canonical Account connect scope evidence is immutable"); + assertThat(f.scopeReader.read(f.account.getAccountUuid(), scope.connectScopeId())) + .isEqualTo(scope); + assertThat(f.snapshot()).isEqualTo(before); + f.assertNoMembershipPairJoinOrPaidReads(); + } + + @Test + void actualAccountLockTimeoutMakesScopeReadUnavailableAndFreshReadRecoversUnchanged() + throws SQLException { + Fixture f = fixture(); + CanonicalJoinScopeV2 scope = f.issueScope("scope-lock-timeout"); + Map before = f.snapshot(); + // Bound only this fixture DataSource's future physical connections. The reader still uses + // its real DataSourceTransactionManager, writable SERIALIZABLE transaction and repositories. + Properties connectionProperties = new Properties(); + connectionProperties.setProperty("connectTimeout", "10"); + connectionProperties.setProperty("socketTimeout", "60"); + connectionProperties.setProperty("options", "-c lock_timeout=150ms"); + f.dataSource.setConnectionProperties(connectionProperties); + try (Connection holder = f.dataSource.getConnection()) { + holder.setAutoCommit(false); + try { + try (var statement = + holder.prepareStatement("SELECT id FROM accounts WHERE account_uuid = ? FOR UPDATE")) { + statement.setObject(1, f.account.getAccountUuid()); + try (var locked = statement.executeQuery()) { + assertThat(locked.next()).isTrue(); + } + } + + AuthenticationException failure = + org.junit.jupiter.api.Assertions.assertThrows( + AuthenticationException.class, + () -> f.scopeReader.read(f.account.getAccountUuid(), scope.connectScopeId())); + + assertThat(failure.getCode()).isEqualTo("AUTH_UNAVAILABLE"); + SQLException sql = Objects.requireNonNull(sqlFailure(failure)); + assertThat(sql.getSQLState()).isEqualTo("55P03"); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + } finally { + holder.rollback(); + } + } + + assertThat(f.scopeReader.read(f.account.getAccountUuid(), scope.connectScopeId())) + .isEqualTo(scope); + assertThat(f.snapshot()).isEqualTo(before); + f.assertNoMembershipPairJoinOrPaidReads(); verify(f.targets, times(2)).listVisiblePublicProductionAdmissionTargets(any()); } @@ -449,6 +591,7 @@ private static void assertCode(String code, Runnable operation) { } private static final class Fixture { + private final DriverManagerDataSource dataSource; private final DSLContext dsl; private final TransactionTemplate transaction; private final AccountRepository accounts; @@ -469,11 +612,13 @@ private static final class Fixture { private final String token; private final AccountPublicBootstrapWorldsOwner worlds; private final AccountCanonicalPublicRealmScopeOwner realmScopes; + private final AccountCanonicalConnectScopeReader scopeReader; private final AtomicInteger targetReadCount = new AtomicInteger(); private long sourceRowId; private Runnable onSecondTargetRead = () -> {}; private Fixture(DriverManagerDataSource dataSource) { + this.dataSource = dataSource; dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); var transactions = new DataSourceTransactionManager(dataSource); transaction = new TransactionTemplate(transactions); @@ -520,6 +665,7 @@ private Fixture(DriverManagerDataSource dataSource) { dsl, new LegacyTenantSourceEvidence(dsl), NAMESPACE), NAMESPACE); scopes = new AccountConnectScopeRepository(dsl, retainedIdentities, tenants); + scopeReader = new AccountCanonicalConnectScopeReader(jwt, scopes, transactions, clock); var tokenProperties = new AccountTokenProperties(); tokenProperties.setConnectScopeExpirationMs(120000L); realmScopes = @@ -573,6 +719,15 @@ private FreshTenantCreationEvidence enrollTenant() { }); } + private CanonicalJoinScopeV2 issueScope(String worldSlug) { + DemoTenant tenant = demo(worldSlug, true); + targetReads(List.of(tenant.target()), List.of(tenant.target())); + return realmScopes + .listRealmScopes(token, tenant.target().tenantSlug(), tenant.target().worldSlug()) + .getFirst() + .scope(); + } + private DemoTenant demo(String worldSlug, boolean available) { FreshTenantCreationEvidence source = enrollTenant(); DemoTenantEntitlementSnapshot snapshot = diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java index 72feec9c3b..7cc00fe148 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java @@ -1255,19 +1255,25 @@ private void lockCanonicalRosterNamespace(CanonicalGameplayRosterTarget target) if (enrolledScope != null && !target.playableStateScope().name().equals(enrolledScope)) { throw new IllegalStateException("CANONICAL_GAMEPLAY_ROSTER_NAMESPACE_SCOPE_MISMATCH"); } - var rows = - canonicalRosterQuery(canonicalAccountUuid, target) - .fetch( - row -> - new net.firedevops.firemud.entitymanagement.bootstrap - .AccountBootstrapRosterActorProjection( - row.get(CHARACTERS.CHARACTER_UUID), - row.get(CHARACTERS.NAME), - row.get(CHARACTERS.LEVEL))); + var rows = canonicalRosterQuery(canonicalAccountUuid, target).fetch(); if (rows.size() > CanonicalGameplayRosterSnapshotDigest.MAX_ROSTER_SIZE) { throw new IllegalStateException("CANONICAL_GAMEPLAY_ROSTER_LIMIT_EXCEEDED"); } - return rows; + var actors = + new ArrayList< + net.firedevops.firemud.entitymanagement.bootstrap + .AccountBootstrapRosterActorProjection>(rows.size()); + for (var row : rows) { + Integer level = row.get(CHARACTERS.LEVEL); + if (level == null) { + throw new IllegalStateException("CANONICAL_ROSTER_LEVEL_NULL"); + } + actors.add( + new net.firedevops.firemud.entitymanagement.bootstrap + .AccountBootstrapRosterActorProjection( + row.get(CHARACTERS.CHARACTER_UUID), row.get(CHARACTERS.NAME), level)); + } + return actors; } private List readCurrentCanonicalRoster( diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/CharacterRepositoryBootstrapRosterTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/CharacterRepositoryBootstrapRosterTest.java new file mode 100644 index 0000000000..7cf31c7442 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/CharacterRepositoryBootstrapRosterTest.java @@ -0,0 +1,127 @@ +package unit.net.firedevops.firemud.entitymanagement.repository; + +import static net.firedevops.firemud.entitymanagement.jooq.Tables.CHARACTERS; +import static net.firedevops.firemud.entitymanagement.jooq.Tables.ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.bootstrap.AccountBootstrapRosterActorProjection; +import net.firedevops.firemud.entitymanagement.bootstrap.AccountBootstrapRosterFixture; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterTarget; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.jooq.tools.jdbc.MockConnection; +import org.jooq.tools.jdbc.MockDataProvider; +import org.jooq.tools.jdbc.MockResult; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Controlled SQL-result mapping only; this does not execute a writer or PostgreSQL/mTLS. */ +class CharacterRepositoryBootstrapRosterTest { + @Test + void nullableStoredLevelRefusesTheEntireProjectionWithBoundedPrecondition() throws Exception { + var source = AccountBootstrapRosterFixture.create(); + var fixture = + new SqlRows( + source, + new ActorRow(UUID.fromString("11111111-1111-4111-8111-111111111111"), "Valid", 7), + new ActorRow(UUID.fromString("22222222-2222-4222-8222-222222222222"), "Missing", null)); + + assertThatThrownBy(fixture::read) + .isExactlyInstanceOf(IllegalStateException.class) + .hasMessage("CANONICAL_ROSTER_LEVEL_NULL"); + assertThat(fixture.queries).hasSize(2); + } + + @Test + void actualZeroAndNonzeroLevelsPreserveTheirSameRowUuidAndName() throws Exception { + var source = AccountBootstrapRosterFixture.create(); + UUID zeroActor = UUID.fromString("11111111-1111-4111-8111-111111111111"); + UUID nonzeroActor = UUID.fromString("22222222-2222-4222-8222-222222222222"); + var fixture = + new SqlRows( + source, + new ActorRow(zeroActor, "Zero Level", 0), + new ActorRow(nonzeroActor, "Nonzero Level", 7)); + + assertThat(fixture.read()) + .containsExactly( + new AccountBootstrapRosterActorProjection(zeroActor, "Zero Level", 0), + new AccountBootstrapRosterActorProjection(nonzeroActor, "Nonzero Level", 7)); + assertThat(fixture.queries).hasSize(2); + } + + @Test + void missingOwnerTransactionRefusesBeforeSql() throws Exception { + var fixture = new SqlRows(AccountBootstrapRosterFixture.create()); + + assertThatThrownBy( + () -> fixture.repository.readAccountBootstrapRoster(fixture.account, fixture.target)) + .isExactlyInstanceOf(IllegalStateException.class) + .hasMessage("Account bootstrap discovery requires owner transaction"); + assertThat(fixture.queries).isEmpty(); + } + + private record ActorRow(UUID characterUuid, String displayName, Integer level) {} + + private static final class SqlRows { + final UUID account; + final CanonicalGameplayRosterTarget target; + final CharacterRepository repository; + final List queries = new ArrayList<>(); + + SqlRows(AccountBootstrapRosterFixture.Fixture source, ActorRow... actors) { + account = UUID.fromString(source.request().getCanonicalAccountUuid()); + target = source.target(); + var resultDsl = DSL.using(SQLDialect.POSTGRES); + MockDataProvider provider = + context -> { + String sql = context.sql().toLowerCase(Locale.ROOT); + queries.add(sql); + assertThat(sql).startsWith("select "); + if (sql.contains("entity_playable_state_namespace_scopes")) { + assertThat(context.bindings()) + .containsExactly(target.tenantUuid(), target.playableStateNamespaceId()); + var field = ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_SCOPE; + var rows = resultDsl.newResult(field); + rows.add(resultDsl.newRecord(field).values(target.playableStateScope().name())); + return new MockResult[] {new MockResult(rows.size(), rows)}; + } + assertThat(sql).contains("characters"); + assertThat(context.bindings()) + .contains( + account, + target.tenantUuid(), + target.playableStateNamespaceId(), + target.playableStateScope().name(), + "OWNER_RESOLVED"); + var rows = + resultDsl.newResult(CHARACTERS.CHARACTER_UUID, CHARACTERS.NAME, CHARACTERS.LEVEL); + for (var actor : actors) { + rows.add( + resultDsl + .newRecord(CHARACTERS.CHARACTER_UUID, CHARACTERS.NAME, CHARACTERS.LEVEL) + .values(actor.characterUuid(), actor.displayName(), actor.level())); + } + return new MockResult[] {new MockResult(rows.size(), rows)}; + }; + repository = + new CharacterRepository(DSL.using(new MockConnection(provider), SQLDialect.POSTGRES)); + } + + List read() { + boolean active = TransactionSynchronizationManager.isActualTransactionActive(); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + return repository.readAccountBootstrapRoster(account, target); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(active); + } + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClient.java index 7d88cf4ae2..ec976cdadb 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClient.java @@ -187,7 +187,11 @@ private RuntimePlayerAdmissionEntitlementEvidence read( requireLoginBinding(evidence, login); requireCurrent(loginCustodyCurrent, requireScopeCurrent); requireLiveLogin(loginCustody, request.target().accountId()); - evidence.requireCurrentAt(clock.instant()); + // Account owns evaluatedAt ordering; an independent receiver clock cannot make it a + // not-before bound. Preserve the exact expiry without any skew allowance or extension. + if (!clock.instant().isBefore(evidence.validUntil())) { + throw failure(Status.Code.DEADLINE_EXCEEDED); + } return evidence; } catch (StatusRuntimeException transport) { throw failure(transport.getStatus().getCode()); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java index 5e982717e8..a2f8a8312a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java @@ -48,6 +48,9 @@ public Assignment assignmentForTransition(UUID transitionId) { return dsl.transactionResult( configuration -> { DSLContext transaction = DSL.using(configuration); + // Issuer barrier claims take this clock before locking the mapping and source rows. + // Keep the same order so a retained claim cannot deadlock with tag resolution. + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); BindingTarget source = loadBindingTarget(transaction, transitionId); requireTenantClaim(transaction, source.tenantId()); return resolveMapping( @@ -242,6 +245,7 @@ Assignment assignmentForTransitionWithCandidate( return dsl.transactionResult( configuration -> { DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); BindingTarget source = loadBindingTarget(transaction, transitionId); requireTenantClaim(transaction, source.tenantId()); return resolveMapping(transaction, source, candidateVersion, candidateTag); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java index 9396137ad6..b133218bff 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java @@ -46,8 +46,11 @@ import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; +import org.jooq.ExecuteContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; +import org.jooq.impl.DefaultExecuteListener; +import org.jooq.impl.DefaultExecuteListenerProvider; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -230,36 +233,78 @@ void concurrentClaimsOfRetainedPreparedReadsHaveOnlyOneFirstCreateWinner() throw UUID operationId = state.fixture().originalOperationId(); var first = state.repository().readPreparedInitializer(operationId); var second = state.repository().readPreparedInitializer(operationId); - CountDownLatch start = new CountDownLatch(1); + assertThat(first.assignment()).isNotNull(); + assertThat(second.assignment()).isNull(); + CountDownLatch retainedMappingLocked = new CountDownLatch(1); + CountDownLatch assignmentLockAttempted = new CountDownLatch(1); + var retainedClaimListener = + new DefaultExecuteListener() { + @Override + public void executeEnd(ExecuteContext context) { + String sql = context.sql(); + if (sql != null + && sql.contains("FROM game_session_canonical_tenant_gameplay_tag") + && sql.endsWith("FOR SHARE")) { + retainedMappingLocked.countDown(); + try { + if (!assignmentLockAttempted.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Controlled assignment lock attempt timed out"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Controlled claim gate interrupted", interrupted); + } + } + } + }; + var assignmentListener = + new DefaultExecuteListener() { + @Override + public void executeStart(ExecuteContext context) { + String sql = context.sql(); + if (sql != null + && sql.endsWith("FOR UPDATE") + && (sql.contains("FROM game_session_canonical_binding_inventory_clock") + || sql.contains("FROM game_session_canonical_tenant_gameplay_tag"))) { + // With the owner lock order this waits on the clock before taking source locks. + // Without it, this reaches the tag only after locking transition/inventory, while + // the retained claim owns the tag and still needs the transition: a real deadlock. + assignmentLockAttempted.countDown(); + } + } + }; + DSLContext dsl = state.fixture().dsl(); + var retainedDsl = + DSL.using( + dsl.configuration().derive(new DefaultExecuteListenerProvider(retainedClaimListener))); + var assignmentDsl = + DSL.using( + dsl.configuration().derive(new DefaultExecuteListenerProvider(assignmentListener))); + String namespace = state.fixture().target().targetNamespace(); + var retainedRepository = + new CanonicalGameplayIssuerAdmissionBarrierRepository( + retainedDsl, + new CanonicalGameplayTenantGameplayTagRepository(dsl, namespace, 1), + state.sourceReader()); + var assignmentRepository = + new CanonicalGameplayIssuerAdmissionBarrierRepository( + dsl, + new CanonicalGameplayTenantGameplayTagRepository(assignmentDsl, namespace, 1), + state.sourceReader()); ExecutorService executor = Executors.newFixedThreadPool(2); try { - var firstClaim = - executor.submit( - () -> { - if (!start.await(10, TimeUnit.SECONDS)) { - throw new IllegalStateException("Controlled claim start timed out"); - } - return state.repository().claimFirstCreatePermit(first); - }); - var secondClaim = - executor.submit( - () -> { - if (!start.await(10, TimeUnit.SECONDS)) { - throw new IllegalStateException("Controlled claim start timed out"); - } - return state.repository().claimFirstCreatePermit(second); - }); - start.countDown(); - assertThat( - List.of(firstClaim.get(10, TimeUnit.SECONDS), secondClaim.get(10, TimeUnit.SECONDS))) - .containsExactlyInAnyOrder(true, false); + var secondClaim = executor.submit(() -> retainedRepository.claimFirstCreatePermit(second)); + assertThat(retainedMappingLocked.await(10, TimeUnit.SECONDS)).isTrue(); + var firstClaim = executor.submit(() -> assignmentRepository.claimFirstCreatePermit(first)); + assertThat(secondClaim.get(10, TimeUnit.SECONDS)).isTrue(); + assertThat(firstClaim.get(10, TimeUnit.SECONDS)).isFalse(); assertThat(initializationState(state, operationId)).isEqualTo("INITIALIZING"); assertThatThrownBy(() -> state.owner().initializeAndRead(operationId)) .isInstanceOf(IllegalStateException.class); assertThat(countReceipt(state, operationId)).isZero(); assertThat(administratorCommands.exists(bytes(first.key()))).isZero(); } finally { - start.countDown(); + assignmentLockAttempted.countDown(); executor.shutdownNow(); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java index 6ca0218ecb..dbd573fd92 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java @@ -138,6 +138,68 @@ void exactAccountPeerReceivesCurrentLoginCredentialAndReturnsBoundCanonicalEvide } } + @Test + void independentReceiverClockMayPrecedeAccountEvaluationWithoutExtendingExpiry() + throws Exception { + var context = context(); + var login = loginCustody(); + var calls = new AtomicInteger(); + var observedJwt = new AtomicReference(); + var observedPeer = new AtomicReference(); + Server server = server("account", calls, observedJwt, observedPeer, context, login.evidence()); + Clock receiverClock = Clock.fixed(NOW.minusMillis(25), ZoneOffset.UTC); + try (var client = client(server, receiverClock)) { + client.init(); + var result = client.read(context, READ_REQUEST, login, () -> true); + assertThat(result.evaluatedAt()).isEqualTo(NOW).isAfter(receiverClock.instant()); + assertThat(result.validUntil()) + .isEqualTo(Instant.ofEpochMilli(context.claims().expiresAtMillis())); + assertThat(calls).hasValue(1); + } finally { + stop(server); + } + } + + @ParameterizedTest + @ValueSource(longs = {-1, 0, 1}) + void exactPaidReceiptExpiryHasNoReceiverSkewAllowance(long offsetMillis) throws Exception { + var context = context(); + var login = loginCustody(); + Instant receiptExpiry = NOW.plusSeconds(1); + var calls = new AtomicInteger(); + var observedJwt = new AtomicReference(); + var observedPeer = new AtomicReference(); + Server server = + server( + "account", + calls, + observedJwt, + observedPeer, + context.resolvedTarget(), + Instant.ofEpochMilli(context.claims().expiresAtMillis()), + login.evidence(), + (target, sources) -> sources.put("paidReceiptValidUntil", receiptExpiry.toString()), + () -> {}); + try (var client = + client(server, Clock.fixed(receiptExpiry.plusMillis(offsetMillis), ZoneOffset.UTC))) { + client.init(); + if (offsetMillis < 0) { + assertThat(client.read(context, READ_REQUEST, login, () -> true).validUntil()) + .isEqualTo(receiptExpiry); + } else { + assertThatThrownBy(() -> client.read(context, READ_REQUEST, login, () -> true)) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + } + assertThat(calls).hasValue(1); + } finally { + stop(server); + } + } + @Test void sameCaWrongServiceAndNamespaceReceiveNoRequestCredential() throws Exception { for (String identity : List.of("wrong-service", "wrong-namespace")) { @@ -686,6 +748,10 @@ private static RuntimePlayerAdmissionEntitlementEvidence evidence( sources.put("worldCaptureId", "77777777-7777-4777-8777-777777777777"); sources.put("worldRowVersion", "0"); drift.accept(target, sources); + if (sources.get("paidReceiptValidUntil") != null) { + facts.put("sourceKind", "PAID_HOSTING"); + facts.put("subscriptionStatus", "active"); + } return RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( request.target().readRequestId(), diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClientMtlsTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClientMtlsTest.java index 93d72b6caa..fd88b0d2f2 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClientMtlsTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClientMtlsTest.java @@ -60,7 +60,17 @@ void protectedReceiverDispatchesExplicitSourcesWithAuthenticatedWorkloadAndNoFal paid.tenantId(), paid.requestId(), paid.expectedWorldWorkload())); return evidence(paid); }); - when(owner.evaluateDemo(any())).thenReturn(evidence(demo)); + when(owner.evaluateDemo(any())) + .thenAnswer( + invocation -> { + var actual = + (AccountTenantOperationEntitlementOwner.Request) invocation.getArgument(0); + assertThat(actual) + .isEqualTo( + new AccountTenantOperationEntitlementOwner.Request( + demo.tenantId(), demo.requestId(), demo.expectedWorldWorkload())); + return evidence(demo); + }); var receiver = new AccountTenantOperationEntitlementGrpcService(owner, "firemud"); Server server = receiver @@ -77,6 +87,7 @@ void protectedReceiverDispatchesExplicitSourcesWithAuthenticatedWorkloadAndNoFal assertThat(read.request()).isEqualTo(paid); assertThat(read.evidence()).isEqualTo(evidence(paid)); assertThat(client.read(demo).evidence()).isEqualTo(evidence(demo)); + verify(owner, org.mockito.Mockito.times(1)).evaluatePaid(any()); doThrow( new AccountTenantOperationEntitlementOwner.SourceUnavailableException( "private source detail")) From d6bee09c1d8448815e6e43ac03a1733981694113 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 7 Nov 2026 20:13:15 +1300 Subject: [PATCH 17/23] fix(account): bound admission reads and tighten owner proofs --- .../gameplay-rules-entities-and-effects.md | 10 ++- ...ccountPlayerAdmissionEntitlementOwner.java | 1 + ...mittedLoginCompositionIntegrationTest.java | 39 +++++++--- ...titlementOwnerPostgresIntegrationTest.java | 30 ++++++++ ...ntPlayerAdmissionEntitlementOwnerTest.java | 71 +++++++++++++++++++ 5 files changed, 140 insertions(+), 11 deletions(-) diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index 355b387de8..f4325210a3 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -235,6 +235,12 @@ Current receiving R1128 passes all 32 selected native executions: 22 Entity crea - Inventory query and mutation proof covers hidden implementation-owned inventory containers, room-ground containers, equipment bindings, basic query filtering, successful audited transfers, failed transfers with no committed audit row, and deterministic retry correlation. - Current parcel documentation proof (parcel-scope run confirmed on 2026-08-20 Pacific/Auckland (2026-08-20 UTC)): `./gradlew linkCheck lintMarkdown` passed with 5,324 total links (5,286 OK, 38 excluded, 0 errors) and 480 Markdown files (0 issues); `bash dev-tools/tests/architecture-doc-contracts.sh` passed 184 tests; and `git diff --check` passed. Runtime/smoke proof is not applicable because this parcel changes documentation only. +### Account bootstrap persisted discovery proof + +Focused [Account client](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClientMtlsTest.java), [Entity peer interceptor](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPeerInterceptorTest.java), [Entity read service](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadServiceTest.java), and [persisted repository](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/CharacterRepositoryBootstrapRosterTest.java) tests cover typed client/codec/adapter composition, exact workload/context refusal, closure and bounds, unsupported scope/policy, unavailable source and source-digest drift across SQL. The combined [PostgreSQL/socket-mTLS test source](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPostgresMtlsIntegrationTest.java) additionally covers actual Entity/Saga migrations and assignment writer, persisted zero/one actor reads, same-row nonzero and zero levels, account/namespace isolation, quarantine exclusion and unchanged actor/selection/snapshot/retention storage. Upstream Game Session/World/publication bytes and assignment eligibility remain controlled fixtures rather than executed upstream owner stores or production custody. Existing preseeded writer uniqueness prevents a physical many-actor fixture; bounded ordered multiple-response validation is unit coverage only. This proof does not establish a complete upstream chain, production registration, Account consumer settlement, private/player-created/auto-provisioned discovery, admission or activation. + +On 2026-11-07, the local correction based on source parent `ab249aa4f93929fbdf2ccc8bc7c8aa3cacc2d70c` freshly passed all 20 cases in the four focused suites linked above: nine Account client, three Entity peer-interceptor, five Entity read-service and three Entity repository cases, with zero failures, errors or skips. The gate used `bash dev-tools/validation/run-locked-gradle.sh`, `:account-service:test` and `:entity-management-service:test` with those class-name filters and `--offline -PfullCheck --max-workers=1`. The combined PostgreSQL/socket-mTLS suite was not executed in this local correction because Docker is unavailable; no physical database execution is claimed. + ### Canonical sealed-roster proof history These paragraphs retain their chronological source/checkpoint attribution. Earlier preparation and run results do not replace the current capability summary or qualify later corrections. @@ -315,6 +321,4 @@ The focused [Ordinary Account UUID copy-carrier test](../../../services/entity-m ### Account bootstrap persisted discovery -The manually composed, unregistered Account bootstrap discovery source now has a distinct purpose proto, exact Account workload guard, current-source adapter overload without a fabricated Game Session session, and a read-only persisted projection. It rereads the complete actual Game Session owner target before and after local SQL and preserves actual same-row UUID/name/level. Its contract and currentness limits are owned by [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#account-bootstrap-persisted-actor-discovery) and [runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md#account-bootstrap-transient-projection). - -Focused unit and combined PostgreSQL/socket-mTLS test sources cover real typed client/codec/adapter composition, actual Entity/Saga migrations and assignment writer, persisted zero/one actor reads, same-row nonzero and zero levels, account/namespace isolation, quarantine exclusion, unchanged actor/selection/snapshot/retention storage, workload/context refusal, closure/bounds, unsupported scope/policy, unavailable source and source-digest drift across SQL. Upstream Game Session/World/publication bytes and assignment eligibility remain controlled fixtures rather than executed upstream owner stores or production custody. Existing preseeded writer uniqueness prevents a physical many-actor fixture; bounded ordered multiple-response validation is unit source coverage only. Preserved source proof309 passes eight focused units and three combined PostgreSQL/socket-mTLS cases. Actual public receiving compilation342 now passes; focused receiving execution and documentation checks remain pending. These executions retain their source attribution and do not establish a complete upstream chain. This source addition does not qualify production registration, Account consumer settlement, private/player-created/auto-provisioned discovery, admission or activation. +The manually composed, unregistered Account bootstrap discovery source now has a distinct purpose proto, exact Account workload guard, current-source adapter overload without a fabricated Game Session session, and a read-only persisted projection. It rereads the complete actual Game Session owner target before and after local SQL and preserves actual same-row UUID/name/level. Its contract and currentness limits are owned by [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#account-bootstrap-persisted-actor-discovery) and [runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md#account-bootstrap-transient-projection). Focused proof and remaining limits are recorded in [Validation and Proof](#account-bootstrap-persisted-discovery-proof). diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java index 90bf77d531..dc80dbb485 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java @@ -115,6 +115,7 @@ public AccountPlayerAdmissionEntitlementOwner( transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); transaction.setReadOnly(false); + transaction.setTimeout(5); } /** Selects the sole current Account-owned billing source; callers cannot select a family. */ diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java index b7fec29bc4..9ef0865509 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java @@ -4,10 +4,15 @@ 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.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.google.protobuf.ByteString; import io.grpc.Server; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.time.Clock; @@ -181,12 +186,13 @@ void actualRecoveredLoginFlowsThroughPlayerAdmissionOwnerAndConsumer() throws Ex when(context.accountId()).thenReturn(scope.accountId().toString()); when(context.connectScopeId()).thenReturn(scope.connectScopeId()); when(context.resolvedTarget()).thenReturn(target); + // This per-fixture spy counts entry into the real receiver; it replaces no authority. + var receiver = spy(new AccountPlayerAdmissionEntitlementGrpcService(owner, NAMESPACE)); Server server = - new AccountPlayerAdmissionEntitlementGrpcService(owner, NAMESPACE) - .createUnregisteredServer( - "127.0.0.1:0", - pki.keyManagerFactory(pki.identity("account")), - pki.trustManagerFactory()); + receiver.createUnregisteredServer( + "127.0.0.1:0", + pki.keyManagerFactory(pki.identity("account")), + pki.trustManagerFactory()); server.start(); var endpoints = new ServiceEndpointsProperties(); endpoints.setAccountService("localhost:" + server.getPort()); @@ -208,15 +214,32 @@ void actualRecoveredLoginFlowsThroughPlayerAdmissionOwnerAndConsumer() throws Ex assertThat(receivedSources.get("callerTokenSha256")).isEqualTo(initial.tokenSha256()); assertThat(receivedSources.get("callerTokenJti")) .isEqualTo(initial.tokenJti().toString()); + verify(receiver).readPlayerAdmissionEntitlement(any(), any()); assertThatThrownBy(() -> client.read(context, UUID.randomUUID(), login, () -> false)) - .isInstanceOf(RuntimeException.class); + .isExactlyInstanceOf(StatusRuntimeException.class) + .hasMessage("CANCELLED: Account player-admission entitlement read did not complete") + .satisfies( + failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.CANCELLED)); + verify(receiver).readPlayerAdmissionEntitlement(any(), any()); // Retaining valid signature bytes and local custody is insufficient after Account moves. + // The caller verifier currently reports that loss as an untyped failure, so the actual + // receiver returns INTERNAL rather than the typed source-outage UNAVAILABLE status. f.beginPlayerEntitlementLoginRevocation(); assertThatThrownBy(() -> client.read(context, UUID.randomUUID(), login, () -> true)) - .isInstanceOf(RuntimeException.class); + .isExactlyInstanceOf(StatusRuntimeException.class) + .hasMessage("INTERNAL: Account player-admission entitlement read did not complete") + .satisfies( + failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.INTERNAL)); + verify(receiver, times(2)).readPlayerAdmissionEntitlement(any(), any()); login.close(); assertThatThrownBy(() -> client.read(context, UUID.randomUUID(), login, () -> true)) - .isInstanceOf(RuntimeException.class); + .isExactlyInstanceOf(IllegalStateException.class) + .hasMessage("Canonical LOGIN private result is closed"); + verify(receiver, times(2)).readPlayerAdmissionEntitlement(any(), any()); } finally { server.shutdownNow(); assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java index c94ecd8279..bff40315cc 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java @@ -296,6 +296,36 @@ void actualFirstJoinRetainsItsPositiveMembershipAndExactScopeBinding() { assertThat(value.toString()).doesNotContain(f.scope.connectScopeId(), CONTROLLED_COMPACT_TOKEN); } + @Test + void blockedAccountSourceReadIsCancelledWithinOwnerTransactionBudget() throws Exception { + Fixture f = fixture(false); + try (Connection blocker = f.dataSource.getConnection()) { + blocker.setAutoCommit(false); + try (var lock = + blocker.prepareStatement( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE")) { + lock.setObject(1, f.account.getAccountUuid()); + lock.executeQuery().close(); + // No database-side lock/statement timeout is installed. The actual transaction-aware + // jOOQ connection must propagate the owner's five-second JDBC query timeout. + assertThatThrownBy(() -> f.owner.evaluate(f.request(), CONTROLLED_COMPACT_TOKEN)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .satisfies( + failure -> { + Throwable cause = failure; + while (cause.getCause() != null) cause = cause.getCause(); + assertThat(cause).isInstanceOf(SQLException.class); + assertThat(((SQLException) cause).getSQLState()).isEqualTo("57014"); + }); + } finally { + blocker.rollback(); + } + } + // Cancellation rolls back the owner transaction and does not damage a later current read. + assertThat(f.owner.evaluate(f.request(), CONTROLLED_COMPACT_TOKEN).fields()) + .containsEntry("variant", "PLAYER_ADMISSION"); + } + @Test void captureHoldsActualAccountWriterLockAndFailureBeforeCommitExposesNoValue() { Fixture f = fixture(false); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java index c32648c446..4389fb6d68 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java @@ -3,15 +3,20 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.intThat; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; 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.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLTimeoutException; import java.time.Clock; import java.time.Instant; import java.util.ArrayList; @@ -20,6 +25,7 @@ import java.util.Map; import java.util.Optional; import java.util.UUID; +import javax.sql.DataSource; import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; @@ -69,12 +75,17 @@ import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import org.jooq.ConnectionRunnable; import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.NullSource; import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; @@ -203,6 +214,63 @@ void paidReadRunsProviderOutsideSqlThenCapturesCurrentReceiptAndPlayerInFinalTra order.verify(f.hosting).readCurrent(fence, observed); } + @Test + void sourceTimeoutReachesJdbcLockingStatementAndRollsBackWithoutReturningEvidence() + throws Exception { + Fixture f = new Fixture(false); + var dataSource = mock(DataSource.class); + var connection = mock(Connection.class); + try (var statement = mock(PreparedStatement.class)) { + when(dataSource.getConnection()).thenReturn(connection); + when(connection.getAutoCommit()).thenReturn(true, false); + when(connection.getTransactionIsolation()) + .thenReturn(Connection.TRANSACTION_READ_COMMITTED, Connection.TRANSACTION_SERIALIZABLE); + when(connection.prepareStatement(anyString())) + .thenAnswer( + invocation -> { + assertThat(invocation.getArgument(0, String.class)).endsWith("for update"); + return statement; + }); + when(statement.execute()).thenThrow(new SQLTimeoutException("Controlled timeout", "57014")); + // The real Spring proxy transfers the remaining transaction budget to jOOQ's JDBC statement. + // The driver is controlled here; physical PostgreSQL cancellation is separate proof. + var dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var owner = + new AccountPlayerAdmissionEntitlementOwner( + dsl, + new AccountRepository(dsl), + f.callers, + f.issuances, + f.memberships, + f.scopes, + f.hosting, + f.observer, + f.demos, + f.sources, + f.targets, + new DataSourceTransactionManager(dataSource), + Clock.fixed(NOW, java.time.ZoneOffset.UTC), + "prod"); + + assertThatThrownBy(() -> owner.evaluate(f.request, "controlled-token")) + .isExactlyInstanceOf(DataAccessException.class) + .hasRootCauseExactlyInstanceOf(SQLTimeoutException.class); + verify(statement).execute(); + verify(statement).close(); + verify(statement).setQueryTimeout(intThat(seconds -> seconds > 0 && seconds <= 5)); + verify(connection).rollback(); + verifyNoInteractions( + f.issuances, + f.memberships, + f.scopes, + f.hosting, + f.observer, + f.demos, + f.sources, + f.targets); + } + } + @Test void scopeDeadlineReachedDuringFinalCommitReturnsNoValue() throws Exception { Fixture f = new Fixture(false); @@ -980,6 +1048,9 @@ public TransactionStatus getTransaction( assertThat(definition.getIsolationLevel()) .isEqualTo(TransactionDefinition.ISOLATION_SERIALIZABLE); assertThat(definition.isReadOnly()).isFalse(); + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getTimeout()).isEqualTo(5); } events.add("begin"); TransactionSynchronizationManager.setActualTransactionActive(true); From 29c012b909cacd6d33a93c9cbb9cc643a4511fc7 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 7 Nov 2026 21:33:04 +1300 Subject: [PATCH 18/23] fix(account): preserve expected admission refusal classification --- ...ccountPlayerAdmissionEntitlementOwner.java | 18 ++- ...PlayerAdmissionEntitlementGrpcService.java | 2 + ...ccountGameplayAdmissionCallerVerifier.java | 21 +++- ...mittedLoginCompositionIntegrationTest.java | 16 +-- ...ntPlayerAdmissionEntitlementOwnerTest.java | 56 +++++++++ ...erAdmissionEntitlementGrpcServiceTest.java | 7 ++ ...ntGameplayAdmissionCallerVerifierTest.java | 68 +++++++++- ...AccountBootstrapRosterReadGrpcService.java | 10 +- ...AccountBootstrapRosterReadServiceTest.java | 117 ++++++++++++++++++ ...countPlayerAdmissionEntitlementClient.java | 3 +- ...yerAdmissionEntitlementClientMtlsTest.java | 5 +- ...yAdmissionDecisionReadGrpcServiceTest.java | 25 ---- 12 files changed, 297 insertions(+), 51 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java index dc80dbb485..9fb8695366 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java @@ -24,6 +24,7 @@ import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.FenceRejectedException; import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceSelection; import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; @@ -145,7 +146,15 @@ public RuntimePlayerAdmissionEntitlementEvidence evaluate( private RuntimePlayerAdmissionEntitlementEvidence capturePaidSources( Request request, VerifiedCaller caller, Prepared prepared) { - var fence = inSourceTransaction(() -> hosting.prepareCurrentRead(request.tenantId())); + var fence = + inSourceTransaction( + () -> { + try { + return hosting.prepareCurrentRead(request.tenantId()); + } catch (FenceRejectedException rejected) { + throw unavailable(); + } + }); requireNoAmbientTransaction(); var observation = observer.observe(fence.binding()); PublishedRealmEvidence target = readProtectedTarget(request, prepared.player().scope()); @@ -154,7 +163,12 @@ private RuntimePlayerAdmissionEntitlementEvidence capturePaidSources( CurrentPlayer player = readCurrentPlayer(request, caller); if (!prepared.player().scope().equals(player.scope())) throw unavailable(); requireSameHead(request, prepared.selection()); - var receipt = hosting.readCurrent(fence, observation); + final AccountHostingSubscriptionCurrentReceipt receipt; + try { + receipt = hosting.readCurrent(fence, observation); + } catch (FenceRejectedException rejected) { + throw unavailable(); + } Instant evaluatedAt = now(); requireFreshReceipt(request, receipt, evaluatedAt); var event = receipt.tenantAuthorityEvent(); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java index c939580312..a6b37bd0f4 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java @@ -19,6 +19,7 @@ import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionLifecycleService; import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner; import net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementGrpcCodec; import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; @@ -102,6 +103,7 @@ public void readPlayerAdmissionEntitlement( var evidence = owner.evaluate(sourceRequest, presented.initialLoginJwt()); response = RuntimePlayerAdmissionEntitlementGrpcCodec.toResponse(request, evidence); } catch (AccountPlayerAdmissionEntitlementOwner.SourceUnavailableException + | AccountGameplayAdmissionCallerVerifier.CallerUnavailableException | AccountHostingSubscriptionLifecycleService.EntitlementUnavailableException | DemoTenantEntitlementException | org.jooq.exception.DataAccessException diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionCallerVerifier.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionCallerVerifier.java index bfc5846ae3..785136a5ff 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionCallerVerifier.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionCallerVerifier.java @@ -86,9 +86,15 @@ public VerifiedCaller verifyPresentedCompactToken(String compactJwt) { currentIssuanceOwner.requireCurrentActiveCommittedCandidateByJti(tokenJti); requireExactCandidate(compactJwt, verified, candidate); return new VerifiedCaller(candidate); - } catch (RuntimeException failure) { - // Do not preserve exception text or causes that could expose credential or parser details. + } catch (CallerUnavailableException + | AccountAsymmetricJwtVerifier.VerificationException + | AccountAsymmetricJwtVerifier.VerificationUnavailableException + | AccountPublicJwksCache.SourceUnavailableException + | AccountGameplayDelegationCommittedIssuanceOwner.OwnerUnavailableException refused) { throw unavailable(); + } catch (RuntimeException unexpected) { + // Preserve fault classification without exposing credential, parser or source details. + throw new IllegalStateException("Account gameplay caller verification failed"); } } @@ -181,8 +187,15 @@ private static long numberClaim(Map claims, String field) { } } - private static IllegalStateException unavailable() { - return new IllegalStateException("Account gameplay caller verification is unavailable"); + private static CallerUnavailableException unavailable() { + return new CallerUnavailableException(); + } + + /** Sanitized refusal to provide a verified current LOGIN caller to admission owners. */ + public static final class CallerUnavailableException extends IllegalStateException { + public CallerUnavailableException() { + super("Account gameplay caller verification is unavailable"); + } } /** diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java index 9ef0865509..6308e443e7 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java @@ -10,6 +10,7 @@ import static org.mockito.Mockito.when; import com.google.protobuf.ByteString; +import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; import io.grpc.Server; import io.grpc.Status; import io.grpc.StatusRuntimeException; @@ -61,18 +62,20 @@ class AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest { private static final String NAMESPACE = "test"; private static final String PEER = "spiffe://firemud/ns/test/sa/game-session-service"; private static final Clock CLOCK = Clock.systemUTC(); + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(true); private final AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest fixtures = - new AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest(); + AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.withPostgres(POSTGRES); @TempDir Path directory; @BeforeAll static void startPostgres() { - AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.startPostgres(); + POSTGRES.start(); } @AfterAll static void stopPostgres() { - AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.stopPostgres(); + POSTGRES.stop(); } @AfterEach @@ -224,16 +227,15 @@ void actualRecoveredLoginFlowsThroughPlayerAdmissionOwnerAndConsumer() throws Ex .isEqualTo(Status.Code.CANCELLED)); verify(receiver).readPlayerAdmissionEntitlement(any(), any()); // Retaining valid signature bytes and local custody is insufficient after Account moves. - // The caller verifier currently reports that loss as an untyped failure, so the actual - // receiver returns INTERNAL rather than the typed source-outage UNAVAILABLE status. + // The actual caller verifier and receiver classify this currentness loss as UNAVAILABLE. f.beginPlayerEntitlementLoginRevocation(); assertThatThrownBy(() -> client.read(context, UUID.randomUUID(), login, () -> true)) .isExactlyInstanceOf(StatusRuntimeException.class) - .hasMessage("INTERNAL: Account player-admission entitlement read did not complete") + .hasMessage("UNAVAILABLE: Account player-admission entitlement read did not complete") .satisfies( failure -> assertThat(((StatusRuntimeException) failure).getStatus().getCode()) - .isEqualTo(Status.Code.INTERNAL)); + .isEqualTo(Status.Code.UNAVAILABLE)); verify(receiver, times(2)).readPlayerAdmissionEntitlement(any(), any()); login.close(); assertThatThrownBy(() -> client.read(context, UUID.randomUUID(), login, () -> true)) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java index 4389fb6d68..fa102f0e2d 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java @@ -50,6 +50,7 @@ import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCurrentRecord; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.FenceRejectedException; import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceKind; import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceSelection; @@ -214,6 +215,61 @@ void paidReadRunsProviderOutsideSqlThenCapturesCurrentReceiptAndPlayerInFinalTra order.verify(f.hosting).readCurrent(fence, observed); } + @ParameterizedTest + @ValueSource(strings = {"prepare", "current"}) + void paidReadFenceRefusalsBecomeSanitizedUnavailableWithoutDemoFallback(String stage) + throws Exception { + Fixture f = new Fixture(true); + when(f.sources.readCurrentSourceSelection(TENANT)) + .thenReturn(new SourceSelection(SourceKind.PAID_HOSTING, f.tenantEvent)); + var fence = mock(ReadFence.class); + var observed = mock(StripeHostingSubscriptionObserver.ObservedSubscription.class); + when(f.hosting.prepareCurrentRead(TENANT)).thenReturn(fence); + when(f.observer.observe(fence.binding())).thenReturn(observed); + var refusal = new FenceRejectedException("private paid read detail"); + if ("prepare".equals(stage)) { + when(f.hosting.prepareCurrentRead(TENANT)).thenThrow(refusal); + } else { + when(f.hosting.readCurrent(fence, observed)).thenThrow(refusal); + } + + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .isExactlyInstanceOf( + AccountPlayerAdmissionEntitlementOwner.SourceUnavailableException.class) + .hasMessage("ENTITLEMENT_UNAVAILABLE: current player source evidence is unavailable") + .hasNoCause(); + assertThat(f.transactions.events).endsWith("rollback"); + verifyNoInteractions(f.demos); + if ("prepare".equals(stage)) { + verifyNoInteractions(f.observer, f.targets); + } else { + verify(f.hosting).readCurrent(fence, observed); + } + } + + @ParameterizedTest + @ValueSource(strings = {"prepare", "current"}) + void unrelatedPaidReadFaultsRemainUnexpectedForInternalClassification(String stage) + throws Exception { + Fixture f = new Fixture(true); + when(f.sources.readCurrentSourceSelection(TENANT)) + .thenReturn(new SourceSelection(SourceKind.PAID_HOSTING, f.tenantEvent)); + var fence = mock(ReadFence.class); + var observed = mock(StripeHostingSubscriptionObserver.ObservedSubscription.class); + when(f.hosting.prepareCurrentRead(TENANT)).thenReturn(fence); + when(f.observer.observe(fence.binding())).thenReturn(observed); + var unexpected = new IllegalArgumentException("private unexpected paid read detail"); + if ("prepare".equals(stage)) { + when(f.hosting.prepareCurrentRead(TENANT)).thenThrow(unexpected); + } else { + when(f.hosting.readCurrent(fence, observed)).thenThrow(unexpected); + } + + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")).isSameAs(unexpected); + assertThat(f.transactions.events).endsWith("rollback"); + verifyNoInteractions(f.demos); + } + @Test void sourceTimeoutReachesJdbcLockingStatementAndRollsBackWithoutReturningEvidence() throws Exception { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java index 8d4335e452..09b763e55d 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java @@ -24,6 +24,7 @@ import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionLifecycleService; import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner; import net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementGrpcCodec; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector; @@ -89,6 +90,9 @@ private static Stream ownerFailures org.junit.jupiter.params.provider.Arguments.of( new AccountPlayerAdmissionEntitlementOwner.SourceUnavailableException(), Status.Code.UNAVAILABLE), + org.junit.jupiter.params.provider.Arguments.of( + new AccountGameplayAdmissionCallerVerifier.CallerUnavailableException(), + Status.Code.UNAVAILABLE), org.junit.jupiter.params.provider.Arguments.of( new AccountHostingSubscriptionLifecycleService.EntitlementUnavailableException( new IllegalStateException(SECRET)), @@ -105,6 +109,9 @@ private static Stream ownerFailures org.junit.jupiter.params.provider.Arguments.of( new org.springframework.transaction.CannotCreateTransactionException(SECRET), Status.Code.UNAVAILABLE), + org.junit.jupiter.params.provider.Arguments.of( + new IllegalStateException("Account gameplay caller verification failed"), + Status.Code.INTERNAL), org.junit.jupiter.params.provider.Arguments.of( new IllegalStateException("ENTITLEMENT_UNAVAILABLE: " + SECRET), Status.Code.INTERNAL), org.junit.jupiter.params.provider.Arguments.of( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionCallerVerifierTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionCallerVerifierTest.java index d03c64a286..9283b0e399 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionCallerVerifierTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionCallerVerifierTest.java @@ -268,9 +268,9 @@ void rejectsCandidateHashIdentityAndAuthorityMismatchWithoutRetainingCredentialD when(fixture.currentIssuanceOwner.requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI)) .thenReturn(mismatchedCandidate); - IllegalStateException failure = + AccountGameplayAdmissionCallerVerifier.CallerUnavailableException failure = assertThrows( - IllegalStateException.class, + AccountGameplayAdmissionCallerVerifier.CallerUnavailableException.class, () -> fixture.verifier.verifyPresentedCompactToken(compactJwt)); assertNull(failure.getCause()); @@ -280,14 +280,69 @@ void rejectsCandidateHashIdentityAndAuthorityMismatchWithoutRetainingCredentialD } } + @Test + void currentIssuanceRefusalUsesSanitizedTypedCallerUnavailableFailure() throws Exception { + Fixture fixture = new Fixture(); + String compactJwt = fixture.signedToken(signingPair, fixture.initialClaims()); + when(fixture.currentIssuanceOwner.requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI)) + .thenThrow(new AccountGameplayDelegationCommittedIssuanceOwner.OwnerUnavailableException()); + + assertUnavailable(fixture.verifier, compactJwt); + + verify(fixture.currentIssuanceOwner).requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI); + } + + @Test + void actualTrustedJwksOutagesRemainTypedBeforePinningAndDuringKeyLoading() throws Exception { + for (boolean alreadyPinned : List.of(false, true)) { + Fixture fixture = new Fixture(); + String compactJwt = fixture.signedToken(signingPair, fixture.initialClaims()); + if (alreadyPinned) { + fixture.trustedJwksSource.sourceIdentity(); + } + when(fixture.configMapClient.observe()) + .thenThrow(new AccountJwtJwksConfigMapClient.ApiFailureException(503)); + + assertUnavailable(fixture.verifier, compactJwt); + + verifyNoInteractions(fixture.currentIssuanceOwner); + } + } + + @Test + void unexpectedTrustedSourceAndCurrentnessFaultsRemainSanitizedInternalFailures() + throws Exception { + for (boolean sourceFault : List.of(false, true)) { + Fixture fixture = new Fixture(); + String compactJwt = fixture.signedToken(signingPair, fixture.initialClaims()); + var unexpected = new NullPointerException("private unexpected detail: " + compactJwt); + if (sourceFault) { + when(fixture.configMapClient.observe()).thenThrow(unexpected); + } else { + when(fixture.currentIssuanceOwner.requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI)) + .thenThrow(unexpected); + } + + IllegalStateException failure = + assertThrows( + IllegalStateException.class, + () -> fixture.verifier.verifyPresentedCompactToken(compactJwt)); + + assertEquals(IllegalStateException.class, failure.getClass()); + assertEquals("Account gameplay caller verification failed", failure.getMessage()); + assertNull(failure.getCause()); + assertFalse(failure.toString().contains(compactJwt)); + } + } + @Test void refusesAmbientTransactionBeforeTrustedSourceOrCurrentnessReads() { Fixture fixture = new Fixture(); TransactionSynchronizationManager.setActualTransactionActive(true); - IllegalStateException failure = + AccountGameplayAdmissionCallerVerifier.CallerUnavailableException failure = assertThrows( - IllegalStateException.class, + AccountGameplayAdmissionCallerVerifier.CallerUnavailableException.class, () -> fixture.verifier.verifyPresentedCompactToken("credential-not-retained")); assertNull(failure.getCause()); @@ -301,9 +356,10 @@ void refusesAmbientTransactionBeforeTrustedSourceOrCurrentnessReads() { private static void assertUnavailable( AccountGameplayAdmissionCallerVerifier verifier, String compactJwt) { - IllegalStateException failure = + AccountGameplayAdmissionCallerVerifier.CallerUnavailableException failure = assertThrows( - IllegalStateException.class, () -> verifier.verifyPresentedCompactToken(compactJwt)); + AccountGameplayAdmissionCallerVerifier.CallerUnavailableException.class, + () -> verifier.verifyPresentedCompactToken(compactJwt)); assertNull(failure.getCause()); assertEquals("Account gameplay caller verification is unavailable", failure.getMessage()); assertFalse(failure.toString().contains(compactJwt)); diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadGrpcService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadGrpcService.java index 0a2d385803..161a73e449 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadGrpcService.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadGrpcService.java @@ -43,7 +43,12 @@ public void readAccountBootstrapRoster( AccountBootstrapRosterReadResponse response; try { AccountBootstrapRosterReadService.requireNoAmbientTransaction(); - AccountBootstrapRosterReadContract.requireRequest(request); + try { + AccountBootstrapRosterReadContract.requireRequest(request); + } catch (IllegalArgumentException invalid) { + refuse(observer, Status.INVALID_ARGUMENT); + return; + } if (!namespace.equals(request.getTargetNamespace())) { refuse(observer, Status.PERMISSION_DENIED); return; @@ -58,9 +63,6 @@ public void readAccountBootstrapRoster( } catch (UnsupportedOperationException | IllegalStateException precondition) { refuse(observer, Status.FAILED_PRECONDITION); return; - } catch (IllegalArgumentException invalid) { - refuse(observer, Status.INVALID_ARGUMENT); - return; } catch (RuntimeException unexpected) { refuse(observer, Status.INTERNAL); return; diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadServiceTest.java index 2b46dfa4b1..a429711959 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadServiceTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadServiceTest.java @@ -7,21 +7,36 @@ import static org.mockito.Mockito.*; import com.google.protobuf.UnknownFieldSet; +import io.grpc.Attributes; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; import java.util.List; import java.util.UUID; +import javax.net.ssl.SSLSession; import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; import net.firedevops.firemud.entitymanagement.bootstrap.AccountBootstrapRosterActorProjection; import net.firedevops.firemud.entitymanagement.bootstrap.AccountBootstrapRosterFixture; +import net.firedevops.firemud.entitymanagement.bootstrap.AccountBootstrapRosterPeerInterceptor; import net.firedevops.firemud.entitymanagement.bootstrap.AccountBootstrapRosterReadContract; +import net.firedevops.firemud.entitymanagement.bootstrap.AccountBootstrapRosterReadGrpcService; import net.firedevops.firemud.entitymanagement.bootstrap.AccountBootstrapRosterReadService; import net.firedevops.firemud.entitymanagement.client.GameSessionCanonicalGameplayRosterOwnerReadClient; import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterOwnerEvidencePort.OwnerEvidenceUnavailableException; import net.firedevops.firemud.entitymanagement.service.impl.GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter; import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterActor; +import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadRequest; import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadResponse; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.AbstractPlatformTransactionManager; import org.springframework.transaction.support.DefaultTransactionStatus; @@ -192,6 +207,108 @@ void exactEchoClosedActorBoundsCanonicalIdsAndDeterministicOrderAreRequired() th } } + @Test + @SuppressWarnings("unchecked") + void receiverKeepsMalformedRequestsInvalidWithoutCallingService() throws Exception { + var f = AccountBootstrapRosterFixture.create(); + var service = mock(AccountBootstrapRosterReadService.class); + var receiver = + new AccountBootstrapRosterReadGrpcService(service, AccountBootstrapRosterFixture.NAMESPACE); + StreamObserver observer = mock(StreamObserver.class); + + withControlledAccountPeer( + () -> + receiver.readAccountBootstrapRoster( + f.request().toBuilder().setCanonicalAccountUuid("malformed").build(), observer)); + + assertReceiverFailure(observer, Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(service); + } + + @Test + @SuppressWarnings("unchecked") + void receiverClassifiesStoredProjectionAndResponseValidationFailuresAsInternal() + throws Exception { + for (boolean invalidProjection : List.of(false, true)) { + var f = AccountBootstrapRosterFixture.create(); + var client = mock(GameSessionCanonicalGameplayRosterOwnerReadClient.class); + var repository = mock(CharacterRepository.class); + when(client.getCanonicalGameplayRosterOwnerRead(any())).thenReturn(f.evidence()); + if (invalidProjection) { + when(repository.readAccountBootstrapRoster(any(), any())) + .thenAnswer( + ignored -> + List.of( + new AccountBootstrapRosterActorProjection( + UUID.randomUUID(), "Persisted Actor", -1))); + } else { + var actor = + new AccountBootstrapRosterActorProjection(UUID.randomUUID(), "Persisted Actor", 0); + // The valid persisted rows form an invalid response because actor identity repeats. + when(repository.readAccountBootstrapRoster(any(), any())).thenReturn(List.of(actor, actor)); + } + var receiver = + new AccountBootstrapRosterReadGrpcService( + service(client, repository), AccountBootstrapRosterFixture.NAMESPACE); + StreamObserver observer = mock(StreamObserver.class); + + withControlledAccountPeer(() -> receiver.readAccountBootstrapRoster(f.request(), observer)); + + assertReceiverFailure(observer, Status.Code.INTERNAL); + verify(repository).readAccountBootstrapRoster(any(), eq(f.target())); + } + } + + private static void assertReceiverFailure( + StreamObserver observer, Status.Code expected) { + var failure = ArgumentCaptor.forClass(Throwable.class); + verify(observer).onError(failure.capture()); + assertThat(Status.fromThrowable(failure.getValue()).getCode()).isEqualTo(expected); + assertThat(failure.getValue()) + .hasMessage(expected.name() + ": Account bootstrap roster read refused") + .hasNoCause(); + verify(observer, never()).onNext(any()); + verify(observer, never()).onCompleted(); + } + + /** Controlled peer context for status mapping only; this is not physical mTLS proof. */ + @SuppressWarnings("unchecked") + private static void withControlledAccountPeer(Runnable action) throws Exception { + ServerCall call = + mock(ServerCall.class); + MethodDescriptor + descriptor = mock(MethodDescriptor.class); + when(descriptor.getFullMethodName()) + .thenReturn(AccountBootstrapRosterPeerInterceptor.METHOD_NAME); + when(call.getMethodDescriptor()).thenReturn(descriptor); + X509Certificate leaf = mock(X509Certificate.class); + when(leaf.getSubjectAlternativeNames()) + .thenReturn( + List.of( + List.of( + 6, + "spiffe://firemud/ns/" + + AccountBootstrapRosterFixture.NAMESPACE + + "/sa/account-service"))); + SSLSession session = mock(SSLSession.class); + when(session.getPeerCertificates()).thenReturn(new Certificate[] {leaf}); + when(call.getAttributes()) + .thenReturn(Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, session).build()); + ServerCallHandler next = + mock(ServerCallHandler.class); + when(next.startCall(any(), any())) + .thenAnswer( + ignored -> { + action.run(); + return new ServerCall.Listener() {}; + }); + + new AccountBootstrapRosterPeerInterceptor(AccountBootstrapRosterFixture.NAMESPACE) + .interceptCall(call, new Metadata(), next); + + verify(next).startCall(any(), any()); + } + private static AccountBootstrapRosterReadService service( GameSessionCanonicalGameplayRosterOwnerReadClient client, CharacterRepository repository) { return new AccountBootstrapRosterReadService( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClient.java index ec976cdadb..dd5f9c3147 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClient.java @@ -380,8 +380,7 @@ protected String defaultTarget() { buildStub(ManagedChannel channel) { return AccountPlayerAdmissionEntitlementReadServiceGrpc.newBlockingStub(channel) .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedAccountPeer)) - .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedAccountPeer)) - .withCompression("gzip"); + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedAccountPeer)); } private static IllegalArgumentException invalid() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java index dbd573fd92..1e6c61309b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java @@ -7,6 +7,7 @@ import static org.mockito.Mockito.when; import com.google.protobuf.ByteString; +import io.grpc.ManagedChannel; import io.grpc.Server; import io.grpc.ServerInterceptors; import io.grpc.Status; @@ -114,7 +115,7 @@ static void certificates() throws Exception { } @Test - void exactAccountPeerReceivesCurrentLoginCredentialAndReturnsBoundCanonicalEvidence() + void exactAccountPeerReceivesUncompressedCurrentLoginCredentialAndReturnsBoundCanonicalEvidence() throws Exception { var context = context(); var login = loginCustody(); @@ -124,6 +125,8 @@ void exactAccountPeerReceivesCurrentLoginCredentialAndReturnsBoundCanonicalEvide Server server = server("account", calls, observedJwt, observedPeer, context, login.evidence()); try (var client = client(server)) { client.init(); + assertThat(client.buildStub(mock(ManagedChannel.class)).getCallOptions().getCompressor()) + .isNull(); var result = client.read(context, READ_REQUEST, login, () -> true); assertThat(result.fields()) .containsEntry("variant", "PLAYER_ADMISSION") diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java index f68d7b3e45..f09b40e6dd 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java @@ -358,31 +358,6 @@ private static void assertDiscoveryFailure( verify(observer, never()).onCompleted(); } - @Test - void discoveryReturnsCompleteMixedPolicyTargetsWithStableIndependentReread() { - var seeded = discoveryTarget("seeded", "Seeded world"); - var created = discoveryTarget("created", "Created world", "PLAYER_CREATED"); - var routes = mock(CanonicalPlayerRouteReadService.class); - when(routes.readVisiblePublicProductionTargets()) - .thenReturn(List.of(seeded, created), List.of(created, seeded)); - var observer = discoveryObserver(); - discoveryService(routes, mock(CanonicalGameplayAdmissionDecisionReadWorkloadGuard.class)) - .listVisiblePublicProductionAdmissionTargets(discoveryRequest(), observer); - var captured = - ArgumentCaptor.forClass(ListVisiblePublicProductionAdmissionTargetsResponse.class); - verify(observer).onNext(captured.capture()); - var request = - CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseDiscoveryRequest(discoveryRequest()); - assertThat( - CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( - request, captured.getValue()) - .targets()) - .extracting(target -> target.characterCreationPolicy()) - .containsExactly("PLAYER_CREATED", "PRESEEDED_ONLY"); - verify(routes, times(2)).readVisiblePublicProductionTargets(); - verify(observer).onCompleted(); - } - private static CanonicalPlayableTarget discoveryTarget(String slug, String displayName) { return discoveryTarget(slug, displayName, "PRESEEDED_ONLY"); } From 4d1d0277d0b37a7f84640060d07af868e84d1efc Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 7 Nov 2026 22:31:59 +1300 Subject: [PATCH 19/23] Classify admission source outages and tighten boundary proofs --- .../api-contracts.md | 2 +- .../game-session-service/api-contracts.md | 2 +- .../gameplay-rules-entities-and-effects.md | 2 +- ...ostingSubscriptionLifecycleRepository.java | 4 + ...ccountPlayerAdmissionEntitlementOwner.java | 33 +++-- ...ngSubscriptionLifecycleRepositoryTest.java | 54 ++++++++ ...ntPlayerAdmissionEntitlementOwnerTest.java | 123 ++++++++++++++++++ ...erAdmissionEntitlementGrpcServiceTest.java | 8 ++ ...yerAdmissionEntitlementClientMtlsTest.java | 35 ++++- 9 files changed, 243 insertions(+), 20 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index ec2afba336..569acfa1af 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -298,4 +298,4 @@ The current contract still leaves player command orchestration, authored stat/co The closed request contains canonical non-nil request and Account UUIDs, the configured workload namespace and the complete existing `CanonicalGameplayRosterTarget`, including every source digest, release reference and positive owner counter. It carries no bootstrap credential, `PlayerExecutionContext`, Game Session session, original selection or retained roster reference. The request bound is 4 KiB; unknown fields, noncanonical UUIDs and incomplete targets are invalid. The response echoes the exact entire request and contains at most 100 unique actors ordered by canonical UUID text within 64 KiB. Each actor has its persisted UUID, trimmed control-free display name of at most 100 Unicode code points, and explicit nonnegative `level` sourced from the same eligible `characters` row. The optional wire field must be present even when the actual persisted level is zero; absence is never normalized to zero. -Entity independently reads the complete current Game Session, sealed publication and World target through its existing Entity-only `GetCanonicalGameplayRosterOwnerRead` client and codec before querying persisted rows, compares the exact reconstructed target with the caller's expected target, and rereads that owner target after the short local projection transaction. Only current visible public-production `SHARED` / `PRESEEDED_ONLY` is supported. A valid supported target may return zero eligible actors; unsupported private, isolated, `PLAYER_CREATED` and `AUTO_PROVISIONED` paths remain explicit obligations and cannot return a fabricated empty success. Malformed input is `INVALID_ARGUMENT`, unsupported or changed preconditions are `FAILED_PRECONDITION`, and unavailable owner or storage reads are `UNAVAILABLE`; failures return no partial projection. This read allocates no actor, selection, snapshot, admission nonce or retention reference and supplies no admission authority or distributed source hold. See [runtime/data limitations](./runtime-and-data.md#account-bootstrap-transient-projection) and the [proof tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#account-bootstrap-persisted-discovery). +Entity independently reads the complete current Game Session, sealed publication and World target through its existing Entity-only `GetCanonicalGameplayRosterOwnerRead` client and codec before querying persisted rows, compares the exact reconstructed target with the caller's expected target, and rereads that owner target after the short local projection transaction. Only current visible public-production `SHARED` / `PRESEEDED_ONLY` is supported. A valid supported target may return zero eligible actors; unsupported private, isolated, `PLAYER_CREATED` and `AUTO_PROVISIONED` paths remain explicit obligations and cannot return a fabricated empty success. Malformed input is `INVALID_ARGUMENT`, unsupported or changed preconditions are `FAILED_PRECONDITION`, unavailable owner or storage reads are `UNAVAILABLE`, and invalid stored projections or server response-validation failures are `INTERNAL`; failures return no partial projection. This read allocates no actor, selection, snapshot, admission nonce or retention reference and supplies no admission authority or distributed source hold. See [runtime/data limitations](./runtime-and-data.md#account-bootstrap-transient-projection) and the [proof tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#account-bootstrap-persisted-discovery). diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 2880fa5364..d86e71ac01 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -16,7 +16,7 @@ The local [canonical NEW admission lease contract](../../system-architecture-ses The initial-LOGIN PostgreSQL journal and exact original-attempt cleanup owner are unregistered source preparation, with no new Game Session endpoint or legacy LOGIN handler composition. Their unregistered Account client authenticates the exact same-namespace Account mTLS peer and validates the explicit initial delegation profile, signature, original request/context, token hash, claim/projection equality and bounded nonsecret evidence. Its one transient invocation permits at most one transport reload/retry under the unchanged deadline. It also uses the original-request retirement contract. The result retains compact private-token bytes only in process; validation supplies neither current registry authority nor live context installation. Journal snapshots and typed closure fixtures supply no authenticated caller custody or physical Redis closure; the separate Redis adapter remains outside runtime composition. See the [canonical coordination contract](../../system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination) and [implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). -The manually composed `AccountPlayerAdmissionEntitlementClient` consumes the distinct [Account player-admission entitlement purpose](../account-service/api-contracts.md#private-player-admission-entitlement-read). It accepts either a verified first-party connect context or an Account-issued canonical direct-text lobby scope inside its current LOGIN-custody callback. The direct-text read retains the exact original attempt, observed transport, target and Account-issued expiry; historical scope decoding does not authenticate custody. Both inputs share bounded peer-qualified transport, before/after currentness checks and exact response/LOGIN bindings. This source installs no custody, registers no handler and supplies no World hold or admission decision; current proof and unfinished runtime composition belong to the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving). +The manually composed `AccountPlayerAdmissionEntitlementClient` consumes the distinct [Account player-admission entitlement purpose](../account-service/api-contracts.md#private-player-admission-entitlement-read). It accepts either a verified first-party connect context or an Account-issued canonical direct-text lobby scope inside its current LOGIN-custody callback. The direct-text read retains the exact original attempt, observed transport, target and Account-issued expiry; historical scope decoding does not authenticate custody. Both inputs share bounded peer-qualified transport, before/after currentness checks and exact response/LOGIN bindings. This source installs no custody, registers no handler and supplies no World hold or admission decision; current proof and unfinished runtime composition belong to the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#player-admission-entitlement-source-preparation). The source-first owner stage consumes the closed Game Design creation/source receipt, four immutable launch snapshots and policy seal through the trusted fixed capability parser. `RunOwnedCanonicalLaunchPreparationOwner` exposes canonical fresh-association, catalog and `STARTING` creation with independent owner readback only through an explicit preparation call; it has no scheduler. The published `RunOwnedInitialAdmissionFixtureCoordinator` bootstrap and existing `GameInstanceServiceImpl` behavior remain until coherent canonical adoption, so this source-first path is not evidence that the current scheduled runtime allocates that canonical launch. Game Design source keys and Game Session's allocated private tenant/runtime keys remain separate. The published numeric fixture path has not been removed by this source-only split. This explicit canonical path establishes no canonical World materialization/activation, canonical first-`OPEN`, or canonical admission result. diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index f4325210a3..d8dec13426 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -239,7 +239,7 @@ Current receiving R1128 passes all 32 selected native executions: 22 Entity crea Focused [Account client](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/AccountBootstrapRosterReadClientMtlsTest.java), [Entity peer interceptor](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPeerInterceptorTest.java), [Entity read service](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadServiceTest.java), and [persisted repository](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/CharacterRepositoryBootstrapRosterTest.java) tests cover typed client/codec/adapter composition, exact workload/context refusal, closure and bounds, unsupported scope/policy, unavailable source and source-digest drift across SQL. The combined [PostgreSQL/socket-mTLS test source](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPostgresMtlsIntegrationTest.java) additionally covers actual Entity/Saga migrations and assignment writer, persisted zero/one actor reads, same-row nonzero and zero levels, account/namespace isolation, quarantine exclusion and unchanged actor/selection/snapshot/retention storage. Upstream Game Session/World/publication bytes and assignment eligibility remain controlled fixtures rather than executed upstream owner stores or production custody. Existing preseeded writer uniqueness prevents a physical many-actor fixture; bounded ordered multiple-response validation is unit coverage only. This proof does not establish a complete upstream chain, production registration, Account consumer settlement, private/player-created/auto-provisioned discovery, admission or activation. -On 2026-11-07, the local correction based on source parent `ab249aa4f93929fbdf2ccc8bc7c8aa3cacc2d70c` freshly passed all 20 cases in the four focused suites linked above: nine Account client, three Entity peer-interceptor, five Entity read-service and three Entity repository cases, with zero failures, errors or skips. The gate used `bash dev-tools/validation/run-locked-gradle.sh`, `:account-service:test` and `:entity-management-service:test` with those class-name filters and `--offline -PfullCheck --max-workers=1`. The combined PostgreSQL/socket-mTLS suite was not executed in this local correction because Docker is unavailable; no physical database execution is claimed. +On 2026-11-07, the historical local correction based on source parent `ab249aa4f93929fbdf2ccc8bc7c8aa3cacc2d70c` passed all 20 cases in the four focused suites linked above: nine Account client, three Entity peer-interceptor, five Entity read-service and three Entity repository cases, with zero failures, errors or skips. The gate used `bash dev-tools/validation/run-locked-gradle.sh`, `:account-service:test` and `:entity-management-service:test` with those class-name filters and `--offline -PfullCheck --max-workers=1`. The combined PostgreSQL/socket-mTLS suite was not executed in this local correction because Docker is unavailable; no physical database execution is claimed. The current source adds two Entity receiver cases for malformed requests and stored projection/response-validation classification, bringing the four-suite source inventory to 22 cases (nine Account client, three Entity peer-interceptor, seven Entity read-service and three Entity repository cases). The consolidated correction gate on 2026-11-07 freshly executed all 22 cases with zero failures, errors or skips using the same class filters and canonical Gradle wrapper. The combined PostgreSQL/socket-mTLS suite remains unrun locally. ### Canonical sealed-roster proof history 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 8733895de8..c3e3b3117b 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 @@ -1540,6 +1540,10 @@ public ExpectedBinding expectedBinding(String providerId) { * Ends one worker attempt without asserting provider absence or cancellation. Failure keeps the * subscription provisioning and its reservation held; even terminal reconciliation failure is * unresolved billing work. The caller must commit this result rather than throw it away. + * + *

An exact retained attempt that expires before the absolute deadline returns {@link + * Disposition#ATTEMPT_EXPIRED} without changing its work or reservation, leaving recovery to the + * next claimant. */ public Disposition deferUnresolved(ProvisioningClaim claim) { requireTransaction(); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java index 9fb8695366..3fd6669121 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.accountservice.service; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.StatusRuntimeException; import java.sql.Connection; import java.time.Clock; import java.time.Instant; @@ -525,17 +526,27 @@ private PublishedRealmEvidence readProtectedTarget( Request request, CanonicalConnectScopeEvidence scope) { requireNoAmbientTransaction(); var selector = selector(request, scope); - var resolved = Objects.requireNonNull(targets.resolvePublishedRealmAdmissionTarget(selector)); - if (!selector.equals(resolved.selector())) throw unavailable(); - requireSupportedTarget(resolved.currentTarget()); - CanonicalGameplayAdmissionDecisionReadGrpcCodec.requireRetainedTargetMatches( - selector, resolved.currentTarget()); - var result = - Objects.requireNonNull(targets.readPublishedRealmAdmissionOwner(resolved.strictSelector())); - if (!resolved.strictSelector().equals(result.selector()) - || !resolved.currentTarget().equals(result.currentTarget())) throw unavailable(); - requireSupportedTarget(result.currentTarget()); - return result; + try { + var resolved = Objects.requireNonNull(targets.resolvePublishedRealmAdmissionTarget(selector)); + if (!selector.equals(resolved.selector())) throw unavailable(); + requireSupportedTarget(resolved.currentTarget()); + CanonicalGameplayAdmissionDecisionReadGrpcCodec.requireRetainedTargetMatches( + selector, resolved.currentTarget()); + var result = + Objects.requireNonNull( + targets.readPublishedRealmAdmissionOwner(resolved.strictSelector())); + if (!resolved.strictSelector().equals(result.selector()) + || !resolved.currentTarget().equals(result.currentTarget())) throw unavailable(); + requireSupportedTarget(result.currentTarget()); + return result; + } catch (CanonicalGameplayAdmissionDecisionReadClient.ClientUnavailableException failure) { + throw unavailable(); + } catch (StatusRuntimeException failure) { + switch (failure.getStatus().getCode()) { + case UNAVAILABLE, DEADLINE_EXCEEDED, CANCELLED, ABORTED -> throw unavailable(); + default -> throw failure; + } + } } private static void requireSupportedTarget( 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 e3f05a037f..c12371cc58 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 @@ -3,7 +3,9 @@ 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.verify; import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import java.time.Clock; @@ -13,10 +15,15 @@ import java.time.ZoneOffset; import java.util.List; import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Disposition; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProvisioningClaim; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReconciliationLimits; import org.jooq.DSLContext; +import org.jooq.Record; 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.support.TransactionSynchronizationManager; class AccountHostingSubscriptionLifecycleRepositoryTest { @@ -58,6 +65,53 @@ void recoveryOriginIsOnlyRetainedEpisodeHistoryAndMissingHistoryStaysUnresolved( .isEqualTo(original); } + @ParameterizedTest + @ValueSource(longs = {0, 1}) + void expiredExactAttemptBeforeAbsoluteDeadlineLeavesWorkAndReservationUntouched( + long secondsAfterExpiry) { + Instant expiresAt = Instant.parse("2026-11-07T00:00:10Z"); + UUID requestId = UUID.randomUUID(); + UUID attemptId = UUID.randomUUID(); + var controlledIntents = mock(AccountSubscriptionIntentRepository.class); + var controlledRepository = + new AccountHostingSubscriptionLifecycleRepository( + dsl, + controlledIntents, + Clock.fixed(expiresAt.plusSeconds(secondsAfterExpiry), ZoneOffset.UTC), + limits(3, 2, Duration.ofSeconds(10), Duration.ofSeconds(1), Duration.ofHours(1)), + new AccountHostingSubscriptionLifecyclePolicy( + Duration.ofSeconds(15), + new AccountHostingSubscriptionLifecyclePolicy.RecoveryTiming( + Duration.ofSeconds(60), Duration.ofSeconds(120))), + "prod", + false); + var creation = mock(AccountSubscriptionCreationRecord.class); + when(creation.requestId()).thenReturn(requestId); + var claim = mock(ProvisioningClaim.class); + when(claim.creation()).thenReturn(creation); + when(claim.attemptId()).thenReturn(attemptId); + 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("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); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThat(controlledRepository.deferUnresolved(claim)).isEqualTo(Disposition.ATTEMPT_EXPIRED); + + // Exactly the owner/retained-work locks are allowed: no SQL writes, intent settlement, + // reservation release, or replacement attempt can occur on this return. + verify(controlledIntents).lockForProvisioningRecovery(requestId, 7L); + verify(dsl).fetchOne(lockedWorkSql, requestId); + verifyNoMoreInteractions(controlledIntents, dsl); + } + @Test void claimAndSettlementRequireWritableOwnerTransactionBeforeSql() { assertTransactionRefusal(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java index fa102f0e2d..e577f8de6c 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java @@ -5,15 +5,21 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.intThat; +import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import io.grpc.protobuf.StatusProto; +import io.grpc.stub.StreamObserver; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLTimeoutException; @@ -25,7 +31,9 @@ import java.util.Map; import java.util.Optional; import java.util.UUID; +import java.util.stream.Stream; import javax.sql.DataSource; +import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementResponse; import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; @@ -54,8 +62,10 @@ 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.security.AccountPlayerAdmissionEntitlementWorkloadGuard; import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner; import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner.Request; +import net.firedevops.firemud.accountservice.service.impl.AccountPlayerAdmissionEntitlementGrpcService; import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier.VerifiedCaller; import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner.AuthenticatedSignerCorrespondence; @@ -65,6 +75,7 @@ import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Checkpoint; import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementGrpcCodec; import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; @@ -74,6 +85,7 @@ import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.shared.v1.ErrorDetail; import org.jooq.ConnectionRunnable; import org.jooq.DSLContext; import org.jooq.SQLDialect; @@ -82,9 +94,12 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.NullSource; import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.transaction.PlatformTransactionManager; @@ -515,6 +530,114 @@ void unavailableProtectedTargetReturnsNoValueOrAlternateEntitlementSource() thro assertThat(f.transactions.events).containsExactly("begin", "commit"); } + @ParameterizedTest + @MethodSource("protectedTargetFailures") + @SuppressWarnings("unchecked") + void protectedTargetFailuresKeepTheirClassificationThroughActualOwnerAndReceiver( + String stage, RuntimeException failure, io.grpc.Status.Code expected) throws Exception { + Fixture f = new Fixture(false); + var resolved = f.targets.resolvePublishedRealmAdmissionTarget(f.request.target()); + // Keep the strict selector stable: the controlled resolver otherwise installs a fresh read. + doReturn(resolved).when(f.targets).resolvePublishedRealmAdmissionTarget(f.request.target()); + if ("resolve".equals(stage)) { + doThrow(failure).when(f.targets).resolvePublishedRealmAdmissionTarget(any()); + } else { + doThrow(failure).when(f.targets).readPublishedRealmAdmissionOwner(any()); + } + clearInvocations(f.targets); + var direct = assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")); + if (expected == io.grpc.Status.Code.UNAVAILABLE) { + direct + .isExactlyInstanceOf( + AccountPlayerAdmissionEntitlementOwner.SourceUnavailableException.class) + .hasMessage("ENTITLEMENT_UNAVAILABLE: current player source evidence is unavailable") + .hasNoCause(); + } else { + direct.isSameAs(failure); + } + String token = "controlled-token.payload.signature"; + var caller = f.callers.verifyPresentedCompactToken("controlled-token"); + when(f.callers.verifyPresentedCompactToken(token)).thenReturn(caller); + try (var guards = + mockConstruction( + AccountPlayerAdmissionEntitlementWorkloadGuard.class, + (guard, context) -> + when(guard.requireAuthenticatedGameSessionCaller()).thenReturn(PEER))) { + var receiver = new AccountPlayerAdmissionEntitlementGrpcService(f.owner, "prod"); + StreamObserver observer = mock(StreamObserver.class); + receiver.readPlayerAdmissionEntitlement( + RuntimePlayerAdmissionEntitlementGrpcCodec.toRequest( + new RuntimePlayerAdmissionEntitlementGrpcCodec.Request( + f.request.target(), f.request.connectScopeId()), + token), + observer); + var refused = ArgumentCaptor.forClass(Throwable.class); + verify(observer).onError(refused.capture()); + var status = StatusProto.fromThrowable(refused.getValue()); + assertThat(status).isNotNull(); + assertThat(status.getCode()).isEqualTo(expected.value()); + String message = "Player-admission entitlement evidence is unavailable"; + assertThat(status.getMessage()).isEqualTo(message); + assertThat(status.getDetailsCount()).isOne(); + assertThat(status.getDetails(0).unpack(ErrorDetail.class)) + .isEqualTo(ErrorDetail.newBuilder().setCode(expected.name()).setMessage(message).build()); + assertThat(refused.getValue()).hasNoCause(); + assertThat(status.toString()) + .doesNotContain(token, f.scope.connectScopeId(), "private target detail"); + verify(observer, never()).onNext(any()); + verify(observer, never()).onCompleted(); + } + verify(f.targets, times(2)).resolvePublishedRealmAdmissionTarget(f.request.target()); + if ("strict".equals(stage)) { + verify(f.targets, times(2)).readPublishedRealmAdmissionOwner(resolved.strictSelector()); + } else { + verify(f.targets, never()).readPublishedRealmAdmissionOwner(any()); + } + verifyNoInteractions(f.demos, f.hosting, f.observer); + assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "commit"); + } + + private static Stream protectedTargetFailures() { + return Stream.of("resolve", "strict") + .flatMap( + stage -> { + Stream outages = + Stream.of( + new CanonicalGameplayAdmissionDecisionReadClient.ClientUnavailableException( + new IllegalStateException("private target detail")), + io.grpc.Status.UNAVAILABLE + .withDescription("private target detail") + .asRuntimeException(), + io.grpc.Status.DEADLINE_EXCEEDED + .withDescription("private target detail") + .asRuntimeException(), + io.grpc.Status.CANCELLED + .withDescription("private target detail") + .asRuntimeException(), + io.grpc.Status.ABORTED + .withDescription("private target detail") + .asRuntimeException()); + Stream unexpected = + Stream.of( + io.grpc.Status.INVALID_ARGUMENT + .withDescription("private target detail") + .asRuntimeException(), + io.grpc.Status.FAILED_PRECONDITION + .withDescription("private target detail") + .asRuntimeException(), + new IllegalArgumentException("private target detail"), + new IllegalStateException( + "Game Session returned invalid current target evidence", + new IllegalArgumentException("private target detail")), + new NullPointerException("private target detail")); + return Stream.concat( + outages.map( + failure -> Arguments.of(stage, failure, io.grpc.Status.Code.UNAVAILABLE)), + unexpected.map( + failure -> Arguments.of(stage, failure, io.grpc.Status.Code.INTERNAL))); + }); + } + @Test void changedOwnerPointerFailsExactRetainedTargetComparison() throws Exception { Fixture f = new Fixture(false); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java index 09b763e55d..a519e0097a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java @@ -20,6 +20,7 @@ import java.util.stream.Stream; import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementRequest; import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementResponse; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; import net.firedevops.firemud.accountservice.security.AccountPlayerAdmissionEntitlementWorkloadGuard; import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionLifecycleService; import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner; @@ -116,6 +117,13 @@ private static Stream ownerFailures new IllegalStateException("ENTITLEMENT_UNAVAILABLE: " + SECRET), Status.Code.INTERNAL), org.junit.jupiter.params.provider.Arguments.of( new IllegalArgumentException(SECRET), Status.Code.INTERNAL), + // Only the protected-target owner boundary may translate its transport failures. + org.junit.jupiter.params.provider.Arguments.of( + Status.UNAVAILABLE.withDescription(SECRET).asRuntimeException(), Status.Code.INTERNAL), + org.junit.jupiter.params.provider.Arguments.of( + new CanonicalGameplayAdmissionDecisionReadClient.ClientUnavailableException( + new IllegalStateException(SECRET)), + Status.Code.INTERNAL), org.junit.jupiter.params.provider.Arguments.of( new NullPointerException(SECRET), Status.Code.INTERNAL)); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java index 1e6c61309b..1df97d26bc 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java @@ -476,6 +476,7 @@ void directTextRechecksLiveInputsAfterRpc(String change) throws Exception { var calls = new AtomicInteger(); var observedJwt = new AtomicReference(); var observedPeer = new AtomicReference(); + var successfulResponses = new AtomicInteger(); Runnable afterRead = () -> { switch (change) { @@ -486,6 +487,7 @@ void directTextRechecksLiveInputsAfterRpc(String change) throws Exception { when(login.compactJwtBytes()).thenThrow(new IllegalStateException("Closed LOGIN")); default -> throw new IllegalArgumentException(change); } + successfulResponses.incrementAndGet(); }; Server server = server( @@ -500,10 +502,29 @@ void directTextRechecksLiveInputsAfterRpc(String change) throws Exception { afterRead); try (var client = client(server, movingClock)) { client.init(); - assertThatThrownBy( - () -> client.read(scope, ORIGINAL, TRANSPORT, READ_REQUEST, login, current::get)) - .isInstanceOf(RuntimeException.class); + var refusal = + assertThatThrownBy( + () -> client.read(scope, ORIGINAL, TRANSPORT, READ_REQUEST, login, current::get)); + switch (change) { + case "custody" -> + refusal + .isExactlyInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.CANCELLED)); + case "scope-expiry", "login-expiry" -> + refusal + .isExactlyInstanceOf(IllegalArgumentException.class) + .hasMessage("Exact authenticated lobby evidence required"); + case "closed-login" -> + refusal.isExactlyInstanceOf(IllegalStateException.class).hasMessage("Closed LOGIN"); + default -> throw new IllegalArgumentException(change); + } assertThat(calls).hasValue(1); + assertThat(successfulResponses).hasValue(1); + assertThat(observedJwt).hasValue(JWT); + assertThat(observedPeer).hasValue(GS_PEER); } finally { stop(server); } @@ -588,10 +609,12 @@ public void readPlayerAdmissionEntitlement( var presented = RuntimePlayerAdmissionEntitlementGrpcCodec.parseRequest(request); observedJwt.set(presented.initialLoginJwt()); var evidence = evidence(presented.request(), target, scopeExpiry, login, drift); - afterRead.run(); - observer.onNext( + // Live-input changes happen only after the successful response is fully encoded. + var response = RuntimePlayerAdmissionEntitlementGrpcCodec.toResponse( - presented.request(), evidence)); + presented.request(), evidence); + afterRead.run(); + observer.onNext(response); observer.onCompleted(); } catch (Exception malformed) { observer.onError( From 96f472e0f5392d57c75481691489958318448b09 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 8 Nov 2026 01:03:56 +1300 Subject: [PATCH 20/23] Tighten entitlement transaction and protected read error boundaries --- ...ostingSubscriptionLifecycleRepository.java | 10 +- ...ccountTenantOperationEntitlementOwner.java | 3 + ...titlementOwnerPostgresIntegrationTest.java | 46 +++++++++- ...ngSubscriptionLifecycleRepositoryTest.java | 42 +++++++++ ...ntTenantOperationEntitlementOwnerTest.java | 92 +++++++++++++++++++ ...AccountBootstrapRosterReadGrpcService.java | 3 +- ...AccountBootstrapRosterReadServiceTest.java | 7 +- ...antOperationEntitlementClientMtlsTest.java | 20 ++-- 8 files changed, 206 insertions(+), 17 deletions(-) create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerTest.java 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 c3e3b3117b..632732fc23 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 @@ -82,6 +82,11 @@ public ResolutionPreparation prepareTerminalResolution(Request request) { requireTransaction(); Objects.requireNonNull(request); var original = intents.findCreation(request.creationRequestId()).orElseThrow(); + if (!request.tenantId().equals(original.tenantId()) + || !request.subscriptionId().equals(original.subscriptionId()) + || !request.actorAccountId().equals(original.owner().accountUuid())) { + throw new FenceRejectedException("Exact same-owner terminal lifecycle target rejected"); + } Record journal = dsl.fetchOne( "SELECT * FROM subscription_lifecycle_terminal_resolutions WHERE resolution_request_id = ? FOR UPDATE", @@ -98,10 +103,7 @@ public ResolutionPreparation prepareTerminalResolution(Request request) { currentVersion = journal.get("result_row_version", Long.class); } Record failed = operationForUpdate(request.failedRequestId()); - if (!request.tenantId().equals(original.tenantId()) - || !request.subscriptionId().equals(original.subscriptionId()) - || !request.actorAccountId().equals(original.owner().accountUuid()) - || !request.creationRequestId().equals(failed.get("creation_request_id", UUID.class)) + if (!request.creationRequestId().equals(failed.get("creation_request_id", UUID.class)) || !request.subscriptionId().equals(failed.get("subscription_id", UUID.class)) || !"BILLING_RECONCILIATION_TERMINAL_FAILURE".equals(failed.get("state", String.class)) || request.expectedFailedOperationVersion() != failed.get("row_version", Long.class)) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwner.java index e528c7e1a1..a576f803db 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwner.java @@ -61,6 +61,9 @@ public AccountTenantOperationEntitlementOwner( .uri(); transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + transaction.setReadOnly(false); + transaction.setTimeout(5); } public RuntimeTenantOperationEntitlementEvidence evaluatePaid(Request request) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java index bff40315cc..6fc7537379 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java @@ -229,7 +229,11 @@ void controlledOwnerReceiverAndGameSessionClientComposeWithoutGrantingAdmission( assertThat(new String(received.canonicalBytes(), StandardCharsets.UTF_8)) .doesNotContain(CONTROLLED_COMPACT_TOKEN); assertThatThrownBy(() -> client.read(context, UUID.randomUUID(), login, () -> false)) - .isInstanceOf(RuntimeException.class); + .isExactlyInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(((io.grpc.StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(io.grpc.Status.Code.CANCELLED)); assertThat(f.dsl.fetchCount(DSL.table("account_tenant_membership"))) .isEqualTo(membershipsBefore); } finally { @@ -250,6 +254,46 @@ private static String controlledTokenDigest() { } } + @Test + void tenantOperationDemoCapturesCurrentSourceOnActualWritableSerializableConnection() { + Fixture f = fixture(false); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + f.dsl.connection( + connection -> { + assertThat(connection.getTransactionIsolation()) + .isEqualTo(Connection.TRANSACTION_SERIALIZABLE); + assertThat(connection.isReadOnly()).isFalse(); + }); + return invocation.callRealMethod(); + }) + .when(f.demos) + .readCurrent(f.tenantId); + var owner = + new AccountTenantOperationEntitlementOwner( + mock(AccountHostingSubscriptionLifecycleService.class), + f.demos, + new DataSourceTransactionManager(f.dataSource), + Clock.fixed(NOW, ZoneOffset.UTC), + NAMESPACE); + var request = + new AccountTenantOperationEntitlementOwner.Request( + f.tenantId, + UUID.randomUUID(), + "spiffe://firemud/ns/" + NAMESPACE + "/sa/world-management-service"); + + var evidence = owner.evaluateDemo(request); + + assertThat(evidence.fields()) + .containsEntry("variant", "TENANT_OPERATION") + .containsEntry("sourceKind", "NON_PAID_DEMO") + .containsEntry("tenantId", f.tenantId.toString()) + .containsEntry("requestId", request.requestId().toString()); + } + @Test void actualAbsenceBaselineReturnsNonadmittingPlayerEvidenceWithoutCreatingMembership() { Fixture f = fixture(false); 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 c12371cc58..3d6f9cb464 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 @@ -14,6 +14,7 @@ import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.util.List; +import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Disposition; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProvisioningClaim; @@ -136,6 +137,47 @@ void terminalResolutionCaptureAndApplyRequireWritableOwnerTransactionBeforeSql() verifyNoInteractions(dsl); } + @ParameterizedTest + @ValueSource(strings = {"tenant", "subscription", "actor"}) + void terminalResolutionRejectsWrongCallerOrTargetBeforeAnyJournalSqlOrLocks(String changed) { + var request = terminalRequest("Same-owner cancellation resolution"); + var original = mock(AccountSubscriptionCreationRecord.class); + when(original.tenantId()) + .thenReturn("tenant".equals(changed) ? UUID.randomUUID() : request.tenantId()); + when(original.subscriptionId()) + .thenReturn("subscription".equals(changed) ? UUID.randomUUID() : request.subscriptionId()); + when(original.owner()) + .thenReturn( + new AccountSubscriptionCreateRequest.OwnerFence( + "actor".equals(changed) ? UUID.randomUUID() : request.actorAccountId(), + 1, + UUID.randomUUID())); + var controlledIntents = mock(AccountSubscriptionIntentRepository.class); + when(controlledIntents.findCreation(request.creationRequestId())) + .thenReturn(Optional.of(original)); + var controlledRepository = + new AccountHostingSubscriptionLifecycleRepository( + dsl, + controlledIntents, + Clock.systemUTC(), + limits(3, 2, Duration.ofSeconds(10), Duration.ofSeconds(1), Duration.ofHours(1)), + new AccountHostingSubscriptionLifecyclePolicy( + Duration.ofSeconds(15), + new AccountHostingSubscriptionLifecyclePolicy.RecoveryTiming( + Duration.ofSeconds(60), Duration.ofSeconds(120))), + "prod", + false); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> controlledRepository.prepareTerminalResolution(request)) + .isExactlyInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class) + .hasMessage("Exact same-owner terminal lifecycle target rejected"); + + verify(controlledIntents).findCreation(request.creationRequestId()); + verifyNoMoreInteractions(controlledIntents); + verifyNoInteractions(dsl); + } + @Test void terminalResolutionReasonIsCanonicalBoundedScalarComparisonData() { var first = terminalRequest("e\u0301 reason"); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerTest.java new file mode 100644 index 0000000000..c2c35caf09 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerTest.java @@ -0,0 +1,92 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.intThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLTimeoutException; +import java.time.Clock; +import java.util.UUID; +import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionLifecycleService; +import net.firedevops.firemud.accountservice.service.AccountTenantOperationEntitlementOwner; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountTenantOperationEntitlementOwnerTest { + @Test + void demoUsesIndependentWritableSerializableTransactionAndPropagatesFiveSecondJdbcBudget() + throws Exception { + var dataSource = mock(DataSource.class); + var connection = mock(Connection.class); + var transactions = spy(new DataSourceTransactionManager(dataSource)); + var demos = mock(AccountDemoTenantEntitlementRepository.class); + var hosting = mock(AccountHostingSubscriptionLifecycleService.class); + UUID tenantId = UUID.randomUUID(); + var request = + new AccountTenantOperationEntitlementOwner.Request( + tenantId, UUID.randomUUID(), "spiffe://firemud/ns/prod/sa/world-management-service"); + try (var statement = mock(PreparedStatement.class)) { + when(dataSource.getConnection()).thenReturn(connection); + when(connection.getAutoCommit()).thenReturn(true, false); + when(connection.getTransactionIsolation()) + .thenReturn(Connection.TRANSACTION_READ_COMMITTED, Connection.TRANSACTION_SERIALIZABLE); + when(connection.prepareStatement(anyString())).thenReturn(statement); + when(statement.execute()).thenThrow(new SQLTimeoutException("Controlled timeout", "57014")); + // The actual Spring proxy carries the transaction timeout to jOOQ's JDBC statement. + // This driver is controlled; the PostgreSQL suite proves physical connection isolation. + var dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + when(demos.readCurrent(tenantId)) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + dsl.connection( + current -> + assertThat(current.getTransactionIsolation()) + .isEqualTo(Connection.TRANSACTION_SERIALIZABLE)); + dsl.execute("SELECT 1"); + throw new AssertionError("The controlled source statement must time out"); + }); + var owner = + new AccountTenantOperationEntitlementOwner( + hosting, demos, transactions, Clock.systemUTC(), "prod"); + + assertThatThrownBy(() -> owner.evaluateDemo(request)) + .isExactlyInstanceOf(DataAccessException.class) + .hasRootCauseExactlyInstanceOf(SQLTimeoutException.class); + + var definition = ArgumentCaptor.forClass(TransactionDefinition.class); + verify(transactions).getTransaction(definition.capture()); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getValue().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_SERIALIZABLE); + assertThat(definition.getValue().isReadOnly()).isFalse(); + assertThat(definition.getValue().getTimeout()).isEqualTo(5); + verify(connection).setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); + verify(statement).setQueryTimeout(intThat(seconds -> seconds > 0 && seconds <= 5)); + verify(connection).rollback(); + verifyNoInteractions(hosting); + } + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadGrpcService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadGrpcService.java index 161a73e449..05742f597d 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadGrpcService.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadGrpcService.java @@ -60,7 +60,8 @@ public void readAccountBootstrapRoster( | org.springframework.transaction.CannotCreateTransactionException unavailable) { refuse(observer, Status.UNAVAILABLE); return; - } catch (UnsupportedOperationException | IllegalStateException precondition) { + } catch (UnsupportedOperationException + | AccountBootstrapRosterReadService.TargetChangedException precondition) { refuse(observer, Status.FAILED_PRECONDITION); return; } catch (RuntimeException unexpected) { diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadServiceTest.java index a429711959..a7f3da5a89 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadServiceTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadServiceTest.java @@ -229,12 +229,15 @@ void receiverKeepsMalformedRequestsInvalidWithoutCallingService() throws Excepti @SuppressWarnings("unchecked") void receiverClassifiesStoredProjectionAndResponseValidationFailuresAsInternal() throws Exception { - for (boolean invalidProjection : List.of(false, true)) { + for (String invalidProjection : List.of("duplicate", "negative-level", "null-level")) { var f = AccountBootstrapRosterFixture.create(); var client = mock(GameSessionCanonicalGameplayRosterOwnerReadClient.class); var repository = mock(CharacterRepository.class); when(client.getCanonicalGameplayRosterOwnerRead(any())).thenReturn(f.evidence()); - if (invalidProjection) { + if ("null-level".equals(invalidProjection)) { + when(repository.readAccountBootstrapRoster(any(), any())) + .thenThrow(new IllegalStateException("CANONICAL_ROSTER_LEVEL_NULL")); + } else if ("negative-level".equals(invalidProjection)) { when(repository.readAccountBootstrapRoster(any(), any())) .thenAnswer( ignored -> diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClientMtlsTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClientMtlsTest.java index fd88b0d2f2..86690ef819 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClientMtlsTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClientMtlsTest.java @@ -251,6 +251,7 @@ void receiverRejectsMalformedUnknownDuplicateWrongNamespaceAndOversizedRequestsB for (var invalid : java.util.List.of( wire.toBuilder().clearSourceKind().build(), + wire.toBuilder().setSourceKind(0, "UNKNOWN_SOURCE").build(), wire.toBuilder().addRequestId(wire.getRequestId(0)).build(), wire.toBuilder().setUnknownFields(unknown).build())) { assertStatus( @@ -261,15 +262,16 @@ void receiverRejectsMalformedUnknownDuplicateWrongNamespaceAndOversizedRequestsB stub.readTenantOperationEntitlement( wire.toBuilder().setTargetNamespace(0, "other").build()), Status.Code.PERMISSION_DENIED); - assertThatThrownBy( - () -> - stub.readTenantOperationEntitlement( - wire.toBuilder().setSourceKind(0, "a".repeat(2048)).build())) - .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isIn(Status.Code.RESOURCE_EXHAUSTED, Status.Code.INVALID_ARGUMENT)); + var oversized = + wire.toBuilder() + .setSourceKind( + 0, + "a".repeat(RuntimeTenantOperationEntitlementGrpcCodec.MAX_REQUEST_WIRE_BYTES + 1)) + .build(); + assertThat(oversized.getSerializedSize()) + .isGreaterThan(RuntimeTenantOperationEntitlementGrpcCodec.MAX_REQUEST_WIRE_BYTES); + assertStatus( + () -> stub.readTenantOperationEntitlement(oversized), Status.Code.RESOURCE_EXHAUSTED); org.mockito.Mockito.verifyNoInteractions(owner); } finally { channel.shutdownNow(); From 77df393a206c35f0b8f1a53349889dc83d88c019 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 8 Nov 2026 01:52:12 +1300 Subject: [PATCH 21/23] Align entitlement target outcomes and canonical evidence bounds --- .../player-access-and-session.md | 2 +- ...ccountPlayerAdmissionEntitlementOwner.java | 32 ++++-- ...PlayerAdmissionEntitlementGrpcService.java | 3 + ...ntPlayerAdmissionEntitlementOwnerTest.java | 108 ++++++++++++++---- ...erAdmissionEntitlementGrpcServiceTest.java | 6 + ...imePlayerAdmissionEntitlementEvidence.java | 14 +++ ...layerAdmissionEntitlementEvidenceTest.java | 49 ++++++++ 7 files changed, 185 insertions(+), 29 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 4617feca46..d4e6960bbe 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -54,7 +54,7 @@ Paid-provider observation remains an activation blocker owned by Account billing The current SDK transport uses socket timeouts while consuming the complete response; the [current-read fence](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java) carries no retained policy budget, and the discovery owner has no provider-latency/429 instrumentation or fleet-wide provider-rate qualification. Before paid facade registration, the owners must complete the linked deadline, retained-policy, load and telemetry gates and their physical proof in the canonical subscription receiver. That receiver's missing V1028–V1032 schema and the unregistered runtime composition leave the complete boundary unqualified here. No cache or registration is supplied. This handoff preserves an open implementation obligation; it does not classify the socket-timeout change as a completed activation fix. -The source owner refuses ambient Account SQL and requires a workload-only `SessionContext` for its Game Session call; it rejects authenticated caller and internal-service contexts. Facade integration must satisfy that guard without clearing or bypassing caller security context, and is not established by this unregistered composition. The Game Session read is the exact same-namespace Account mTLS source and now prepares the complete visible public-production `SHARED` collection for both `PRESEEDED_ONLY` and `PLAYER_CREATED`. It preserves complete canonical identity/namespace checks, committed owner/no-abort evidence, tenant UUID/slug and realm uniqueness, bounded closed frames and two complete reads with whole-set equality. Strict target selection, roster and admission remain `PRESEEDED_ONLY`. The owning contract is [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md#public-production-bootstrap-target-collection-read); the expanded collection passes the selected closed-codec, owner and receiver tests recorded above. Neither owner supplies a fresh World lifecycle read or hold, and this source does not issue a scope, perform JOIN, or admit gameplay. +The source owner refuses ambient Account SQL and requires a workload-only `SessionContext` for its Game Session call; it rejects authenticated caller and internal-service contexts. Facade integration must satisfy that guard without clearing or bypassing caller security context, and is not established by this unregistered composition. The Game Session read is the exact same-namespace Account mTLS source and now prepares the complete visible public-production `SHARED` collection for both `PRESEEDED_ONLY` and `PLAYER_CREATED`. It preserves complete canonical identity/namespace checks, committed owner/no-abort evidence, tenant UUID/slug and realm uniqueness, bounded closed frames and two complete reads with whole-set equality. Strict target selection, roster and admission remain `PRESEEDED_ONLY`. The owning contract is [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md#public-production-bootstrap-target-collection-read). Focused mixed-policy proof sources are `AccountPublicBootstrapWorldsOwnerTest.mixedPublicCreationPoliciesBothParticipateInCompleteWorldDiscovery` and `CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.discoveryReturnsCompletePlayerCreatedAndMixedPolicyCollectionsOnBothReads`; `CanonicalGameplayAdmissionDecisionReadGrpcCodecTest.discoveryCarriesBothSupportedPublicCreationPoliciesWithoutChangingTargetEvidence` separately covers each supported policy. The CLI12 focused receiving run passes these named cases among 194 selected cases (102 Account, 74 Game Session and 18 Common Security), with no failures, errors or skips; the historical 523-case foundation run is not attributed as their proof. Neither owner supplies a fresh World lifecycle read or hold, and this source does not issue a scope, perform JOIN, or admit gameplay. Earlier component proof is bounded by the [Account discovery-owner tests](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java), [entitlement-owner tests](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwnerTest.java), [Account target-client tests](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClientTest.java), [Game Session collection-read tests](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java), and [workload-guard tests](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayAdmissionDecisionReadWorkloadGuardTest.java). The prior affected regression run passed 76 selected Account and Game Session cases without failures, errors or skips, plus enabled affected static analysis, formatting and documentation checks. It covers concurrent requests across separate owners, unchanged target projection and sanitized dependency failures, not the local mixed-policy addition. Retained physical proof passed all 10 [Account DEMO discovery and scope PostgreSQL cases](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java), including deterministic filtering, source-head drift, expiry refusal and immutable rows. Earlier broader unit, loopback-mTLS and final-admission composition runs overlap this coverage and are not additive or a current whole-system qualification. The PostgreSQL discovery tests use controlled Game Session responses; client mTLS tests use a controlled Game Session server, and final-admission composition uses a controlled World capture. These proofs do not establish the complete authenticated cross-owner source chain, deployment custody, paid discovery activation or production capacity. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java index 3fd6669121..bb0d77e073 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java @@ -354,7 +354,6 @@ private CurrentPlayer readCurrentPlayer(Request request, VerifiedCaller caller) .findCanonicalEvidenceByTokenHash(AccountJoinDigest.tokenHash(request.connectScopeId())) .orElseThrow(AccountPlayerAdmissionEntitlementOwner::unavailable); if (!"PUBLIC_PRODUCTION".equals(scope.targetClass()) - || !"SHARED".equals(scope.playableStateScope()) || scope.tenantProvenance().kind() != TenantProvenanceKind.FRESH_GAME_DESIGN || scope.tenantProvenance().legacyTenantId() != null || !accountId.equals(scope.accountUuid()) @@ -363,7 +362,8 @@ private CurrentPlayer readCurrentPlayer(Request request, VerifiedCaller caller) || !Objects.equals(account.getId(), scope.privateAccountId())) { throw unavailable(); } - if (!request.target().equals(selector(request, scope))) throw unavailable(); + if (!"SHARED".equals(scope.playableStateScope())) throw targetPrecondition(); + if (!request.target().equals(selector(request, scope))) throw targetPrecondition(); return new CurrentPlayer(snapshot, scope, current); } @@ -468,6 +468,18 @@ public SourceUnavailableException() { } } + private static TargetPreconditionException targetPrecondition() { + return new TargetPreconditionException(); + } + + /** The current target is unsupported or differs from the exact retained selectors. */ + public static final class TargetPreconditionException extends IllegalStateException { + public TargetPreconditionException() { + super( + "ENTITLEMENT_TARGET_PRECONDITION: current target does not match the supported retained target"); + } + } + private void requireSameHead(Request request, SourceSelection selected) { SourceSelection current = sources.readCurrentSourceSelection(request.tenantId()); if (selected.kind() != current.kind() || !selected.matches(current.checkpoint())) @@ -528,15 +540,20 @@ private PublishedRealmEvidence readProtectedTarget( var selector = selector(request, scope); try { var resolved = Objects.requireNonNull(targets.resolvePublishedRealmAdmissionTarget(selector)); - if (!selector.equals(resolved.selector())) throw unavailable(); + if (!selector.equals(resolved.selector())) throw targetPrecondition(); requireSupportedTarget(resolved.currentTarget()); - CanonicalGameplayAdmissionDecisionReadGrpcCodec.requireRetainedTargetMatches( - selector, resolved.currentTarget()); + try { + CanonicalGameplayAdmissionDecisionReadGrpcCodec.requireRetainedTargetMatches( + selector, resolved.currentTarget()); + } catch (IllegalArgumentException changedTarget) { + // Only this exact target comparison is a precondition, not arbitrary codec failures. + throw targetPrecondition(); + } var result = Objects.requireNonNull( targets.readPublishedRealmAdmissionOwner(resolved.strictSelector())); if (!resolved.strictSelector().equals(result.selector()) - || !resolved.currentTarget().equals(result.currentTarget())) throw unavailable(); + || !resolved.currentTarget().equals(result.currentTarget())) throw targetPrecondition(); requireSupportedTarget(result.currentTarget()); return result; } catch (CanonicalGameplayAdmissionDecisionReadClient.ClientUnavailableException failure) { @@ -544,6 +561,7 @@ private PublishedRealmEvidence readProtectedTarget( } catch (StatusRuntimeException failure) { switch (failure.getStatus().getCode()) { case UNAVAILABLE, DEADLINE_EXCEEDED, CANCELLED, ABORTED -> throw unavailable(); + case FAILED_PRECONDITION -> throw targetPrecondition(); default -> throw failure; } } @@ -552,7 +570,7 @@ private PublishedRealmEvidence readProtectedTarget( private static void requireSupportedTarget( CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target target) { if (!"SHARED".equals(target.playableStateScope()) - || !"PRESEEDED_ONLY".equals(target.characterCreationPolicy())) throw unavailable(); + || !"PRESEEDED_ONLY".equals(target.characterCreationPolicy())) throw targetPrecondition(); } private static RuntimePlayerAdmissionEntitlementEvidence capture( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java index a6b37bd0f4..1a4efe1a70 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java @@ -102,6 +102,9 @@ public void readPlayerAdmissionEntitlement( request.target(), request.connectScopeId(), authenticatedCaller); var evidence = owner.evaluate(sourceRequest, presented.initialLoginJwt()); response = RuntimePlayerAdmissionEntitlementGrpcCodec.toResponse(request, evidence); + } catch (AccountPlayerAdmissionEntitlementOwner.TargetPreconditionException rejectedTarget) { + fail(observer, Status.FAILED_PRECONDITION); + return; } catch (AccountPlayerAdmissionEntitlementOwner.SourceUnavailableException | AccountGameplayAdmissionCallerVerifier.CallerUnavailableException | AccountHostingSubscriptionLifecycleService.EntitlementUnavailableException diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java index e577f8de6c..400ad928b7 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java @@ -532,7 +532,6 @@ void unavailableProtectedTargetReturnsNoValueOrAlternateEntitlementSource() thro @ParameterizedTest @MethodSource("protectedTargetFailures") - @SuppressWarnings("unchecked") void protectedTargetFailuresKeepTheirClassificationThroughActualOwnerAndReceiver( String stage, RuntimeException failure, io.grpc.Status.Code expected) throws Exception { Fixture f = new Fixture(false); @@ -552,9 +551,28 @@ void protectedTargetFailuresKeepTheirClassificationThroughActualOwnerAndReceiver AccountPlayerAdmissionEntitlementOwner.SourceUnavailableException.class) .hasMessage("ENTITLEMENT_UNAVAILABLE: current player source evidence is unavailable") .hasNoCause(); + } else if (expected == io.grpc.Status.Code.FAILED_PRECONDITION) { + direct + .isExactlyInstanceOf( + AccountPlayerAdmissionEntitlementOwner.TargetPreconditionException.class) + .hasNoCause(); } else { direct.isSameAs(failure); } + assertReceiverRefusal(f, expected); + verify(f.targets, times(2)).resolvePublishedRealmAdmissionTarget(f.request.target()); + if ("strict".equals(stage)) { + verify(f.targets, times(2)).readPublishedRealmAdmissionOwner(resolved.strictSelector()); + } else { + verify(f.targets, never()).readPublishedRealmAdmissionOwner(any()); + } + verifyNoInteractions(f.demos, f.hosting, f.observer); + assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "commit"); + } + + @SuppressWarnings("unchecked") + private static void assertReceiverRefusal(Fixture f, io.grpc.Status.Code expected) + throws Exception { String token = "controlled-token.payload.signature"; var caller = f.callers.verifyPresentedCompactToken("controlled-token"); when(f.callers.verifyPresentedCompactToken(token)).thenReturn(caller); @@ -587,14 +605,6 @@ void protectedTargetFailuresKeepTheirClassificationThroughActualOwnerAndReceiver verify(observer, never()).onNext(any()); verify(observer, never()).onCompleted(); } - verify(f.targets, times(2)).resolvePublishedRealmAdmissionTarget(f.request.target()); - if ("strict".equals(stage)) { - verify(f.targets, times(2)).readPublishedRealmAdmissionOwner(resolved.strictSelector()); - } else { - verify(f.targets, never()).readPublishedRealmAdmissionOwner(any()); - } - verifyNoInteractions(f.demos, f.hosting, f.observer); - assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "commit"); } private static Stream protectedTargetFailures() { @@ -622,17 +632,22 @@ private static Stream protectedTargetFailures() { io.grpc.Status.INVALID_ARGUMENT .withDescription("private target detail") .asRuntimeException(), - io.grpc.Status.FAILED_PRECONDITION - .withDescription("private target detail") - .asRuntimeException(), new IllegalArgumentException("private target detail"), new IllegalStateException( "Game Session returned invalid current target evidence", new IllegalArgumentException("private target detail")), new NullPointerException("private target detail")); return Stream.concat( - outages.map( - failure -> Arguments.of(stage, failure, io.grpc.Status.Code.UNAVAILABLE)), + Stream.concat( + outages.map( + failure -> Arguments.of(stage, failure, io.grpc.Status.Code.UNAVAILABLE)), + Stream.of( + Arguments.of( + stage, + io.grpc.Status.FAILED_PRECONDITION + .withDescription("private target detail") + .asRuntimeException(), + io.grpc.Status.Code.FAILED_PRECONDITION))), unexpected.map( failure -> Arguments.of(stage, failure, io.grpc.Status.Code.INTERNAL))); }); @@ -660,8 +675,53 @@ void changedOwnerPointerFailsExactRetainedTargetComparison() throws Exception { when(resolved.currentTarget().pointerVersion()).thenReturn(f.scope.pointerVersion() + 1); doReturn(resolved).when(f.targets).resolvePublishedRealmAdmissionTarget(selector); assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) - .hasMessageContaining("retained"); + .isExactlyInstanceOf( + AccountPlayerAdmissionEntitlementOwner.TargetPreconditionException.class) + .hasNoCause(); + assertReceiverRefusal(f, io.grpc.Status.Code.FAILED_PRECONDITION); + verifyNoInteractions(f.demos, f.hosting, f.observer); + } + + @ParameterizedTest + @ValueSource(strings = {"resolved-selector", "strict-selector", "strict-target", "current-scope"}) + void changedProtectedTargetComparisonsRemainPreconditionsThroughOwnerAndReceiver(String change) + throws Exception { + Fixture f = new Fixture(false); + var resolved = f.targets.resolvePublishedRealmAdmissionTarget(f.request.target()); + var read = f.targets.readPublishedRealmAdmissionOwner(resolved.strictSelector()); + doReturn(resolved).when(f.targets).resolvePublishedRealmAdmissionTarget(f.request.target()); + clearInvocations(f.targets); + switch (change) { + case "resolved-selector" -> + when(resolved.selector()) + .thenReturn( + mock( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector + .class)); + case "strict-selector" -> + when(read.selector()) + .thenReturn(mock(CanonicalGameplayRosterOwnerReadEvidence.Request.class)); + case "strict-target" -> + when(read.currentTarget()) + .thenReturn(mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target.class)); + case "current-scope" -> + when(resolved.currentTarget().playableStateScope()).thenReturn("ISOLATED"); + default -> throw new AssertionError("Unknown controlled target change"); + } + + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .isExactlyInstanceOf( + AccountPlayerAdmissionEntitlementOwner.TargetPreconditionException.class) + .hasNoCause(); + assertReceiverRefusal(f, io.grpc.Status.Code.FAILED_PRECONDITION); + verify(f.targets, times(2)).resolvePublishedRealmAdmissionTarget(f.request.target()); + if (change.startsWith("strict-")) { + verify(f.targets, times(2)).readPublishedRealmAdmissionOwner(resolved.strictSelector()); + } else { + verify(f.targets, never()).readPublishedRealmAdmissionOwner(any()); + } verifyNoInteractions(f.demos, f.hosting, f.observer); + assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "commit"); } @ParameterizedTest @@ -675,12 +735,14 @@ void unsupportedCurrentPolicyCannotBecomePreseededPlayerEvidence(String policy) assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) .isExactlyInstanceOf( - AccountPlayerAdmissionEntitlementOwner.SourceUnavailableException.class); + AccountPlayerAdmissionEntitlementOwner.TargetPreconditionException.class) + .hasNoCause(); + assertReceiverRefusal(f, io.grpc.Status.Code.FAILED_PRECONDITION); org.mockito.Mockito.verify(f.targets, org.mockito.Mockito.never()) .readPublishedRealmAdmissionOwner(any()); verifyNoInteractions(f.demos, f.hosting, f.observer); - assertThat(f.transactions.events).containsExactly("begin", "commit"); + assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "commit"); } @Test @@ -689,10 +751,12 @@ void isolatedRetainedScopeFailsBeforeProtectedTargetOrEntitlementCapture() throw assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) .isExactlyInstanceOf( - AccountPlayerAdmissionEntitlementOwner.SourceUnavailableException.class); + AccountPlayerAdmissionEntitlementOwner.TargetPreconditionException.class) + .hasNoCause(); + assertReceiverRefusal(f, io.grpc.Status.Code.FAILED_PRECONDITION); verifyNoInteractions(f.targets, f.sources, f.demos, f.hosting, f.observer); - assertThat(f.transactions.events).containsExactly("begin", "rollback"); + assertThat(f.transactions.events).containsExactly("begin", "rollback", "begin", "rollback"); } @Test @@ -710,10 +774,12 @@ void protectedReadCannotReplaceSupportedPolicyBeforeEvidenceCapture() throws Exc assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) .isExactlyInstanceOf( - AccountPlayerAdmissionEntitlementOwner.SourceUnavailableException.class); + AccountPlayerAdmissionEntitlementOwner.TargetPreconditionException.class) + .hasNoCause(); + assertReceiverRefusal(f, io.grpc.Status.Code.FAILED_PRECONDITION); verifyNoInteractions(f.demos, f.hosting, f.observer); - assertThat(f.transactions.events).containsExactly("begin", "commit"); + assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "commit"); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java index a519e0097a..a6b0fc81aa 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java @@ -88,6 +88,9 @@ void ownerFailuresRetainExactAvailabilityClassificationWithoutSourceDetails( private static Stream ownerFailures() { return Stream.of( + org.junit.jupiter.params.provider.Arguments.of( + new AccountPlayerAdmissionEntitlementOwner.TargetPreconditionException(), + Status.Code.FAILED_PRECONDITION), org.junit.jupiter.params.provider.Arguments.of( new AccountPlayerAdmissionEntitlementOwner.SourceUnavailableException(), Status.Code.UNAVAILABLE), @@ -120,6 +123,9 @@ private static Stream ownerFailures // Only the protected-target owner boundary may translate its transport failures. org.junit.jupiter.params.provider.Arguments.of( Status.UNAVAILABLE.withDescription(SECRET).asRuntimeException(), Status.Code.INTERNAL), + org.junit.jupiter.params.provider.Arguments.of( + Status.FAILED_PRECONDITION.withDescription(SECRET).asRuntimeException(), + Status.Code.INTERNAL), org.junit.jupiter.params.provider.Arguments.of( new CanonicalGameplayAdmissionDecisionReadClient.ClientUnavailableException( new IllegalStateException(SECRET)), diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java index ced10986f5..a522ead2f2 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java @@ -122,6 +122,14 @@ public static RuntimePlayerAdmissionEntitlementEvidence fromOwnerEvaluation( Map source, Instant evaluatedAt) { Objects.requireNonNull(membership); + for (List bounded : + List.of( + membership.roles(), + membership.checkpoints(), + membership.sourceEvidence(), + membership.authorityTuple().privateRealmGrantVersions())) { + if (bounded.size() > 16) throw invalid("Bounded list required"); + } RuntimeMembershipAuthorityEvidenceValidator.validate(membership); requireUuid(membership.accountId()); requireUuid(membership.tenantId()); @@ -260,6 +268,12 @@ public static RuntimePlayerAdmissionEntitlementEvidence fromOwnerEvaluation( evaluatedAt.toString()))); byte[] bytes = canonical(fields); if (bytes.length > MAX_CANONICAL_BYTES) throw invalid("Player evidence exceeds size bound"); + // Apply the decoder's exact JSON limits without recursively invoking parseCanonical. + try { + if (!JSON.readTree(bytes).isObject()) throw invalid("Player evidence object required"); + } catch (RuntimeException malformed) { + throw invalid("Player evidence exceeds decoder constraints"); + } return new RuntimePlayerAdmissionEntitlementEvidence(membership, bytes); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java index 32ca98404d..88367c3487 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java @@ -51,6 +51,55 @@ void canonicalVariantRetainsExplicitAbsenceAndCompleteApplicableAuthority() { .isInstanceOf(IllegalArgumentException.class); } + @Test + void ownerEmissionUsesTheDecoderStringLimitBeforeReturningEvidence() { + var atLimit = target(); + atLimit.put("worldSlug", "a".repeat(65536)); + var value = capture(atLimit, facts(), sources(), NOW); + assertThat( + RuntimePlayerAdmissionEntitlementEvidence.parseCanonical(value.canonicalBytes()) + .canonicalBytes()) + .containsExactly(value.canonicalBytes()); + var tooLong = target(); + tooLong.put("worldSlug", "a".repeat(65537)); + assertThatThrownBy(() -> capture(tooLong, facts(), sources(), NOW)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Player evidence exceeds decoder constraints"); + } + + @Test + void ownerEmissionRejectsOversizedRoleInventoryBeforeReturningEvidence() { + var original = membership(); + var oversized = + new Snapshot( + original.issuerId(), + original.accountId(), + original.tenantId(), + original.membershipExists(), + original.membershipLifecycleState(), + original.gameplayAdmissionAllowed(), + original.membershipVersion(), + original.membershipAuthorityGeneration(), + java.util.stream.IntStream.range(0, 17).mapToObj(i -> "role" + i).toList(), + original.authorityTuple(), + original.issuanceFence(), + original.checkpoints(), + original.sourceEvidence()); + assertThatThrownBy( + () -> + RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( + REQUEST, + PEER, + "controlled-scope", + oversized, + target(), + facts(), + sources(), + NOW)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Bounded list required"); + } + @Test void identitiesBindActualInputsAndSeparateSnapshotFromEvaluation() { var first = capture(target(), facts(), sources(), NOW); From 06f980831d9e95976c0a09997542f4aafbc19052 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 8 Nov 2026 02:59:40 +1300 Subject: [PATCH 22/23] Distinguish roster server faults and sharpen admission proof --- .../AccountBootstrapRosterReadService.java | 3 +- ...AccountBootstrapRosterReadServiceTest.java | 44 ++++++++++++++++++- ...ssionBarrierRepositoryIntegrationTest.java | 3 ++ ...yerAdmissionEntitlementClientMtlsTest.java | 41 +++++++++++++++-- 4 files changed, 86 insertions(+), 5 deletions(-) diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadService.java index a4e104cfcc..245d1c3885 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadService.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadService.java @@ -83,7 +83,8 @@ private void requireCurrent( public static void requireNoAmbientTransaction() { if (TransactionSynchronizationManager.isActualTransactionActive() || TransactionSynchronizationManager.isSynchronizationActive()) { - throw new TargetChangedException(); + throw new IllegalStateException( + "Account bootstrap roster read requires no ambient transaction or synchronization"); } } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadServiceTest.java index a7f3da5a89..7a170ef426 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadServiceTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadServiceTest.java @@ -36,6 +36,8 @@ import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadResponse; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.AbstractPlatformTransactionManager; @@ -88,6 +90,7 @@ void realAdapterReadsCurrentSourceBeforeAndAfterShortLocalProjectionIncludingEmp } @Test + @SuppressWarnings("unchecked") void sourceChangedBeforeSqlOrDuringProjectionNeverReturnsEmptySuccess() throws Exception { var f = AccountBootstrapRosterFixture.create(); var changed = @@ -102,6 +105,11 @@ void sourceChangedBeforeSqlOrDuringProjectionNeverReturnsEmptySuccess() throws E when(client.getCanonicalGameplayRosterOwnerRead(any())).thenReturn(changed); assertThatThrownBy(() -> service.read(f.request())) .isInstanceOf(AccountBootstrapRosterReadService.TargetChangedException.class); + var receiver = + new AccountBootstrapRosterReadGrpcService(service, AccountBootstrapRosterFixture.NAMESPACE); + StreamObserver observer = mock(StreamObserver.class); + withControlledAccountPeer(() -> receiver.readAccountBootstrapRoster(f.request(), observer)); + assertReceiverFailure(observer, Status.Code.FAILED_PRECONDITION); verifyNoInteractions(repository); when(client.getCanonicalGameplayRosterOwnerRead(any())).thenReturn(f.evidence(), changed); when(repository.readAccountBootstrapRoster(any(), any())).thenReturn(List.of()); @@ -160,11 +168,45 @@ void malformedUnsupportedAndAmbientTransactionRefuseBeforeAnySourceOrSql() throw .executeWithoutResult( ignored -> { assertThatThrownBy(() -> service.read(f.request())) - .isInstanceOf(AccountBootstrapRosterReadService.TargetChangedException.class); + .isExactlyInstanceOf(IllegalStateException.class) + .hasMessage( + "Account bootstrap roster read requires no ambient transaction or synchronization") + .hasNoCause(); }); verifyNoInteractions(client, repository); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + @SuppressWarnings("unchecked") + void ambientTransactionOrSynchronizationIsInternalBeforeAnySourceOrSql(boolean transactionActive) + throws Exception { + var f = AccountBootstrapRosterFixture.create(); + var client = mock(GameSessionCanonicalGameplayRosterOwnerReadClient.class); + var repository = mock(CharacterRepository.class); + var service = service(client, repository); + var receiver = + new AccountBootstrapRosterReadGrpcService(service, AccountBootstrapRosterFixture.NAMESPACE); + StreamObserver observer = mock(StreamObserver.class); + TransactionSynchronizationManager.setActualTransactionActive(transactionActive); + if (!transactionActive) TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> service.read(f.request())) + .isExactlyInstanceOf(IllegalStateException.class) + .hasMessage( + "Account bootstrap roster read requires no ambient transaction or synchronization") + .hasNoCause(); + + withControlledAccountPeer(() -> receiver.readAccountBootstrapRoster(f.request(), observer)); + + assertReceiverFailure(observer, Status.Code.INTERNAL); + verifyNoInteractions(client, repository); + } finally { + if (!transactionActive) TransactionSynchronizationManager.clearSynchronization(); + TransactionSynchronizationManager.setActualTransactionActive(false); + } + } + @Test void exactEchoClosedActorBoundsCanonicalIdsAndDeterministicOrderAreRequired() throws Exception { var f = AccountBootstrapRosterFixture.create(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java index b133218bff..38387b4fc1 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java @@ -296,6 +296,9 @@ public void executeStart(ExecuteContext context) { var secondClaim = executor.submit(() -> retainedRepository.claimFirstCreatePermit(second)); assertThat(retainedMappingLocked.await(10, TimeUnit.SECONDS)).isTrue(); var firstClaim = executor.submit(() -> assignmentRepository.claimFirstCreatePermit(first)); + assertThat(assignmentLockAttempted.await(10, TimeUnit.SECONDS)) + .as("Assignment claim must reach its lock attempt before the retained claim can finish") + .isTrue(); assertThat(secondClaim.get(10, TimeUnit.SECONDS)).isTrue(); assertThat(firstClaim.get(10, TimeUnit.SECONDS)).isFalse(); assertThat(initializationState(state, operationId)).isEqualTo("INITIALIZING"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java index 1df97d26bc..196fb522d1 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java @@ -370,9 +370,44 @@ void directTextInvalidOrStaleInputsDiscloseNoCredential(String change) throws Ex server("account", calls, observedJwt, observedPeer, context(), login.evidence()); try (var client = client(server, clientClock)) { client.init(); - assertThatThrownBy( - () -> client.read(scope, original, transport, selectedReadId, login, current)) - .isInstanceOf(RuntimeException.class); + var refusal = + assertThatThrownBy( + () -> client.read(scope, original, transport, selectedReadId, login, current)) + .as(change); + switch (change) { + case "stale-custody", "throwing-custody", "null-custody", "custody-lost-before-rpc" -> + refusal + .isExactlyInstanceOf(StatusRuntimeException.class) + .hasMessage("CANCELLED: Account player-admission entitlement read did not complete") + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.CANCELLED)); + case "original-request", + "original-context", + "attempt-fence", + "transport-session", + "transport-proxy", + "expired-login", + "expired-scope" -> + refusal + .isExactlyInstanceOf(IllegalArgumentException.class) + .hasMessage("Exact authenticated lobby evidence required"); + case "closed-login" -> + refusal + .isExactlyInstanceOf(IllegalStateException.class) + .hasMessage("Controlled closed LOGIN"); + case "wrong-namespace", + "private-scope", + "created-policy", + "durable-abort", + "read-correlation" -> + refusal + .isExactlyInstanceOf(IllegalArgumentException.class) + .hasMessage( + "Exact live LOGIN custody and verified player-admission scope required"); + default -> throw new IllegalArgumentException(change); + } assertThat(calls).hasValue(0); assertThat(observedJwt).hasValue(null); assertThat(observedPeer).hasValue(null); From 7bdf6ed50397a0e67e37d5661e7a90c71e7c4b9f Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 8 Nov 2026 09:40:49 +1300 Subject: [PATCH 23/23] Fix Account JWKS outage classification and close review proof gaps --- ...ostingSubscriptionLifecycleRepository.java | 8 +++-- .../session/AccountJwtJwksTrustedSource.java | 5 ++++ ...StripeBillingPrerequisiteObserverTest.java | 29 +++++++++++++++++++ .../AccountJwtJwksTrustedSourceTest.java | 21 ++++++++++++++ ...yerAdmissionEntitlementClientMtlsTest.java | 22 ++++++++++++++ 5 files changed, 83 insertions(+), 2 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java index 632732fc23..4ce8feca92 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 @@ -168,8 +168,12 @@ public ResolutionPreparation prepareTerminalResolution(Request request) { /** * Final cancellation-only owner mutation. The mandatory callback runs under exact target locks - * immediately before writes; callback inputs/outputs alone do not establish Account authority. - * The caller must roll back the transaction on every failure, including callback/commit failure. + * immediately before writes; callback inputs/outputs alone do not establish Account authority. If + * the callback throws an authentication denial, the caller may catch it outside this method and + * commit its own failed-login accounting because this method has made no repository writes before + * invoking the callback. A repository write added before the callback removes this narrow + * exception; all other failures require rollback. Commit failures remain the caller transaction + * manager’s responsibility. */ public TransitionResult applyTerminalResolution( ResolutionPreparation prepared, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java index 03f9b957c7..5f1c502a44 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java @@ -34,6 +34,7 @@ import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceUnavailableException; import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionException; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; import tools.jackson.core.StreamReadFeature; @@ -304,6 +305,10 @@ private OwnerProjection currentOwnerProjection(Binding binding, BindingIdentity throw unavailable(); } return result; + } catch (org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException + | TransactionException ownerStateUnavailable) { + throw unavailable(); } catch (RuntimeException ownerStateUnavailable) { if (ownerStateUnavailable instanceof SourceUnavailableException unavailable) { throw unavailable; diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeBillingPrerequisiteObserverTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeBillingPrerequisiteObserverTest.java index 42ab782925..4e76953162 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeBillingPrerequisiteObserverTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeBillingPrerequisiteObserverTest.java @@ -86,6 +86,29 @@ void retrievesBothExactObjectsThroughSdkAndReturnsOnlyBoundedImmutableEvidence() Instant.class)); } + @Test + void propagatesCallerTransportOptionsToBothStripeReads() { + ControlledStripeTransport transport = + new ControlledStripeTransport(customerResponse(), paymentMethodResponse()); + RequestOptions options = + RequestOptions.builder() + .setConnectTimeout(1_234) + .setReadTimeout(5_678) + .setMaxNetworkRetries(2) + .build(); + + observer(transport, fixedClock()).observe(expected(), options); + + assertEquals(2, transport.requestOptions().size()); + assertTrue(transport.requestOptions().stream().allMatch(received -> received == options)); + assertEquals(1_234, transport.requestOptions().get(0).getConnectTimeout()); + assertEquals(5_678, transport.requestOptions().get(0).getReadTimeout()); + assertEquals(2, transport.requestOptions().get(0).getMaxNetworkRetries()); + assertEquals(1_234, transport.requestOptions().get(1).getConnectTimeout()); + assertEquals(5_678, transport.requestOptions().get(1).getReadTimeout()); + assertEquals(2, transport.requestOptions().get(1).getMaxNetworkRetries()); + } + @Test void rejectsDeletedMismatchedModeAndWrongCustomerObjectsOrIDs() { assertInvalid( @@ -397,6 +420,7 @@ private static final class ControlledStripeTransport implements StripeResponseGe private final java.util.ArrayList paths = new java.util.ArrayList<>(); private final java.util.ArrayList methods = new java.util.ArrayList<>(); private final java.util.ArrayList> parameters = new java.util.ArrayList<>(); + private final java.util.ArrayList requestOptions = new java.util.ArrayList<>(); private ControlledStripeTransport(String customerResponse, String paymentMethodResponse) { this(customerResponse, paymentMethodResponse, null, null); @@ -434,6 +458,7 @@ public T request( paths.add(requestPath); methods.add(requestMethod); parameters.add(params == null ? Map.of() : Map.copyOf(params)); + requestOptions.add(options); if (requestPath.equals(failurePath)) { throw failure; } @@ -471,5 +496,9 @@ private List methods() { private List> parameters() { return List.copyOf(parameters); } + + private List requestOptions() { + return List.copyOf(requestOptions); + } } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java index 509d581672..3e84bf697e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java @@ -41,7 +41,9 @@ import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceUnavailableException; import org.junit.jupiter.api.Test; +import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionException; import org.springframework.transaction.support.SimpleTransactionStatus; class AccountJwtJwksTrustedSourceTest { @@ -256,6 +258,25 @@ void treatsUnreceiptedOrAmbiguousOwnerPublicationAsUnavailableNotAsAKeySet() { verify(fixture.configMapClient, never()).observe(); } + @Test + void treatsDatabaseAndTransactionFailuresAsRetryableSourceUnavailability() { + List failures = + List.of( + new org.jooq.exception.DataAccessException("database unavailable"), + new DataAccessResourceFailureException("database unavailable"), + new TransactionException("transaction unavailable") {}); + + for (RuntimeException failure : failures) { + Fixture fixture = new Fixture(); + when(fixture.desiredStateRepository.readEnrollmentState(fixture.binding.accountBinding())) + .thenThrow(failure); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(SourceUnavailableException.class) + .hasNoCause(); + } + } + @Test void doesNotTrustUnexpectedOwnerFailureByMatchingItsMessageText() { Fixture fixture = new Fixture(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java index 196fb522d1..74d686b52e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java @@ -141,6 +141,28 @@ void exactAccountPeerReceivesUncompressedCurrentLoginCredentialAndReturnsBoundCa } } + @Test + void firstPartyPlayerCreatedTargetRefusesBeforeRpcOrCredentialDisclosure() throws Exception { + var context = context(); + doReturn("PLAYER_CREATED").when(context.resolvedTarget()).characterCreationPolicy(); + var login = loginCustody(); + var calls = new AtomicInteger(); + var observedJwt = new AtomicReference(); + var observedPeer = new AtomicReference(); + Server server = server("account", calls, observedJwt, observedPeer, context, login.evidence()); + try (var client = client(server)) { + client.init(); + assertThatThrownBy(() -> client.read(context, READ_REQUEST, login, () -> true)) + .isExactlyInstanceOf(IllegalArgumentException.class) + .hasMessage("Exact live LOGIN custody and verified player-admission scope required"); + assertThat(calls).hasValue(0); + assertThat(observedJwt).hasValue(null); + assertThat(observedPeer).hasValue(null); + } finally { + stop(server); + } + } + @Test void independentReceiverClockMayPrecedeAccountEvaluationWithoutExtendingExpiry() throws Exception {