diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 5ebc307a79..301928afb1 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -97,6 +97,18 @@ The distinct platform-admin break-glass owner transport is `POST /internal/opera At effective expiry or revocation, Account publishes the monotonic grant-authority change. The grant becomes invalid for discovery, connect-token issuance, `PLAY`, reconnect, and continued gameplay authority; Game Session consumes that change through bounded indexes/reconciliation and terminates affected active bindings under the session contract. A planned friendly ending is separate: close admission, complete bounded drain, then revoke/expire grants. Grant revocation is never a request to drain indefinitely. This contract is target state; the registered legacy four-field `AccountRealmAccessGrant` persistence and internal reads do not provide expiry, exact request replay, or retained tombstones. Local lifecycle-bound storage retains those capabilities, while its management and consumer entry points remain unregistered; tenant-admin mutation, qualified actor authorization, and end-to-end active-binding ejection remain unproved. +### Public bootstrap WORLDS discovery + +`ListBootstrapWorlds` returns the complete set of unambiguous visible public-production worlds whose current Account entitlement says gameplay is available. Account verifies the existing browser-bootstrap credential against its persisted account identity, obtains the complete canonical target collection from Game Session, evaluates current entitlement once for each represented canonical tenant, and revalidates the caller and checks each original entitlement observation deadline before returning a deterministic `worldSlug` ordering. The Account owner fails the whole request when the target collection changes, is ambiguous, or cannot be read completely, or when any required entitlement is unavailable or expired; it never returns a partial list. The canonical target collection contract and limits are owned by [Game Session's public-production target collection read](../game-session-service/api-contracts.md#public-production-bootstrap-target-collection-read). + +Independent tenant entitlement evaluations run outside ambient SQL with at most eight concurrent workers per discovery request. A shared fair eight-permit bound also limits active evaluations across all discovery requests and owner instances in the Account process. Waiting for a permit occurs outside SQL and lasts at most five seconds; contention expiry fails the whole discovery request as `ENTITLEMENT_UNAVAILABLE`. Success, source failure and interruption return acquired permits. This bounds this owner’s aggregate connection demand without resizing the Account pool or guaranteeing production capacity. Each tenant is evaluated once and retains its owner’s independent transaction/isolation checks; caller and SQL context are not propagated to workers. The owner waits for the complete set, validates every returned tenant identity and returns no partial result on failure or interruption. Original observation deadlines remain unchanged and are checked after the second complete target read and final caller check. This bound reduces serialized latency; it is not a production capacity guarantee or permission to extend expired evidence, and slow or large collections can still refuse when their original observations expire. + +An unreachable Game Session authority maps to `AUTH_UNAVAILABLE`; a reachable malformed, ambiguous, or changed collection maps to `ADMISSION_POINTER_UNAVAILABLE`; and an unavailable or expired entitlement maps to `ENTITLEMENT_UNAVAILABLE`. Bootstrap-caller verification retains its authentication failure. None of these failures produces an empty or partial success. + +`gameplayAvailable` controls discovery visibility; `allowPublicJoin` does not. This pre-scope result contains only world slug and display name and creates no membership, JOIN, connect scope, or gameplay-admission authority. Public bootstrap discovery does not resolve private playtest realms or substitute for later target selection, current entitlement, membership, grant, or admission checks. + +The manually composed `AccountCanonicalPublicRealmScopeOwner` uses the same public source collection for UUID-bearing V2 selector scopes. It rechecks Account identity, fresh tenant provenance, current membership and billing-head observations in short Account transactions, retains the exact signed scope preimage and verifies its immutable readback. Protected Game Session, registry and provider reads stay outside those transactions. Scope expiry follows the configured scope lifetime capped by the original verified bootstrap expiry; a later check cannot restamp an expired observation. Public visibility remains membership-independent, while current membership and `allowPublicJoin` are facts for subsequent fresh selection and JOIN checks. The scope grants neither membership repair nor gameplay admission. This source remains unregistered and separate from the existing numeric facade and private-realm path; its proof and receiving gaps are recorded in [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md#public-bootstrap-worlds-source-preparation). + ### Account-Owned Safety Restriction Contract Account is the sole enforcement owner for the two global safety categories defined by [Moderation Policies](../logging-admin-service/moderation-policies.md): `account_security_lock` and `platform_access_ban`. They are separate durable lifecycles, not aliases or one combined account-ban state. Both apply to the global account subject across tenants; neither accepts a tenant, realm, or channel scope. @@ -113,6 +125,8 @@ 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 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. diff --git a/design/architecture/microservices/account-service/stripe-integration.md b/design/architecture/microservices/account-service/stripe-integration.md index 0af82353cc..48b11f8140 100644 --- a/design/architecture/microservices/account-service/stripe-integration.md +++ b/design/architecture/microservices/account-service/stripe-integration.md @@ -25,6 +25,17 @@ The current append-only inbox has no processing terminal, guarded payload minimi The billing-customer and saved-method owners have the same prerequisite. Their append-only observation histories retain provider bindings and versioned card-display metadata; customer and instrument rows also retain Account references that currently block deletion. Before registering these sources, their exact categories require approved finite retention schedules, guarded minimization or erasure, and explicit account-deletion and backup treatment in the same canonical retention registry. Card-display history is not automatically necessary settlement evidence. Minimize or erase it when its authorized purpose ends, retaining only the minimum billing evidence authorized by ADR 0043 and any applicable legal hold. The owner must preserve unresolved provider and subscription obligations while completing the Account erasure workflow; neither indefinite Account retention nor bypassing a foreign-key or immutability guard is an acceptable deletion policy. The current owners remain unregistered until these paths and their physical proof exist. +### Paid discovery observation activation prerequisites + +Account billing runtime composition owns bounded Stripe observation and its binding to the retained subscription policy. Account public-discovery composition owns the aggregate discovery workload and its qualification. Before registering paid discovery or claiming production paid discovery support, these owners must satisfy the following gates together with the [runtime entitlement contract](./subscription-management.md#runtime-entitlement-contract) and [public discovery contract](./api-contracts.md#public-bootstrap-worlds-discovery): + +- **End-to-end provider deadline and resource release.** Apply an explicit finite deadline to the complete provider attempt, including connection establishment and response-body consumption, with SDK retries disabled on discovery reads. Connect/read socket timeouts alone are insufficient: repeated successful reads can keep a response in progress beyond the observation window. Prove deadline expiry stops the underlying provider work and releases its resources before the shared execution capacity is reused. Timing out a waiting future, interrupting a worker, or returning an unavailable response is not proof that its network work ended. Late results cannot become evidence or renew freshness. +- **Exact retained-policy budget.** Carry the policy budget belonging to the exact committed receipt and original operation into the provider-read preparation; do not substitute current configuration for a retained policy. The total attempt budget must fit strictly within that policy's `maximumObservationAge`, measured from the original read start, and leave time for the existing final current-row, receipt and freshness checks. Refuse an absent, elapsed or incompatible budget before provider dispatch. Reacquire and revalidate the same receipt/source fence afterward; a shorter network budget never extends the receipt's committed fact bound or the observation deadline. +- **Aggregate provider-load qualification.** Qualify the planned paid-tenant collection sizes and concurrent discovery request rate across all Account instances against the provider account's applicable limits. Include rate limiting, slow and trickling responses, exhausted execution capacity, repeated concurrent requests and recovery. Demonstrate that failed required reads still refuse the complete collection without partial results, retry amplification, leaked provider work or capacity released while work continues. The existing process-local concurrency bound does not establish a fleet-wide request-rate bound. Production rate/size limits must come from this qualification rather than inferred SDK defaults. +- **Operational evidence.** Publish bounded-cardinality measurements of provider attempts per discovery call, provider-read latency, timeout and HTTP 429 outcomes, and discovery capacity refusal and complete-call failure. Use fixed operation/outcome labels, not Account, tenant, subscription or request identifiers, provider payloads, payment metadata or exception text. Qualification must demonstrate these signals for controlled success, timeout and rate-limit cases and show how operators detect exhaustion before activation. + +These gates do not authorize caching or a longer freshness window. Any separately selected observation reuse must preserve the exact committed receipt, current authority fence and original observation deadline; a cache cannot replace the deadline, load or failure-semantics proof. The [implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#public-bootstrap-worlds-source-preparation) records the current preparation boundary and missing qualification. + ## Implementation Status The hosting-subscription, provider-reconciliation, and account-deletion billing-owner precondition contracts below are canonical target-state behavior. Account now has an unregistered verified Stripe event inbox, durable billing-customer intent and first-dispatch claim, and saved-method confirmation bound to the exact customer. The inbox is event intake only; the customer and instrument owners have controlled Stripe SDK/readback source and PostgreSQL proof, not a live provider or registered route. Current payment code records payment transactions, donations, refunds, platform fees, and creator shares, but still needs subscription webhook lifecycle processing, durable idempotent hosting-billing fulfillment/reconciliation, caller-stable subscription create retry evidence, active-subscription deletion guards, and end-to-end entitlement enforcement. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs now fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the underlying provider-mutating service methods remain unsupported substrate. Only separately typed hosting-billing operations may mutate Stripe. `purchase_entitlement` and paid-but-unfulfilled compensation are reserved for a separately accepted future marketplace path under [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md), and remain unsupported until its launch gates are implemented and proved. diff --git a/design/architecture/microservices/account-service/subscription-management.md b/design/architecture/microservices/account-service/subscription-management.md index 36d9d008e6..ea6dd50a10 100644 --- a/design/architecture/microservices/account-service/subscription-management.md +++ b/design/architecture/microservices/account-service/subscription-management.md @@ -170,6 +170,10 @@ These behaviors tie directly into the revocation rules in [Session Behavior](../ The canonical per-tenant membership, entitlement response, freshness, and billing-sequence contract is [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). This document retains the subscription-local consequences: +A committed subscription receipt retains the provider/policy fact boundary separately from the maximum age of one provider observation. For an active or trialing receipt, that bound is the earlier of the paid period end and effective scheduled cancellation; payment-recovery phases additionally stop at their next configured grace or suspension boundary. A later read obtains fresh provider evidence and bounds its response by that read's own observation deadline and the unchanged committed fact bound. Reading does not renew a receipt, advance tenant authority, or append billing events. Stale observations, changed provider facts, elapsed fact bounds, or a changed current row require refusal or explicit lifecycle reconciliation. Existing immutable receipts keep their originally committed bounds. + +The existing `CANCELED` status is a terminal negative marker: after the original receipt's observation deadline, a current read may independently confirm the exact same provider facts and return `gameplayAvailable=false` with its new read deadline. It must still prove the unchanged committed receipt, current row and authority source; stale or changed provider evidence refuses. This negative projection never extends a positive entitlement, rewrites the receipt or treats unknown provider state as cancellation. Discovery omits that confirmed unavailable tenant rather than failing the complete collection solely because its old observation aged. + - Account exposes separate runtime, tenant-admin, and support-safe entitlement surfaces; subscription status and plan metadata are projected into the canonical runtime response rather than maintained by consumers. - Game Session and World Management use `GetTenantEntitlementsForRuntime(tenantId, requestId)` before instance start, new bindings, scaling, or other capacity-affecting lifecycle work. This read assesses eligibility only and never commits capacity. Capacity-changing work must use `CommitTenantCapacityAdmission` when implemented and fail closed until that Account-owned commitment route exists. `grace` may preserve already-authorized gameplay while blocking new commitments. - Runtime consumers invalidate or refresh cached entitlement state when Account emits `SubscriptionStatusChanged` or `TenantBillingStateChanged`; Account remains the sole producer of those events. diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index da43173b07..846a5e980c 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -62,6 +62,26 @@ The World Management database row and monotonic lifecycle epoch are the admissio Multi-Tenancy owns the realm catalog, the canonical durable `{tenantId, realmId}` pointer identity and its routing/admission semantics, while Game Session is the sole runtime resolver, persister, and compare-and-set orchestrator for that resolved catalog and admission-pointer state; neither service owns World lifecycle state. Replacement preparation and pointer swap carry the catalog-bound `worldSlug`/`realmSlug` selectors, stable `playableStateNamespaceId`/`playableStateScope`, and, for private/playtest targets, the canonical lifecycle proof tuple `{playtestLifecycleId, playtestStateGeneration}` from [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); changing `gameInstanceId` does not authorize a new realm identity, namespace, or durable-state copy. Cutover remains closed unless every owner reports fresh compatible state and the fenced pointer CAS succeeds. After a source swap, Game Session drains and closes source bindings, then asks World to progress termination; it reports a stopped runtime only after authoritative `TERMINATED` readback. Public-production requests omit both playtest fields and reject supplied values. +### 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. + +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. + +### Published public-production target resolution + +The manually composed, unregistered `CanonicalGameplayAdmissionDecisionReadService.ResolvePublishedRealmAdmissionTarget` resolves a retained public selector against Game Session's current route owner before a later strict published-source read. The closed schema-1 request in [`canonical_gameplay_admission_decision_read.proto`](../../../../protos/game-session/v1/canonical_gameplay_admission_decision_read.proto) carries one read-request UUID, Account UUID, workload namespace, canonical tenant UUID and slug, world slug, realm UUID and slug, playable-state namespace and scope, canonical runtime-instance UUID, and the expected catalog revision and pointer version. Account UUID and selector values are correlation and exact-match inputs; they authenticate no caller. The request cannot supply a canonical content-version UUID, World epoch, private storage handle, bearer, or Account-issued scope. + +Game Session reads the current target, requires an exact match to the retained tenant/world/realm/runtime tuple, `SHARED` scope, `PRESEEDED_ONLY` policy, and committed initial-owner proof without a positive durable abort, then rereads the target and requires the complete values unchanged. The closed response echoes the exact request and one complete canonical target, including the owner-selected version and active World epoch. Its 16 KiB request and 64 KiB response bounds apply to this RPC; the Account client uses a five-second deadline. It resolves missing strict-read selectors only. It does not perform the full publication read or an independent World lifecycle read, acquire a World hold, authenticate the Account user, issue a scope, or admit gameplay. + +### Published realm admission-owner read + +The manually composed, unregistered `CanonicalGameplayAdmissionDecisionReadService.GetPublishedRealmAdmissionOwnerRead` accepts one existing `GetCanonicalGameplayRosterOwnerReadRequest` selector from the exact same-namespace Account mTLS workload, without propagated player context or an ambient SQL transaction. The selector binds a read-request UUID, Account UUID, workload namespace, canonical tenant UUID, world/realm selectors, canonical realm UUID, playable-state namespace/scope, canonical runtime-instance and version UUIDs, and the expected catalog revision, pointer version, and active World epoch. The request is bounded to 2,304 bytes: the existing 2 KiB roster selector plus outer-message framing. It is a pre-lease read selector, not Account authentication, membership, grant, entitlement, or admission authority. + +For that selector, Game Session reads its current target and launch association and the complete existing published-source response, then makes a mandatory World lifecycle read for the same namespace, canonical tenant, world, runtime instance, playable-state namespace/scope, and canonical version. The World request also binds the selected launch's control-plane request ID and the exact descriptor request/result and release-attestation digests. World must return the same complete launch binding, `ACTIVE` lifecycle state, and epoch equal to the target's current `activeWorldEpoch`. Game Session then rereads the published source, route target, and launch association and returns evidence only if each complete value remains equal to its first read. The response carries the complete current target, the existing full published-source response, and the exact canonical `WorldCanonicalInstanceLifecycleEvidence` bytes defined by the [World lifecycle-read proto](../../../../protos/world-management/v1/world_canonical_instance_lifecycle_read.proto). This source capture is an as-of read, not a World hold or cross-owner protection through a later Account transaction. + +The Account client uses a 30-second deadline for this composed read; the nested World client uses its own five-second deadline. The complete published-read response is bounded to exactly 6,422,545 bytes, including the full existing publication response, a 64 KiB target, the current 4 MiB World response allowance, and protobuf framing. The World carrier has no intrinsic evidence-size bound; this method refuses an oversized complete response rather than dropping evidence. These limits and deadlines apply to `GetPublishedRealmAdmissionOwnerRead`, not to `ResolvePublishedRealmAdmissionTarget`. The RPC proves neither current Account authority nor a World hold, issuer/custody qualification, runtime activation, or gameplay admission. Local source and proof status are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#public-bootstrap-worlds-source-preparation). + ### Initial `FRESH` playtest lifecycle source preparation [ADR 0137](../../decisions/adr-0137-isolated-playtest-state-modes-and-reset.md) owns playtest initialization modes and isolated lifecycle identity; [ADR 0138](../../decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) owns explicit expiry and grant consequences. The local, unregistered `GameSessionInitialPlaytestLifecycleRepository.prepare` boundary supports only an initial `FRESH` preparation. Its exact request binds a stable `requestId`, `targetNamespace`, `tenantId`, `worldSlug`, `realmSlug`, and explicit future `forkExpiresAt`, plus `sourceCatalogRealmId`, `sourceCatalogRequestId`, `sourceCatalogRevision` fixed at `1`, `sourceIntakeOperationId`, `canonicalVersionId`, `publishedReleaseBundleRef`, and `publishedReleaseBundleDigest`. Game Session locks and validates the retained canonical public-production catalog and its complete published policy evidence against the same tenant/world, distinct target realm, source-intake operation, canonical version, and published release bundle; fixture-only source records are excluded. The target must also be an exact visible, non-public, `ISOLATED` realm policy in that complete immutable Human-published policy set. The retained preparation binds its policy identity, canonical bytes, digest and source revision; a public build or catalog alone cannot authorize an arbitrary private target. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index ce6889df8b..5b63293b6e 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -48,3 +48,9 @@ A small inbox for unresolved agent, tooling, environment, and workflow issues; s - `2026-11-02` (Pacific/Auckland): Hosted collection retained an active operation after a completed review with no actionable-count header. - #3380 operation `review_operation_8c61b77debf885a012a9c2d3f2a292ba` retained `active/trigger_recovered` while its observer reported `invalid_actionable_count`. GitHub review `5733397589` completed on `f3da62b19c1b` at 8:47:31pm NZDT with a final `batch=1/1` publication marker and two inline findings, but its body contained no actionable-count header. Gameplay verified the immutable submission and fixed its findings without reposting, resetting rounds or replacing the original source. FireController Worker has the exact operation and review references for capture recovery. Next: retain the original complete capture and correct counts, expose the collection refusal in the top-level diagnostic, and verify native completion without another provider review; an active controller state alone did not establish ongoing provider work. + +- `2026-11-03` (Pacific/Auckland): Protobuf generation discards local Gradle configuration-cache entries. + - Successful canonical Gameplay proof147 discarded its configuration-cache entry with 118 serialization problems, including generated-proto tasks retaining `SourceDirectorySet` and `Project`; proof151 and focused bridge attempts reproduce the same class of warning. Documentation-only proof148 stores its entry normally. These are local configuration-cache observations, separate from task-output caches or proof that remote CI lost cache hits. Next: assess the pinned Gradle/protobuf generation configuration in the owning CI programme without changing source, fork or cache policies from source counts alone; the affected checks themselves passed. + +- `2026-11-03` (Pacific/Auckland): Physical issuer retirement lost a fresh Redis connection before mutation. + - #3382 substantive Validation run [41474380442](https://github.com/benhook1013/FireMUD/actions/runs/41474380442), Game Session partition 1, passed 85 of 86 physical cases; `retiresOriginalReleasesAndContinuesPastThePhysicalHistoryBound` failed at its release step because a newly opened Lettuce connection disconnected before `ACL WHOAMI`. No Redis mutation was dispatched by that attempt. The unchanged complete case passed locally in proof160 (93.841s); this does not establish the remote cause or completed remote improvement from the separately qualified PostgreSQL fixture pool. Source inspection found no intentional in-test shutdown or ACL change. Next: on a natural recurrence, retain Redis container health/logs and the exact turnover iteration alongside connection events; preserve fail-closed handling and the full history-bound proof. Reported to Overseer; no reconnect, blind mutation retry, assertion reduction or production workaround was added. 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 226116eefe..9d0c58965d 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -14,6 +14,30 @@ Local source includes [`RealmGrantMutation`](../../../services/common-platform-c Bounded source/storage proof passes: 24 shared codec/mutation unit cases and 10 Account PostgreSQL cases, with affected static/format checks in proof130 (2m29); unchanged shared units retain their earlier exact-source execution. Local expansion now composes the internal Game Session current private-preparation read with the Account-owned exact lifecycle grant read. Current-parent proof147 passes 38 selected units, 31 physical PostgreSQL cases across Account and Game Session, and five in-process Game Session transport cases, with affected static/format checks (5m30). Account's four physical composition cases use its real SQL and peer-qualified client over controlled loopback mTLS replies; Game Session SQL is proved separately, so this is not an authenticated whole cross-owner receiving chain. Subsequent proof151 passes 15 affected codec/mutation units and 29 physical cases across both owners for NUL rejection, full representable audit-reason retention and canonical realm-display-name bounds; these overlap prior cases rather than add to a whole-system count. Actor authorization, protected lifecycle currentness through mutation commit, registered runtime consumer convergence, event delivery/reconciliation and active-binding ejection remain incomplete. Data construction and storage source do not activate a route or establish authority. Focused executable anchors are the [grant PostgreSQL test](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountLifecycleBoundRealmGrantPostgresIntegrationTest.java) and [composed-read PostgreSQL test](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCurrentLifecycleRealmGrantReadPostgresIntegrationTest.java). This implementation narrative does not change the capability ratings below. +### Public bootstrap WORLDS source preparation + +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; 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. 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. + +Independent tenant entitlement evaluations now overlap, with shared resource bounds across concurrent requests and owner instances under the [Account API contract](../../architecture/microservices/account-service/api-contracts.md#public-bootstrap-worlds-discovery). The implementation preserves transaction isolation, exact tenant identity and original observation expiry. Production pool sizing, throughput and capacity remain unqualified. + +Paid-provider observation remains an activation blocker owned by Account billing runtime composition and Account public-discovery composition under the [Stripe observation activation gates](../../architecture/microservices/account-service/stripe-integration.md#paid-discovery-observation-activation-prerequisites). The [hosting observer](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserver.java) requires explicit finite connect/read limits and disables SDK retries per retrieval. Its targeted observer/policy proof passed 23 cases covering option propagation, one-attempt timeout behavior, rate-limit refusal and unchanged freshness decisions; this overlapping component proof is not production load or wall-clock deadline qualification. + +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. + +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. + +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. This scope owner is not consumed by the existing facade, and this source slice adds no browser scope reader. 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: 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 unimplemented in this source slice. 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 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. + ### Account Tenant-Creation Admission Preparation Account has local, unregistered preparation for the exact tenant-creation admission receipt and a separate exact8-source ordering record. The preparation leaves the existing JWT and `session:auth:token:` record unchanged; it adds no public creation route, default registration, credential custody, PKI, live ACL, issuer activation, or caller authority. The normative authorization, denial ordering, deadline, and recovery contract is in [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#account-tenant-creation-admission-receipt); key ownership/slot/retention, script semantics, reset behavior, and physical qualification are owned respectively by [Redis hub](../../architecture/system-architecture-redis.md#account-tenant-creation-admission-receipt), [Redis Lua Patterns](../../architecture/system-architecture-redis-lua-patterns.md#account-tenant-creation-admission-script), [Redis Reset & Recovery](../../architecture/system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary), and [Redis Usage & Profiles](../../architecture/system-architecture-redis-usage-and-profiles.md#account-creation-admission-durability). @@ -497,7 +521,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) | [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) | [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. Numeric subscription code and schema remain unchanged in this cut; `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 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. | diff --git a/protos/game-session/v1/canonical_gameplay_admission_decision_read.proto b/protos/game-session/v1/canonical_gameplay_admission_decision_read.proto index f09d6c7248..e40465795d 100644 --- a/protos/game-session/v1/canonical_gameplay_admission_decision_read.proto +++ b/protos/game-session/v1/canonical_gameplay_admission_decision_read.proto @@ -11,6 +11,12 @@ option java_outer_classname = "CanonicalGameplayAdmissionDecisionReadProto"; // Explicit, manually composed Account-purpose reads. GS requires the exact same-namespace Account // workload and returns existing owner evidence without claiming gameplay admission. service CanonicalGameplayAdmissionDecisionReadService { + // Complete point-in-time discovery from current canonical owners; no admission or World hold. + rpc ListVisiblePublicProductionAdmissionTargets(ListVisiblePublicProductionAdmissionTargetsRequest) + returns (ListVisiblePublicProductionAdmissionTargetsResponse); + // Resolves only missing strict-read selectors from current owner rows; never grants admission. + rpc ResolvePublishedRealmAdmissionTarget(ResolvePublishedRealmAdmissionTargetRequest) + returns (ResolvePublishedRealmAdmissionTargetResponse); rpc GetOriginalNewNeverAdmittedDecision(GetOriginalNewNeverAdmittedDecisionRequest) returns (GetOriginalNewNeverAdmittedDecisionResponse); rpc GetCanonicalGameplayAdmissionDecision( @@ -21,6 +27,49 @@ service CanonicalGameplayAdmissionDecisionReadService { returns (GetPublishedRealmAdmissionOwnerReadResponse); } +// Closed workload-only discovery correlation. No player credential or guessed target is accepted. +message ListVisiblePublicProductionAdmissionTargetsRequest { + repeated uint32 schema_version = 1; + repeated string read_request_uuid = 2; + repeated string target_namespace = 3; +} + +// All current visible public SHARED PRESEEDED targets or refusal. An authenticated empty list is +// valid. The complete serialized response is bounded to exactly 4 MiB; each complete target is +// bounded to 64 KiB. No truncation or pagination, and no fresh World lifecycle/hold is implied. +message ListVisiblePublicProductionAdmissionTargetsResponse { + repeated uint32 schema_version = 1; + repeated ListVisiblePublicProductionAdmissionTargetsRequest request = 2; + repeated CanonicalPlayableTargetEvidence current_targets = 3; +} + +// Exact retained public-production target plus read/account correlation. No content-version UUID, +// World epoch, private storage handle, bearer, or Account-issued scope may be supplied here. +message ResolvePublishedRealmAdmissionTargetRequest { + repeated uint32 schema_version = 1; + repeated string read_request_uuid = 2; + repeated string account_uuid = 3; + repeated string target_namespace = 4; + repeated string canonical_tenant_uuid = 5; + repeated string tenant_slug = 6; + repeated string world_slug = 7; + repeated string realm_uuid = 8; + repeated string realm_slug = 9; + repeated string playable_state_namespace_uuid = 10; + repeated string playable_state_scope = 11; + repeated string canonical_game_instance_uuid = 12; + repeated string catalog_revision = 13; + repeated string pointer_version = 14; +} + +// Point-in-time PRESEEDED_ONLY SHARED owner target, including actual version/epoch and committed +// OPEN proof. This selects a subsequent strict published read and supplies no fresh World lease. +message ResolvePublishedRealmAdmissionTargetResponse { + repeated uint32 schema_version = 1; + repeated ResolvePublishedRealmAdmissionTargetRequest request = 2; + repeated CanonicalPlayableTargetEvidence current_target = 3; +} + // Repeated fields preserve wire presence and duplicate evidence for closed receiver validation. // Lease evidence is the complete unchanged canonical AccountGameplayAdmissionLeaseEvidence UTF-8. message GetCanonicalGameplayAdmissionDecisionRequest { @@ -126,14 +175,17 @@ message CanonicalPlayableTargetEvidence { repeated string character_creation_policy = 32; } -// Complete current GS target and the existing full source response (owner proof, launch/source, -// complete published policy set). The existing source response remains independently validated -// by CanonicalGameplayRosterOwnerReadGrpcCodec. Total bound is below 4 MiB and includes target -// protobuf headroom; the Account client applies it only to this RPC. +// Complete current GS target, the existing full publication source, and a mandatory fresh World +// ACTIVE capture of the same launch. Existing owner codecs independently validate both carried +// sources. The complete 6,422,545-byte bound includes all three carriers and protobuf framing; +// oversized complete source refuses rather than dropping evidence. message GetPublishedRealmAdmissionOwnerReadResponse { repeated uint32 schema_version = 1; repeated GetCanonicalGameplayRosterOwnerReadResponse published_source = 2; repeated CanonicalPlayableTargetEvidence current_target = 3; + // Exact existing WorldCanonicalInstanceLifecycleEvidence canonical bytes. Required once; + // ACTIVE and complete request/launch/publication binding must match the same owner target. + repeated bytes world_lifecycle_evidence = 4; } // Independently reads the original selected abandonment and actual qualified physical closure. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClient.java index 774d9a2519..d46193f9d3 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClient.java @@ -13,6 +13,8 @@ import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Evidence; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RequestEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.ResolvedPublishedTarget; +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; @@ -29,7 +31,8 @@ public final class CanonicalGameplayAdmissionDecisionReadClient CanonicalGameplayAdmissionDecisionReadServiceGrpc .CanonicalGameplayAdmissionDecisionReadServiceBlockingStub> { private static final long CALL_DEADLINE_SECONDS = 5L; - private static final long PUBLISHED_REALM_READ_DEADLINE_SECONDS = 15L; + // Two complete publication reads can each make two five-second policy calls, plus World. + private static final long PUBLISHED_REALM_READ_DEADLINE_SECONDS = 30L; private final String workloadNamespace; public CanonicalGameplayAdmissionDecisionReadClient( @@ -78,7 +81,7 @@ public Evidence read( RequestEvidence expected = CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest(wireRequest); var response = - requireInitializedStub("Gameplay admission decision client is not initialized") + requireAvailableStub() .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) .getCanonicalGameplayAdmissionDecision(wireRequest); try { @@ -108,7 +111,7 @@ public Evidence read( transitionId, abandonmentId, lease); var expected = AccountGameplayAdmissionNeverAdmittedGrpcCodec.parseDecisionRequest(request); var response = - requireInitializedStub("Gameplay admission decision client is not initialized") + requireAvailableStub() .withMaxInboundMessageSize( AccountGameplayAdmissionNeverAdmittedGrpcCodec.MAX_WIRE_BYTES) .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) @@ -122,6 +125,61 @@ public Evidence read( } } + /** Reads the complete canonical discovery collection; no player admission or World hold. */ + public CanonicalGameplayAdmissionDecisionReadGrpcCodec.VisiblePublicProductionTargets + listVisiblePublicProductionAdmissionTargets(UUID readRequestId) { + requireNoAmbientSql("Canonical discovery requires no ambient Account transaction"); + requirePublishedSourceContext(); + var expected = + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.DiscoveryRequest( + readRequestId, workloadNamespace); + var request = CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryRequest(expected); + var response = + requireAvailableStub() + .withMaxInboundMessageSize( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.MAX_DISCOVERY_RESPONSE_WIRE_BYTES) + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .listVisiblePublicProductionAdmissionTargets(request); + try { + return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + expected, response); + } catch (IllegalArgumentException malformed) { + throw new IllegalStateException( + "Game Session returned invalid canonical discovery evidence", malformed); + } + } + + /** + * Resolves missing strict-read selectors from actual current Game Session owner rows. The caller + * supplies only its retained target tuple; the result is selection evidence, not admission. + */ + public ResolvedPublishedTarget resolvePublishedRealmAdmissionTarget( + RetainedTargetSelector selector) { + requireNoAmbientSql("Published target resolution requires no ambient Account transaction"); + requirePublishedSourceContext(); + Objects.requireNonNull(selector, "selector"); + if (!workloadNamespace.equals(selector.targetNamespace())) { + throw new IllegalArgumentException( + "Published target resolution requires configured namespace"); + } + var request = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionRequest(selector); + var response = + requireAvailableStub() + .withMaxInboundMessageSize( + CanonicalGameplayAdmissionDecisionReadGrpcCodec + .MAX_TARGET_RESOLUTION_RESPONSE_WIRE_BYTES) + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .resolvePublishedRealmAdmissionTarget(request); + try { + return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromTargetResolutionResponse( + selector, response); + } catch (IllegalArgumentException malformed) { + throw new IllegalStateException( + "Game Session returned invalid current target evidence", malformed); + } + } + /** * Reads the current published route and complete sealed source before Account lease allocation. * Selector account identity and expected counters are correlation only, never authorization. @@ -129,10 +187,7 @@ public Evidence read( public PublishedRealmEvidence readPublishedRealmAdmissionOwner( CanonicalGameplayRosterOwnerReadEvidence.Request selector) { requireNoAmbientSql("Published realm owner read requires no ambient Account transaction"); - if (SessionContext.hasAuthenticatedCallerContext() || SessionContext.isInternalService()) { - throw new IllegalStateException( - "Published realm owner read requires a workload-only caller context"); - } + requirePublishedSourceContext(); Objects.requireNonNull(selector, "selector"); if (!workloadNamespace.equals(selector.targetNamespace())) { throw new IllegalArgumentException( @@ -144,7 +199,7 @@ public PublishedRealmEvidence readPublishedRealmAdmissionOwner( var expected = CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest(wireRequest); var response = - requireInitializedStub("Gameplay admission decision client is not initialized") + requireAvailableStub() .withMaxInboundMessageSize( CanonicalGameplayAdmissionDecisionReadGrpcCodec .MAX_PUBLISHED_REALM_RESPONSE_WIRE_BYTES) @@ -159,6 +214,33 @@ public PublishedRealmEvidence readPublishedRealmAdmissionOwner( } } + private CanonicalGameplayAdmissionDecisionReadServiceGrpc + .CanonicalGameplayAdmissionDecisionReadServiceBlockingStub + requireAvailableStub() { + try { + return requireInitializedStub("Gameplay admission decision client is not initialized"); + } catch (IllegalStateException lifecycleFailure) { + throw new ClientUnavailableException(lifecycleFailure); + } + } + + /** A source read cannot run before explicit initialization or after this client is closed. */ + public static final class ClientUnavailableException extends IllegalStateException { + public ClientUnavailableException(IllegalStateException cause) { + super("Canonical gameplay admission decision client is unavailable", cause); + } + } + + private static void requirePublishedSourceContext() { + if (SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService() + || SessionContext.getServiceName() != null + || SessionContext.getServiceInstanceId() != null) { + throw new IllegalStateException( + "Published source reads require workload-only caller context"); + } + } + @Override protected String configuredTarget(ServiceEndpointsProperties endpoints) { return endpoints.getGameSessionService(); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserver.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserver.java new file mode 100644 index 0000000000..c23d83b454 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserver.java @@ -0,0 +1,674 @@ +package net.firedevops.firemud.accountservice.client; + +import com.stripe.exception.StripeException; +import com.stripe.model.Price; +import com.stripe.model.Subscription; +import com.stripe.model.SubscriptionItem; +import com.stripe.model.SubscriptionItemCollection; +import com.stripe.net.RequestOptions; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Clock; +import java.time.DateTimeException; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; + +/** + * Reads one exact Stripe hosting subscription and returns immutable provider evidence only. + * + *

This manually composed observer does not authorize a caller, locate a local subscription, + * mutate Stripe, or apply an Account lifecycle transition. Its metadata contract is internal and + * versioned: {@code firemud_metadata_schema_version=1}, {@code firemud_operation_type}, {@code + * firemud_operation_id}, and {@code firemud_subscription_id}. Operation types are exactly {@code + * subscription_provisioning} and {@code subscription_update}. Provider IDs and this metadata are + * retained evidence, not substitutes for Account's durable operation and provider history mappings. + */ +public final class StripeHostingSubscriptionObserver { + private static final String METADATA_SCHEMA_VERSION_KEY = "firemud_metadata_schema_version"; + private static final String METADATA_SCHEMA_VERSION = "1"; + private static final String METADATA_OPERATION_TYPE_KEY = "firemud_operation_type"; + private static final String METADATA_OPERATION_ID_KEY = "firemud_operation_id"; + private static final String METADATA_SUBSCRIPTION_ID_KEY = "firemud_subscription_id"; + + private static final String SUBSCRIPTION_OBJECT = "subscription"; + private static final String SUBSCRIPTION_ITEM_OBJECT = "subscription_item"; + private static final String PRICE_OBJECT = "price"; + + private static final List SUPPORTED_PROVIDER_STATUSES = + List.of( + "active", + "canceled", + "incomplete", + "incomplete_expired", + "past_due", + "paused", + "trialing", + "unpaid"); + + private final com.stripe.StripeClient stripeClient; + private final Clock clock; + private final RequestOptions requestOptions; + + /** + * Explicit transport limits are required; composition must keep them below the applicable + * lifecycle policy's maximum observation age. Socket timeouts are not a wall-clock deadline: the + * owner still rejects evidence whose read-start freshness bound has elapsed. + */ + public StripeHostingSubscriptionObserver( + com.stripe.StripeClient stripeClient, + Clock clock, + Duration connectTimeout, + Duration readTimeout) { + this.stripeClient = Objects.requireNonNull(stripeClient, "stripe client is required"); + this.clock = Objects.requireNonNull(clock, "clock is required"); + this.requestOptions = + RequestOptions.builder() + .setConnectTimeout(timeoutMillis(connectTimeout)) + .setReadTimeout(timeoutMillis(readTimeout)) + .setMaxNetworkRetries(0) + .build(); + } + + /** + * Retrieves and validates the provider object named by the internal expected-binding tuple. + * + *

A provider read failure, including a provider ID that cannot be resolved, is returned as an + * unresolved retryable result with its original typed Stripe exception. It is never represented + * as provider absence. A successfully read but incomplete, unsupported, or contradictory object + * is returned as a bounded invalid result. + */ + public Result observe(ExpectedBinding expected) { + Objects.requireNonNull(expected, "expected binding is required"); + Instant readStartedAt = clock.instant(); + Subscription subscription; + try { + subscription = + stripeClient.subscriptions().retrieve(expected.providerSubscriptionId(), requestOptions); + } catch (StripeException providerFailure) { + return new UnresolvedObservation( + expected.providerSubscriptionId(), readStartedAt, clock.instant(), providerFailure); + } + + Instant observedAt = clock.instant(); + if (observedAt.isBefore(readStartedAt)) { + return new InvalidObservation( + expected.providerSubscriptionId(), + readStartedAt, + observedAt, + InvalidReason.READ_INTERVAL_REVERSED); + } + try { + return validate(subscription, expected, readStartedAt, observedAt); + } catch (InvalidEvidence invalid) { + return new InvalidObservation( + expected.providerSubscriptionId(), readStartedAt, observedAt, invalid.reason); + } + } + + private static int timeoutMillis(Duration timeout) { + Objects.requireNonNull(timeout, "explicit Stripe observation timeout is required"); + // Zero means unbounded to the SDK. Reject sub-millisecond and overflowing values rather + // than truncating them into a different transport policy. + if (timeout.isNegative() + || timeout.isZero() + || timeout.compareTo(Duration.ofMillis(Integer.MAX_VALUE)) > 0 + || timeout.getNano() % 1_000_000 != 0) { + throw new IllegalArgumentException( + "Stripe observation timeouts must be positive whole milliseconds within the SDK range"); + } + return (int) timeout.toMillis(); + } + + private static ObservedSubscription validate( + Subscription subscription, + ExpectedBinding expected, + Instant readStartedAt, + Instant observedAt) { + require(subscription != null, InvalidReason.MISSING_SUBSCRIPTION_OBJECT); + require( + SUBSCRIPTION_OBJECT.equals(subscription.getObject()), + InvalidReason.SUBSCRIPTION_OBJECT_MISMATCH); + require( + expected.providerSubscriptionId().equals(subscription.getId()), + InvalidReason.SUBSCRIPTION_ID_MISMATCH); + + String customerId = subscription.getCustomer(); + require(expected.providerCustomerId().equals(customerId), InvalidReason.CUSTOMER_ID_MISMATCH); + + // Only the explicit subscription default_payment_method is evidence of the selected + // instrument. Do not fall back to default_source, customer invoice settings, or a customer + // default when Stripe omits this field. + String paymentMethodId = subscription.getDefaultPaymentMethod(); + require( + paymentMethodId != null && !paymentMethodId.isBlank(), + InvalidReason.EXPLICIT_PAYMENT_METHOD_MISSING); + require( + expected.providerPaymentMethodId().equals(paymentMethodId), + InvalidReason.PAYMENT_METHOD_ID_MISMATCH); + + Boolean livemode = subscription.getLivemode(); + require(livemode != null, InvalidReason.LIVEMODE_MISSING); + require(livemode == expected.livemode(), InvalidReason.LIVEMODE_MISMATCH); + + String status = subscription.getStatus(); + require( + status != null && SUPPORTED_PROVIDER_STATUSES.contains(status), + InvalidReason.UNSUPPORTED_PROVIDER_STATUS); + + SubscriptionCorrelation correlation = parseCorrelation(subscription.getMetadata(), expected); + SubscriptionItem item = requireSingleHostingItem(subscription, expected); + Price price = item.getPrice(); + require(price != null, InvalidReason.PRICE_MISSING); + require(PRICE_OBJECT.equals(price.getObject()), InvalidReason.PRICE_OBJECT_MISMATCH); + require(expected.providerPriceId().equals(price.getId()), InvalidReason.PRICE_ID_MISMATCH); + Long quantity = item.getQuantity(); + require(quantity != null, InvalidReason.ITEM_QUANTITY_MISSING); + require(quantity > 0, InvalidReason.ITEM_QUANTITY_INVALID); + require(quantity == expected.expectedQuantity(), InvalidReason.ITEM_QUANTITY_MISMATCH); + + boolean canceled = "canceled".equals(status); + Instant periodStart = + providerInstant(item.getCurrentPeriodStart(), InvalidReason.PERIOD_INVALID); + Instant periodEnd = providerInstant(item.getCurrentPeriodEnd(), InvalidReason.PERIOD_INVALID); + if (!canceled) { + require(periodStart != null && periodEnd != null, InvalidReason.PERIOD_MISSING); + } + if (periodStart != null && periodEnd != null) { + require(periodEnd.isAfter(periodStart), InvalidReason.PERIOD_INVALID); + } + + Boolean cancelAtPeriodEnd = subscription.getCancelAtPeriodEnd(); + require(cancelAtPeriodEnd != null, InvalidReason.CANCEL_METADATA_MISSING); + Instant cancelAt = + providerInstant(subscription.getCancelAt(), InvalidReason.CANCEL_TIMESTAMP_INVALID); + Instant canceledAt = + providerInstant(subscription.getCanceledAt(), InvalidReason.CANCEL_TIMESTAMP_INVALID); + Instant endedAt = + providerInstant(subscription.getEndedAt(), InvalidReason.CANCEL_TIMESTAMP_INVALID); + + Map metadata = immutableMetadata(subscription.getMetadata()); + return new ObservedSubscription( + subscription.getId(), + customerId, + paymentMethodId, + item.getId(), + price.getId(), + quantity, + periodStart, + periodEnd, + cancelAtPeriodEnd, + cancelAt, + canceledAt, + endedAt, + status, + correlation, + metadata, + livemode, + readStartedAt, + observedAt); + } + + private static SubscriptionItem requireSingleHostingItem( + Subscription subscription, ExpectedBinding expected) { + SubscriptionItemCollection items = subscription.getItems(); + require(items != null, InvalidReason.ITEMS_MISSING); + require(Boolean.FALSE.equals(items.getHasMore()), InvalidReason.ITEMS_INCOMPLETE); + List data = items.getData(); + if (data == null || data.size() != 1) { + throw new InvalidEvidence(InvalidReason.ITEM_CARDINALITY_UNSUPPORTED); + } + SubscriptionItem item = data.get(0); + require(item != null, InvalidReason.ITEM_MISSING); + require(SUBSCRIPTION_ITEM_OBJECT.equals(item.getObject()), InvalidReason.ITEM_OBJECT_MISMATCH); + require(item.getId() != null && !item.getId().isBlank(), InvalidReason.ITEM_ID_MISSING); + require( + expected.providerSubscriptionId().equals(item.getSubscription()), + InvalidReason.ITEM_SUBSCRIPTION_MISMATCH); + return item; + } + + private static SubscriptionCorrelation parseCorrelation( + Map metadata, ExpectedBinding expected) { + require(metadata != null, InvalidReason.METADATA_MISSING); + require( + METADATA_SCHEMA_VERSION.equals(metadata.get(METADATA_SCHEMA_VERSION_KEY)), + InvalidReason.METADATA_SCHEMA_UNSUPPORTED); + OperationType operationType = + OperationType.fromProviderValue(metadata.get(METADATA_OPERATION_TYPE_KEY)); + require(operationType != null, InvalidReason.OPERATION_TYPE_INVALID); + require(operationType == expected.operationType(), InvalidReason.OPERATION_TYPE_MISMATCH); + + UUID operationId = parseCanonicalNonNilUuid(metadata.get(METADATA_OPERATION_ID_KEY)); + UUID subscriptionId = parseCanonicalNonNilUuid(metadata.get(METADATA_SUBSCRIPTION_ID_KEY)); + if (operationId == null || subscriptionId == null) { + throw new InvalidEvidence(InvalidReason.METADATA_UUID_INVALID); + } + require(operationId.equals(expected.operationId()), InvalidReason.OPERATION_ID_MISMATCH); + require( + subscriptionId.equals(expected.subscriptionId()), + InvalidReason.SUBSCRIPTION_METADATA_ID_MISMATCH); + return new SubscriptionCorrelation(operationType, operationId, subscriptionId); + } + + private static Map immutableMetadata(Map metadata) { + require(metadata != null, InvalidReason.METADATA_MISSING); + for (Map.Entry entry : metadata.entrySet()) { + require( + entry.getKey() != null && entry.getValue() != null, InvalidReason.METADATA_VALUE_INVALID); + } + return Map.copyOf(metadata); + } + + private static UUID parseCanonicalNonNilUuid(String value) { + if (value == null) { + return null; + } + try { + UUID parsed = UUID.fromString(value); + return parsed.toString().equals(value) && !isNil(parsed) ? parsed : null; + } catch (IllegalArgumentException invalidUuid) { + return null; + } + } + + private static Instant providerInstant(Long epochSeconds, InvalidReason invalidReason) { + if (epochSeconds == null) { + return null; + } + require(epochSeconds > 0, invalidReason); + try { + return Instant.ofEpochSecond(epochSeconds); + } catch (DateTimeException | ArithmeticException invalidTimestamp) { + throw new InvalidEvidence(invalidReason); + } + } + + private static void require(boolean condition, InvalidReason reason) { + if (!condition) { + throw new InvalidEvidence(reason); + } + } + + private static boolean isNil(UUID value) { + return value.getMostSignificantBits() == 0 && value.getLeastSignificantBits() == 0; + } + + public sealed interface Result + permits ObservedSubscription, InvalidObservation, UnresolvedObservation { + String providerSubscriptionId(); + + Instant readStartedAt(); + + Instant observedAt(); + } + + /** A complete exact-binding provider read; it remains evidence and grants no local authority. */ + public static final class ObservedSubscription implements Result { + private final String providerSubscriptionId; + private final String providerCustomerId; + private final String providerPaymentMethodId; + private final String providerSubscriptionItemId; + private final String providerPriceId; + private final long providerQuantity; + private final Instant currentPeriodStart; + private final Instant currentPeriodEnd; + private final boolean cancelAtPeriodEnd; + private final Instant cancelAt; + private final Instant canceledAt; + private final Instant endedAt; + private final String providerStatus; + private final SubscriptionCorrelation correlation; + private final Map providerMetadata; + private final boolean livemode; + private final Instant readStartedAt; + private final Instant observedAt; + + private ObservedSubscription( + String providerSubscriptionId, + String providerCustomerId, + String providerPaymentMethodId, + String providerSubscriptionItemId, + String providerPriceId, + long providerQuantity, + Instant currentPeriodStart, + Instant currentPeriodEnd, + boolean cancelAtPeriodEnd, + Instant cancelAt, + Instant canceledAt, + Instant endedAt, + String providerStatus, + SubscriptionCorrelation correlation, + Map providerMetadata, + boolean livemode, + Instant readStartedAt, + Instant observedAt) { + this.providerSubscriptionId = providerSubscriptionId; + this.providerCustomerId = providerCustomerId; + this.providerPaymentMethodId = providerPaymentMethodId; + this.providerSubscriptionItemId = providerSubscriptionItemId; + this.providerPriceId = providerPriceId; + this.providerQuantity = providerQuantity; + this.currentPeriodStart = currentPeriodStart; + this.currentPeriodEnd = currentPeriodEnd; + this.cancelAtPeriodEnd = cancelAtPeriodEnd; + this.cancelAt = cancelAt; + this.canceledAt = canceledAt; + this.endedAt = endedAt; + this.providerStatus = providerStatus; + this.correlation = correlation; + this.providerMetadata = Map.copyOf(providerMetadata); + this.livemode = livemode; + this.readStartedAt = readStartedAt; + this.observedAt = observedAt; + } + + @Override + public String providerSubscriptionId() { + return providerSubscriptionId; + } + + public String providerCustomerId() { + return providerCustomerId; + } + + public String providerPaymentMethodId() { + return providerPaymentMethodId; + } + + public String providerSubscriptionItemId() { + return providerSubscriptionItemId; + } + + public String providerPriceId() { + return providerPriceId; + } + + public long providerQuantity() { + return providerQuantity; + } + + public Optional currentPeriodStart() { + return Optional.ofNullable(currentPeriodStart); + } + + public Optional currentPeriodEnd() { + return Optional.ofNullable(currentPeriodEnd); + } + + public boolean cancelAtPeriodEnd() { + return cancelAtPeriodEnd; + } + + public Optional cancelAt() { + return Optional.ofNullable(cancelAt); + } + + public Optional canceledAt() { + return Optional.ofNullable(canceledAt); + } + + public Optional endedAt() { + return Optional.ofNullable(endedAt); + } + + /** The provider's raw lifecycle value; no FireMUD lifecycle transition is inferred. */ + public String providerStatus() { + return providerStatus; + } + + /** True only as a description of the raw provider value, not an Account terminal commit. */ + public boolean providerStatusIsCanceled() { + return "canceled".equals(providerStatus); + } + + public SubscriptionCorrelation correlation() { + return correlation; + } + + public Map providerMetadata() { + return providerMetadata; + } + + public boolean livemode() { + return livemode; + } + + @Override + public Instant readStartedAt() { + return readStartedAt; + } + + @Override + public Instant observedAt() { + return observedAt; + } + + public String source() { + return "stripe.subscriptions.retrieve"; + } + } + + /** A read completed, but its provider data did not satisfy the bounded hosting contract. */ + public static final class InvalidObservation implements Result { + private final String providerSubscriptionId; + private final Instant readStartedAt; + private final Instant observedAt; + private final InvalidReason reason; + + private InvalidObservation( + String providerSubscriptionId, + Instant readStartedAt, + Instant observedAt, + InvalidReason reason) { + this.providerSubscriptionId = providerSubscriptionId; + this.readStartedAt = readStartedAt; + this.observedAt = observedAt; + this.reason = reason; + } + + @Override + public String providerSubscriptionId() { + return providerSubscriptionId; + } + + @Override + public Instant readStartedAt() { + return readStartedAt; + } + + @Override + public Instant observedAt() { + return observedAt; + } + + public InvalidReason reason() { + return reason; + } + } + + /** A provider read did not establish current state and must remain retryable/unresolved. */ + public static final class UnresolvedObservation implements Result { + private final String providerSubscriptionId; + private final Instant readStartedAt; + private final Instant observedAt; + private final StripeException providerFailure; + + private UnresolvedObservation( + String providerSubscriptionId, + Instant readStartedAt, + Instant observedAt, + StripeException providerFailure) { + this.providerSubscriptionId = providerSubscriptionId; + this.readStartedAt = readStartedAt; + this.observedAt = observedAt; + this.providerFailure = providerFailure; + } + + @Override + public String providerSubscriptionId() { + return providerSubscriptionId; + } + + @Override + public Instant readStartedAt() { + return readStartedAt; + } + + @Override + public Instant observedAt() { + return observedAt; + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "Preserve the original typed provider failure for diagnostics; this result remains unresolved and cannot authorize a transition.") + public StripeException providerFailure() { + return providerFailure; + } + + public boolean retryable() { + return true; + } + } + + public enum InvalidReason { + MISSING_SUBSCRIPTION_OBJECT, + SUBSCRIPTION_OBJECT_MISMATCH, + SUBSCRIPTION_ID_MISMATCH, + CUSTOMER_ID_MISMATCH, + EXPLICIT_PAYMENT_METHOD_MISSING, + PAYMENT_METHOD_ID_MISMATCH, + LIVEMODE_MISSING, + LIVEMODE_MISMATCH, + UNSUPPORTED_PROVIDER_STATUS, + ITEMS_MISSING, + ITEMS_INCOMPLETE, + ITEM_CARDINALITY_UNSUPPORTED, + ITEM_MISSING, + ITEM_OBJECT_MISMATCH, + ITEM_ID_MISSING, + ITEM_SUBSCRIPTION_MISMATCH, + PRICE_MISSING, + PRICE_OBJECT_MISMATCH, + PRICE_ID_MISMATCH, + ITEM_QUANTITY_MISSING, + ITEM_QUANTITY_INVALID, + ITEM_QUANTITY_MISMATCH, + PERIOD_MISSING, + PERIOD_INVALID, + READ_INTERVAL_REVERSED, + CANCEL_METADATA_MISSING, + CANCEL_TIMESTAMP_INVALID, + METADATA_MISSING, + METADATA_SCHEMA_UNSUPPORTED, + METADATA_VALUE_INVALID, + OPERATION_TYPE_INVALID, + OPERATION_TYPE_MISMATCH, + METADATA_UUID_INVALID, + OPERATION_ID_MISMATCH, + SUBSCRIPTION_METADATA_ID_MISMATCH + } + + public enum OperationType { + SUBSCRIPTION_PROVISIONING("subscription_provisioning"), + SUBSCRIPTION_UPDATE("subscription_update"); + + private final String providerValue; + + OperationType(String providerValue) { + this.providerValue = providerValue; + } + + public String providerValue() { + return providerValue; + } + + private static OperationType fromProviderValue(String value) { + for (OperationType type : values()) { + if (type.providerValue.equals(value)) { + return type; + } + } + return null; + } + } + + /** Typed operation metadata retained as provider evidence, separate from provider IDs. */ + public static final class SubscriptionCorrelation { + private final OperationType operationType; + private final UUID operationId; + private final UUID subscriptionId; + + private SubscriptionCorrelation( + OperationType operationType, UUID operationId, UUID subscriptionId) { + this.operationType = operationType; + this.operationId = operationId; + this.subscriptionId = subscriptionId; + } + + public OperationType operationType() { + return operationType; + } + + public UUID operationId() { + return operationId; + } + + public UUID subscriptionId() { + return subscriptionId; + } + } + + /** Expected binding supplied by internal composition; it is data, not authorization. */ + public record ExpectedBinding( + String providerSubscriptionId, + UUID subscriptionId, + String providerCustomerId, + String providerPaymentMethodId, + String providerPriceId, + long expectedQuantity, + OperationType operationType, + UUID operationId, + boolean livemode) { + public ExpectedBinding { + requireText(providerSubscriptionId, "provider subscription ID"); + requireNonNilUuid(subscriptionId, "internal subscription ID"); + requireText(providerCustomerId, "provider customer ID"); + requireText(providerPaymentMethodId, "provider payment-method ID"); + requireText(providerPriceId, "provider hosting price ID"); + if (expectedQuantity <= 0) { + throw new IllegalArgumentException("expected subscription-item quantity must be positive"); + } + Objects.requireNonNull(operationType, "operation type is required"); + requireNonNilUuid(operationId, "operation ID"); + } + + private static void requireText(String value, String label) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(label + " must not be blank"); + } + } + + private static void requireNonNilUuid(UUID value, String label) { + Objects.requireNonNull(value, label + " is required"); + if (isNil(value)) { + throw new IllegalArgumentException(label + " must not be nil"); + } + } + } + + private static final class InvalidEvidence extends RuntimeException { + private static final long serialVersionUID = 1L; + + private final InvalidReason reason; + + private InvalidEvidence(InvalidReason reason) { + this.reason = reason; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSources.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSources.java index dcf7055cfb..06100be2ae 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSources.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSources.java @@ -41,6 +41,10 @@ *

Exact non-admitting recovery uses a separately named caller-only read. That path retains the * global issuer/account authority and ACTIVE token checks but deliberately does not require the * original tenant membership or entitlement baseline to remain unchanged. + * + *

The NEW lease projection currently supports explicit DEMO entitlements only. Paid current + * tenant authority remains readable by the generic membership source, but this DEMO-shaped lease + * projection refuses paid hosting rather than decoding it as DEMO or consulting a provider in SQL. */ final class AccountGameplayAdmissionCurrentSources { private static final String ACCOUNT_ISSUER = GameSessionAccountDelegationProfile.ISSUER; @@ -152,8 +156,11 @@ Current readCurrentPublicProductionNew( lockExactAccountFirst(accountId); Snapshot snapshot = membershipSnapshots.readCurrent(accountId, targetTenantId); - TenantAuthorityEventV1Codec.Event authorityEvent = - tenantAuthorityEvents.readCurrentByTenant(targetTenantId); + var selected = tenantAuthorityEvents.readCurrentSourceSelection(targetTenantId); + if (selected.kind() != AccountTenantAuthorityEventRepository.SourceKind.NON_PAID_DEMO) { + throw unavailable(); + } + TenantAuthorityEventV1Codec.Event authorityEvent = selected.checkpoint(); DemoTenantEntitlementEventV1Codec.Event typedTenantEvent = readExactCurrentTenantEntitlement(targetTenantId, authorityEvent); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalog.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalog.java new file mode 100644 index 0000000000..604c75157e --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalog.java @@ -0,0 +1,80 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +/** + * Manually composed immutable operator/server configuration. No live default plans, environment + * discovery, provider lookup, bean registration or actor authority. Replace the catalog explicitly + * for new requests; retained subscription operations must never be repriced from this catalog. + */ +public final class AccountHostingPlanCatalog { + private final Map plans; + + public AccountHostingPlanCatalog(Collection configuration) { + if (configuration == null) { + throw new IllegalArgumentException("Explicit hosting-plan configuration is required"); + } + Map resolved = new HashMap<>(); + for (ConfiguredPlan entry : configuration) { + if (entry == null) { + throw new IllegalArgumentException("Hosting-plan configuration is incomplete"); + } + var quote = + new AccountHostingPlanQuote( + entry.planCode(), + entry.providerPriceId(), + integral(entry.providerQuantity()), + integral(entry.maxActiveSessions()), + integral(entry.maxConcurrentGameInstances()), + integral(entry.maxStorageBytes())); + quote.payload(); + if (resolved.putIfAbsent(quote.planCode(), quote) != null) { + throw new IllegalArgumentException( + "Ambiguous hosting-plan configuration: duplicate exact plan code"); + } + } + plans = Map.copyOf(resolved); + } + + public AccountHostingPlanQuote resolve(String normalizedPlanCode) { + AccountHostingPlanQuote.requirePlanCode(normalizedPlanCode); + var quote = plans.get(normalizedPlanCode); + if (quote == null) { + throw new PlanUnavailableException( + "Explicit hosting-plan configuration is absent for the requested plan"); + } + return quote; + } + + private static long integral(String value) { + if (value == null || value.length() > 19 || !value.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException( + "Explicit bounded unsigned integral plan value is required"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException overflow) { + throw new IllegalArgumentException( + "Hosting-plan value exceeds signed BIGINT range", overflow); + } + } + + /** + * Exact configuration values only. Strings permit rejecting incomplete/fractional/overflow input. + */ + public record ConfiguredPlan( + String planCode, + String providerPriceId, + String providerQuantity, + String maxActiveSessions, + String maxConcurrentGameInstances, + String maxStorageBytes) {} + + public static final class PlanUnavailableException extends IllegalStateException { + public PlanUnavailableException(String message) { + super(message); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingPlanQuote.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingPlanQuote.java new file mode 100644 index 0000000000..a84c8e47f2 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingPlanQuote.java @@ -0,0 +1,103 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.io.IOException; +import java.nio.CharBuffer; +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.util.Arrays; +import java.util.HexFormat; +import java.util.Map; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.json.JsonMapper; + +/** Server-resolved immutable hosting quote, not caller/owner authentication or an entitlement. */ +public record AccountHostingPlanQuote( + String planCode, + String providerPriceId, + long providerQuantity, + long maxActiveSessions, + long maxConcurrentGameInstances, + long maxStorageBytes) { + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final int MAX_PAYLOAD_BYTES = 4096; + + public AccountHostingPlanQuote { + requirePlanCode(planCode); + if (providerPriceId == null + || providerPriceId.length() > 255 + || !providerPriceId.matches("price_[A-Za-z0-9]+")) { + throw new IllegalArgumentException("Explicit Stripe price reference is required"); + } + if (providerQuantity < 1 + || maxActiveSessions < 0 + || maxConcurrentGameInstances < 0 + || maxStorageBytes < 0) { + throw new IllegalArgumentException( + "Positive quantity and explicit nonnegative quotas are required"); + } + } + + /** Fresh canonical bytes on every read; no mutable retained buffer escapes this value. */ + public byte[] payload() { + // Decimal strings preserve every BIGINT exactly, including values beyond JSON's safe-integer + // range. This is a versioned quote encoding, independent of the caller create-digest grammar. + var fields = + Map.of( + "schemaVersion", "account-hosting-plan-quote/v1", + "planCode", planCode, + "providerPriceId", providerPriceId, + "providerQuantity", Long.toString(providerQuantity), + "maxActiveSessions", Long.toString(maxActiveSessions), + "maxConcurrentGameInstances", Long.toString(maxConcurrentGameInstances), + "maxStorageBytes", Long.toString(maxStorageBytes)); + try { + byte[] bytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(fields)); + if (bytes.length > MAX_PAYLOAD_BYTES) { + throw new IllegalArgumentException("Hosting quote payload exceeds its retained byte bound"); + } + return bytes; + } catch (IOException failure) { + throw new IllegalStateException("Hosting quote encoding failed", failure); + } + } + + public String digest() { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(payload())); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + /** Exact canonical readback: neither altered bytes nor changed projection fields are accepted. */ + void requireRetained(byte[] retainedPayload, String retainedDigest) { + if (retainedPayload == null + || retainedPayload.length > MAX_PAYLOAD_BYTES + || !Arrays.equals(payload(), retainedPayload) + || !digest().equals(retainedDigest)) { + throw new IllegalStateException("Retained hosting quote bytes/digest/fields disagree"); + } + } + + static void requirePlanCode(String planCode) { + if (planCode == null + || planCode.isBlank() + || planCode.length() > 255 + || !planCode.equals(planCode.strip())) { + throw new IllegalArgumentException("Exact normalized plan code is required"); + } + try { + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(planCode)); + } catch (CharacterCodingException malformed) { + throw new IllegalArgumentException("Plan code must have an exact UTF-8 encoding", malformed); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionCurrentReceipt.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionCurrentReceipt.java new file mode 100644 index 0000000000..ca9e734463 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionCurrentReceipt.java @@ -0,0 +1,33 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy.Status; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; + +/** + * Consistent backend-only evaluation of one committed hosting receipt and fresh SDK evidence. It is + * NOT the caller-bound runtime/auth-evidence bundle, a capacity commitment, or a public API DTO. + * Quotas come only from current.planQuote(); neither numeric archives nor today's catalog is read. + */ +public record AccountHostingSubscriptionCurrentReceipt( + AccountSubscriptionCurrentRecord current, + UUID receiptRequestId, + Status subscriptionStatus, + boolean gameplayAvailable, + boolean allowPublicJoin, + boolean allowNewGameplayBindings, + boolean allowNewInstanceStarts, + long entitlementVersion, + long tenantBillingSequence, + UUID billingEventId, + String billingEventDigest, + TenantAuthorityEventV1Codec.Event tenantAuthorityEvent, + String rawProviderStatus, + Instant currentPeriodStart, + Instant currentPeriodEnd, + boolean cancelAtPeriodEnd, + Instant cancelAt, + Instant cutoffAt, + Instant evaluatedAt, + Instant validUntil) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleEvidence.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleEvidence.java new file mode 100644 index 0000000000..7957c27a6c --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleEvidence.java @@ -0,0 +1,234 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.io.IOException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +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 net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver.ObservedSubscription; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Narrow canonical persisted provider facts and production billing envelope; never authority alone. + */ +final class AccountHostingSubscriptionLifecycleEvidence { + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final Set BILLING_FIELDS = + Set.of( + "schemaVersion", + "eventType", + "tenantBillingStateChanged", + "eventTypes", + "tenantId", + "requestId", + "requestDigest", + "tenantBillingSequence", + "eventId", + "receipt"); + + private AccountHostingSubscriptionLifecycleEvidence() {} + + static Map facts(StripeHostingSubscriptionObserver.Result result) { + Map fields = new LinkedHashMap<>(); + fields.put("providerSubscriptionId", result.providerSubscriptionId()); + if (result instanceof ObservedSubscription observed) { + fields.put("kind", "SDK_OBSERVED"); + fields.put("providerCustomerId", observed.providerCustomerId()); + fields.put("providerPaymentMethodId", observed.providerPaymentMethodId()); + fields.put("providerSubscriptionItemId", observed.providerSubscriptionItemId()); + fields.put("providerPriceId", observed.providerPriceId()); + fields.put("providerQuantity", Long.toString(observed.providerQuantity())); + fields.put("providerStatus", observed.providerStatus()); + fields.put("periodStart", observed.currentPeriodStart().map(Object::toString).orElse(null)); + fields.put("periodEnd", observed.currentPeriodEnd().map(Object::toString).orElse(null)); + fields.put("cancelAtPeriodEnd", observed.cancelAtPeriodEnd()); + fields.put("cancelAt", observed.cancelAt().map(Object::toString).orElse(null)); + fields.put("canceledAt", observed.canceledAt().map(Object::toString).orElse(null)); + fields.put("endedAt", observed.endedAt().map(Object::toString).orElse(null)); + fields.put("metadata", observed.providerMetadata()); + fields.put("livemode", observed.livemode()); + } else if (result instanceof StripeHostingSubscriptionObserver.InvalidObservation invalid) { + fields.put("kind", "SDK_INVALID"); + fields.put("reason", invalid.reason().name()); + } else { + fields.put("kind", "SDK_UNRESOLVED"); + // Exception text can contain sensitive provider details; it is not absence or progress. + } + return fields; + } + + static byte[] observation(StripeHostingSubscriptionObserver.Result result) { + return observation( + facts(result), + result.readStartedAt().truncatedTo(java.time.temporal.ChronoUnit.MICROS), + result.observedAt().truncatedTo(java.time.temporal.ChronoUnit.MICROS)); + } + + static byte[] observation( + Map facts, java.time.Instant readStartedAt, java.time.Instant observedAt) { + Map fields = new LinkedHashMap<>(facts); + fields.put("schemaVersion", "account-hosting-provider-observation/v1"); + fields.put("readStartedAt", readStartedAt.toString()); + fields.put("observedAt", observedAt.toString()); + return encode(fields); + } + + static byte[] encode(Map fields) { + try { + byte[] payload = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(fields)); + if (payload.length > 32768) { + throw new IllegalArgumentException("Hosting evidence exceeds the retained payload bound"); + } + return payload; + } catch (IOException failure) { + throw new IllegalStateException("Hosting evidence encoding failed", failure); + } + } + + static String digest(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + static BillingEvent billing( + UUID tenantId, + UUID requestId, + String requestDigest, + long sequence, + UUID eventId, + Map receipt) { + Map fields = new LinkedHashMap<>(); + fields.put("schemaVersion", "account-hosting-subscription-event/v1"); + fields.put("eventType", "SubscriptionStatusChanged"); + fields.put("tenantBillingStateChanged", Boolean.TRUE.equals(receipt.get("hardCutoff"))); + // One atomic sequenced envelope carries both typed domain notifications for a hard cutoff. + fields.put( + "eventTypes", + Boolean.TRUE.equals(receipt.get("hardCutoff")) + ? java.util.List.of("SubscriptionStatusChanged", "TenantBillingStateChanged") + : java.util.List.of("SubscriptionStatusChanged")); + fields.put("tenantId", tenantId.toString()); + fields.put("requestId", requestId.toString()); + fields.put("requestDigest", requestDigest); + fields.put("tenantBillingSequence", Long.toString(sequence)); + fields.put("eventId", eventId.toString()); + fields.put("receipt", receipt); + return new BillingEvent(tenantId, requestId, requestDigest, sequence, eventId, encode(fields)); + } + + /** Inverse of billing: validates bounded canonical envelope data, never receipt authority. */ + static BillingEvent verifyBilling(byte[] payload) { + if (payload == null || payload.length == 0 || payload.length > 32768) { + throw new IllegalArgumentException("Hosting billing envelope is absent or oversized"); + } + final Map fields; + try { + fields = JSON.readValue(payload, new TypeReference<>() {}); + } catch (RuntimeException failure) { + throw new IllegalArgumentException("Hosting billing envelope is malformed", failure); + } + if (fields == null + || !fields.keySet().equals(BILLING_FIELDS) + || !"account-hosting-subscription-event/v1".equals(fields.get("schemaVersion")) + || !"SubscriptionStatusChanged".equals(fields.get("eventType")) + || !(fields.get("receipt") instanceof Map receipt) + || !(receipt.get("hardCutoff") instanceof Boolean hardCutoff) + || !hardCutoff.equals(fields.get("tenantBillingStateChanged")) + || !(hardCutoff + ? List.of("SubscriptionStatusChanged", "TenantBillingStateChanged") + : List.of("SubscriptionStatusChanged")) + .equals(fields.get("eventTypes"))) { + throw new IllegalArgumentException("Hosting billing envelope profile is inconsistent"); + } + UUID tenant = billingUuid(fields.get("tenantId")); + UUID request = billingUuid(fields.get("requestId")); + UUID event = billingUuid(fields.get("eventId")); + if (!(fields.get("requestDigest") instanceof String requestDigest) + || !requestDigest.matches("sha256:[0-9a-f]{64}") + || !TenantAuthorityEventV1Codec.tenantBillingEventId(request).equals(event) + || !"account-hosting-current-receipt/v1".equals(receipt.get("schemaVersion")) + || !tenant.toString().equals(receipt.get("tenantId")) + || !request.toString().equals(receipt.get("requestId")) + || !requestDigest.equals(receipt.get("requestDigest")) + || !(fields.get("tenantBillingSequence") instanceof String sequenceText) + || !sequenceText.matches("[1-9][0-9]{0,18}")) { + throw new IllegalArgumentException("Hosting billing envelope identity is inconsistent"); + } + final long sequence; + try { + sequence = Long.parseLong(sequenceText); + } catch (NumberFormatException failure) { + throw new IllegalArgumentException("Hosting billing sequence is invalid", failure); + } + if (!Arrays.equals(payload, encode(fields))) { + throw new IllegalArgumentException("Hosting billing envelope is not canonical JSON"); + } + return new BillingEvent(tenant, request, requestDigest, sequence, event, payload); + } + + private static UUID billingUuid(Object value) { + if (!(value instanceof String text)) { + throw new IllegalArgumentException("Canonical hosting billing UUID required"); + } + UUID uuid = UUID.fromString(text); + if (!uuid.toString().equals(text) || new UUID(0L, 0L).equals(uuid)) { + throw new IllegalArgumentException("Canonical hosting billing UUID required"); + } + return uuid; + } + + static final class BillingEvent { + final UUID tenantId; + final UUID requestId; + final String requestDigest; + final long sequence; + final UUID eventId; + private final byte[] payload; + + BillingEvent( + UUID tenantId, + UUID requestId, + String requestDigest, + long sequence, + UUID eventId, + byte[] payload) { + this.tenantId = tenantId; + this.requestId = requestId; + this.requestDigest = requestDigest; + this.sequence = sequence; + this.eventId = eventId; + this.payload = payload.clone(); + } + + byte[] payload() { + return payload.clone(); + } + + String digest() { + return AccountHostingSubscriptionLifecycleEvidence.digest(payload); + } + + boolean matches(byte[] bytes, String digest) { + return Arrays.equals(payload, bytes) && digest().equals(digest); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecyclePolicy.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecyclePolicy.java new file mode 100644 index 0000000000..89b2308505 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecyclePolicy.java @@ -0,0 +1,237 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.time.DateTimeException; +import java.time.Duration; +import java.time.Instant; +import java.util.Objects; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver.ObservedSubscription; + +/** + * Pure hosting lifecycle mapping of actual SDK observations. Manually composed; no live defaults, + * timers, provider mutation, current-row selection, or entitlement authority. The lifecycle owner + * must separately fence the original binding and atomically commit its receipt and canonical + * events. + */ +public final class AccountHostingSubscriptionLifecyclePolicy { + private final Duration maximumObservationAge; + private final RecoveryTiming recovery; + + public AccountHostingSubscriptionLifecyclePolicy( + Duration maximumObservationAge, RecoveryTiming recovery) { + this.maximumObservationAge = positive(maximumObservationAge, "maximum observation age"); + this.recovery = + Objects.requireNonNull(recovery, "Explicit payment recovery timing is required"); + } + + public Duration maximumObservationAge() { + return maximumObservationAge; + } + + public RecoveryTiming recoveryTiming() { + return recovery; + } + + /** + * The recovery origin must come from retained Account history for this uninterrupted payment + * failure episode, never from the delivery time of a retry. Null means that origin is + * unavailable; it does not start a new warning or grace window. Results are mapping evidence, not + * permissions. + */ + public Decision evaluate( + StripeHostingSubscriptionObserver.Result result, + Instant evaluatedAt, + Instant retainedPastDueSince) { + Objects.requireNonNull(result, "Actual SDK read result is required"); + Objects.requireNonNull(evaluatedAt, "Account evaluation time is required"); + if (!(result instanceof ObservedSubscription observed)) { + return unavailable(Reason.PROVIDER_UNRESOLVED); + } + if (observed.readStartedAt().isAfter(observed.observedAt()) + || observed.observedAt().isAfter(evaluatedAt)) { + return unavailable(Reason.UNSAFE_READ_INTERVAL); + } + // Read-start, rather than response-arrival, bounds the age of provider knowledge. A slow + // response cannot refresh stale input merely because it completed recently. + Instant observationDeadline = + plus( + observed.readStartedAt().truncatedTo(java.time.temporal.ChronoUnit.MICROS), + maximumObservationAge); + if (!evaluatedAt.isBefore(observationDeadline)) { + return unavailable(Reason.OBSERVATION_EXPIRED); + } + if (observed.providerStatusIsCanceled()) { + // canceled_at is the cancellation-request time for period-end cancellation, NOT paid-through. + Instant endedAt = + observed + .endedAt() + .orElse(observed.observedAt().truncatedTo(java.time.temporal.ChronoUnit.MICROS)); + if (endedAt.isAfter(evaluatedAt)) { + return unavailable(Reason.CONTRADICTORY_PROVIDER_FACTS); + } + return new Decision( + Status.CANCELED, + Reason.PROVIDER_CONFIRMED, + observationDeadline, + observationDeadline, + endedAt); + } + + Instant start = observed.currentPeriodStart().orElse(null); + Instant end = observed.currentPeriodEnd().orElse(null); + if (start == null || end == null || !start.isBefore(end) || evaluatedAt.isBefore(start)) { + return unavailable(Reason.PERIOD_UNRESOLVED); + } + if (observed.endedAt().isPresent()) { + return unavailable(Reason.CONTRADICTORY_PROVIDER_FACTS); + } + Instant cancellation = observed.cancelAt().orElse(null); + if (observed.cancelAtPeriodEnd()) { + cancellation = earlier(cancellation, end); + } + if (cancellation != null && !evaluatedAt.isBefore(cancellation)) { + return new Decision( + Status.CANCELED, + Reason.EFFECTIVE_CANCELLATION, + observationDeadline, + observationDeadline, + cancellation); + } + if (!evaluatedAt.isBefore(end)) { + // An expired period without a confirmed end schedule is unknown renewal state, not an + // invented cancellation and not permission to extend the last positive period. + return unavailable(Reason.PERIOD_UNRESOLVED); + } + Instant receiptValidUntil = earlier(end, cancellation); + Instant validUntil = earlier(observationDeadline, receiptValidUntil); + return switch (observed.providerStatus()) { + case "active" -> + new Decision( + Status.ACTIVE, Reason.PROVIDER_CONFIRMED, validUntil, receiptValidUntil, null); + case "trialing" -> + new Decision( + Status.TRIALING, Reason.PROVIDER_CONFIRMED, validUntil, receiptValidUntil, null); + case "past_due" -> + pastDue(evaluatedAt, retainedPastDueSince, receiptValidUntil, observationDeadline); + // These provider values cannot establish an active/trialing hosting agreement. Their + // resolution remains explicit rather than inventing a grace policy for an incomplete or + // paused subscription. Automatic suspension is driven by the configured past_due episode. + default -> unavailable(Reason.UNMAPPED_PROVIDER_STATUS); + }; + } + + private Decision pastDue( + Instant now, Instant origin, Instant receiptValidUntil, Instant observationDeadline) { + if (origin == null || origin.isAfter(now)) { + return unavailable(Reason.RECOVERY_ORIGIN_UNRESOLVED); + } + Instant graceAt = plus(origin, recovery.pastDueWarning()); + Instant suspendAt = plus(graceAt, recovery.grace()); + if (!now.isBefore(suspendAt)) { + return new Decision( + Status.SUSPENDED, + Reason.PAYMENT_RECOVERY_EXHAUSTED, + earlier(observationDeadline, receiptValidUntil), + receiptValidUntil, + suspendAt); + } + if (!now.isBefore(graceAt)) { + return new Decision( + Status.GRACE, + Reason.PAYMENT_RECOVERY, + earlier(observationDeadline, earlier(receiptValidUntil, suspendAt)), + earlier(receiptValidUntil, suspendAt), + null); + } + return new Decision( + Status.PAST_DUE, + Reason.PAYMENT_RECOVERY, + earlier(observationDeadline, earlier(receiptValidUntil, graceAt)), + earlier(receiptValidUntil, graceAt), + null); + } + + private static Decision unavailable(Reason reason) { + return new Decision(null, reason, null, null, null); + } + + private static Instant earlier(Instant left, Instant right) { + if (left == null) { + return right; + } + return right == null || left.isBefore(right) ? left : right; + } + + private static Instant plus(Instant instant, Duration duration) { + try { + return instant.plus(duration); + } catch (DateTimeException | ArithmeticException overflow) { + throw new IllegalArgumentException( + "Configured lifecycle timing overflows the UTC time domain", overflow); + } + } + + private static Duration positive(Duration duration, String name) { + if (duration == null || duration.isZero() || duration.isNegative()) { + throw new IllegalArgumentException("Explicit positive " + name + " is required"); + } + // Validate the configuration, not only whichever branch first happens to consume it. + plus(Instant.EPOCH, duration); + return duration; + } + + public record RecoveryTiming(Duration pastDueWarning, Duration grace) { + public RecoveryTiming { + pastDueWarning = positive(pastDueWarning, "past-due warning duration"); + grace = positive(grace, "grace duration"); + try { + plus(Instant.EPOCH, pastDueWarning.plus(grace)); + } catch (ArithmeticException overflow) { + throw new IllegalArgumentException("Combined recovery timing overflows", overflow); + } + } + } + + public enum Status { + TRIALING, + ACTIVE, + PAST_DUE, + GRACE, + SUSPENDED, + CANCELED; + + public String storageValue() { + return name().toLowerCase(java.util.Locale.ROOT); + } + } + + public enum Reason { + PROVIDER_CONFIRMED, + EFFECTIVE_CANCELLATION, + PAYMENT_RECOVERY, + PAYMENT_RECOVERY_EXHAUSTED, + PROVIDER_UNRESOLVED, + UNSAFE_READ_INTERVAL, + OBSERVATION_EXPIRED, + PERIOD_UNRESOLVED, + CONTRADICTORY_PROVIDER_FACTS, + RECOVERY_ORIGIN_UNRESOLVED, + UNMAPPED_PROVIDER_STATUS + } + + /** + * Null status denotes unavailable mapping, not a known suspended/canceled entitlement. The fresh + * read's validUntil includes observation age; receiptValidUntil retains the provider/policy fact + * boundary so a later independently fresh read does not require another lifecycle mutation. + */ + public record Decision( + Status status, + Reason reason, + Instant validUntil, + Instant receiptValidUntil, + Instant cutoffAt) { + public boolean resolved() { + return status != null; + } + } +} 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 new file mode 100644 index 0000000000..f1c7283e82 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java @@ -0,0 +1,1483 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +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.AccountHostingSubscriptionLifecyclePolicy.RecoveryTiming; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy.Status; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.FenceRejectedException; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Manually composed hosting lifecycle owner. All methods use short writable Account transactions; + * the service performs actual SDK reads strictly between them. No provider mutation or runtime + * route is registered. Stored status rows alone are never a positive internal read. + */ +public final class AccountHostingSubscriptionLifecycleRepository { + private final DSLContext dsl; + private final AccountSubscriptionIntentRepository intents; + private final Clock clock; + private final ReconciliationLimits limits; + private final AccountHostingSubscriptionLifecyclePolicy policy; + private final boolean livemode; + private final AccountAuthorityGenerationRepository generations; + private final FreshTenantIdentityAssociationRepository tenantIdentity; + private final AccountTenantEntitlementOutboxRepository billing; + private final AccountTenantAuthorityEventRepository tenantEvents; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected owner transaction collaborators are retained privately and never exposed.") + public AccountHostingSubscriptionLifecycleRepository( + DSLContext dsl, + AccountSubscriptionIntentRepository intents, + Clock clock, + ReconciliationLimits limits, + AccountHostingSubscriptionLifecyclePolicy policy, + String namespace, + boolean livemode) { + this.dsl = Objects.requireNonNull(dsl); + this.intents = Objects.requireNonNull(intents); + this.clock = Objects.requireNonNull(clock); + this.limits = + Objects.requireNonNull(limits, "Explicit bounded reconciliation limits are required"); + this.policy = Objects.requireNonNull(policy); + ReconciliationLimits.wholeMilliseconds(policy.maximumObservationAge()); + ReconciliationLimits.wholeMilliseconds(policy.recoveryTiming().pastDueWarning()); + ReconciliationLimits.wholeMilliseconds(policy.recoveryTiming().grace()); + this.livemode = livemode; + if (namespace == null || namespace.isBlank()) { + throw new IllegalArgumentException("Explicit Account workload namespace is required"); + } + generations = new AccountAuthorityGenerationRepository(dsl); + tenantIdentity = new FreshTenantIdentityAssociationRepository(dsl, namespace); + billing = new AccountTenantEntitlementOutboxRepository(dsl); + tenantEvents = + new AccountTenantAuthorityEventRepository( + dsl, new AccountAuthorityOutboxRepository(dsl), billing, tenantIdentity, generations); + } + + /** + * Reserves currentness before an SDK read; stable request replay never issues a second + * transition. + */ + public Preparation prepare( + UUID requestId, + UUID creationId, + long expectedVersion, + String providerId, + UUID provisioningAttemptId) { + requireTransaction(); + AccountBillingCustomerRecord.requireUuid(requestId); + AccountBillingCustomerRecord.requireUuid(creationId); + if (expectedVersion < 1 + || expectedVersion >= Long.MAX_VALUE - 1 + || providerId == null + || !providerId.matches("sub_[A-Za-z0-9]{1,251}")) { + throw new IllegalArgumentException( + "Exact provider identity and advanceable current version are required"); + } + byte[] input = + AccountHostingSubscriptionLifecycleEvidence.encode( + Map.of( + "schemaVersion", + "account-hosting-reconciliation-request/v1", + "requestId", + requestId.toString(), + "creationRequestId", + creationId.toString(), + "expectedRowVersion", + Long.toString(expectedVersion), + "providerSubscriptionId", + providerId, + "provisioningAttemptId", + provisioningAttemptId == null ? "" : provisioningAttemptId.toString())); + var original = intents.findCreation(creationId).orElseThrow(); + // Serialize same-owner retries before reading the mutable operation head. A same-request + // contender observes the winner's pending/committed outcome instead of a stale pre-lock image. + new AccountPaymentInstrumentRepository(dsl) + .findByOwnerForUpdate(original.owner().accountUuid(), original.paymentInstrumentId()) + .orElseThrow(() -> new FenceRejectedException("Original provisioning wallet is absent")); + Record operation = + dsl.fetchOne( + "SELECT * FROM subscription_lifecycle_operations WHERE request_id = ?", requestId); + if (operation != null + && !Arrays.equals(input, operation.get("request_payload", byte[].class))) { + throw new FenceRejectedException("IDEMPOTENCY_CONFLICT: lifecycle request changed"); + } + if (operation != null && !"PENDING".equals(operation.get("state", String.class))) { + return preparationOutcome(operation); + } + var current = + intents.lockForLifecycle( + creationId, + operation == null + ? expectedVersion + : operation.get("reserved_row_version", Long.class)); + Instant now = now(); + if (now.isBefore(original.createdAt())) { + throw new FenceRejectedException("Lifecycle clock predates its durable creation operation"); + } + if (operation == null) { + Record currentLinks = links(current.subscriptionId()); + if (currentLinks.get("lifecycle_inflight_request_id") != null) { + throw new FenceRejectedException("Another lifecycle request owns the current fence"); + } + Record priorReceipt = receiptForCurrent(currentLinks); + if (current.providerSubscriptionId() != null + && !providerId.equals(current.providerSubscriptionId())) { + throw new FenceRejectedException( + "Reconciliation cannot rebind the canonical provider identity"); + } + if (priorReceipt == null) { + Record work = workForUpdate(creationId); + Record claimedAttempt = + provisioningAttemptId == null + ? null + : dsl.fetchOne( + "SELECT claimed_at FROM subscription_provisioning_attempts WHERE attempt_id = ?", + provisioningAttemptId); + if (provisioningAttemptId == null + || !"provisioning".equals(current.status()) + || claimedAttempt == null + || now.isBefore(instant(claimedAttempt, "claimed_at")) + || !"CLAIMED".equals(work.get("phase", String.class)) + || !provisioningAttemptId.equals(work.get("last_attempt_id", UUID.class)) + || current.rowVersion() != work.get("subscription_row_version", Long.class) + || !now.isBefore(instant(work, "lease_expires_at")) + || !now.isBefore(instant(work, "deadline_at"))) { + throw new FenceRejectedException( + "Initial confirmation lacks its exact durable provisioning claim"); + } + } else if (current.providerSubscriptionId() == null || provisioningAttemptId != null) { + throw new FenceRejectedException( + "Reconciliation cannot rebind a provider or reuse provisioning work"); + } + long warning = + priorReceipt != null && priorReceipt.get("past_due_since") != null + ? priorReceipt.get("warning_millis", Long.class) + : policy.recoveryTiming().pastDueWarning().toMillis(); + long grace = + priorReceipt != null && priorReceipt.get("past_due_since") != null + ? priorReceipt.get("grace_millis", Long.class) + : policy.recoveryTiming().grace().toMillis(); + 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) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'PENDING', 1, ?, ?, ?, ?, ?, ?, ?, ?::timestamptz, ?::timestamptz, ?::timestamptz)", + requestId, + creationId, + current.subscriptionId(), + current.tenantId(), + expectedVersion, + expectedVersion + 1, + providerId, + provisioningAttemptId, + input, + AccountHostingSubscriptionLifecycleEvidence.digest(input), + limits.maximumAttempts(), + limits.maximumStalledAttempts(), + limits.lease().toMillis(), + limits.backoff().toMillis(), + policy.maximumObservationAge().toMillis(), + warning, + grace, + utc(now.plus(limits.absoluteTimeout())), + utc(now), + utc(now)); + 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 IS NULL AND superseded_at IS NULL", + requestId, + current.subscriptionId(), + expectedVersion) + != 1) { + throw new FenceRejectedException("Lifecycle prepare expected-current CAS rejected"); + } + } + operation = operationForUpdate(requestId); + if (!now.isBefore(instant(operation, "deadline_at"))) { + terminalLifecycle(operation, "ABSOLUTE_DEADLINE", now); + return preparationOutcome(operationForUpdate(requestId)); + } + if (operation.get("attempt_count", Integer.class) + >= operation.get("max_attempts", Integer.class) + || operation.get("stalled_count", Integer.class) + >= operation.get("max_stalled_attempts", Integer.class)) { + terminalLifecycle(operation, "ATTEMPT_OR_STALL_BUDGET", now); + return preparationOutcome(operationForUpdate(requestId)); + } + if (now.isBefore(instant(operation, "retry_at"))) { + return new Preparation(requestId, null, null, Outcome.RECONCILING, "BACKOFF_OR_INFLIGHT", 0); + } + UUID attemptId = UUID.randomUUID(); + Instant expires = + earlier( + now.plusMillis(operation.get("lease_millis", Long.class)), + instant(operation, "deadline_at")); + int number = operation.get("attempt_count", Integer.class) + 1; + dsl.execute( + "INSERT INTO subscription_lifecycle_attempts (attempt_id, request_id, attempt_number, started_at, expires_at) VALUES (?, ?, ?, ?::timestamptz, ?::timestamptz)", + attemptId, + requestId, + number, + utc(now), + utc(expires)); + dsl.execute( + "UPDATE subscription_lifecycle_operations SET attempt_count = ?, last_attempt_id = ?, retry_at = ?::timestamptz, " + + "row_version = row_version + 1 WHERE request_id = ?", + number, + attemptId, + utc(expires.plusMillis(operation.get("backoff_millis", Long.class))), + requestId); + return new Preparation( + requestId, + attemptId, + expected(original, providerId), + Outcome.READY, + null, + operation.get("reserved_row_version", Long.class)); + } + + /** + * Accepts only the observer's sealed SDK result, rechecking every binding under the original lock + * order. + */ + public TransitionResult apply( + Preparation prepared, StripeHostingSubscriptionObserver.Result result) { + requireTransaction(); + Objects.requireNonNull(prepared); + Objects.requireNonNull(result); + Record retained = operationForUpdateRead(prepared.requestId()); + var current = + intents.lockForLifecycle( + retained.get("creation_request_id", UUID.class), + retained.get("reserved_row_version", Long.class)); + Record operation = operationForUpdate(prepared.requestId()); + Instant now = now(); + Record attempt = + dsl.fetchOne( + "SELECT * FROM subscription_lifecycle_attempts WHERE attempt_id = ?", + prepared.attemptId()); + if (!"PENDING".equals(operation.get("state", String.class)) + || !prepared.attemptId().equals(operation.get("last_attempt_id", UUID.class)) + || attempt == null + || now.isBefore(instant(attempt, "started_at")) + || !now.isBefore(instant(attempt, "expires_at")) + || !now.isBefore(instant(operation, "deadline_at")) + || result.readStartedAt().isBefore(instant(attempt, "started_at")) + || !result + .providerSubscriptionId() + .equals(operation.get("provider_subscription_id", String.class))) { + throw new FenceRejectedException("Stale, expired or mismatched lifecycle SDK attempt"); + } + var original = intents.findCreation(current.creationRequestId()).orElseThrow(); + ExpectedBinding binding = + expected(original, operation.get("provider_subscription_id", String.class)); + if (result instanceof ObservedSubscription observed) { + requireObservedBinding(binding, observed); + } + Record oldReceipt = receiptForCurrent(links(current.subscriptionId())); + Instant origin = retainedPastDueOrigin(oldReceipt); + // A provider read cannot establish when an uninterrupted payment-failure episode began. + // Missing retained history must remain unresolved rather than restarting warning/grace. + var decision = retainedPolicy(operation).evaluate(result, now, origin); + byte[] observation = AccountHostingSubscriptionLifecycleEvidence.observation(result); + String observationDigest = AccountHostingSubscriptionLifecycleEvidence.digest(observation); + String factsDigest = + AccountHostingSubscriptionLifecycleEvidence.digest( + AccountHostingSubscriptionLifecycleEvidence.encode( + AccountHostingSubscriptionLifecycleEvidence.facts(result))); + ObservedSubscription observed = result instanceof ObservedSubscription value ? value : null; + dsl.execute( + "INSERT INTO subscription_lifecycle_observations (attempt_id, request_id, payload, evidence_digest, facts_digest, " + + "raw_status, period_start, period_end, read_started_at, observed_at, mapping_reason) VALUES (?, ?, ?, ?, ?, ?, ?::timestamptz, ?::timestamptz, ?::timestamptz, ?::timestamptz, ?)", + prepared.attemptId(), + prepared.requestId(), + observation, + observationDigest, + factsDigest, + observed == null ? null : observed.providerStatus(), + observed == null ? null : utcNullable(observed.currentPeriodStart().orElse(null)), + observed == null ? null : utcNullable(observed.currentPeriodEnd().orElse(null)), + utc(result.readStartedAt().truncatedTo(ChronoUnit.MICROS)), + utc(result.observedAt().truncatedTo(ChronoUnit.MICROS)), + decision.reason().name()); + if (!decision.resolved()) { + int stalled = + factsDigest.equals(operation.get("last_facts_digest", String.class)) + ? operation.get("stalled_count", Integer.class) + 1 + : 1; + dsl.execute( + "UPDATE subscription_lifecycle_operations SET last_facts_digest = ?, stalled_count = ?, failure_reason = ?, " + + "retry_at = ?::timestamptz, row_version = row_version + 1 WHERE request_id = ?", + factsDigest, + stalled, + decision.reason().name(), + utc( + earlier( + now.plusMillis(operation.get("backoff_millis", Long.class)), + instant(operation, "deadline_at"))), + prepared.requestId()); + operation = operationForUpdate(prepared.requestId()); + if (stalled >= operation.get("max_stalled_attempts", Integer.class) + || operation.get("attempt_count", Integer.class) + >= operation.get("max_attempts", Integer.class)) { + terminalLifecycle(operation, "ATTEMPT_OR_STALL_BUDGET", now); + return new TransitionResult( + prepared.requestId(), Outcome.TERMINAL_FAILURE, 0, decision.reason().name()); + } + return new TransitionResult( + prepared.requestId(), Outcome.RECONCILING, 0, decision.reason().name()); + } + Objects.requireNonNull(observed); + if (current.status().equals("canceled") && decision.status() != Status.CANCELED) { + throw new FenceRejectedException("A canceled subscription cannot be reactivated"); + } + UUID inflight = + links(current.subscriptionId()).get("lifecycle_inflight_request_id", UUID.class); + if (!prepared.requestId().equals(inflight)) { + throw new FenceRejectedException("Lifecycle operation lost its current fence"); + } + if (current.providerSubscriptionId() == null) { + 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, ?)", + observed.providerSubscriptionId(), + current.subscriptionId(), + original.requestId(), + original.subscriptionProvisioningRequestId(), + utc(observed.observedAt()), + observationDigest); + } else { + var mapping = intents.lookupProviderId(observed.providerSubscriptionId()); + if (mapping.history().isEmpty() + || !mapping.history().orElseThrow().subscriptionId().equals(current.subscriptionId()) + || !observed.providerSubscriptionId().equals(current.providerSubscriptionId())) { + throw new FenceRejectedException("Provider reconciliation has no exact canonical mapping"); + } + } + var source = tenantIdentity.read(current.tenantId()).orElseThrow(); + var authority = + generations.read( + AccountAuthorityGenerationRepository.AuthorityScope.tenant(current.tenantId())); + if (dsl.fetchOne( + "SELECT tenant_uuid FROM account_tenant_authority_source_records WHERE tenant_uuid = ? FOR UPDATE", + current.tenantId()) + == null) { + tenantEvents.establishFirstEventSource( + current.tenantId(), prepared.requestId(), source, authority); + } + var next = generations.advance(authority, null); + long entitlementVersion = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT greatest(" + + "coalesce((SELECT max(entitlement_version) FROM subscription_lifecycle_receipts WHERE tenant_id = ?), 0), " + + "coalesce((SELECT entitlement_version FROM account_demo_tenant_entitlements WHERE tenant_uuid = ?), 0)) + 1 AS next_version", + current.tenantId(), + current.tenantId())) + .get("next_version", Long.class); + if (!observed.providerStatus().equals("past_due")) { + origin = null; + } + Map receipt = + receiptFields( + operation, + original, + current.rowVersion() + 1, + entitlementVersion, + observed, + observationDigest, + decision, + origin, + next.generation(), + next.sourceVersion()); + byte[] receiptPayload = AccountHostingSubscriptionLifecycleEvidence.encode(receipt); + UUID eventId = TenantAuthorityEventV1Codec.tenantBillingEventId(prepared.requestId()); + var event = + billing.appendHosting( + current.tenantId(), + prepared.requestId(), + sequence -> + AccountHostingSubscriptionLifecycleEvidence.billing( + current.tenantId(), + prepared.requestId(), + retained.get("request_digest", String.class), + sequence, + eventId, + receipt)); + var authorityEvent = + tenantEvents.appendHosting( + prepared.requestId(), + operation.get("request_digest", String.class), + source, + next, + event.sequence, + event.eventId, + event.digest()); + dsl.execute( + "INSERT INTO subscription_lifecycle_receipts (request_id, subscription_id, tenant_id, request_digest, subscription_row_version, " + + "status, plan_quote_digest, provider_subscription_id, attempt_id, observation_digest, receipt_payload, receipt_digest, valid_until, cutoff_at, " + + "past_due_since, warning_millis, grace_millis, entitlement_version, billing_sequence, billing_event_id, billing_event_digest, authority_generation, " + + "authority_source_version, authority_sequence, authority_event_id, authority_event_digest, committed_at) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?::timestamptz, ?::timestamptz, ?::timestamptz, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?::timestamptz)", + prepared.requestId(), + current.subscriptionId(), + current.tenantId(), + operation.get("request_digest", String.class), + current.rowVersion() + 1, + decision.status().storageValue(), + original.planQuote().digest(), + observed.providerSubscriptionId(), + prepared.attemptId(), + observationDigest, + receiptPayload, + AccountHostingSubscriptionLifecycleEvidence.digest(receiptPayload), + utc(decision.receiptValidUntil()), + utcNullable(decision.cutoffAt()), + utcNullable(origin), + operation.get("warning_millis", Long.class), + operation.get("grace_millis", Long.class), + entitlementVersion, + event.sequence, + event.eventId, + event.digest(), + next.generation(), + next.sourceVersion(), + authorityEvent.outboxSequence(), + authorityEvent.eventId().toString(), + authorityEvent.eventDigest(), + utc(now)); + UUID terminalResolution = current.terminalResolutionId(); + if (observed.providerStatusIsCanceled() && terminalResolution == null) { + terminalResolution = UUID.randomUUID(); + 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 (?, ?, ?, ?, ?, 'CANCELED', ?::timestamptz, ?)", + terminalResolution, + original.requestId(), + current.subscriptionId(), + original.cleanupProviderIdentity(), + observed.providerSubscriptionId(), + utc(decision.cutoffAt()), + observationDigest); + dsl.execute( + "UPDATE subscription_instrument_reservations SET terminal_resolution_id = ?, released_at = ?::timestamptz WHERE request_id = ? AND released_at IS NULL", + terminalResolution, + utc(now), + original.requestId()); + } + if (dsl.execute( + "UPDATE subscription SET status = ?, provider_subscription_id = ?, terminal_resolution_id = ?, " + + "lifecycle_inflight_request_id = NULL, current_receipt_request_id = ?, row_version = row_version + 1 " + + "WHERE subscription_id = ? AND row_version = ? AND lifecycle_inflight_request_id = ? AND superseded_at IS NULL", + decision.status().storageValue(), + observed.providerSubscriptionId(), + terminalResolution, + prepared.requestId(), + current.subscriptionId(), + current.rowVersion(), + prepared.requestId()) + != 1) { + throw new FenceRejectedException("Lifecycle expected-current commit CAS rejected"); + } + dsl.execute( + "UPDATE subscription_lifecycle_operations SET state = 'COMMITTED', last_facts_digest = ?, failure_reason = NULL, " + + "row_version = row_version + 1 WHERE request_id = ?", + factsDigest, + prepared.requestId()); + if (operation.get("provisioning_attempt_id") != null) { + dsl.execute( + "UPDATE subscription_provisioning_work SET phase = 'CONFIRMED', row_version = row_version + 1 WHERE request_id = ? AND phase = 'CLAIMED'", + original.requestId()); + } + tenantEvents.readHostingCheckpoint(current.tenantId(), prepared.requestId()); + return new TransitionResult( + prepared.requestId(), Outcome.COMMITTED, current.rowVersion() + 1, null); + } + + private Map receiptFields( + Record operation, + AccountSubscriptionCreationRecord original, + long rowVersion, + long entitlementVersion, + ObservedSubscription observed, + String observationDigest, + AccountHostingSubscriptionLifecyclePolicy.Decision decision, + Instant origin, + long generation, + long sourceVersion) { + Map fields = new LinkedHashMap<>(); + fields.put("schemaVersion", "account-hosting-current-receipt/v1"); + fields.put("requestId", operation.get("request_id", UUID.class).toString()); + fields.put("requestDigest", operation.get("request_digest", String.class)); + fields.put("subscriptionId", original.subscriptionId().toString()); + fields.put("tenantId", original.tenantId().toString()); + fields.put("creationRequestId", original.requestId().toString()); + fields.put("billingOwnerAccountId", original.owner().accountUuid().toString()); + fields.put("billingOwnerVersion", Long.toString(original.owner().version())); + fields.put("billingOwnerGeneration", original.owner().generation().toString()); + fields.put("paymentInstrumentId", original.paymentInstrumentId().toString()); + fields.put("reservedInstrumentVersion", Long.toString(original.reservedInstrumentVersion())); + fields.put( + "customerProvisioningRequestId", original.customerProvisioningRequestId().toString()); + fields.put("providerCustomerId", original.providerCustomerId()); + fields.put("subscriptionRowVersion", Long.toString(rowVersion)); + fields.put("entitlementVersion", Long.toString(entitlementVersion)); + fields.put("subscriptionStatus", decision.status().storageValue()); + fields.put("planQuoteDigest", original.planQuote().digest()); + fields.put( + "planQuote", + new String(original.planQuote().payload(), java.nio.charset.StandardCharsets.UTF_8)); + fields.put("observationDigest", observationDigest); + fields.put("providerSubscriptionId", observed.providerSubscriptionId()); + fields.put("providerFacts", AccountHostingSubscriptionLifecycleEvidence.facts(observed)); + fields.put( + "hardCutoff", + decision.status() == Status.SUSPENDED || decision.status() == Status.CANCELED); + fields.put("validUntil", decision.receiptValidUntil().toString()); + fields.put("cutoffAt", decision.cutoffAt() == null ? null : decision.cutoffAt().toString()); + fields.put("pastDueSince", origin == null ? null : origin.toString()); + fields.put("authorityGeneration", Long.toString(generation)); + fields.put("authoritySourceVersion", Long.toString(sourceVersion)); + return fields; + } + + private void terminalLifecycle(Record operation, String reason, Instant now) { + dsl.execute( + "UPDATE subscription_lifecycle_operations SET state = 'BILLING_RECONCILIATION_TERMINAL_FAILURE', " + + "failure_reason = ?, row_version = row_version + 1 WHERE request_id = ?", + reason, + operation.get("request_id", UUID.class)); + dsl.execute( + "INSERT INTO subscription_lifecycle_operator_outbox (request_id, reason, recorded_at) VALUES (?, ?, ?::timestamptz)", + operation.get("request_id", UUID.class), + reason, + utc(now)); + } + + private Preparation preparationOutcome(Record operation) { + boolean committed = "COMMITTED".equals(operation.get("state", String.class)); + return new Preparation( + operation.get("request_id", UUID.class), + null, + null, + committed ? Outcome.COMMITTED : Outcome.TERMINAL_FAILURE, + operation.get("failure_reason", String.class), + committed ? operation.get("reserved_row_version", Long.class) + 1 : 0); + } + + private Record links(UUID subscriptionId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT lifecycle_inflight_request_id, current_receipt_request_id " + + "FROM subscription WHERE subscription_id = ?", + subscriptionId)); + } + + private Record receiptForCurrent(Record links) { + UUID id = links.get("current_receipt_request_id", UUID.class); + return id == null + ? null + : dsl.fetchOne("SELECT * FROM subscription_lifecycle_receipts WHERE request_id = ?", id); + } + + private Record operationForUpdateRead(UUID id) { + return Objects.requireNonNull( + dsl.fetchOne("SELECT * FROM subscription_lifecycle_operations WHERE request_id = ?", id)); + } + + private Record operationForUpdate(UUID id) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM subscription_lifecycle_operations WHERE request_id = ? FOR UPDATE", id)); + } + + private ExpectedBinding expected(AccountSubscriptionCreationRecord original, String providerId) { + var wallet = + new AccountPaymentInstrumentRepository(dsl) + .findByOwner(original.owner().accountUuid(), original.paymentInstrumentId()) + .orElseThrow(); + return new ExpectedBinding( + providerId, + original.subscriptionId(), + original.providerCustomerId(), + wallet.providerPaymentMethodId(), + original.planQuote().providerPriceId(), + original.planQuote().providerQuantity(), + StripeHostingSubscriptionObserver.OperationType.SUBSCRIPTION_PROVISIONING, + original.subscriptionProvisioningRequestId(), + livemode); + } + + private static void requireObservedBinding( + ExpectedBinding binding, ObservedSubscription observed) { + if (!binding.providerSubscriptionId().equals(observed.providerSubscriptionId()) + || !binding.providerCustomerId().equals(observed.providerCustomerId()) + || !binding.providerPaymentMethodId().equals(observed.providerPaymentMethodId()) + || !binding.providerPriceId().equals(observed.providerPriceId()) + || binding.expectedQuantity() != observed.providerQuantity() + || binding.livemode() != observed.livemode() + || binding.operationType() != observed.correlation().operationType() + || !binding.operationId().equals(observed.correlation().operationId()) + || !binding.subscriptionId().equals(observed.correlation().subscriptionId())) { + throw new FenceRejectedException( + "Actual SDK evidence differs from the exact retained binding"); + } + } + + private AccountHostingSubscriptionLifecyclePolicy retainedPolicy(Record operation) { + return new AccountHostingSubscriptionLifecyclePolicy( + Duration.ofMillis(operation.get("observation_age_millis", Long.class)), + new RecoveryTiming( + Duration.ofMillis(operation.get("warning_millis", Long.class)), + Duration.ofMillis(operation.get("grace_millis", Long.class)))); + } + + private Instant now() { + return clock.instant().truncatedTo(ChronoUnit.MICROS); + } + + /** Captures the locked current fence; it contains no gameplay permission and is not a receipt. */ + public ReadFence prepareCurrentRead(UUID tenantId) { + requireTransaction(); + var candidate = intents.findCurrentByTenant(tenantId).orElseThrow(); + var current = intents.lockForLifecycle(candidate.creationRequestId(), candidate.rowVersion()); + Record currentLinks = links(current.subscriptionId()); + if (currentLinks.get("lifecycle_inflight_request_id") != null + || current.providerSubscriptionId() == null) { + throw new FenceRejectedException( + "ENTITLEMENT_UNAVAILABLE: lifecycle is unresolved or in flight"); + } + Record receipt = + Objects.requireNonNull( + receiptForCurrent(currentLinks), "Committed current receipt is absent"); + // CANCELED is a terminal negative projection, never a time-bounded positive entitlement. + // Its retained observation deadline does not prevent a fresh SDK confirmation below; the + // original receipt/source bytes remain mandatory and the result still has its own deadline. + boolean terminalCanceled = Status.CANCELED.storageValue().equals(current.status()); + if (current.supersededAt() != null + || current.rowVersion() != receipt.get("subscription_row_version", Long.class) + || !current.status().equals(receipt.get("status", String.class)) + || !current + .providerSubscriptionId() + .equals(receipt.get("provider_subscription_id", String.class)) + || now().isBefore(instant(receipt, "committed_at")) + || (!terminalCanceled && !now().isBefore(instant(receipt, "valid_until")))) { + throw new FenceRejectedException( + "ENTITLEMENT_UNAVAILABLE: current receipt is expired or inconsistent"); + } + tenantEvents.readHostingCheckpoint(tenantId, receipt.get("request_id", UUID.class)); + var original = intents.findCreation(current.creationRequestId()).orElseThrow(); + return new ReadFence( + tenantId, + current.creationRequestId(), + current.rowVersion(), + receipt.get("request_id", UUID.class), + expected(original, current.providerSubscriptionId())); + } + + /** + * A positive internal result requires a fresh REAL SDK read AND the same committed receipt/source + * under reacquired original-binding locks. Raw SQL-shaped status/quote rows alone never + * authorize. The SDK call is outside SQL; a changed/in-flight row, period or provider fact + * rejects the fence. + */ + public AccountHostingSubscriptionCurrentReceipt readCurrent( + ReadFence fence, StripeHostingSubscriptionObserver.Result result) { + requireTransaction(); + Objects.requireNonNull(fence); + if (!(result instanceof ObservedSubscription observed)) { + throw new FenceRejectedException("ENTITLEMENT_UNAVAILABLE: provider authority is unresolved"); + } + var current = intents.lockForLifecycle(fence.creationId, fence.version); + ReadFence rechecked = prepareCurrentRead(fence.tenantId); + if (!rechecked.receiptId.equals(fence.receiptId) || rechecked.version != fence.version) { + throw new FenceRejectedException("ENTITLEMENT_UNAVAILABLE: current read fence changed"); + } + var original = intents.findCreation(fence.creationId).orElseThrow(); + requireObservedBinding(expected(original, current.providerSubscriptionId()), observed); + Record receipt = receiptForCurrent(links(current.subscriptionId())); + Objects.requireNonNull(receipt); + Record operation = operationForUpdateRead(fence.receiptId); + Record observation = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM subscription_lifecycle_observations WHERE attempt_id = ?", + receipt.get("attempt_id", UUID.class))); + byte[] storedObservation = observation.get("payload", byte[].class); + if (!AccountHostingSubscriptionLifecycleEvidence.digest(storedObservation) + .equals(receipt.get("observation_digest", String.class)) + || !Arrays.equals( + storedObservation, + AccountHostingSubscriptionLifecycleEvidence.observation( + AccountHostingSubscriptionLifecycleEvidence.facts(observed), + instant(observation, "read_started_at"), + instant(observation, "observed_at"))) + || !AccountHostingSubscriptionLifecycleEvidence.digest( + AccountHostingSubscriptionLifecycleEvidence.encode( + AccountHostingSubscriptionLifecycleEvidence.facts(observed))) + .equals(observation.get("facts_digest", String.class))) { + throw new FenceRejectedException( + "ENTITLEMENT_UNAVAILABLE: provider facts differ from the committed receipt"); + } + Instant evaluatedAt = now(); + var decision = + retainedPolicy(operation) + .evaluate(observed, evaluatedAt, nullableInstant(receipt, "past_due_since")); + if (!decision.resolved() || !decision.status().storageValue().equals(current.status())) { + throw new FenceRejectedException( + "ENTITLEMENT_UNAVAILABLE: lifecycle/period requires reconciliation"); + } + var committedDecision = + new AccountHostingSubscriptionLifecyclePolicy.Decision( + decision.status(), + decision.reason(), + instant(receipt, "valid_until"), + instant(receipt, "valid_until"), + nullableInstant(receipt, "cutoff_at")); + Map fields = + receiptFields( + operation, + original, + current.rowVersion(), + receipt.get("entitlement_version", Long.class), + observed, + receipt.get("observation_digest", String.class), + committedDecision, + nullableInstant(receipt, "past_due_since"), + receipt.get("authority_generation", Long.class), + receipt.get("authority_source_version", Long.class)); + byte[] expectedPayload = AccountHostingSubscriptionLifecycleEvidence.encode(fields); + if (!Arrays.equals(expectedPayload, receipt.get("receipt_payload", byte[].class)) + || !AccountHostingSubscriptionLifecycleEvidence.digest(expectedPayload) + .equals(receipt.get("receipt_digest", String.class))) { + throw new FenceRejectedException("ENTITLEMENT_UNAVAILABLE: receipt fields/bytes disagree"); + } + var expectedEvent = + AccountHostingSubscriptionLifecycleEvidence.billing( + fence.tenantId, + fence.receiptId, + receipt.get("request_digest", String.class), + receipt.get("billing_sequence", Long.class), + receipt.get("billing_event_id", UUID.class), + fields); + Record storedEvent = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT e.*, 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 = ? FOR SHARE OF s", + fence.tenantId, + expectedEvent.sequence)); + if (storedEvent.get("last_sequence", Long.class) != expectedEvent.sequence + || !expectedEvent.matches( + storedEvent.get("payload", byte[].class), storedEvent.get("event_digest", String.class)) + || !expectedEvent.digest().equals(receipt.get("billing_event_digest", String.class))) { + throw new FenceRejectedException( + "ENTITLEMENT_UNAVAILABLE: billing checkpoint does not cover the current receipt"); + } + var authority = tenantEvents.readHostingCheckpoint(fence.tenantId, fence.receiptId); + boolean available = + decision.status() != Status.SUSPENDED && decision.status() != Status.CANCELED; + boolean admit = available && decision.status() != Status.GRACE; + return new AccountHostingSubscriptionCurrentReceipt( + current, + fence.receiptId, + decision.status(), + available, + admit, + admit, + admit, + receipt.get("entitlement_version", Long.class), + expectedEvent.sequence, + expectedEvent.eventId, + expectedEvent.digest(), + authority, + observed.providerStatus(), + observed.currentPeriodStart().orElse(null), + observed.currentPeriodEnd().orElse(null), + observed.cancelAtPeriodEnd(), + observed.cancelAt().orElse(null), + nullableInstant(receipt, "cutoff_at"), + evaluatedAt, + decision.status() == Status.CANCELED + ? decision.validUntil() + : earlier(instant(receipt, "valid_until"), decision.validUntil())); + } + + public static final class ReadFence { + private final UUID tenantId; + private final UUID creationId; + private final long version; + private final UUID receiptId; + private final ExpectedBinding binding; + + private ReadFence( + UUID tenantId, UUID creationId, long version, UUID receiptId, ExpectedBinding binding) { + this.tenantId = tenantId; + this.creationId = creationId; + this.version = version; + this.receiptId = receiptId; + this.binding = binding; + } + + public ExpectedBinding binding() { + return binding; + } + } + + static Instant retainedPastDueOrigin(Record receipt) { + return receipt == null ? null : nullableInstant(receipt, "past_due_since"); + } + + private static Instant nullableInstant(Record row, String field) { + OffsetDateTime value = row.get(field, OffsetDateTime.class); + return value == null ? null : value.toInstant(); + } + + private static OffsetDateTime utcNullable(Instant instant) { + return instant == null ? null : utc(instant); + } + + public enum Outcome { + READY, + COMMITTED, + RECONCILING, + TERMINAL_FAILURE + } + + public record TransitionResult( + UUID requestId, Outcome outcome, long committedRowVersion, String reason) {} + + public static final class Preparation { + private final UUID requestId; + private final UUID attemptId; + private final ExpectedBinding binding; + private final Outcome outcome; + private final String reason; + private final long version; + + private Preparation( + UUID requestId, + UUID attemptId, + ExpectedBinding binding, + Outcome outcome, + String reason, + long version) { + this.requestId = requestId; + this.attemptId = attemptId; + this.binding = binding; + this.outcome = outcome; + this.reason = reason; + this.version = version; + } + + public UUID requestId() { + return requestId; + } + + public UUID attemptId() { + return attemptId; + } + + public ExpectedBinding binding() { + return binding; + } + + public Outcome outcome() { + return outcome; + } + + public TransitionResult result() { + return new TransitionResult(requestId, outcome, version, reason); + } + } + + /** + * Claims only the original durable create work. Recovery never allocates a new provider identity. + * A recovered attempt requires provider reconciliation before any retry of the original create; + * even the first claim is not remote instrument/customer validation or permission to charge. + */ + public ClaimResult claim(UUID requestId, long expectedRowVersion, UUID attemptId) { + requireTransaction(); + AccountBillingCustomerRecord.requireUuid(requestId); + AccountBillingCustomerRecord.requireUuid(attemptId); + if (expectedRowVersion < 1 || expectedRowVersion == Long.MAX_VALUE) { + throw new IllegalArgumentException("Positive advanceable subscription version is required"); + } + Record prior = + dsl.fetchOne( + "SELECT * FROM subscription_provisioning_attempts WHERE attempt_id = ?", attemptId); + if (prior != null + && (!requestId.equals(prior.get("request_id", UUID.class)) + || expectedRowVersion != prior.get("expected_row_version", Long.class))) { + throw new FenceRejectedException( + "Provisioning attempt identity was reused with different input"); + } + long versionToLock = + prior == null ? expectedRowVersion : prior.get("claimed_row_version", Long.class); + var current = intents.lockForProvisioningRecovery(requestId, versionToLock); + var original = intents.findCreation(requestId).orElseThrow(); + Instant now = clock.instant().truncatedTo(ChronoUnit.MICROS); + if (now.isBefore(original.createdAt())) { + throw new FenceRejectedException("Provisioning clock predates the durable intent"); + } + dsl.execute( + "INSERT INTO subscription_provisioning_work (request_id, subscription_id, phase, row_version, " + + "attempt_count, max_attempts, max_stalled_attempts, lease_millis, backoff_millis, deadline_at, retry_at) " + + "VALUES (?, ?, 'RECONCILING', 1, 0, ?, ?, ?, ?, ?::timestamptz, ?::timestamptz) ON CONFLICT (request_id) DO NOTHING", + requestId, + original.subscriptionId(), + limits.maximumAttempts(), + limits.maximumStalledAttempts(), + limits.lease().toMillis(), + limits.backoff().toMillis(), + utc(original.createdAt().plus(limits.absoluteTimeout())), + utc(original.createdAt())); + Record work = workForUpdate(requestId); + if ("BILLING_RECONCILIATION_TERMINAL_FAILURE".equals(work.get("phase", String.class))) { + return new ClaimResult(Disposition.TERMINAL_FAILURE, null); + } + if (prior != null) { + if (!attemptId.equals(work.get("last_attempt_id", UUID.class)) + || !"CLAIMED".equals(work.get("phase", String.class)) + || now.isBefore(instant(prior, "claimed_at")) + || !now.isBefore(instant(prior, "expires_at")) + || !now.isBefore(instant(work, "deadline_at"))) { + return new ClaimResult(Disposition.ATTEMPT_EXPIRED, null); + } + return new ClaimResult(Disposition.CLAIMED, claim(original, prior)); + } + if (!now.isBefore(instant(work, "deadline_at"))) { + return fail(work, "ABSOLUTE_DEADLINE", now); + } + if ("CLAIMED".equals(work.get("phase", String.class)) + && now.isBefore(instant(work, "lease_expires_at"))) { + return new ClaimResult(Disposition.WAITING, null); + } + if (work.get("attempt_count", Integer.class) >= work.get("max_attempts", Integer.class)) { + return fail(work, "ATTEMPT_BUDGET", now); + } + // No completed provider/current commit has established progress in this pre-confirmation owner. + // Timeouts and lost responses do not reset a stalled counter or authorize another resource. + if (work.get("attempt_count", Integer.class) + >= work.get("max_stalled_attempts", Integer.class)) { + return fail(work, "STALLED_WITHOUT_COMMITTED_PROGRESS", now); + } + if (now.isBefore(instant(work, "retry_at"))) { + return new ClaimResult(Disposition.WAITING, null); + } + if (current.providerSubscriptionId() != null) { + throw new FenceRejectedException( + "Mapped provider work requires lifecycle reconciliation, not a create claim"); + } + Instant expiresAt = + earlier(now.plusMillis(work.get("lease_millis", Long.class)), instant(work, "deadline_at")); + int number = Math.addExact(work.get("attempt_count", Integer.class), 1); + long claimedVersion = Math.addExact(current.rowVersion(), 1L); + int updated = + dsl.execute( + "UPDATE subscription SET status = 'provisioning', row_version = row_version + 1 " + + "WHERE subscription_id = ? AND row_version = ? AND superseded_at IS NULL " + + "AND status IN ('pending','provisioning') AND provider_subscription_id IS NULL", + original.subscriptionId(), + current.rowVersion()); + if (updated != 1) { + throw new FenceRejectedException("Provisioning expected-current CAS rejected"); + } + dsl.execute( + "INSERT INTO subscription_provisioning_attempts (attempt_id, request_id, subscription_id, " + + "attempt_number, expected_row_version, claimed_row_version, claimed_at, expires_at) " + + "VALUES (?, ?, ?, ?, ?, ?, ?::timestamptz, ?::timestamptz)", + attemptId, + requestId, + original.subscriptionId(), + number, + current.rowVersion(), + claimedVersion, + utc(now), + utc(expiresAt)); + int claimed = + dsl.execute( + "UPDATE subscription_provisioning_work SET phase = 'CLAIMED', row_version = row_version + 1, " + + "attempt_count = ?, last_attempt_id = ?, subscription_row_version = ?, lease_expires_at = ?::timestamptz, " + + "retry_at = ?::timestamptz, failure_reason = NULL WHERE request_id = ? AND row_version = ?", + number, + attemptId, + claimedVersion, + utc(expiresAt), + utc(expiresAt.plusMillis(work.get("backoff_millis", Long.class))), + requestId, + work.get("row_version", Long.class)); + if (claimed != 1) { + throw new FenceRejectedException("Provisioning work claim CAS rejected"); + } + Record attempt = + dsl.fetchOne( + "SELECT * FROM subscription_provisioning_attempts WHERE attempt_id = ?", attemptId); + return new ClaimResult(Disposition.CLAIMED, claim(original, Objects.requireNonNull(attempt))); + } + + /** + * 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. + */ + public ProviderDispatch prepareProviderDispatch(ProvisioningClaim supplied, UUID dispatchId) { + requireTransaction(); + AccountBillingCustomerRecord.requireUuid(dispatchId); + ProvisioningClaim retained = requireLiveProvisioningClaim(supplied); + var original = retained.creation(); + int inserted = + dsl.execute( + "INSERT INTO subscription_provider_dispatch_claim " + + "(creation_request_id, subscription_id, provider_operation_id, dispatch_id, classification, " + + "first_attempt_id, first_claimed_row_version, recorded_at) " + + "VALUES (?, ?, ?, ?, 'FIRST_DISPATCH', ?, ?, ?::timestamptz) " + + "ON CONFLICT (creation_request_id) DO NOTHING", + original.requestId(), + original.subscriptionId(), + original.subscriptionProvisioningRequestId(), + dispatchId, + retained.attemptId(), + retained.subscriptionRowVersion(), + utc(now())); + DispatchReceipt receipt = dispatchReceipt(original.requestId()); + 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()); + } + + /** + * Independent committed readback. Carries only the inserting invocation's existing private + * permission; the persisted row, a replayed claim or a new invocation cannot mint permission. + */ + public ProviderDispatch readProviderDispatch(ProviderDispatch supplied) { + requireTransaction(); + Objects.requireNonNull(supplied); + if (transactionId() == supplied.preparationTransactionId) { + throw new FenceRejectedException( + "Independent provider dispatch readback requires a new transaction"); + } + ProvisioningClaim retained = requireLiveProvisioningClaim(supplied.claim()); + DispatchReceipt receipt = dispatchReceipt(retained.creation().requestId()); + requireDispatchBinding(retained, receipt); + if (!receipt.equals(supplied.receipt)) { + throw new FenceRejectedException("Committed provider dispatch receipt changed"); + } + return providerDispatch( + retained, receipt, supplied.initialPermission, true, supplied.preparationTransactionId); + } + + private ProvisioningClaim requireLiveProvisioningClaim(ProvisioningClaim supplied) { + Objects.requireNonNull(supplied, "Genuine retained provisioning claim is required"); + ClaimResult replay = + claim( + supplied.creation().requestId(), + supplied.subscriptionRowVersion() - 1, + supplied.attemptId()); + ProvisioningClaim retained = replay.claim(); + if (replay.disposition() != Disposition.CLAIMED + || retained == null + || !retained.creation().equals(supplied.creation()) + || retained.attemptNumber() != supplied.attemptNumber() + || retained.subscriptionRowVersion() != supplied.subscriptionRowVersion() + || !retained.claimedAt().equals(supplied.claimedAt()) + || !retained.expiresAt().equals(supplied.expiresAt())) { + throw new FenceRejectedException("Exact live provisioning claim readback rejected"); + } + Record current = links(retained.creation().subscriptionId()); + if (current.get("lifecycle_inflight_request_id") != null) { + throw new FenceRejectedException("Lifecycle reconciliation already owns provider work"); + } + return retained; + } + + private DispatchReceipt dispatchReceipt(UUID creationId) { + Record row = + dsl.fetchOne( + "SELECT * FROM subscription_provider_dispatch_claim WHERE creation_request_id = ?", + creationId); + if (row == null) { + throw new FenceRejectedException("Provider dispatch receipt is absent"); + } + return new DispatchReceipt( + row.get("creation_request_id", UUID.class), + row.get("subscription_id", UUID.class), + row.get("provider_operation_id", UUID.class), + row.get("dispatch_id", UUID.class), + row.get("classification", String.class), + row.get("first_attempt_id", UUID.class), + row.get("first_claimed_row_version", Long.class), + instant(row, "recorded_at")); + } + + private static void requireDispatchBinding(ProvisioningClaim claim, DispatchReceipt receipt) { + var original = claim.creation(); + if (!original.requestId().equals(receipt.creationId()) + || !original.subscriptionId().equals(receipt.subscriptionId()) + || !original.subscriptionProvisioningRequestId().equals(receipt.providerOperationId())) { + throw new FenceRejectedException("Provider dispatch changed original immutable operation"); + } + } + + private ProviderDispatch providerDispatch( + ProvisioningClaim claim, + DispatchReceipt receipt, + boolean initialPermission, + boolean independentlyRead, + long preparationTransactionId) { + var original = claim.creation(); + var customer = + new AccountBillingCustomerRepository(dsl) + .findByAccountForUpdate(original.owner().accountUuid()) + .orElseThrow(); + var wallet = + new AccountPaymentInstrumentRepository(dsl) + .findByOwner(original.owner().accountUuid(), original.paymentInstrumentId()) + .orElseThrow(); + if (customer.state() != AccountBillingCustomerRecord.State.CONFIRMED + || !original + .customerProvisioningRequestId() + .equals(customer.customerProvisioningRequestId()) + || !original.providerCustomerId().equals(customer.providerCustomerId()) + || !original.providerCustomerId().equals(wallet.providerCustomerId()) + || !original.customerProvisioningRequestId().equals(wallet.customerProvisioningRequestId()) + || wallet.rowVersion() != original.reservedInstrumentVersion() + || wallet.state() != AccountPaymentInstrumentRecord.State.ATTACHABLE) { + throw new FenceRejectedException( + "Provider dispatch lost confirmed customer/instrument binding"); + } + return new ProviderDispatch( + claim, + receipt, + wallet.providerPaymentMethodId(), + customer.providerIdempotencyId(), + livemode, + initialPermission, + independentlyRead, + preparationTransactionId); + } + + private long transactionId() { + return Objects.requireNonNull(dsl.fetchOne("SELECT txid_current() AS xid")) + .get("xid", Long.class); + } + + private record DispatchReceipt( + UUID creationId, + UUID subscriptionId, + UUID providerOperationId, + UUID dispatchId, + String classification, + UUID firstAttemptId, + Long firstClaimedRowVersion, + Instant recordedAt) {} + + /** Private durable producer result; prepared values are unusable until committed readback. */ + public static final class ProviderDispatch { + private final ProvisioningClaim claim; + private final DispatchReceipt receipt; + private final String paymentMethodId; + private final UUID customerProviderIdempotencyId; + private final boolean livemode; + private final boolean initialPermission; + private final boolean independentlyRead; + private final long preparationTransactionId; + + private ProviderDispatch( + ProvisioningClaim claim, + DispatchReceipt receipt, + String paymentMethodId, + UUID customerProviderIdempotencyId, + boolean livemode, + boolean initialPermission, + boolean independentlyRead, + long preparationTransactionId) { + this.claim = claim; + this.receipt = receipt; + this.paymentMethodId = paymentMethodId; + this.customerProviderIdempotencyId = customerProviderIdempotencyId; + this.livemode = livemode; + this.initialPermission = initialPermission; + this.independentlyRead = independentlyRead; + this.preparationTransactionId = preparationTransactionId; + } + + public ProvisioningClaim claim() { + return claim; + } + + public String providerPaymentMethodId() { + return paymentMethodId; + } + + public UUID customerProviderIdempotencyId() { + return customerProviderIdempotencyId; + } + + public boolean readyForProviderIo() { + return independentlyRead; + } + + public boolean initialCallAllowed() { + return independentlyRead && initialPermission; + } + + public ExpectedBinding expectedBinding(String providerId) { + var original = claim.creation(); + return new ExpectedBinding( + providerId, + original.subscriptionId(), + original.providerCustomerId(), + paymentMethodId, + original.planQuote().providerPriceId(), + original.planQuote().providerQuantity(), + StripeHostingSubscriptionObserver.OperationType.SUBSCRIPTION_PROVISIONING, + original.subscriptionProvisioningRequestId(), + livemode); + } + } + + /** + * 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. + */ + public Disposition deferUnresolved(ProvisioningClaim claim) { + requireTransaction(); + Objects.requireNonNull(claim); + intents.lockForProvisioningRecovery( + claim.creation().requestId(), claim.subscriptionRowVersion()); + Record work = workForUpdate(claim.creation().requestId()); + Instant now = clock.instant().truncatedTo(ChronoUnit.MICROS); + if (now.isBefore(claim.claimedAt())) { + throw new FenceRejectedException("Provisioning clock predates its retained claim"); + } + if (!claim.attemptId().equals(work.get("last_attempt_id", UUID.class))) { + throw new FenceRejectedException("A stale worker cannot settle a replacement attempt"); + } + String phase = work.get("phase", String.class); + if ("BILLING_RECONCILIATION_TERMINAL_FAILURE".equals(phase)) { + return Disposition.TERMINAL_FAILURE; + } + if ("RECONCILING".equals(phase)) { + return Disposition.WAITING; + } + if (!now.isBefore(instant(work, "deadline_at"))) { + return fail(work, "ABSOLUTE_DEADLINE", now).disposition(); + } + if (!now.isBefore(claim.expiresAt())) { + throw new FenceRejectedException("Expired attempt cannot record provider completion"); + } + if (work.get("attempt_count", Integer.class) >= work.get("max_attempts", Integer.class)) { + return fail(work, "ATTEMPT_BUDGET", now).disposition(); + } + if (work.get("attempt_count", Integer.class) + >= work.get("max_stalled_attempts", Integer.class)) { + return fail(work, "STALLED_WITHOUT_COMMITTED_PROGRESS", now).disposition(); + } + int deferred = + dsl.execute( + "UPDATE subscription_provisioning_work SET phase = 'RECONCILING', row_version = row_version + 1, " + + "retry_at = ?::timestamptz, failure_reason = 'UNRESOLVED_PROVIDER_WORK' WHERE request_id = ? AND row_version = ?", + utc( + earlier( + now.plusMillis(work.get("backoff_millis", Long.class)), + instant(work, "deadline_at"))), + claim.creation().requestId(), + work.get("row_version", Long.class)); + if (deferred != 1) { + throw new FenceRejectedException("Provisioning deferred-attempt CAS rejected"); + } + return Disposition.WAITING; + } + + private ClaimResult fail(Record work, String reason, Instant now) { + int failed = + dsl.execute( + "UPDATE subscription_provisioning_work SET phase = 'BILLING_RECONCILIATION_TERMINAL_FAILURE', " + + "row_version = row_version + 1, failure_reason = ?, terminal_at = ?::timestamptz " + + "WHERE request_id = ? AND row_version = ?", + reason, + utc(now), + work.get("request_id", UUID.class), + work.get("row_version", Long.class)); + if (failed != 1) { + throw new FenceRejectedException("Provisioning failure CAS rejected"); + } + dsl.execute( + "INSERT INTO subscription_provisioning_operator_outbox (request_id, subscription_id, reason, recorded_at) " + + "VALUES (?, ?, ?, ?::timestamptz)", + work.get("request_id", UUID.class), + work.get("subscription_id", UUID.class), + reason, + utc(now)); + return new ClaimResult(Disposition.TERMINAL_FAILURE, null); + } + + private Record workForUpdate(UUID requestId) { + Record work = + dsl.fetchOne( + "SELECT * FROM subscription_provisioning_work WHERE request_id = ? FOR UPDATE", + requestId); + if (work == null) { + throw new FenceRejectedException("Original durable provisioning work is absent"); + } + return work; + } + + private static ProvisioningClaim claim(AccountSubscriptionCreationRecord original, Record row) { + return new ProvisioningClaim( + original, + row.get("attempt_id", UUID.class), + row.get("attempt_number", Integer.class), + row.get("claimed_row_version", Long.class), + instant(row, "claimed_at"), + instant(row, "expires_at")); + } + + private static Instant earlier(Instant left, Instant right) { + return left.isBefore(right) ? left : right; + } + + private static OffsetDateTime utc(Instant instant) { + return instant.atOffset(ZoneOffset.UTC); + } + + private static Instant instant(Record row, String field) { + return Objects.requireNonNull(row.get(field, OffsetDateTime.class)).toInstant(); + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Hosting provisioning requires a writable Account transaction"); + } + } + + public enum Disposition { + CLAIMED, + WAITING, + ATTEMPT_EXPIRED, + TERMINAL_FAILURE + } + + public record ClaimResult(Disposition disposition, ProvisioningClaim claim) {} + + /** + * Private construction prevents mistaking caller-supplied status/version booleans for a claim. + */ + public static final class ProvisioningClaim { + private final AccountSubscriptionCreationRecord creation; + private final UUID attemptId; + private final int attemptNumber; + private final long subscriptionRowVersion; + private final Instant claimedAt; + private final Instant expiresAt; + + private ProvisioningClaim( + AccountSubscriptionCreationRecord creation, + UUID attemptId, + int attemptNumber, + long subscriptionRowVersion, + Instant claimedAt, + Instant expiresAt) { + this.creation = creation; + this.attemptId = attemptId; + this.attemptNumber = attemptNumber; + this.subscriptionRowVersion = subscriptionRowVersion; + this.claimedAt = claimedAt; + this.expiresAt = expiresAt; + } + + public AccountSubscriptionCreationRecord creation() { + return creation; + } + + public UUID attemptId() { + return attemptId; + } + + public int attemptNumber() { + return attemptNumber; + } + + public long subscriptionRowVersion() { + return subscriptionRowVersion; + } + + public Instant claimedAt() { + return 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. */ + public record ReconciliationLimits( + int maximumAttempts, + int maximumStalledAttempts, + Duration lease, + Duration backoff, + Duration absoluteTimeout) { + public ReconciliationLimits { + if (maximumAttempts < 1 || maximumStalledAttempts < 1) { + throw new IllegalArgumentException( + "Explicit positive attempt and stall budgets are required"); + } + wholeMilliseconds(lease); + wholeMilliseconds(backoff); + wholeMilliseconds(absoluteTimeout); + if (lease.compareTo(absoluteTimeout) > 0) { + throw new IllegalArgumentException( + "Worker lease cannot exceed the absolute reconciliation timeout"); + } + } + + private static void wholeMilliseconds(Duration duration) { + if (duration == null || duration.isNegative() || duration.isZero()) { + throw new IllegalArgumentException( + "Explicit positive reconciliation durations are required"); + } + try { + if (!Duration.ofMillis(duration.toMillis()).equals(duration)) { + throw new IllegalArgumentException("Reconciliation durations must be whole milliseconds"); + } + Instant.EPOCH.plus(duration); + } catch (ArithmeticException | java.time.DateTimeException overflow) { + throw new IllegalArgumentException( + "Reconciliation duration exceeds the supported time domain", overflow); + } + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionCreateDigest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionCreateDigest.java new file mode 100644 index 0000000000..d2b581d63d --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionCreateDigest.java @@ -0,0 +1,87 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.io.IOException; +import java.nio.CharBuffer; +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.util.HexFormat; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.json.JsonMapper; + +/** Account-computed request evidence; encoding does not authenticate or reserve its inputs. */ +final class AccountSubscriptionCreateDigest { + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private AccountSubscriptionCreateDigest() {} + + /** + * Encodes the resolved owner and exact normalized create fields, independently of caller and + * provider operation keys. The caller must resolve the plan and owner, and revalidate the owner + * fence and instrument reservation in the intent transaction. + */ + static EncodedRequest encode( + UUID tenantId, UUID ownerAccountId, String planCode, UUID paymentInstrumentId) { + requireIdentity(tenantId); + requireIdentity(ownerAccountId); + requireIdentity(paymentInstrumentId); + if (planCode == null || planCode.isBlank() || !planCode.equals(planCode.strip())) { + throw new IllegalArgumentException("An exact normalized plan code is required"); + } + try { + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(planCode)); + } catch (CharacterCodingException malformed) { + throw new IllegalArgumentException("Plan code must have an exact UTF-8 encoding", malformed); + } + Map request = + Map.of( + "schemaVersion", "account-subscription-create-request/v1", + "tenantId", tenantId.toString(), + "ownerAccountId", ownerAccountId.toString(), + "planCode", planCode, + "instrumentSelection", + Map.of( + "kind", + "EXACT_SAVED_INSTRUMENT", + "paymentInstrumentId", + paymentInstrumentId.toString())); + try { + byte[] payload = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(request)); + return new EncodedRequest( + payload, + "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(payload))); + } catch (IOException encodingFailure) { + throw new IllegalStateException( + "Subscription create request encoding failed", encodingFailure); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static void requireIdentity(UUID value) { + if (value == null + || (value.getMostSignificantBits() == 0 && value.getLeastSignificantBits() == 0)) { + throw new IllegalArgumentException("A non-nil canonical UUID is required"); + } + } + + record EncodedRequest(byte[] payload, String digest) { + EncodedRequest { + payload = payload.clone(); + } + + @Override + public byte[] payload() { + return payload.clone(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionCreateRequest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionCreateRequest.java new file mode 100644 index 0000000000..86b4e840e9 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionCreateRequest.java @@ -0,0 +1,63 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.util.Objects; +import java.util.UUID; + +/** + * Unregistered composition input, not a route grant. A genuine producer must authenticate/authorize + * the actor, resolve the plan and owner, and verify current authority before this local SQL + * boundary. Neither these values nor their digest authenticate anyone. Only exact saved instruments + * exist here. + */ +public record AccountSubscriptionCreateRequest( + UUID requestId, + UUID tenantId, + OwnerFence owner, + String planCode, + UUID paymentInstrumentId, + long instrumentVersion, + ProducerEvidence producer, + ReplacementFence replacement) { + public AccountSubscriptionCreateRequest { + AccountBillingCustomerRecord.requireUuid(requestId); + Objects.requireNonNull(owner, "resolved owner fence"); + Objects.requireNonNull(producer, "authenticated producer evidence input"); + AccountSubscriptionCreateDigest.encode( + tenantId, owner.accountUuid(), planCode, paymentInstrumentId); + if (planCode.length() > 255 || instrumentVersion < 1 || instrumentVersion == Long.MAX_VALUE) { + throw new IllegalArgumentException( + "Bounded normalized plan and advanceable instrument version are required"); + } + } + + public record OwnerFence(UUID accountUuid, long version, UUID generation) { + public OwnerFence { + AccountBillingCustomerRecord.requireUuid(accountUuid); + AccountBillingCustomerRecord.requireUuid(generation); + if (version < 1) { + throw new IllegalArgumentException("Positive captured owner version is required"); + } + } + } + + public record ProducerEvidence( + UUID actorAccountUuid, UUID authorizationOperationId, String authorizationDigest) { + public ProducerEvidence { + AccountBillingCustomerRecord.requireUuid(actorAccountUuid); + AccountBillingCustomerRecord.requireUuid(authorizationOperationId); + AccountBillingCustomerRecord.requireDigest(authorizationDigest); + } + } + + /** + * Internal expected-current replacement CAS, not an update-only public CreateSubscription field. + */ + public record ReplacementFence(UUID subscriptionId, long expectedRowVersion) { + public ReplacementFence { + AccountBillingCustomerRecord.requireUuid(subscriptionId); + if (expectedRowVersion < 1 || expectedRowVersion == Long.MAX_VALUE) { + throw new IllegalArgumentException("Advanceable canceled-current row version is required"); + } + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionCreationRecord.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionCreationRecord.java new file mode 100644 index 0000000000..8f863e9872 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionCreationRecord.java @@ -0,0 +1,26 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.OwnerFence; + +/** + * Immutable original creation result. A pending result is not a provider resource or entitlement. + */ +public record AccountSubscriptionCreationRecord( + UUID requestId, + String requestDigest, + UUID subscriptionId, + UUID tenantId, + OwnerFence owner, + String planCode, + AccountHostingPlanQuote planQuote, + UUID paymentInstrumentId, + long reservedInstrumentVersion, + UUID customerProvisioningRequestId, + String providerCustomerId, + UUID subscriptionProvisioningRequestId, + UUID cleanupProviderIdentity, + String initialStatus, + long initialRowVersion, + Instant createdAt) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionCurrentRecord.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionCurrentRecord.java new file mode 100644 index 0000000000..d68a3f6c36 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionCurrentRecord.java @@ -0,0 +1,26 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.OwnerFence; + +/** + * Current storage snapshot only. No runtime entitlement DTO or provider/lifecycle authority claim. + */ +public record AccountSubscriptionCurrentRecord( + UUID subscriptionId, + UUID tenantId, + OwnerFence owner, + String planCode, + AccountHostingPlanQuote planQuote, + UUID paymentInstrumentId, + long reservedInstrumentVersion, + UUID customerProvisioningRequestId, + String providerCustomerId, + UUID creationRequestId, + long rowVersion, + String status, + String providerSubscriptionId, + UUID terminalResolutionId, + Instant supersededAt, + UUID supersededByRequestId) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java new file mode 100644 index 0000000000..a453192439 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java @@ -0,0 +1,489 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.time.Instant; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.OwnerFence; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionProviderHistoryRecord.TerminalResolution; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.exception.IntegrityConstraintViolationException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered, local-only pending intent/current/history persistence. No provider business call, + * lifecycle producer, grant, transfer or generic update API. Producer evidence is input, not auth. + * The caller owns one short transaction and must roll it back after any rejected SQL statement. + * Lock order: Account -> customer -> instrument -> tenant owner -> current subscription -> + * operation and reservation. Root must compose future transfer/update paths in that same global + * order. + */ +public final class AccountSubscriptionIntentRepository { + private static final String CURRENT_SELECT = + "SELECT s.*, o.plan_quote_payload, o.provider_price_id, o.provider_quantity, " + + "o.max_active_sessions, o.max_concurrent_game_instances, o.max_storage_bytes " + + "FROM subscription s JOIN subscription_create_operations o ON o.request_id = s.creation_request_id "; + private final DSLContext dsl; + private final AccountPaymentInstrumentRepository instruments; + private final AccountHostingPlanCatalog plans; + + public AccountSubscriptionIntentRepository(DSLContext dsl, AccountHostingPlanCatalog plans) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + this.plans = Objects.requireNonNull(plans, "Explicit server hosting-plan catalog is required"); + instruments = new AccountPaymentInstrumentRepository(dsl); + } + + /** Replays the original immutable pending result, even after the current row has advanced. */ + public AccountSubscriptionCreationRecord retainPending(AccountSubscriptionCreateRequest request) { + requireWritableTransaction(); + Objects.requireNonNull(request, "subscription create request"); + var encoded = + AccountSubscriptionCreateDigest.encode( + request.tenantId(), + request.owner().accountUuid(), + request.planCode(), + request.paymentInstrumentId()); + Optional replay = replay(request.requestId(), encoded); + if (replay.isPresent()) { + return replay.orElseThrow(); + } + var instrument = + instruments + .findByOwnerForUpdate(request.owner().accountUuid(), request.paymentInstrumentId()) + .orElseThrow(() -> new FenceRejectedException("Selected Account instrument is absent")); + if (instrument.rowVersion() != request.instrumentVersion() + || instrument.state() != AccountPaymentInstrumentRecord.State.ATTACHABLE) { + throw new FenceRejectedException( + "Exact saved instrument version/attachability fence rejected"); + } + lockOwner(request.tenantId(), request.owner()); + // Account/tenant serialization may have waited for an exact same-request commit. + replay = replay(request.requestId(), encoded); + if (replay.isPresent()) { + return replay.orElseThrow(); + } + // A replay never consults today's catalog. Only a new operation freezes this server quote, + // before any supersession/intent/reservation/outbox write in the local transaction. + AccountHostingPlanQuote quote = plans.resolve(request.planCode()); + var current = currentForUpdate(request.tenantId()); + if (request.replacement() == null) { + if (current.isPresent()) { + throw new ConflictException("Tenant already has a current subscription"); + } + } else { + var predecessor = + current.orElseThrow( + () -> new FenceRejectedException("Canceled current subscription is absent")); + if (!predecessor.subscriptionId().equals(request.replacement().subscriptionId()) + || predecessor.rowVersion() != request.replacement().expectedRowVersion()) { + throw new FenceRejectedException("Canceled replacement expected-current CAS rejected"); + } + if (!predecessor.status().equals("canceled") || predecessor.terminalResolutionId() == null) { + throw new ConflictException("Current subscription is not terminal canceled"); + } + // Deferred reciprocal FKs require the exact successor intent before this can commit. + int changed = + dsl.execute( + "UPDATE subscription SET superseded_at = clock_timestamp(), " + + "superseded_by_request_id = ?, row_version = row_version + 1 " + + "WHERE subscription_id = ? AND tenant_id = ? AND status = 'canceled' AND row_version = ? AND superseded_at IS NULL", + request.requestId(), + predecessor.subscriptionId(), + request.tenantId(), + request.replacement().expectedRowVersion()); + if (changed != 1) { + throw new FenceRejectedException("Canceled replacement CAS lost"); + } + } + UUID subscriptionId = UUID.randomUUID(); + UUID providerCreate = UUID.randomUUID(); + UUID providerCleanup = UUID.randomUUID(); + try { + int inserted = + 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, replaced_subscription_id, replaced_row_version, " + + "plan_quote_payload, plan_quote_digest, provider_price_id, provider_quantity, max_active_sessions, max_concurrent_game_instances, max_storage_bytes) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (request_id) DO NOTHING", + request.requestId(), + subscriptionId, + request.tenantId(), + request.owner().accountUuid(), + request.owner().version(), + request.owner().generation(), + request.producer().actorAccountUuid(), + request.producer().authorizationOperationId(), + request.producer().authorizationDigest(), + request.planCode(), + request.paymentInstrumentId(), + request.instrumentVersion(), + instrument.customerProvisioningRequestId(), + instrument.providerCustomerId(), + providerCreate, + providerCleanup, + encoded.payload(), + encoded.digest(), + request.replacement() == null ? null : request.replacement().subscriptionId(), + request.replacement() == null ? null : request.replacement().expectedRowVersion(), + quote.payload(), + quote.digest(), + quote.providerPriceId(), + quote.providerQuantity(), + quote.maxActiveSessions(), + quote.maxConcurrentGameInstances(), + quote.maxStorageBytes()); + if (inserted != 1) { + // A cross-owner request collision cannot be replayed after our supersession write. Reject + // and roll back rather than retaining a half-applied replacement or guessing an outcome. + throw new ConflictException( + "Caller create request was concurrently retained; retry after rollback"); + } + dsl.execute( + "INSERT INTO subscription (subscription_id, tenant_id, account_uuid, owner_version, owner_generation, " + + "plan_code, payment_instrument_id, reserved_instrument_version, customer_provisioning_request_id, provider_customer_id, " + + "creation_request_id, row_version, status, plan_quote_digest) SELECT subscription_id, tenant_id, account_uuid, owner_version, owner_generation, " + + "plan_code, payment_instrument_id, reserved_instrument_version, customer_provisioning_request_id, provider_customer_id, " + + "request_id, 1, 'pending', plan_quote_digest FROM subscription_create_operations WHERE request_id = ?", + request.requestId()); + dsl.execute( + "INSERT INTO subscription_instrument_reservations (request_id, subscription_id, payment_instrument_id, instrument_version) " + + "VALUES (?, ?, ?, ?)", + request.requestId(), + subscriptionId, + request.paymentInstrumentId(), + request.instrumentVersion()); + dsl.execute( + "INSERT INTO subscription_create_outbox (request_id, subscription_id, work_kind) " + + "VALUES (?, ?, 'SUBSCRIPTION_PROVISIONING_INTENT')", + request.requestId(), + subscriptionId); + } catch (IntegrityConstraintViolationException conflict) { + throw new ConflictException( + "Subscription identity/current mapping conflicts with retained intent", conflict); + } + return replay(request.requestId(), encoded).orElseThrow(); + } + + /** + * Read-only original receipt. A real caller must separately authorize disclosure of this record. + */ + public Optional findCreation(UUID requestId) { + AccountBillingCustomerRecord.requireUuid(requestId); + Record row = + dsl.fetchOne( + "SELECT * FROM subscription_create_operations WHERE request_id = ?", requestId); + return row == null ? Optional.empty() : Optional.of(creation(row)); + } + + public Optional findCurrentByTenant(UUID tenantId) { + AccountBillingCustomerRecord.requireUuid(tenantId); + Record row = + dsl.fetchOne( + CURRENT_SELECT + "WHERE s.tenant_id = ? AND s.superseded_at IS NULL", tenantId); + return row == null ? Optional.empty() : Optional.of(current(row)); + } + + /** + * Locked, version-fenced read for a future genuine worker's local claim transaction. This method + * does NOT claim/dispatch work, move to provisioning, validate Stripe, or confer provider + * authority. Root must add the actual durable claim/recovery/outbox state machine before any + * remote work. + */ + public AccountSubscriptionCurrentRecord lockPendingForClaim( + UUID requestId, long expectedRowVersion) { + return lockProvisioningBinding(requestId, expectedRowVersion, false); + } + + /** Exact original-binding fence for the durable provisioning owner's recovery transaction. */ + public AccountSubscriptionCurrentRecord lockForProvisioningRecovery( + UUID requestId, long expectedRowVersion) { + return lockProvisioningBinding(requestId, expectedRowVersion, true); + } + + /** + * Original-binding lock for provider reconciliation and the consistent internal reader. Later + * display/availability observations do not invalidate the immutable reserved instrument binding. + * This read does not authorize a new provider dispatch. + */ + public AccountSubscriptionCurrentRecord lockForLifecycle( + UUID requestId, long expectedRowVersion) { + return lockBinding(requestId, expectedRowVersion, true, true); + } + + private AccountSubscriptionCurrentRecord lockProvisioningBinding( + UUID requestId, long expectedRowVersion, boolean allowProvisioning) { + return lockBinding(requestId, expectedRowVersion, allowProvisioning, false); + } + + private AccountSubscriptionCurrentRecord lockBinding( + UUID requestId, long expectedRowVersion, boolean allowProvisioning, boolean lifecycle) { + requireWritableTransaction(); + AccountBillingCustomerRecord.requireUuid(requestId); + if (expectedRowVersion < 1) { + throw new IllegalArgumentException("Positive expected subscription version is required"); + } + var original = + findCreation(requestId) + .orElseThrow(() -> new ConflictException("Subscription create is absent")); + var instrument = + instruments + .findByOwnerForUpdate(original.owner().accountUuid(), original.paymentInstrumentId()) + .orElseThrow(() -> new FenceRejectedException("Reserved instrument owner is absent")); + lockOwner(original.tenantId(), original.owner()); + var current = + currentForUpdate(original.tenantId()) + .orElseThrow(() -> new FenceRejectedException("Current subscription is absent")); + boolean instrumentVersionAndStateMatch = + lifecycle + ? instrument.rowVersion() >= original.reservedInstrumentVersion() + && (instrument.state() == AccountPaymentInstrumentRecord.State.ATTACHABLE + || instrument.state() == AccountPaymentInstrumentRecord.State.UNAVAILABLE) + : instrument.rowVersion() == original.reservedInstrumentVersion() + && instrument.state() == AccountPaymentInstrumentRecord.State.ATTACHABLE; + if (!current.subscriptionId().equals(original.subscriptionId()) + || !current.tenantId().equals(original.tenantId()) + || !current.owner().equals(original.owner()) + || !current.creationRequestId().equals(original.requestId()) + || !current.paymentInstrumentId().equals(original.paymentInstrumentId()) + || current.reservedInstrumentVersion() != original.reservedInstrumentVersion() + || !current.customerProvisioningRequestId().equals(original.customerProvisioningRequestId()) + || !current.providerCustomerId().equals(original.providerCustomerId()) + || current.rowVersion() != expectedRowVersion + || !(lifecycle + || current.status().equals("pending") + || (allowProvisioning && current.status().equals("provisioning"))) + || current.supersededAt() != null + || !instrument.instrumentUuid().equals(original.paymentInstrumentId()) + || !instrument.accountUuid().equals(original.owner().accountUuid()) + || !instrumentVersionAndStateMatch + || !instrument + .customerProvisioningRequestId() + .equals(original.customerProvisioningRequestId()) + || !instrument.providerCustomerId().equals(original.providerCustomerId())) { + throw new FenceRejectedException( + "Pending claim owner/customer/instrument/subscription fence rejected"); + } + Record hold = + dsl.fetchOne( + "SELECT r.* FROM subscription_instrument_reservations r " + + "JOIN subscription_create_outbox o USING (request_id, subscription_id) WHERE r.request_id = ? FOR UPDATE OF r", + requestId); + if (hold == null + || (hold.get("released_at") != null + && !(lifecycle + && current.status().equals("canceled") + && Objects.equals( + current.terminalResolutionId(), + hold.get("terminal_resolution_id", UUID.class)))) + || !original.subscriptionId().equals(hold.get("subscription_id", UUID.class)) + || !original.paymentInstrumentId().equals(hold.get("payment_instrument_id", UUID.class)) + || original.reservedInstrumentVersion() != hold.get("instrument_version", Long.class)) { + throw new FenceRejectedException( + "Exact durable operation/version reservation or work intent is absent"); + } + return current; + } + + /** Unknown/predecessor/conflicting IDs never repair, rebind, or choose billing authority. */ + public ProviderLookup lookupProviderId(String providerSubscriptionId) { + if (providerSubscriptionId == null + || providerSubscriptionId.length() > 255 + || !providerSubscriptionId.matches("sub_[A-Za-z0-9]+")) { + throw new IllegalArgumentException("Exact Stripe subscription reference is required"); + } + Record row = + dsl.fetchOne( + "SELECT h.*, s.provider_subscription_id AS current_provider_id, s.superseded_at, " + + "s.status AS current_status, s.terminal_resolution_id FROM subscription_provider_history h " + + "JOIN subscription s USING (subscription_id) WHERE h.provider_subscription_id = ?", + providerSubscriptionId); + if (row == null) { + return new ProviderLookup(MappingDisposition.UNRESOLVED, Optional.empty(), Optional.empty()); + } + var history = + new AccountSubscriptionProviderHistoryRecord( + row.get("provider_subscription_id", String.class), + row.get("subscription_id", UUID.class), + row.get("operation_kind", String.class), + row.get("request_id", UUID.class), + row.get("provider_operation_id", UUID.class), + row.get("role", String.class), + instant(row, "effective_at"), + row.get("evidence_digest", String.class), + instant(row, "recorded_at")); + Record terminal = + dsl.fetchOne( + "SELECT * FROM subscription_provider_terminal_resolutions " + + "WHERE subscription_id = ? AND provider_subscription_id = ?", + history.subscriptionId(), + providerSubscriptionId); + if (terminal != null) { + var evidence = + new TerminalResolution( + terminal.get("resolution_id", UUID.class), + terminal.get("request_id", UUID.class), + terminal.get("subscription_id", UUID.class), + terminal.get("cleanup_provider_identity", UUID.class), + terminal.get("provider_subscription_id", String.class), + terminal.get("outcome", String.class), + instant(terminal, "effective_at"), + terminal.get("evidence_digest", String.class), + instant(terminal, "recorded_at")); + return new ProviderLookup( + MappingDisposition.TERMINAL_HISTORY, Optional.of(history), Optional.of(evidence)); + } + // A mapped resource with no current match stays evidence-only, regardless of timestamps. + MappingDisposition disposition = + row.get("superseded_at") == null + && providerSubscriptionId.equals(row.get("current_provider_id", String.class)) + && !"canceled".equals(row.get("current_status", String.class)) + ? MappingDisposition.CURRENT_MAPPING + : MappingDisposition.HISTORY_ONLY; + return new ProviderLookup(disposition, Optional.of(history), Optional.empty()); + } + + private Optional replay( + UUID requestId, AccountSubscriptionCreateDigest.EncodedRequest encoded) { + Record row = + dsl.fetchOne( + "SELECT * FROM subscription_create_operations WHERE request_id = ?", requestId); + if (row == null) { + return Optional.empty(); + } + if (!encoded.digest().equals(row.get("request_digest", String.class)) + || !Arrays.equals(encoded.payload(), row.get("request_payload", byte[].class))) { + throw new ConflictException( + "IDEMPOTENCY_CONFLICT: caller create request has changed normalized fields"); + } + return Optional.of(creation(row)); + } + + private void lockOwner(UUID tenantId, OwnerFence expected) { + Record row = + dsl.fetchOne( + "SELECT * FROM account_tenant_billing_owners WHERE tenant_uuid = ? FOR UPDATE", + tenantId); + if (row == null + || !expected.accountUuid().equals(row.get("owner_account_uuid", UUID.class)) + || expected.version() != row.get("owner_version", Long.class) + || !expected.generation().equals(row.get("owner_generation", UUID.class))) { + throw new FenceRejectedException( + "Exact current tenant billing-owner version/generation fence rejected"); + } + } + + private Optional currentForUpdate(UUID tenantId) { + Record row = + dsl.fetchOne( + CURRENT_SELECT + "WHERE s.tenant_id = ? AND s.superseded_at IS NULL FOR UPDATE OF s", + tenantId); + return row == null ? Optional.empty() : Optional.of(current(row)); + } + + private static AccountSubscriptionCreationRecord creation(Record row) { + return new AccountSubscriptionCreationRecord( + row.get("request_id", UUID.class), + row.get("request_digest", String.class), + row.get("subscription_id", UUID.class), + row.get("tenant_id", UUID.class), + owner(row), + row.get("plan_code", String.class), + quote(row), + row.get("payment_instrument_id", UUID.class), + row.get("reserved_instrument_version", Long.class), + row.get("customer_provisioning_request_id", UUID.class), + row.get("provider_customer_id", String.class), + row.get("subscription_provisioning_request_id", UUID.class), + row.get("cleanup_provider_identity", UUID.class), + row.get("result_status", String.class), + row.get("result_row_version", Long.class), + instant(row, "created_at")); + } + + private static AccountSubscriptionCurrentRecord current(Record row) { + return new AccountSubscriptionCurrentRecord( + row.get("subscription_id", UUID.class), + row.get("tenant_id", UUID.class), + owner(row), + row.get("plan_code", String.class), + quote(row), + row.get("payment_instrument_id", UUID.class), + row.get("reserved_instrument_version", Long.class), + row.get("customer_provisioning_request_id", UUID.class), + row.get("provider_customer_id", String.class), + row.get("creation_request_id", UUID.class), + row.get("row_version", Long.class), + row.get("status", String.class), + row.get("provider_subscription_id", String.class), + row.get("terminal_resolution_id", UUID.class), + instant(row, "superseded_at"), + row.get("superseded_by_request_id", UUID.class)); + } + + private static AccountHostingPlanQuote quote(Record row) { + var quote = + new AccountHostingPlanQuote( + row.get("plan_code", String.class), + row.get("provider_price_id", String.class), + row.get("provider_quantity", Long.class), + row.get("max_active_sessions", Long.class), + row.get("max_concurrent_game_instances", Long.class), + row.get("max_storage_bytes", Long.class)); + quote.requireRetained( + row.get("plan_quote_payload", byte[].class), row.get("plan_quote_digest", String.class)); + return quote; + } + + private static OwnerFence owner(Record row) { + return new OwnerFence( + row.get("account_uuid", UUID.class), + row.get("owner_version", Long.class), + row.get("owner_generation", UUID.class)); + } + + private static Instant instant(Record row, String column) { + OffsetDateTime value = row.get(column, OffsetDateTime.class); + return value == null ? null : value.toInstant(); + } + + private static void requireWritableTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Subscription intent requires an active writable Account transaction"); + } + } + + public enum MappingDisposition { + UNRESOLVED, + CURRENT_MAPPING, + HISTORY_ONLY, + TERMINAL_HISTORY + } + + public record ProviderLookup( + MappingDisposition disposition, + Optional history, + Optional terminalResolution) {} + + public static final class ConflictException extends IllegalStateException { + public ConflictException(String message) { + super(message); + } + + public ConflictException(String message, Throwable cause) { + super(message, cause); + } + } + + public static final class FenceRejectedException extends IllegalStateException { + public FenceRejectedException(String message) { + super(message); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionProviderHistoryRecord.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionProviderHistoryRecord.java new file mode 100644 index 0000000000..a9ad16e288 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionProviderHistoryRecord.java @@ -0,0 +1,31 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.time.Instant; +import java.util.UUID; + +/** Immutable typed creation mapping, not current billing authority. Transfer writers are absent. */ +public record AccountSubscriptionProviderHistoryRecord( + String providerSubscriptionId, + UUID subscriptionId, + String operationKind, + UUID requestId, + UUID providerOperationId, + String role, + Instant effectiveAt, + String evidenceDigest, + Instant recordedAt) { + + /** + * Separate immutable provider absence/cancellation evidence; not inferred from mapping or time. + */ + public record TerminalResolution( + UUID resolutionId, + UUID requestId, + UUID subscriptionId, + UUID cleanupProviderIdentity, + String providerSubscriptionId, + String outcome, + Instant effectiveAt, + String evidenceDigest, + Instant recordedAt) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java index 5ae037a921..ac817af7f1 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java @@ -15,6 +15,10 @@ import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; /** Typed tenant-authority source, outbox, receipt, and current-checkpoint readback. */ @Repository @@ -24,6 +28,11 @@ "Injected Account repositories and DSLContext are private transaction collaborators.") public class AccountTenantAuthorityEventRepository { private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final JsonMapper SOURCE_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); private final DSLContext dsl; private final AccountAuthorityOutboxRepository authorityOutbox; @@ -48,6 +57,132 @@ public AccountTenantAuthorityEventRepository( this.generations = Objects.requireNonNull(generations); } + /** Data-only routing hint over the exact current source; it grants no entitlement authority. */ + @Transactional(propagation = Propagation.MANDATORY) + public SourceSelection readCurrentSourceSelection(UUID tenantId) { + requireTransaction(); + requireTenant(tenantId); + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Source selection requires a writable Account transaction"); + } + ScopeState authority = + generations.read(AccountAuthorityGenerationRepository.AuthorityScope.tenant(tenantId)); + Record head = + dsl.fetchOne( + "SELECT * FROM account_tenant_authority_source_records WHERE tenant_uuid = ? FOR SHARE", + tenantId); + if (head == null) { + throw new IllegalStateException("Current tenant source is absent"); + } + long sequence = positive(head, "tenant_billing_sequence"); + UUID requestId = requiredUuid(head, "last_request_id"); + UUID eventId = requiredUuid(head, "tenant_billing_event_id"); + String digest = requiredText(head, "tenant_billing_event_digest"); + Record billing = + dsl.fetchOne( + "SELECT e.*, 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 = ? FOR SHARE OF s", + tenantId, + sequence); + if (billing == null + || positive(billing, "last_sequence") != sequence + || positive(billing, "tenant_billing_sequence") != sequence + || !requestId.equals(billing.get("request_id", UUID.class)) + || !eventId.equals(billing.get("event_id", UUID.class)) + || !digest.equals(billing.get("event_digest", String.class))) { + throw new IllegalStateException("Tenant source differs from the current billing checkpoint"); + } + byte[] payload = billing.get("payload", byte[].class); + if (payload == null || payload.length == 0 || payload.length > 32768) { + throw new IllegalStateException("Tenant billing payload is absent or oversized"); + } + JsonNode envelope; + try { + envelope = SOURCE_JSON.readTree(payload); + } catch (RuntimeException exception) { + throw new IllegalStateException("Tenant billing envelope is unreadable", exception); + } + if (envelope == null + || !tenantId.toString().equals(envelope.path("tenantId").asText()) + || !requestId.toString().equals(envelope.path("requestId").asText()) + || !requiredText(head, "last_request_digest") + .equals(envelope.path("requestDigest").asText()) + || !eventId.toString().equals(envelope.path("eventId").asText()) + || !Long.toString(sequence).equals(envelope.path("tenantBillingSequence").asText())) { + throw new IllegalStateException("Tenant billing envelope differs from its exact source head"); + } + SourceKind kind; + Event checkpoint; + switch (envelope.path("schemaVersion").asText()) { + case "account-hosting-subscription-event/v1" -> { + kind = SourceKind.PAID_HOSTING; + var hosting = AccountHostingSubscriptionLifecycleEvidence.verifyBilling(payload); + if (!digest.equals(hosting.digest())) { + throw new IllegalStateException( + "Hosting billing payload differs from its committed digest"); + } + checkpoint = readHostingCheckpoint(tenantId, requestId); + Record receipt = + dsl.fetchOne( + "SELECT receipt_payload FROM subscription_lifecycle_receipts WHERE request_id = ? AND tenant_id = ?", + requestId, + tenantId); + if (receipt == null + || !"SubscriptionStatusChanged".equals(envelope.path("eventType").asText()) + || !envelope + .path("receipt") + .equals(SOURCE_JSON.readTree(receipt.get("receipt_payload", byte[].class)))) { + throw new IllegalStateException("Hosting envelope differs from its committed receipt"); + } + } + case DemoTenantEntitlementEventV1Codec.SCHEMA_VERSION -> { + kind = SourceKind.NON_PAID_DEMO; + if (!digest.equals(DemoTenantEntitlementEventV1Codec.verify(payload).eventDigest())) { + throw new IllegalStateException("Demo billing payload differs from its committed digest"); + } + checkpoint = readCurrentDemoByTenant(tenantId); + } + default -> throw new IllegalStateException("Tenant billing source family is unknown"); + } + if (authority.generation() != checkpoint.tenantAuthorityGeneration() + || authority.sourceVersion() != checkpoint.tenantAuthoritySourceVersion() + || !requestId.equals(checkpoint.requestId()) + || !requiredText(head, "last_request_digest").equals(checkpoint.requestDigest()) + || positive(head, "current_generation") != checkpoint.tenantAuthorityGeneration() + || positive(head, "current_source_version") != checkpoint.tenantAuthoritySourceVersion() + || positive(head, "last_outbox_sequence") != checkpoint.outboxSequence() + || !requiredText(head, "last_event_id").equals(checkpoint.eventId().toString()) + || !requiredText(head, "last_event_digest").equals(checkpoint.eventDigest()) + || sequence != checkpoint.tenantBillingSequence() + || !eventId.equals(checkpoint.tenantBillingEventId()) + || !digest.equals(checkpoint.tenantBillingEventDigest())) { + throw new IllegalStateException("Tenant authority changed during source selection"); + } + return new SourceSelection(kind, checkpoint); + } + + public enum SourceKind { + PAID_HOSTING, + NON_PAID_DEMO + } + + /** The checkpoint is source identity only; callers still require the owning positive reader. */ + public record SourceSelection(SourceKind kind, Event checkpoint) { + public SourceSelection { + Objects.requireNonNull(kind); + Objects.requireNonNull(checkpoint); + } + + public boolean matches(Event current) { + return current != null + && checkpoint.tenantId().equals(current.tenantId()) + && checkpoint.eventId().equals(current.eventId()) + && checkpoint.eventDigest().equals(current.eventDigest()) + && java.util.Arrays.equals(checkpoint.payload(), current.payload()); + } + } + /** Establishes sequence zero only from the same Account transaction that enrolled the tenant. */ @Transactional(propagation = Propagation.MANDATORY) public void establishFirstEventSource( @@ -152,6 +287,161 @@ public void establishFirstEventSource( } } + /** Appends one tenant-scoped event after the owner has advanced the exact generation row. */ + @Transactional(propagation = Propagation.MANDATORY) + public Event appendHosting( + UUID requestId, + String requestDigest, + FreshTenantCreationEvidence source, + ScopeState nextAuthority, + long billingSequence, + UUID billingEventId, + String billingEventDigest) { + requireTransaction(); + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Hosting source requires a writable Account transaction"); + } + UUID tenantId = source.canonicalTenantId(); + requireExactTenant(tenantId, source, nextAuthority); + String key = TenantAuthorityEventV1Codec.streamKey(tenantId); + Record head = + dsl.fetchOne( + "SELECT * FROM account_tenant_authority_source_records WHERE outbox_stream_key = ? FOR UPDATE", + key); + if (head == null + || positive(head, "current_generation") + 1 != nextAuthority.generation() + || positive(head, "current_source_version") + 1 != nextAuthority.sourceVersion()) { + throw new IllegalStateException( + "Hosting source does not extend the exact canonical tenant head"); + } + var stored = + authorityOutbox.append( + key, + requestId.toString(), + sequence -> + evidence( + TenantAuthorityEventV1Codec.seal( + new TenantAuthorityEventV1Codec.AuthorityRequest( + requestId, + requestDigest, + tenantId, + source.creationRequestId(), + source.requestDigest()), + source, + nextAuthority.generation(), + nextAuthority.sourceVersion(), + sequence, + new TenantAuthorityEventV1Codec.BillingReceipt( + tenantId, + requestId, + requestDigest, + TenantAuthorityEventV1Codec.tenantBillingStreamKey(tenantId), + billingSequence, + billingEventId, + billingEventDigest)))); + Event event = TenantAuthorityEventV1Codec.verify(stored.payload()); + if (!event.eventDigest().equals(stored.eventDigest()) + || !event.eventId().toString().equals(stored.eventId()) + || !event.requestId().equals(requestId) + || !event.sourceEvidence().equals(source) + || event.outboxSequence() != nonnegative(head, "last_outbox_sequence") + 1) { + throw new IllegalStateException("Hosting authority event differs from its exact source"); + } + if (dsl.execute( + "UPDATE account_tenant_authority_source_records SET current_generation = ?, current_source_version = ?, " + + "last_outbox_sequence = ?, last_request_id = ?, last_request_digest = ?, last_event_id = ?, last_event_digest = ?, " + + "tenant_billing_sequence = ?, tenant_billing_event_id = ?, tenant_billing_event_digest = ? " + + "WHERE outbox_stream_key = ? AND current_generation = ? AND current_source_version = ? AND last_outbox_sequence = ?", + event.tenantAuthorityGeneration(), + event.tenantAuthoritySourceVersion(), + event.outboxSequence(), + requestId, + requestDigest, + event.eventId().toString(), + event.eventDigest(), + billingSequence, + billingEventId, + billingEventDigest, + key, + nextAuthority.generation() - 1, + nextAuthority.sourceVersion() - 1, + event.outboxSequence() - 1) + != 1) { + throw new IllegalStateException("Hosting source checkpoint CAS rejected"); + } + return event; + } + + /** Exact hosting receipt readback; demo receipt interpretation is deliberately not used. */ + @Transactional(propagation = Propagation.MANDATORY) + public Event readHostingCheckpoint(UUID tenantId, UUID requestId) { + requireTransaction(); + FreshTenantCreationEvidence source = tenantIdentity.read(tenantId).orElseThrow(); + ScopeState authority = + generations.read(AccountAuthorityGenerationRepository.AuthorityScope.tenant(tenantId)); + Record receipt = + dsl.fetchOne( + "SELECT r.* FROM subscription_lifecycle_receipts r " + + "JOIN subscription_lifecycle_operations o USING (request_id) WHERE r.request_id = ? AND r.tenant_id = ? " + + "AND o.state = 'COMMITTED'", + requestId, + tenantId); + Record head = + dsl.fetchOne( + "SELECT * FROM account_tenant_authority_source_records WHERE tenant_uuid = ? FOR SHARE", + tenantId); + if (receipt == null + || head == null + || !requestId.equals(head.get("last_request_id", UUID.class)) + || !receipt + .get("request_digest", String.class) + .equals(head.get("last_request_digest", String.class)) + || authority.generation() != positive(receipt, "authority_generation") + || authority.sourceVersion() != positive(receipt, "authority_source_version") + || authority.generation() != positive(head, "current_generation") + || authority.sourceVersion() != positive(head, "current_source_version") + || positive(receipt, "authority_sequence") != positive(head, "last_outbox_sequence") + || positive(receipt, "billing_sequence") != positive(head, "tenant_billing_sequence") + || !receipt + .get("billing_event_id", UUID.class) + .equals(head.get("tenant_billing_event_id", UUID.class)) + || !receipt + .get("billing_event_digest", String.class) + .equals(head.get("tenant_billing_event_digest", String.class))) { + throw new IllegalStateException("Hosting receipt is not the current canonical tenant source"); + } + var stored = + authorityOutbox + .findEvent( + TenantAuthorityEventV1Codec.streamKey(tenantId), + positive(receipt, "authority_sequence")) + .orElseThrow(); + Event event = TenantAuthorityEventV1Codec.verify(stored.payload()); + var checkpoint = authorityOutbox.readCheckpoint(stored.outboxStreamKey()).orElseThrow(); + if (!event.sourceEvidence().equals(source) + || !event.requestId().equals(requestId) + || !event.requestDigest().equals(receipt.get("request_digest", String.class)) + || event.tenantAuthorityGeneration() != authority.generation() + || event.tenantAuthoritySourceVersion() != authority.sourceVersion() + || event.tenantBillingSequence() != positive(receipt, "billing_sequence") + || !event.tenantBillingEventId().equals(receipt.get("billing_event_id", UUID.class)) + || !event + .tenantBillingEventDigest() + .equals(receipt.get("billing_event_digest", String.class)) + || !event.eventId().toString().equals(receipt.get("authority_event_id", String.class)) + || !event.eventDigest().equals(receipt.get("authority_event_digest", String.class)) + || !stored.eventId().equals(event.eventId().toString()) + || !stored.eventDigest().equals(event.eventDigest()) + || !checkpoint.sourceEventId().equals(stored.eventId()) + || !checkpoint.sourceEventDigest().equals(stored.eventDigest()) + || checkpoint.outboxSequence() != stored.outboxSequence() + || !stored.eventId().equals(head.get("last_event_id", String.class)) + || !stored.eventDigest().equals(head.get("last_event_digest", String.class))) { + throw new IllegalStateException("Hosting source/outbox/receipt readback is inconsistent"); + } + return event; + } + /** Appends one tenant-scoped event after the owner has advanced the exact generation row. */ @Transactional(propagation = Propagation.MANDATORY) public Event append( @@ -254,7 +544,8 @@ public Event append( } /** - * Verifies the exact event and owning committed receipt, without requiring it to remain latest. + * Verifies the exact DEMO event and owning committed DEMO receipt, without requiring it to remain + * latest. Hosting receipts use readHostingCheckpoint instead. */ @Transactional(propagation = Propagation.MANDATORY, readOnly = true) public Event readCommittedReceipt( @@ -335,7 +626,10 @@ public Event readCommittedReceipt( return event; } - /** Verifies that a current Account generation is represented by the exact latest source event. */ + /** + * Verifies the exact latest DEMO source against its owning DEMO operation. Hosting currentness + * uses readHostingCheckpoint through the shared source selector. + */ @Transactional(propagation = Propagation.MANDATORY, readOnly = true) public Event readCurrentCheckpoint( UUID tenantId, @@ -402,8 +696,17 @@ public Event readCurrentCheckpoint( */ @Transactional(propagation = Propagation.MANDATORY) public Event readCurrentByTenant(UUID tenantId) { + return readCurrentSourceSelection(tenantId).checkpoint(); + } + + /** DEMO-owned current read; retains the same owner transaction and exact source checks. */ + Event readCurrentDemoByTenant(UUID tenantId) { requireTransaction(); requireTenant(tenantId); + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "DEMO current source requires a writable Account transaction"); + } Record freshIdentity = dsl.fetchOne( "SELECT canonical_tenant_id FROM account_fresh_tenant_identity_associations " diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java index 3f721a213a..4790bfd48f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java @@ -15,13 +15,21 @@ import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; -/** Account-owned per-tenant billing/entitlement event stream for demo entitlement currentness. */ +/** Account-owned shared tenant billing stream; DEMO events retain their explicit typed reader. */ @Repository @SuppressFBWarnings( value = "EI_EXPOSE_REP2", justification = "Injected DSLContext is an internal Account transaction collaborator.") public class AccountTenantEntitlementOutboxRepository { + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); private static final UUID NIL_UUID = new UUID(0L, 0L); private final DSLContext dsl; @@ -37,6 +45,71 @@ public static String streamKey(UUID canonicalTenantId) { return TenantAuthorityEventV1Codec.tenantBillingStreamKey(canonicalTenantId); } + /** + * Production hosting writer over the SAME canonical tenant billing stream; no demo conversion. + */ + AccountHostingSubscriptionLifecycleEvidence.BillingEvent appendHosting( + UUID tenantId, + UUID requestId, + LongFunction factory) { + requireTransaction(); + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Hosting billing events require a writable owner transaction"); + } + streamKey(tenantId); + dsl.execute( + "INSERT INTO account_tenant_entitlement_outbox_streams (tenant_uuid, last_sequence) " + + "VALUES (?, 0) ON CONFLICT (tenant_uuid) DO NOTHING", + tenantId); + Record head = + dsl.fetchOne( + "SELECT last_sequence FROM account_tenant_entitlement_outbox_streams " + + "WHERE tenant_uuid = ? FOR UPDATE", + tenantId); + Record prior = + dsl.fetchOne( + "SELECT * FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ? AND request_id = ?", + tenantId, + requestId); + long sequence = + prior == null + ? Math.addExact(nonnegative(head, "last_sequence"), 1L) + : positive(prior, "tenant_billing_sequence"); + var event = Objects.requireNonNull(factory.apply(sequence)); + if (!tenantId.equals(event.tenantId) + || !requestId.equals(event.requestId) + || event.sequence != sequence) { + throw new IllegalStateException("Hosting event differs from its canonical billing stream"); + } + if (prior != null) { + if (!event.eventId.equals(prior.get("event_id", UUID.class)) + || !event.matches( + prior.get("payload", byte[].class), prior.get("event_digest", String.class))) { + throw new IllegalStateException("Hosting billing request conflicts with retained evidence"); + } + return event; + } + if (dsl.execute( + "UPDATE account_tenant_entitlement_outbox_streams SET last_sequence = ? WHERE tenant_uuid = ? AND last_sequence = ?", + sequence, + tenantId, + sequence - 1) + != 1) { + throw new IllegalStateException("Hosting billing stream CAS rejected"); + } + dsl.execute( + "INSERT INTO account_tenant_entitlement_outbox_events " + + "(tenant_uuid, tenant_billing_sequence, request_id, event_id, event_digest, payload) VALUES (?, ?, ?, ?, ?, ?)", + tenantId, + sequence, + requestId, + event.eventId, + event.digest(), + event.payload()); + return event; + } + /** Appends one event or returns only an exact request and payload replay. */ @Transactional(propagation = Propagation.MANDATORY) public Event append(UUID tenantId, UUID requestId, LongFunction eventFactory) { @@ -128,18 +201,51 @@ public Optional readCheckpoint(UUID tenantId) { return Optional.empty(); } long sequence = positive(stream, "last_sequence"); - Event event = - readEvent(tenantId, sequence) - .orElseThrow( - () -> new IllegalStateException("Tenant entitlement checkpoint has no event")); - return Optional.of( - new Checkpoint( - streamKey(tenantId), - event.tenantBillingSequence(), - event.eventId(), - event.eventDigest())); + Record row = + dsl.fetchOne( + "SELECT tenant_uuid, tenant_billing_sequence, request_id, event_id, event_digest, payload " + + "FROM account_tenant_entitlement_outbox_events " + + "WHERE tenant_uuid = ? AND tenant_billing_sequence = ?", + tenantId, + sequence); + if (row == null + || !tenantId.equals(row.get("tenant_uuid", UUID.class)) + || positive(row, "tenant_billing_sequence") != sequence) { + throw new IllegalStateException("Tenant entitlement checkpoint has no exact event"); + } + byte[] payload = row.get("payload", byte[].class); + if (payload == null || payload.length == 0 || payload.length > 32768) { + throw new IllegalStateException("Tenant billing envelope is absent or oversized"); + } + String schema; + try { + schema = JSON.readTree(payload).path("schemaVersion").asText(); + } catch (RuntimeException failure) { + throw new IllegalStateException("Tenant billing envelope is malformed", failure); + } + return switch (schema) { + case DemoTenantEntitlementEventV1Codec.SCHEMA_VERSION -> { + Event demo = event(tenantId, row); + yield Optional.of( + new Checkpoint(streamKey(tenantId), sequence, demo.eventId(), demo.eventDigest())); + } + case "account-hosting-subscription-event/v1" -> { + var hosting = AccountHostingSubscriptionLifecycleEvidence.verifyBilling(payload); + if (!tenantId.equals(hosting.tenantId) + || hosting.sequence != sequence + || !hosting.requestId.equals(row.get("request_id", UUID.class)) + || !hosting.eventId.equals(row.get("event_id", UUID.class)) + || !hosting.digest().equals(row.get("event_digest", String.class))) { + throw new IllegalStateException("Stored hosting billing event differs from its payload"); + } + yield Optional.of( + new Checkpoint(streamKey(tenantId), sequence, hosting.eventId, hosting.digest())); + } + default -> throw new IllegalStateException("Tenant billing source family is unknown"); + }; } + /** DEMO-only event read; hosting callers use the source-neutral checkpoint and owning receipt. */ @Transactional(propagation = Propagation.MANDATORY) public Optional readEvent(UUID tenantId, long sequence) { requireTransaction(); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java new file mode 100644 index 0000000000..87b37f7260 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java @@ -0,0 +1,555 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.JwtException; +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.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; +import net.firedevops.firemud.accountservice.config.AccountTokenProperties; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +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.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceSelection; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.AccountPublicBootstrapEntitlementOwner.Evaluation; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.session.AccountPlayerBootstrapCallerVerifier; +import net.firedevops.firemud.accountservice.service.session.AccountPlayerBootstrapCallerVerifier.VerifiedCaller; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.DiscoveryRequest; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.security.JwtClaims; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Manually composed public SHARED/PRESEEDED REALMS and canonical selector-scope producer. Bootstrap + * registry, provider and protected GS reads occur outside SQL. Short Account transactions read + * current identity, provenance, membership and billing heads; the final transaction retains and + * exactly reads back the V2 scope. Every repository must use the supplied transaction manager. + * + *

Membership-independent public visibility is preserved when enrollment is closed. Returned + * membership/entitlement facts are observations for later selection, never permission to JOIN, + * create a character or admit gameplay. This owner neither enrolls membership nor claims a World + * hold, private/ISOLATED support, a registered facade, or qualified credential custody. + */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Explicitly composed owner collaborators remain private transaction sources.") +public final class AccountCanonicalPublicRealmScopeOwner { + private final AccountPlayerBootstrapCallerVerifier callers; + private final CanonicalGameplayAdmissionDecisionReadClient targets; + private final AccountPublicBootstrapEntitlementOwner entitlements; + private final AccountRepository accounts; + private final AccountTenantMembershipRepository memberships; + private final FreshTenantIdentityAssociationRepository tenants; + private final AccountTenantAuthorityEventRepository heads; + private final AccountConnectScopeRepository scopes; + private final JwtUtil jwt; + private final Clock clock; + private final String namespace; + private final long scopeLifetimeMillis; + private final TransactionTemplate transaction; + + public AccountCanonicalPublicRealmScopeOwner( + AccountPlayerBootstrapCallerVerifier callers, + CanonicalGameplayAdmissionDecisionReadClient targets, + AccountPublicBootstrapEntitlementOwner entitlements, + AccountRepository accounts, + AccountTenantMembershipRepository memberships, + FreshTenantIdentityAssociationRepository tenants, + AccountTenantAuthorityEventRepository heads, + AccountConnectScopeRepository scopes, + JwtUtil jwt, + AccountTokenProperties tokenProperties, + Clock clock, + PlatformTransactionManager transactions, + String namespace) { + this.callers = Objects.requireNonNull(callers); + this.targets = Objects.requireNonNull(targets); + this.entitlements = Objects.requireNonNull(entitlements); + this.accounts = Objects.requireNonNull(accounts); + this.memberships = Objects.requireNonNull(memberships); + this.tenants = Objects.requireNonNull(tenants); + this.heads = Objects.requireNonNull(heads); + this.scopes = Objects.requireNonNull(scopes); + this.jwt = Objects.requireNonNull(jwt); + this.clock = Objects.requireNonNull(clock); + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.namespace = namespace; + scopeLifetimeMillis = Objects.requireNonNull(tokenProperties).getConnectScopeExpirationMs(); + if (scopeLifetimeMillis <= 0L) { + throw new IllegalArgumentException("Configured positive connect-scope lifetime required"); + } + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + transaction.setReadOnly(false); + } + + /** Selects only the canonical tenant/world pair; a bare global world slug is not authority. */ + public List listRealmScopes( + String bootstrapToken, String tenantSlug, String worldSlug) { + requireSourceContext(); + Caller original = verifyCaller(bootstrapToken); + if (!RealmEntryPolicy.isCanonicalSlug(tenantSlug) + || !RealmEntryPolicy.isCanonicalSlug(worldSlug)) { + throw pointerUnavailable(null); + } + Optional selected = select(readTargets(), tenantSlug, worldSlug); + if (selected.isEmpty()) { + if (select(readTargets(), tenantSlug, worldSlug).isPresent()) { + throw pointerUnavailable(null); + } + requireSameCaller(original, verifyCaller(bootstrapToken)); + return List.of(); + } + Target target = selected.orElseThrow(); + Evaluation entitlement = evaluate(target); + if (!entitlement.gameplayAvailable()) { + requireSameTarget(target, select(readTargets(), tenantSlug, worldSlug)); + requireSameCaller(original, verifyCaller(bootstrapToken)); + requireFresh(entitlement); + return List.of(); + } + + Prepared prepared = inTransaction(() -> readSources(original, target, entitlement)); + requireSameTarget(target, select(readTargets(), tenantSlug, worldSlug)); + requireSameCaller(original, verifyCaller(bootstrapToken)); + requireFresh(entitlement); + RealmScope retained = + inTransaction( + () -> { + Prepared current = readSources(original, target, entitlement); + if (!prepared.tenant().equals(current.tenant()) + || !prepared.membership().equals(current.membership())) { + throw authUnavailable("Account discovery sources changed", null); + } + if (prepared.head().kind() != current.head().kind() + || !prepared.head().matches(current.head().checkpoint())) { + throw entitlementUnavailable(null); + } + requireFresh(entitlement); + Instant evaluatedAt = now(); + Instant expiresAt = evaluatedAt.plusMillis(scopeLifetimeMillis); + if (original.expiresAt().isBefore(expiresAt)) expiresAt = original.expiresAt(); + // JWT NumericDate has second precision. The persisted preimage uses that exact + // expiry. + expiresAt = expiresAt.truncatedTo(ChronoUnit.SECONDS); + if (!evaluatedAt.isBefore(expiresAt)) { + throw new AuthenticationException( + "CONNECT_CONTEXT_INVALID", "Bootstrap credential expired"); + } + CanonicalJoinScopeV2 scope = mintScope(original, target, evaluatedAt, expiresAt); + VerifiedTenantProvenance provenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + current.tenant().operationId(), + current.tenant().evidenceDigest()); + scopes.insertCanonical(original.caller().accountId(), scope, provenance); + if (!scope.equals(scopes.findCanonical(scope.connectScopeId()).orElse(null))) { + throw authUnavailable("Canonical scope readback differs", null); + } + CanonicalConnectScopeEvidence expected = evidence(original, scope, provenance); + if (!expected.equals( + scopes + .findCanonicalEvidenceByTokenHash(expected.scopeTokenHash()) + .orElse(null))) { + throw authUnavailable("Canonical scope evidence readback differs", null); + } + return new RealmScope(target, scope, current.membership(), entitlement); + }); + // No value escapes a failed commit or a caller/source observation that expired during commit. + requireSameCaller(original, verifyCaller(bootstrapToken)); + requireFresh(entitlement); + if (!now().isBefore(Instant.parse(retained.scope().connectScopeExpiresAt()))) { + throw authUnavailable("Canonical scope expired before publication", null); + } + return List.of(retained); + } + + private Caller verifyCaller(String token) { + requireSourceContext(); + try { + VerifiedCaller caller = Objects.requireNonNull(callers.requireCaller(token)); + Claims claims = jwt.parseToken(token).getPayload(); + if (claims.getIssuedAt() == null || claims.getExpiration() == null) { + throw new AuthenticationException( + "CONNECT_CONTEXT_INVALID", "Incomplete bootstrap credential"); + } + Instant issuedAt = claims.getIssuedAt().toInstant(); + Instant expiresAt = claims.getExpiration().toInstant(); + JwtClaims.requireText(claims.get("jti"), "jti"); + Instant current = now(); + if (!"player-bootstrap".equals(JwtClaims.requireText(claims.get("aud"), "aud")) + || !caller.accountUuid().toString().equals(claims.getSubject()) + || !caller.accountUuid().toString().equals(claims.get("accountId")) + || !issuedAt.isAfter(Instant.EPOCH) + || !issuedAt.isBefore(expiresAt) + || current.isBefore(issuedAt) + || !current.isBefore(expiresAt)) { + throw new AuthenticationException( + "CONNECT_CONTEXT_INVALID", "Invalid bootstrap credential"); + } + return new Caller(caller, issuedAt, expiresAt); + } catch (AuthenticationException failure) { + throw failure; + } catch (JwtException | IllegalArgumentException failure) { + throw new AuthenticationException("CONNECT_CONTEXT_INVALID", "Invalid bootstrap credential"); + } catch (RuntimeException failure) { + throw authUnavailable("Bootstrap caller authority is unavailable", failure); + } + } + + private List readTargets() { + requireSourceContext(); + try { + UUID requestId = UUID.randomUUID(); + var response = + Objects.requireNonNull(targets.listVisiblePublicProductionAdmissionTargets(requestId)); + if (!new DiscoveryRequest(requestId, namespace).equals(response.request())) { + throw pointerUnavailable(null); + } + return List.copyOf(response.targets()); + } catch (AuthenticationException failure) { + throw failure; + } catch (RuntimeException failure) { + if (AccountPublicDiscoverySourceFailure.isUnavailable(failure)) { + throw authUnavailable("Game Session discovery source is unavailable", failure); + } + throw pointerUnavailable(failure); + } + } + + private Optional select(List complete, String tenantSlug, String worldSlug) { + List matches = + complete.stream() + .filter( + target -> + tenantSlug.equals(target.tenantSlug()) && worldSlug.equals(target.worldSlug())) + .toList(); + if (matches.size() > 1) throw pointerUnavailable(null); + for (Target target : matches) { + if (!namespace.equals(target.targetNamespace()) + || !"SHARED".equals(target.playableStateScope()) + || !"PRESEEDED_ONLY".equals(target.characterCreationPolicy())) { + throw pointerUnavailable(null); + } + } + return matches.stream().findFirst(); + } + + private Evaluation evaluate(Target target) { + requireSourceContext(); + try { + Evaluation evaluation = + Objects.requireNonNull(entitlements.evaluate(target.canonicalTenantId())); + if (!target.canonicalTenantId().equals(evaluation.canonicalTenantId()) + || evaluation.sourceKind() == null + || evaluation.entitlementVersion() <= 0L + || evaluation.tenantBillingSequence() <= 0L) throw entitlementUnavailable(null); + requireFresh(evaluation); + return evaluation; + } catch (AuthenticationException failure) { + throw failure; + } catch (RuntimeException failure) { + throw entitlementUnavailable(failure); + } + } + + private Prepared readSources(Caller caller, Target target, Evaluation entitlement) { + Account account = + accounts + .findByAccountUuidForUpdate(caller.caller().accountUuid()) + .orElseThrow(() -> authUnavailable("Account owner is unavailable", null)); + if (!Objects.equals(account.getId(), caller.caller().accountId()) + || !caller.caller().accountUuid().equals(account.getAccountUuid()) + || !Objects.equals(account.getId(), account.getAccountUuidSourceNumericId()) + || !AccountIdentityProvenance.isAccepted(account.getAccountUuidProvenance()) + || account.getLifecycleState() != AccountLifecycleState.ACTIVE) { + throw authUnavailable("Account owner changed or is ineligible", null); + } + FreshTenantCreationEvidence tenant = + tenants + .read(target.canonicalTenantId()) + .orElseThrow(() -> authUnavailable("Fresh tenant provenance is unavailable", null)); + if (!namespace.equals(tenant.targetNamespace()) + || !target.canonicalTenantId().equals(tenant.canonicalTenantId())) { + throw authUnavailable("Fresh tenant provenance differs from the target", null); + } + SourceSelection head; + try { + head = Objects.requireNonNull(heads.readCurrentSourceSelection(target.canonicalTenantId())); + if (head.kind() != entitlement.sourceKind() + || !target.canonicalTenantId().equals(head.checkpoint().tenantId()) + || head.checkpoint().tenantBillingSequence() != entitlement.tenantBillingSequence()) { + throw entitlementUnavailable(null); + } + } catch (AuthenticationException failure) { + throw failure; + } catch (RuntimeException failure) { + throw entitlementUnavailable(failure); + } + Optional member = + memberships.findFreshMembershipForUpdate( + caller.caller().accountUuid(), target.canonicalTenantId()); + Optional current = + member.map( + value -> { + if (value.getId() == null + || value.getId() <= 0L + || value.getAccount() == null + || !Objects.equals(account.getId(), value.getAccount().getId()) + || !account.getAccountUuid().equals(value.getAccount().getAccountUuid()) + || value.getTenantId() != null + || !target.canonicalTenantId().equals(value.getTenantUuid()) + || !TenantProvenanceKind.FRESH_GAME_DESIGN + .name() + .equals(value.getTenantProvenanceKind()) + || !tenant.operationId().equals(value.getTenantSourceOperationId()) + || !tenant.evidenceDigest().equals(value.getTenantProvenanceDigest()) + || value.getMembershipVersion() <= 0L + || value.getMembershipAuthorityGeneration() <= 0L + || !List.of("ACTIVE", "INACTIVE").contains(value.getLifecycleState())) { + throw authUnavailable("Canonical membership evidence is malformed", null); + } + return new ExistingMembership( + value.getId(), + value.getLifecycleState(), + value.isGameplayAdmissionAllowed(), + value.getMembershipVersion(), + value.getMembershipAuthorityGeneration()); + }); + return new Prepared( + tenant, + new MembershipFacts(account.getAccountUuid(), target.canonicalTenantId(), current), + head); + } + + private CanonicalJoinScopeV2 mintScope( + Caller caller, Target target, Instant evaluatedAt, Instant expiresAt) { + Map claims = new LinkedHashMap<>(); + claims.put("aud", "bootstrap-connect-scope"); + claims.put("accountId", caller.caller().accountUuid().toString()); + claims.put("targetClass", "PUBLIC_PRODUCTION"); + claims.put("scopeDigestVersion", 2L); + claims.put("tenantId", target.canonicalTenantId().toString()); + claims.put("tenantSlug", target.tenantSlug()); + claims.put("worldSlug", target.worldSlug()); + claims.put("realmId", target.realmId().toString()); + claims.put("realmSlug", target.realmSlug()); + claims.put("playableStateNamespaceId", target.playableStateNamespaceId().toString()); + claims.put("playableStateScope", target.playableStateScope()); + claims.put("gameInstanceId", target.canonicalGameInstanceId().toString()); + claims.put("catalogRevision", target.catalogRevision()); + claims.put("pointerVersion", target.pointerVersion()); + claims.put("evaluatedAt", evaluatedAt.toString()); + claims.put("connectScopeExpiresAt", expiresAt.toString()); + claims.put("jti", UUID.randomUUID().toString()); + // Preserve the owner-selected absolute expiry even if signing starts after a scheduling pause. + final String token; + try { + token = jwt.generateToken(caller.caller().accountUuid().toString(), expiresAt, claims); + } catch (IllegalArgumentException expired) { + throw authUnavailable("Scope signing clock is outside its validity", expired); + } + Claims signed = jwt.parseToken(token).getPayload(); + if (!caller.caller().accountUuid().toString().equals(signed.getSubject()) + || signed.getExpiration() == null + || !expiresAt.equals(signed.getExpiration().toInstant()) + || signed.getIssuedAt() == null + || !signed.getIssuedAt().toInstant().isBefore(expiresAt) + || !"bootstrap-connect-scope".equals(JwtClaims.requireText(signed.get("aud"), "aud"))) { + throw authUnavailable("Signed scope profile differs from the retained preimage", null); + } + for (var entry : claims.entrySet()) { + if (entry.getKey().equals("aud")) continue; + Object actual = signed.get(entry.getKey()); + if (entry.getValue() instanceof Long number) { + if (JwtClaims.requireLong(actual, entry.getKey(), false) != number) { + throw authUnavailable("Signed scope fields differ from the retained preimage", null); + } + } else if (!entry.getValue().equals(actual)) { + throw authUnavailable("Signed scope fields differ from the retained preimage", null); + } + } + return new CanonicalJoinScopeV2( + token, + caller.caller().accountUuid(), + target.canonicalTenantId(), + target.realmId(), + target.tenantSlug(), + target.worldSlug(), + target.realmSlug(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + target.catalogRevision(), + target.pointerVersion(), + evaluatedAt.toString(), + expiresAt.toString()); + } + + private static CanonicalConnectScopeEvidence evidence( + Caller caller, CanonicalJoinScopeV2 scope, VerifiedTenantProvenance provenance) { + return new CanonicalConnectScopeEvidence( + AccountJoinDigest.tokenHash(scope.connectScopeId()), + caller.caller().accountId(), + "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), + provenance); + } + + private T inTransaction(java.util.function.Supplier action) { + requireSourceContext(); + try { + return Objects.requireNonNull( + transaction.execute( + status -> { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw authUnavailable("Writable Account source transaction required", null); + } + return action.get(); + })); + } catch (AuthenticationException failure) { + throw failure; + } catch (RuntimeException failure) { + throw authUnavailable("Account scope transaction is unavailable", failure); + } + } + + private void requireFresh(Evaluation evaluation) { + Instant current = now(); + if (evaluation.evaluatedAt() == null + || evaluation.validUntil() == null + || current.isBefore(evaluation.evaluatedAt()) + || !current.isBefore(evaluation.validUntil())) { + throw entitlementUnavailable(null); + } + } + + private static void requireSameCaller(Caller original, Caller current) { + if (original.caller().accountId() != current.caller().accountId() + || !original.caller().accountUuid().equals(current.caller().accountUuid()) + || !original.issuedAt().equals(current.issuedAt()) + || !original.expiresAt().equals(current.expiresAt())) { + throw new AuthenticationException("CONNECT_CONTEXT_INVALID", "Bootstrap caller changed"); + } + } + + private static void requireSameTarget(Target original, Optional current) { + if (current.isEmpty() || !original.equals(current.orElseThrow())) + throw pointerUnavailable(null); + } + + private Instant now() { + return clock.instant().truncatedTo(ChronoUnit.MICROS); + } + + private static void requireSourceContext() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("Canonical public scope preparation refuses ambient SQL"); + } + if (SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService() + || SessionContext.getServiceName() != null + || SessionContext.getServiceInstanceId() != null) { + throw new IllegalStateException( + "Canonical public scope preparation requires workload-only source context"); + } + } + + private static AuthenticationException authUnavailable(String message, Throwable cause) { + return new AuthenticationException("AUTH_UNAVAILABLE", message, cause); + } + + private static AuthenticationException pointerUnavailable(Throwable cause) { + return new AuthenticationException( + "ADMISSION_POINTER_UNAVAILABLE", + "Canonical public realm target is unavailable or changed", + cause); + } + + private static AuthenticationException entitlementUnavailable(Throwable cause) { + return new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", + "Original public discovery entitlement is unavailable or changed", + cause); + } + + private record Caller(VerifiedCaller caller, Instant issuedAt, Instant expiresAt) {} + + private record Prepared( + FreshTenantCreationEvidence tenant, MembershipFacts membership, SourceSelection head) {} + + /** Current owner facts only; absence does not fabricate versions, generations or membership. */ + public record MembershipFacts( + UUID accountId, UUID tenantId, Optional current) { + public MembershipFacts { + Objects.requireNonNull(accountId); + Objects.requireNonNull(tenantId); + current = Objects.requireNonNull(current); + } + } + + public record ExistingMembership( + long membershipId, + String lifecycleState, + boolean gameplayAdmissionAllowed, + long membershipVersion, + long membershipAuthorityGeneration) {} + + /** An as-of target plus persisted selector evidence, never admission or JOIN permission. */ + public record RealmScope( + Target target, + CanonicalJoinScopeV2 scope, + MembershipFacts membership, + Evaluation entitlement) { + @Override + public String toString() { + return "CanonicalPublicRealmScope[nonadmitting, redacted]"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleService.java new file mode 100644 index 0000000000..37d8f30220 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleService.java @@ -0,0 +1,121 @@ +package net.firedevops.firemud.accountservice.service; + +import java.util.Objects; +import java.util.UUID; +import java.util.function.Function; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionCurrentReceipt; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ClaimResult; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Outcome; +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; + +/** + * Production backend composition, deliberately unregistered. Only actual Stripe SDK reads occur, + * strictly outside SQL transactions. No provider create/update/cancel, public billing + * authorization, runtime protocol bundle, bean, route, scheduler, or deployment activation is + * supplied here. + */ +public final class AccountHostingSubscriptionLifecycleService { + private final AccountHostingSubscriptionLifecycleRepository repository; + private final StripeHostingSubscriptionObserver observer; + private final TransactionTemplate transaction; + + public AccountHostingSubscriptionLifecycleService( + AccountHostingSubscriptionLifecycleRepository repository, + StripeHostingSubscriptionObserver observer, + PlatformTransactionManager transactions) { + this.repository = Objects.requireNonNull(repository); + this.observer = Objects.requireNonNull(observer); + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + } + + public ClaimResult claimProvisioning( + UUID creationRequestId, long expectedRowVersion, UUID attemptId) { + requireNoAmbientTransaction(); + return Objects.requireNonNull( + transaction.execute( + s -> repository.claim(creationRequestId, expectedRowVersion, attemptId))); + } + + /** + * Provider ID is a locator only. The retained exact binding and actual SDK response decide + * acceptance. + */ + public TransitionResult reconcile( + UUID requestId, + UUID creationRequestId, + long expectedRowVersion, + String providerSubscriptionId, + UUID provisioningAttemptId) { + requireNoAmbientTransaction(); + var prepared = + Objects.requireNonNull( + transaction.execute( + s -> + repository.prepare( + requestId, + creationRequestId, + expectedRowVersion, + providerSubscriptionId, + provisioningAttemptId))); + if (prepared.outcome() != Outcome.READY) { + return prepared.result(); + } + requireNoAmbientTransaction(); + var actualSdkResult = observer.observe(prepared.binding()); + return Objects.requireNonNull( + transaction.execute(s -> repository.apply(prepared, actualSdkResult))); + } + + /** + * Fresh SDK facts cannot override the same locked committed receipt; discrepancies require + * reconciliation. + */ + public AccountHostingSubscriptionCurrentReceipt readCurrent(UUID tenantId) { + return readCurrentAndCapture(tenantId, Function.identity()); + } + + /** + * Captures Account-owned evidence while the final current-receipt locks remain held. The capture + * must perform no network calls or independently committed reads. This is an internal composition + * seam, not caller authentication or a registered runtime endpoint. + */ + public T readCurrentAndCapture( + UUID tenantId, Function capture) { + requireNoAmbientTransaction(); + Objects.requireNonNull(capture, "Current receipt capture is required"); + try { + var fence = + Objects.requireNonNull(transaction.execute(s -> repository.prepareCurrentRead(tenantId))); + requireNoAmbientTransaction(); + var actualSdkResult = observer.observe(fence.binding()); + return Objects.requireNonNull( + transaction.execute( + s -> + Objects.requireNonNull( + capture.apply(repository.readCurrent(fence, actualSdkResult))))); + } catch (RuntimeException unavailable) { + throw new EntitlementUnavailableException(unavailable); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Hosting SDK composition refuses an ambient SQL transaction or synchronization"); + } + } + + public static final class EntitlementUnavailableException extends IllegalStateException { + public EntitlementUnavailableException(Throwable cause) { + super("ENTITLEMENT_UNAVAILABLE: consistent hosting authority requires reconciliation", cause); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwner.java new file mode 100644 index 0000000000..1f3cb4c545 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwner.java @@ -0,0 +1,193 @@ +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.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.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceKind; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceSelection; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Manually composed, unregistered pre-scope public discovery evaluation. Its facts do not + * authenticate a caller, admit a player, reserve capacity, or constitute a runtime evidence bundle. + */ +public final class AccountPublicBootstrapEntitlementOwner { + private final AccountTenantAuthorityEventRepository sources; + private final AccountHostingSubscriptionLifecycleService hosting; + private final AccountDemoTenantEntitlementRepository demos; + private final TransactionTemplate transaction; + private final Clock clock; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Private injected owner collaborators retain their transaction boundaries.") + public AccountPublicBootstrapEntitlementOwner( + AccountTenantAuthorityEventRepository sources, + AccountHostingSubscriptionLifecycleService hosting, + AccountDemoTenantEntitlementRepository demos, + PlatformTransactionManager transactions, + Clock clock) { + this.sources = Objects.requireNonNull(sources); + this.hosting = Objects.requireNonNull(hosting); + this.demos = Objects.requireNonNull(demos); + this.clock = Objects.requireNonNull(clock); + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + transaction.setReadOnly(false); + } + + public Evaluation evaluate(UUID tenantId) { + if (tenantId == null || new UUID(0L, 0L).equals(tenantId)) { + throw new IllegalArgumentException("Canonical non-nil tenant UUID is required"); + } + requireNoAmbientTransaction(); + try { + Prepared prepared = + Objects.requireNonNull( + transaction.execute( + status -> { + requireSourceTransaction(); + SourceSelection selection = sources.readCurrentSourceSelection(tenantId); + Instant observedAt = now(); + DemoTenantEntitlementSnapshot demo = + selection.kind() == SourceKind.NON_PAID_DEMO + ? demos.readCurrent(tenantId) + : null; + return new Prepared(selection, demo, observedAt); + })); + Evaluation evaluation = + switch (prepared.selection().kind()) { + case PAID_HOSTING -> + hosting.readCurrentAndCapture( + tenantId, receipt -> capturePaid(tenantId, prepared.selection(), receipt)); + case NON_PAID_DEMO -> + Objects.requireNonNull( + transaction.execute(status -> captureDemo(tenantId, prepared))); + }; + requireFresh(evaluation.evaluatedAt(), evaluation.validUntil()); + return evaluation; + } catch (RuntimeException exception) { + throw new UnavailableException(exception); + } + } + + private Evaluation capturePaid( + UUID tenantId, SourceSelection selected, AccountHostingSubscriptionCurrentReceipt receipt) { + requireSourceTransaction(); + requireSameHead(tenantId, selected); + if (receipt == null + || !tenantId.equals(receipt.current().tenantId()) + || !selected.matches(receipt.tenantAuthorityEvent()) + || receipt.tenantBillingSequence() != selected.checkpoint().tenantBillingSequence() + || !receipt.billingEventId().equals(selected.checkpoint().tenantBillingEventId()) + || !receipt.billingEventDigest().equals(selected.checkpoint().tenantBillingEventDigest())) { + throw new IllegalStateException("Paid discovery source differs from its selected head"); + } + requireFresh(receipt.evaluatedAt(), receipt.validUntil()); + return new Evaluation( + tenantId, + SourceKind.PAID_HOSTING, + receipt.gameplayAvailable(), + receipt.allowPublicJoin(), + receipt.entitlementVersion(), + receipt.tenantBillingSequence(), + receipt.evaluatedAt(), + receipt.validUntil()); + } + + private Evaluation captureDemo(UUID tenantId, Prepared prepared) { + requireSourceTransaction(); + requireSameHead(tenantId, prepared.selection()); + DemoTenantEntitlementSnapshot demo = demos.revalidate(prepared.demo()); + var event = prepared.selection().checkpoint(); + if (!tenantId.equals(demo.canonicalTenantId()) + || demo.tenantBillingSequence() != event.tenantBillingSequence() + || !demo.eventId().equals(event.tenantBillingEventId()) + || !demo.eventDigest().equals(event.tenantBillingEventDigest()) + || !demo.tenantAuthorityEventId().equals(event.eventId()) + || !demo.tenantAuthorityEventDigest().equals(event.eventDigest()) + || demo.tenantAuthorityGeneration() != event.tenantAuthorityGeneration() + || demo.tenantAuthoritySourceVersion() != event.tenantAuthoritySourceVersion()) { + throw new IllegalStateException("Demo discovery source differs from its selected head"); + } + // Demo has no provider period. Bound this observation from its initial capture, never + // revalidation. + Instant validUntil = prepared.observedAt().plusSeconds(15); + requireFresh(prepared.observedAt(), validUntil); + return new Evaluation( + tenantId, + SourceKind.NON_PAID_DEMO, + demo.gameplayAvailable(), + demo.allowPublicJoin(), + demo.entitlementVersion(), + demo.tenantBillingSequence(), + prepared.observedAt(), + validUntil); + } + + private void requireSameHead(UUID tenantId, SourceSelection selected) { + SourceSelection current = sources.readCurrentSourceSelection(tenantId); + if (selected.kind() != current.kind() || !selected.matches(current.checkpoint())) { + throw new IllegalStateException("Discovery source head changed after selection"); + } + } + + private void requireFresh(Instant evaluatedAt, Instant validUntil) { + Instant current = now(); + if (evaluatedAt == null + || validUntil == null + || current.isBefore(evaluatedAt) + || !current.isBefore(validUntil)) { + throw new IllegalStateException("Discovery source observation is no longer current"); + } + } + + private Instant now() { + return clock.instant().truncatedTo(ChronoUnit.MICROS); + } + + private static void requireSourceTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Discovery capture requires a writable Account transaction"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("Discovery source preparation refuses ambient SQL"); + } + } + + private record Prepared( + SourceSelection selection, DemoTenantEntitlementSnapshot demo, Instant observedAt) {} + + /** Nonadmitting discovery facts only; no caller, connect scope, target, or authority bundle. */ + public record Evaluation( + UUID canonicalTenantId, + SourceKind sourceKind, + boolean gameplayAvailable, + boolean allowPublicJoin, + long entitlementVersion, + long tenantBillingSequence, + Instant evaluatedAt, + Instant validUntil) {} + + public static final class UnavailableException extends IllegalStateException { + public UnavailableException(Throwable cause) { + super("ENTITLEMENT_UNAVAILABLE: current discovery source is unavailable", cause); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwner.java new file mode 100644 index 0000000000..5c8cfbe185 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwner.java @@ -0,0 +1,246 @@ +package net.firedevops.firemud.accountservice.service; + +import java.time.Clock; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; +import net.firedevops.firemud.accountservice.dto.BootstrapWorldDto; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.session.AccountPlayerBootstrapCallerVerifier; +import net.firedevops.firemud.accountservice.service.session.AccountPlayerBootstrapCallerVerifier.VerifiedCaller; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.VisiblePublicProductionTargets; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Manually composed, nonadmitting public bootstrap world discovery over canonical public targets. + * This owner creates no scope, membership, JOIN, or gameplay-admission authority. + */ +public final class AccountPublicBootstrapWorldsOwner { + private static final int ENTITLEMENT_CONCURRENCY = 8; + private static final Semaphore ENTITLEMENT_PERMITS = new Semaphore(ENTITLEMENT_CONCURRENCY, true); + private final AccountPlayerBootstrapCallerVerifier callerVerifier; + private final CanonicalGameplayAdmissionDecisionReadClient targets; + private final AccountPublicBootstrapEntitlementOwner entitlements; + private final Clock clock; + + public AccountPublicBootstrapWorldsOwner( + AccountPlayerBootstrapCallerVerifier callerVerifier, + CanonicalGameplayAdmissionDecisionReadClient targets, + AccountPublicBootstrapEntitlementOwner entitlements, + Clock clock) { + this.callerVerifier = Objects.requireNonNull(callerVerifier); + this.targets = Objects.requireNonNull(targets); + this.entitlements = Objects.requireNonNull(entitlements); + this.clock = Objects.requireNonNull(clock); + } + + /** Returns the complete deterministic public-world list for the verified bootstrap caller. */ + public List listWorlds(String bootstrapToken) { + requireNoAmbientTransaction(); + requireWorkloadOnlySourceContext(); + + VerifiedCaller originalCaller = verifyCaller(bootstrapToken); + List initialTargets = readCompleteTargets(); + Map evaluated = + evaluateEachTenantOnce(initialTargets); + List finalTargets = readCompleteTargets(); + + Map initialByTenant = targetsByCanonicalTenant(initialTargets); + Map finalByTenant = targetsByCanonicalTenant(finalTargets); + if (!initialByTenant.equals(finalByTenant)) { + throw admissionPointerUnavailable( + new IllegalStateException("Canonical public target collection changed during discovery")); + } + + rejectAmbiguousWorldSlugs(initialTargets); + requireSameCaller(originalCaller, verifyCaller(bootstrapToken)); + requireFreshEvaluations(initialByTenant, evaluated); + + List visible = new ArrayList<>(); + for (Target target : initialTargets) { + AccountPublicBootstrapEntitlementOwner.Evaluation evaluation = + evaluated.get(target.canonicalTenantId()); + if (evaluation.gameplayAvailable()) { + visible.add(new BootstrapWorldDto(target.worldSlug(), target.worldDisplayName())); + } + } + visible.sort(Comparator.comparing(BootstrapWorldDto::worldSlug)); + return List.copyOf(visible); + } + + private VerifiedCaller verifyCaller(String bootstrapToken) { + try { + return Objects.requireNonNull(callerVerifier.requireCaller(bootstrapToken)); + } catch (AuthenticationException failure) { + throw failure; + } catch (RuntimeException unavailable) { + throw authUnavailable("Bootstrap caller authority is unavailable", unavailable); + } + } + + private List readCompleteTargets() { + try { + VisiblePublicProductionTargets result = + Objects.requireNonNull( + targets.listVisiblePublicProductionAdmissionTargets(UUID.randomUUID())); + return List.copyOf(Objects.requireNonNull(result.targets())); + } catch (RuntimeException failure) { + if (AccountPublicDiscoverySourceFailure.isUnavailable(failure)) { + throw authUnavailable("Game Session discovery authority is unavailable", failure); + } + throw admissionPointerUnavailable(failure); + } + } + + private Map evaluateEachTenantOnce( + List canonicalTargets) { + List tenants = + canonicalTargets.stream() + .map(target -> Objects.requireNonNull(target.canonicalTenantId())) + .distinct() + .toList(); + if (tenants.isEmpty()) return Map.of(); + // Independent tenant owners retain their own transactions. No caller or SQL context is copied + // to these bounded workers, and no observation is extended to hide slow discovery. + try (var workers = + Executors.newFixedThreadPool( + ENTITLEMENT_CONCURRENCY, + Thread.ofVirtual() + .name("account-public-world-entitlement-", 0) + .inheritInheritableThreadLocals(false) + .factory())) { + List> reads = + tenants.stream() + .>map( + tenantId -> + () -> { + requireNoAmbientTransaction(); + requireWorkloadOnlySourceContext(); + if (!ENTITLEMENT_PERMITS.tryAcquire(5, TimeUnit.SECONDS)) + throw new IllegalStateException( + "Discovery entitlement capacity is unavailable"); + try { + var evaluation = Objects.requireNonNull(entitlements.evaluate(tenantId)); + if (!tenantId.equals(evaluation.canonicalTenantId())) + throw new IllegalStateException( + "Entitlement source returned another canonical tenant"); + return evaluation; + } finally { + ENTITLEMENT_PERMITS.release(); + } + }) + .toList(); + var completed = workers.invokeAll(reads); + Map evaluations = + new LinkedHashMap<>(); + for (int index = 0; index < tenants.size(); index++) + evaluations.put(tenants.get(index), completed.get(index).get()); + return Map.copyOf(evaluations); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw entitlementUnavailable(interrupted); + } catch (ExecutionException unavailable) { + throw entitlementUnavailable(unavailable.getCause()); + } catch (RuntimeException unavailable) { + throw entitlementUnavailable(unavailable); + } + } + + private Map targetsByCanonicalTenant(List completeTargets) { + Map byTenant = new HashMap<>(); + for (Target target : completeTargets) { + if (target == null + || target.canonicalTenantId() == null + || byTenant.putIfAbsent(target.canonicalTenantId(), target) != null) { + throw admissionPointerUnavailable( + new IllegalStateException("Canonical public target collection is ambiguous")); + } + } + return Map.copyOf(byTenant); + } + + private void rejectAmbiguousWorldSlugs(List completeTargets) { + Map tenantsByWorldSlug = new HashMap<>(); + for (Target target : completeTargets) { + UUID previousTenant = + tenantsByWorldSlug.putIfAbsent(target.worldSlug(), target.canonicalTenantId()); + if (previousTenant != null && !previousTenant.equals(target.canonicalTenantId())) { + throw admissionPointerUnavailable( + new IllegalStateException("Public world slug is ambiguous across canonical tenants")); + } + } + } + + private void requireSameCaller(VerifiedCaller original, VerifiedCaller current) { + if (original.accountId() != current.accountId() + || !original.accountUuid().equals(current.accountUuid())) { + throw new AuthenticationException( + "CONNECT_CONTEXT_INVALID", "Bootstrap caller changed during world discovery"); + } + } + + private void requireFreshEvaluations( + Map currentTargets, + Map evaluations) { + Instant now = clock.instant().truncatedTo(ChronoUnit.MICROS); + for (UUID tenantId : currentTargets.keySet()) { + AccountPublicBootstrapEntitlementOwner.Evaluation evaluation = evaluations.get(tenantId); + if (evaluation == null + || evaluation.evaluatedAt() == null + || evaluation.validUntil() == null + || now.isBefore(evaluation.evaluatedAt()) + || !now.isBefore(evaluation.validUntil())) { + throw entitlementUnavailable( + new IllegalStateException("Public discovery entitlement observation expired")); + } + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("Public bootstrap world discovery refuses ambient SQL"); + } + } + + private static void requireWorkloadOnlySourceContext() { + if (SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService() + || SessionContext.getServiceName() != null + || SessionContext.getServiceInstanceId() != null) { + throw new IllegalStateException( + "Public bootstrap discovery requires workload-only Game Session source context"); + } + } + + private static AuthenticationException authUnavailable(String message, Throwable cause) { + return new AuthenticationException("AUTH_UNAVAILABLE", message, cause); + } + + private static AuthenticationException admissionPointerUnavailable(Throwable cause) { + return new AuthenticationException( + "ADMISSION_POINTER_UNAVAILABLE", + "Canonical public-world discovery source is unavailable or changed", + cause); + } + + private static AuthenticationException entitlementUnavailable(Throwable cause) { + return new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", "Current public discovery entitlement is unavailable", cause); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicDiscoverySourceFailure.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicDiscoverySourceFailure.java new file mode 100644 index 0000000000..b0d1ef12d6 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicDiscoverySourceFailure.java @@ -0,0 +1,18 @@ +package net.firedevops.firemud.accountservice.service; + +import io.grpc.StatusRuntimeException; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient.ClientUnavailableException; + +/** Availability classification only for the canonical Game Session public-discovery source. */ +final class AccountPublicDiscoverySourceFailure { + private AccountPublicDiscoverySourceFailure() {} + + static boolean isUnavailable(RuntimeException failure) { + if (failure instanceof ClientUnavailableException) return true; + if (!(failure instanceof StatusRuntimeException transport)) return false; + return switch (transport.getStatus().getCode()) { + case UNAVAILABLE, DEADLINE_EXCEEDED, CANCELLED, ABORTED -> true; + default -> false; + }; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerBootstrapCallerVerifier.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerBootstrapCallerVerifier.java new file mode 100644 index 0000000000..668198f099 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerBootstrapCallerVerifier.java @@ -0,0 +1,125 @@ +package net.firedevops.firemud.accountservice.service.session; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.JwtException; +import java.util.UUID; +import net.firedevops.firemud.accountservice.AccountUuidText; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.common.security.JwtClaims; +import net.firedevops.firemud.common.security.JwtUtil; +import org.springframework.dao.DataAccessException; + +/** + * Verifies the existing browser-bootstrap credential and its persisted Account owner. This manually + * composed verifier supplies identity only; it grants no tenant, membership, or admission + * authority. + */ +public final class AccountPlayerBootstrapCallerVerifier { + private static final UUID NIL_ACCOUNT_UUID = new UUID(0L, 0L); + + private final JwtUtil jwtUtil; + private final AccountRepository accountRepository; + private final SessionService sessionService; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Retains the owner-managed JWT, persistence, and session collaborators") + public AccountPlayerBootstrapCallerVerifier( + JwtUtil jwtUtil, AccountRepository accountRepository, SessionService sessionService) { + this.jwtUtil = jwtUtil; + this.accountRepository = accountRepository; + this.sessionService = sessionService; + } + + public VerifiedCaller requireCaller(String bootstrapToken) { + Claims claims = requireSignedBootstrapClaims(bootstrapToken); + 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 { + Account account = + accountRepository + .findByAccountUuid(accountUuid) + .orElseThrow(() -> new IllegalArgumentException("Account not found")); + accountId = requireAccountStorageId(account, 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 VerifiedCaller(accountId, accountUuid); + } + + private Claims requireSignedBootstrapClaims(String token) { + if (token == null || token.isBlank()) { + throw new AuthenticationException("CONNECT_CONTEXT_INVALID", "Missing bootstrap token"); + } + Claims claims; + try { + claims = jwtUtil.parseToken(token).getPayload(); + } catch (JwtException | IllegalArgumentException ex) { + throw new AuthenticationException("CONNECT_CONTEXT_INVALID", "Invalid bootstrap token"); + } + try { + if (!"player-bootstrap".equals(JwtClaims.requireText(claims.get("aud"), "aud"))) { + throw new AuthenticationException("CONNECT_CONTEXT_INVALID", "Invalid bootstrap token"); + } + return claims; + } catch (IllegalArgumentException ex) { + throw new AuthenticationException("CONNECT_CONTEXT_INVALID", "Invalid bootstrap token"); + } + } + + private long requireAccountStorageId(Account account, UUID accountUuid) { + if (account == null) { + throw new IllegalStateException( + "Account UUID readback did not match its exact persisted source row"); + } + AccountIdentityProvenance provenance = account.getAccountUuidProvenance(); + if (account.getId() == null + || account.getId() <= 0L + || account.getAccountUuid() == null + || NIL_ACCOUNT_UUID.equals(account.getAccountUuid()) + || account.getAccountUuidSourceNumericId() == null + || !account.getId().equals(account.getAccountUuidSourceNumericId()) + || (provenance != AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT + && provenance != AccountIdentityProvenance.ACCOUNT_V29_MIGRATION + && provenance != AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT) + || !accountUuid.equals(account.getAccountUuid())) { + throw new IllegalStateException( + "Account UUID readback did not match its exact persisted source row"); + } + return account.getId(); + } + + /** + * Identity produced only after signed-token, persisted-owner, and active-session verification. + */ + public static final class VerifiedCaller { + private final long accountId; + private final UUID accountUuid; + + private VerifiedCaller(long accountId, UUID accountUuid) { + this.accountId = accountId; + this.accountUuid = accountUuid; + } + + public long accountId() { + return accountId; + } + + public UUID accountUuid() { + return accountUuid; + } + } +} 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 new file mode 100644 index 0000000000..5422151555 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java @@ -0,0 +1,804 @@ +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.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; +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.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; +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.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceKind; +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.ApprovedLegacyTenantAssociationRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.repository.LegacyTenantSourceEvidence; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.session.AccountPlayerBootstrapCallerVerifier; +import net.firedevops.firemud.accountservice.service.session.SessionService; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.DiscoveryRequest; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.OriginKind; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; +import net.firedevops.firemud.common.security.JwtClaims; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +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.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.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Real pre-V1028 Account SQL, demo mutations, source-head selection and discovery composition. + * 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. + */ +class AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest { + private static final String NAMESPACE = "demo-worlds-proof"; + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + private static final List OBSERVED_TABLES = + List.of( + "accounts", + "account_tenant_membership", + "account_membership_pair_authority", + "account_connect_scope_records", + "account_join_operations", + "account_audit_outbox", + "account_authority_generations", + "account_authority_issuance_fences", + "account_authority_outbox_streams", + "account_authority_outbox_events", + "account_tenant_authority_source_records", + "account_tenant_entitlement_outbox_streams", + "account_tenant_entitlement_outbox_events", + "account_demo_tenant_entitlement_operations", + "account_demo_tenant_entitlements"); + private final Set ownedSchemas = new LinkedHashSet<>(); + + @BeforeAll + static void startPostgres() { + POSTGRES.start(); + } + + @AfterEach + void removeOwnedSchemas() { + SessionContext.clear(); + JdbcTemplate jdbc = new JdbcTemplate(POSTGRES.dataSource()); + for (String schema : ownedSchemas) { + jdbc.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } + ownedSchemas.clear(); + } + + @AfterAll + static void stopPostgres() { + POSTGRES.stop(); + } + + @Test + void actualDemoHeadsProduceSortedPublicWorldsWithoutMembershipJoinOrAnyReadMutation() { + Fixture f = fixture(); + DemoTenant zulu = f.demo("zulu", true); + DemoTenant alpha = f.demo("alpha", true); + DemoTenant denied = f.demo("closed", false); + f.targetReads( + List.of(zulu.target(), denied.target(), alpha.target()), + List.of(alpha.target(), zulu.target(), denied.target())); + Map before = f.snapshot(); + + assertThat(f.worlds.listWorlds(f.token)) + .containsExactly( + new BootstrapWorldDto("alpha", "World alpha"), + new BootstrapWorldDto("zulu", "World zulu")); + assertThat(f.worlds.listWorlds(f.token)) + .containsExactly( + new BootstrapWorldDto("alpha", "World alpha"), + new BootstrapWorldDto("zulu", "World zulu")); + + assertThat(f.snapshot()).isEqualTo(before); + assertThat(f.inTransaction(() -> f.sources.readCurrentSourceSelection(alpha.tenantId()).kind())) + .isEqualTo(SourceKind.NON_PAID_DEMO); + assertThat(alpha.snapshot().subscriptionStatus()).isNull(); + assertThat(alpha.snapshot().paid()).isFalse(); + assertThat(alpha.snapshot().allowPublicJoin()).isFalse(); + f.assertNoAdmissionRowsOrPaidReads(); + verify(f.targets, times(4)).listVisiblePublicProductionAdmissionTargets(any()); + verify(f.sessions, times(4)).isAccountSessionActive(f.account.getId(), f.token); + } + + @Test + void missingDemoAndSourceHeadRefuseTheWholeListWithoutPaidOrFreeFallback() { + Fixture f = fixture(); + DemoTenant available = f.demo("available", true); + FreshTenantCreationEvidence missing = f.enrollTenant(); + Target missingTarget = target(missing.canonicalTenantId(), "missing", 1, f.clock.instant()); + f.targetReads( + List.of(available.target(), missingTarget), List.of(available.target(), missingTarget)); + Map before = f.snapshot(); + + assertCode("ENTITLEMENT_UNAVAILABLE", () -> f.worlds.listWorlds(f.token)); + + assertThat(f.snapshot()).isEqualTo(before); + f.assertNoAdmissionRowsOrPaidReads(); + verify(f.targets).listVisiblePublicProductionAdmissionTargets(any()); + } + + @Test + void realDemoMutationBetweenSourceTransactionsInvalidatesTheOriginalSelectedHead() { + Fixture f = fixture(); + DemoTenant tenant = f.demo("changing", true); + f.targetReads(List.of(tenant.target()), List.of(tenant.target())); + AtomicReference> afterMutation = new AtomicReference<>(); + f.clock.afterNextObservation.set( + () -> { + DemoTenantEntitlementSnapshot updated = f.update(tenant, false); + assertThat(updated.entitlementVersion()).isEqualTo(2L); + afterMutation.set(f.snapshot()); + }); + + assertCode("ENTITLEMENT_UNAVAILABLE", () -> f.worlds.listWorlds(f.token)); + + assertThat(afterMutation.get()).isNotNull(); + assertThat(f.snapshot()).isEqualTo(afterMutation.get()); + assertThat(f.inTransaction(() -> f.demos.readCurrent(tenant.tenantId())).gameplayAvailable()) + .isFalse(); + f.assertNoAdmissionRowsOrPaidReads(); + } + + @Test + void originalDemoObservationExpiresDuringFinalCollectionReadWithoutRestamping() { + Fixture f = fixture(); + DemoTenant tenant = f.demo("expiring", true); + f.targetReads(List.of(tenant.target()), List.of(tenant.target())); + f.onSecondTargetRead = () -> f.clock.offset.set(Duration.ofSeconds(16)); + Map before = f.snapshot(); + + assertCode("ENTITLEMENT_UNAVAILABLE", () -> f.worlds.listWorlds(f.token)); + + assertThat(f.snapshot()).isEqualTo(before); + f.assertNoAdmissionRowsOrPaidReads(); + verify(f.targets, times(2)).listVisiblePublicProductionAdmissionTargets(any()); + } + + @Test + void ambiguousWorldSlugAcrossTwoRealDemoTenantsRefusesInsteadOfChoosingOne() { + Fixture f = fixture(); + DemoTenant first = f.demo("same-world", true); + DemoTenant second = f.demo("same-world", true); + f.targetReads( + List.of(first.target(), second.target()), List.of(second.target(), first.target())); + Map before = f.snapshot(); + + assertCode("ADMISSION_POINTER_UNAVAILABLE", () -> f.worlds.listWorlds(f.token)); + + assertThat(f.snapshot()).isEqualTo(before); + f.assertNoAdmissionRowsOrPaidReads(); + } + + @Test + void changedCompleteTargetCollectionRefusesWithRealDemoAuthorityUntouched() { + Fixture f = fixture(); + DemoTenant tenant = f.demo("moving", true); + Target changed = target(tenant.tenantId(), "moving", 2, f.clock.instant()); + f.targetReads(List.of(tenant.target()), List.of(changed)); + Map before = f.snapshot(); + + assertCode("ADMISSION_POINTER_UNAVAILABLE", () -> f.worlds.listWorlds(f.token)); + + assertThat(f.snapshot()).isEqualTo(before); + f.assertNoAdmissionRowsOrPaidReads(); + } + + @Test + void lostBootstrapRegistryCurrentnessRefusesAfterActualPersistedAccountReverification() { + Fixture f = fixture(); + DemoTenant tenant = f.demo("caller-loss", true); + f.targetReads(List.of(tenant.target()), List.of(tenant.target())); + f.onSecondTargetRead = () -> f.sessionActive.set(false); + Map before = f.snapshot(); + + assertCode("CONNECT_CONTEXT_INVALID", () -> f.worlds.listWorlds(f.token)); + + assertThat(f.snapshot()).isEqualTo(before); + assertThat(f.accounts.findByAccountUuid(f.account.getAccountUuid())).isPresent(); + f.assertNoAdmissionRowsOrPaidReads(); + verify(f.sessions, times(2)).isAccountSessionActive(f.account.getId(), f.token); + } + + @Test + void absentMembershipAndClosedEnrollmentPersistOnlyTheExactCanonicalPublicSelectorScope() { + Fixture f = fixture(); + DemoTenant tenant = f.demo("scope-proof", true); + f.targetReads(List.of(tenant.target()), List.of(tenant.target())); + Map before = f.snapshot(); + + var result = + f.realmScopes + .listRealmScopes(f.token, tenant.target().tenantSlug(), tenant.target().worldSlug()) + .getFirst(); + + var scope = result.scope(); + assertThat(result.target()).isEqualTo(tenant.target()); + assertThat(result.membership().accountId()).isEqualTo(f.account.getAccountUuid()); + assertThat(result.membership().tenantId()).isEqualTo(tenant.tenantId()); + assertThat(result.membership().current()).isEmpty(); + assertThat(result.entitlement().sourceKind()).isEqualTo(SourceKind.NON_PAID_DEMO); + assertThat(result.entitlement().gameplayAvailable()).isTrue(); + assertThat(result.entitlement().allowPublicJoin()).isFalse(); + assertThat(result.entitlement().tenantBillingSequence()) + .isEqualTo(tenant.snapshot().tenantBillingSequence()); + assertThat(scope.accountId()).isEqualTo(f.account.getAccountUuid()); + assertThat(scope.tenantId()).isEqualTo(tenant.tenantId()); + assertThat(scope.realmId()).isEqualTo(tenant.target().realmId()); + assertThat(scope.playableStateNamespaceId()) + .isEqualTo(tenant.target().playableStateNamespaceId()); + assertThat(scope.gameInstanceId()).isEqualTo(tenant.target().canonicalGameInstanceId()); + assertThat(scope.playableStateScope()).isEqualTo("SHARED"); + var signed = f.jwt.parseToken(scope.connectScopeId()).getPayload(); + assertThat(signed.getSubject()).isEqualTo(f.account.getAccountUuid().toString()); + assertThat(signed.get("accountId")).isEqualTo(f.account.getAccountUuid().toString()); + assertThat(JwtClaims.requireText(signed.get("aud"), "aud")) + .isEqualTo("bootstrap-connect-scope"); + assertThat(signed.get("targetClass")).isEqualTo("PUBLIC_PRODUCTION"); + assertThat(JwtClaims.requireLong(signed.get("scopeDigestVersion"), "scopeDigestVersion", false)) + .isEqualTo(2L); + assertThat(signed.get("tenantId")).isEqualTo(tenant.tenantId().toString()); + assertThat(signed.get("gameInstanceId")) + .isEqualTo(tenant.target().canonicalGameInstanceId().toString()); + assertThat(signed.get("evaluatedAt")).isEqualTo(scope.evaluatedAt()); + assertThat(signed.get("connectScopeExpiresAt")).isEqualTo(scope.connectScopeExpiresAt()); + assertThat(signed.getExpiration().toInstant()) + .isEqualTo(Instant.parse(scope.connectScopeExpiresAt())); + assertThat(signed.getExpiration().toInstant()) + .isBeforeOrEqualTo(f.jwt.parseToken(f.token).getPayload().getExpiration().toInstant()); + assertThat(f.inTransaction(() -> f.scopes.findCanonical(scope.connectScopeId()).orElseThrow())) + .isEqualTo(scope); + String tokenHash = AccountJoinDigest.tokenHash(scope.connectScopeId()); + var evidence = + f.inTransaction(() -> f.scopes.findCanonicalEvidenceByTokenHash(tokenHash).orElseThrow()); + assertThat(evidence.scopeTokenHash()).isEqualTo(tokenHash); + assertThat(evidence.privateAccountId()).isEqualTo(f.account.getId()); + assertThat(evidence.scopeDigestVersion()).isEqualTo(2); + assertThat(evidence.scopeDigest()).isEqualTo(AccountJoinDigest.scopeV2(scope)); + assertThat(evidence.tenantProvenance().kind()) + .isEqualTo(AccountMembershipPairAuthorityRepository.TenantProvenanceKind.FRESH_GAME_DESIGN); + assertThat(evidence.tenantProvenance().legacyTenantId()).isNull(); + assertThat(evidence.tenantProvenance().sourceOperationId()) + .isEqualTo(tenant.source().operationId()); + assertThat(evidence.tenantProvenance().digest()).isEqualTo(tenant.source().evidenceDigest()); + var row = + Objects.requireNonNull( + f.dsl.fetchOne( + "SELECT * FROM account_connect_scope_records WHERE scope_token_hash = ?", + tokenHash)); + assertThat(row.get("account_uuid", UUID.class)).isEqualTo(f.account.getAccountUuid()); + assertThat(row.get("tenant_uuid", UUID.class)).isEqualTo(tenant.tenantId()); + assertThat(row.get("game_instance_uuid", UUID.class)) + .isEqualTo(tenant.target().canonicalGameInstanceId()); + assertThat(row.get("tenant_id")).isNull(); + assertThat(row.get("game_instance_id")).isNull(); + assertThat(row.get("playable_state_namespace_id")).isNull(); + assertThat(row.get("snapshot_digest", String.class)) + .isEqualTo(AccountJoinDigest.scopeV2(scope)); + Map after = f.snapshot(); + before.forEach( + (table, original) -> { + if (!table.equals("account_connect_scope_records")) { + assertThat(after.get(table)).as("unchanged %s", table).isEqualTo(original); + } + }); + assertThat( + Objects.requireNonNull( + f.dsl.fetchOne("SELECT COUNT(*) FROM account_connect_scope_records")) + .get(0, Long.class)) + .isEqualTo(1L); + f.assertNoMembershipPairJoinOrPaidReads(); + verify(f.targets, times(2)).listVisiblePublicProductionAdmissionTargets(any()); + } + + @Test + void actualDemoMutationDuringScopeTargetRereadRefusesBeforeAnySelectorWrite() { + Fixture f = fixture(); + DemoTenant tenant = f.demo("scope-head-race", true); + f.targetReads(List.of(tenant.target()), List.of(tenant.target())); + AtomicReference> afterMutation = new AtomicReference<>(); + f.onSecondTargetRead = + () -> { + DemoTenantEntitlementSnapshot updated = f.update(tenant, false); + assertThat(updated.tenantBillingSequence()) + .isEqualTo(tenant.snapshot().tenantBillingSequence() + 1L); + afterMutation.set(f.snapshot()); + }; + + assertCode( + "ENTITLEMENT_UNAVAILABLE", + () -> + f.realmScopes.listRealmScopes( + f.token, tenant.target().tenantSlug(), tenant.target().worldSlug())); + + assertThat(afterMutation.get()).isNotNull(); + assertThat(f.snapshot()).isEqualTo(afterMutation.get()); + f.assertNoAdmissionRowsOrPaidReads(); + f.assertNoMembershipPairJoinOrPaidReads(); + verify(f.targets, times(2)).listVisiblePublicProductionAdmissionTargets(any()); + } + + @Test + void actualCanonicalScopeInsertFailureRollsBackWithoutScopeOrOtherAuthorityMutation() { + Fixture f = fixture(); + DemoTenant tenant = f.demo("scope-insert-failure", true); + f.targetReads(List.of(tenant.target()), List.of(tenant.target())); + // The function and trigger belong only to this test's disposable schema. AFTER INSERT + // ensures PostgreSQL staged the actual row before aborting the same physical transaction. + f.dsl.execute( + "CREATE FUNCTION reject_test_canonical_scope_insert() RETURNS trigger LANGUAGE plpgsql AS $$ " + + "BEGIN IF NEW.scope_digest_version = 2 THEN " + + "RAISE EXCEPTION 'controlled canonical scope insert refusal' USING ERRCODE = '23514'; " + + "END IF; RETURN NEW; END; $$"); + f.dsl.execute( + "CREATE TRIGGER reject_test_canonical_scope_insert AFTER INSERT ON account_connect_scope_records " + + "FOR EACH ROW EXECUTE FUNCTION reject_test_canonical_scope_insert()"); + Map before = f.snapshot(); + + AuthenticationException failure = + org.junit.jupiter.api.Assertions.assertThrows( + AuthenticationException.class, + () -> + f.realmScopes.listRealmScopes( + f.token, tenant.target().tenantSlug(), tenant.target().worldSlug())); + + assertThat(failure.getCode()).isEqualTo("AUTH_UNAVAILABLE"); + SQLException sql = + Objects.requireNonNull(sqlFailure(failure), "Expected actual PostgreSQL refusal"); + assertThat(sql.getSQLState()).isEqualTo("23514"); + assertThat(sql.getMessage()).contains("controlled canonical scope insert refusal"); + assertThat(f.snapshot()).isEqualTo(before); + f.assertNoAdmissionRowsOrPaidReads(); + f.assertNoMembershipPairJoinOrPaidReads(); + // A fresh transaction remains usable after the failed owner transaction was rolled back. + assertThat(f.inTransaction(() -> f.demos.readCurrent(tenant.tenantId()))) + .isEqualTo(tenant.snapshot()); + } + + private static SQLException sqlFailure(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sql) return sql; + } + return null; + } + + private Fixture fixture() { + String schema = "demo_worlds_" + UUID.randomUUID().toString().replace("-", ""); + ownedSchemas.add(schema); + new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA \"" + schema + "\""); + DriverManagerDataSource dataSource = POSTGRES.dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target("1027.2") + .load() + .migrate(); + return new Fixture(dataSource); + } + + private static void assertCode(String code, Runnable operation) { + assertThatThrownBy(operation::run) + .isInstanceOf(AuthenticationException.class) + .extracting(failure -> ((AuthenticationException) failure).getCode()) + .isEqualTo(code); + } + + private static final class Fixture { + private final DSLContext dsl; + private final TransactionTemplate transaction; + private final AccountRepository accounts; + private final AccountConnectScopeRepository scopes; + private final FreshTenantIdentityAssociationRepository tenants; + private final AccountAuthorityGenerationRepository generations; + private final AccountTenantAuthorityEventRepository sources; + private final AccountDemoTenantEntitlementRepository demos; + private final AccountHostingSubscriptionLifecycleService hosting = + mock(AccountHostingSubscriptionLifecycleService.class); + private final CanonicalGameplayAdmissionDecisionReadClient targets = + mock(CanonicalGameplayAdmissionDecisionReadClient.class); + private final SessionService sessions = mock(SessionService.class); + private final AtomicBoolean sessionActive = new AtomicBoolean(true); + private final DatabaseClock clock; + private final Account account; + private final JwtUtil jwt; + private final String token; + private final AccountPublicBootstrapWorldsOwner worlds; + private final AccountCanonicalPublicRealmScopeOwner realmScopes; + private final AtomicInteger targetReadCount = new AtomicInteger(); + private long sourceRowId; + private Runnable onSecondTargetRead = () -> {}; + + private Fixture(DriverManagerDataSource dataSource) { + dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var transactions = new DataSourceTransactionManager(dataSource); + transaction = new TransactionTemplate(transactions); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + accounts = new AccountRepository(dsl); + tenants = new FreshTenantIdentityAssociationRepository(dsl, NAMESPACE); + generations = new AccountAuthorityGenerationRepository(dsl); + var authorityOutbox = new AccountAuthorityOutboxRepository(dsl); + var billing = new AccountTenantEntitlementOutboxRepository(dsl); + sources = + new AccountTenantAuthorityEventRepository( + dsl, authorityOutbox, billing, tenants, generations); + demos = + new AccountDemoTenantEntitlementRepository(dsl, tenants, generations, billing, sources); + clock = new DatabaseClock(new JdbcTemplate(dataSource)); + Account fresh = new Account(); + fresh.setUsername("demo-worlds-reader"); + fresh.setEmail("demo-worlds-reader@example.test"); + fresh.setPasswordHash("controlled-unused-password-verifier"); + fresh.setRole("player"); + account = inTransaction(() -> accounts.save(fresh)); + jwt = new JwtUtil("controlled-local-bootstrap-key-01234567890123456789", 300000L); + token = + jwt.generateToken( + account.getAccountUuid().toString(), + Map.of( + "aud", + "player-bootstrap", + "accountId", + account.getAccountUuid().toString(), + "jti", + UUID.randomUUID().toString())); + when(sessions.isAccountSessionActive(account.getId(), token)) + .thenAnswer(invocation -> sessionActive.get()); + var caller = new AccountPlayerBootstrapCallerVerifier(jwt, accounts, sessions); + var entitlement = + new AccountPublicBootstrapEntitlementOwner(sources, hosting, demos, transactions, clock); + worlds = new AccountPublicBootstrapWorldsOwner(caller, targets, entitlement, clock); + var pairs = new AccountMembershipPairAuthorityRepository(dsl); + var memberships = new AccountTenantMembershipRepository(dsl, accounts, tenants, pairs); + var retainedIdentities = + new AccountTenantIdentityResolver( + new ApprovedLegacyTenantAssociationRepository( + dsl, new LegacyTenantSourceEvidence(dsl), NAMESPACE), + NAMESPACE); + scopes = new AccountConnectScopeRepository(dsl, retainedIdentities, tenants); + var tokenProperties = new AccountTokenProperties(); + tokenProperties.setConnectScopeExpirationMs(120000L); + realmScopes = + new AccountCanonicalPublicRealmScopeOwner( + caller, + targets, + entitlement, + accounts, + memberships, + tenants, + sources, + scopes, + jwt, + tokenProperties, + clock, + transactions, + NAMESPACE); + assertThat( + Objects.requireNonNull( + dsl.fetchOne("SELECT to_regclass('subscription_lifecycle_receipts')")) + .get(0)) + .isNull(); + } + + private FreshTenantCreationEvidence enrollTenant() { + UUID tenantId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String key = "demo" + tenantId.toString().replace("-", ""); + String digest = + GameTenantCreationDigest.requestDigest(NAMESPACE, requestId, key, "Demo", null); + long rowId = ++sourceRowId; + var source = + new FreshTenantCreationEvidence( + 1, + NAMESPACE, + requestId, + operationId, + digest, + tenantId, + rowId, + key, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + NAMESPACE, requestId, operationId, digest, tenantId, rowId, key, "NEW_GAME_ROW")); + return inTransaction( + () -> { + tenants.importVerified(source); + generations.initializeTenantIfAbsent(tenantId); + return source; + }); + } + + private DemoTenant demo(String worldSlug, boolean available) { + FreshTenantCreationEvidence source = enrollTenant(); + DemoTenantEntitlementSnapshot snapshot = + inTransaction(() -> demos.provision(request(source, null, available), source)); + return new DemoTenant( + source, snapshot, target(source.canonicalTenantId(), worldSlug, 1, clock.instant())); + } + + private DemoTenantEntitlementSnapshot update(DemoTenant tenant, boolean available) { + return inTransaction( + () -> + demos.provision( + request(tenant.source(), tenant.snapshot(), available), tenant.source())); + } + + private T inTransaction(Supplier operation) { + return Objects.requireNonNull(transaction.execute(status -> operation.get())); + } + + private void targetReads(List first, List second) { + when(targets.listVisiblePublicProductionAdmissionTargets(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + int read = targetReadCount.incrementAndGet(); + if (read == 2) onSecondTargetRead.run(); + List values = read == 1 ? first : second; + DiscoveryRequest request = + new DiscoveryRequest(invocation.getArgument(0, UUID.class), NAMESPACE); + return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + request, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( + request, values)); + }); + } + + private Map snapshot() { + Map result = new LinkedHashMap<>(); + for (String table : OBSERVED_TABLES) { + result.put( + table, + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COALESCE(jsonb_agg(to_jsonb(t) ORDER BY to_jsonb(t)::text)::text, '[]') FROM " + + table + + " t")) + .get(0, String.class)); + } + return result; + } + + private void assertNoAdmissionRowsOrPaidReads() { + for (String table : + List.of( + "account_tenant_membership", + "account_connect_scope_records", + "account_join_operations")) { + assertThat( + Objects.requireNonNull(dsl.fetchOne("SELECT COUNT(*) FROM " + table)) + .get(0, Long.class)) + .isZero(); + } + verifyNoInteractions(hosting); + } + + private void assertNoMembershipPairJoinOrPaidReads() { + for (String table : + List.of( + "account_tenant_membership", + "account_membership_pair_authority", + "account_join_operations")) { + assertThat( + Objects.requireNonNull(dsl.fetchOne("SELECT COUNT(*) FROM " + table)) + .get(0, Long.class)) + .isZero(); + } + verifyNoInteractions(hosting); + } + } + + private static DemoTenantEntitlementRequest request( + FreshTenantCreationEvidence source, DemoTenantEntitlementSnapshot prior, boolean available) { + return new DemoTenantEntitlementRequest( + UUID.randomUUID(), + source.canonicalTenantId(), + source.creationRequestId(), + source.requestDigest(), + prior == null ? null : prior.entitlementVersion(), + prior == null ? null : prior.tenantAuthorityGeneration(), + prior == null ? null : prior.tenantAuthoritySourceVersion(), + available, + false, + false, + false, + new DemoTenantEntitlementRequest.Quotas(3, 2, 4096)); + } + + private record DemoTenant( + FreshTenantCreationEvidence source, DemoTenantEntitlementSnapshot snapshot, Target target) { + private UUID tenantId() { + return source.canonicalTenantId(); + } + } + + /** + * DB time is real; the explicit offset and commit hook exercise expiry and a genuine head race. + */ + private static final class DatabaseClock extends Clock { + private final JdbcTemplate jdbc; + private final AtomicReference offset = new AtomicReference<>(Duration.ZERO); + private final AtomicReference afterNextObservation = new AtomicReference<>(); + + private DatabaseClock(JdbcTemplate jdbc) { + this.jdbc = jdbc; + } + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + Objects.requireNonNull(zone); + Clock source = this; + return new Clock() { + @Override + public ZoneId getZone() { + return zone; + } + + @Override + public Clock withZone(ZoneId nextZone) { + return source.withZone(nextZone); + } + + @Override + public Instant instant() { + return source.instant(); + } + }; + } + + @Override + public Instant instant() { + Instant time = + Objects.requireNonNull(jdbc.queryForObject("SELECT clock_timestamp()", Timestamp.class)) + .toInstant(); + Runnable mutation = afterNextObservation.getAndSet(null); + if (mutation != null) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + TransactionSynchronizationManager.registerSynchronization( + new TransactionSynchronization() { + @Override + public void afterCommit() { + mutation.run(); + } + }); + } + return time.plus(offset.get()); + } + } + + /** + * Complete structurally validated GS input only; no World hold or owner provenance is claimed. + */ + private static Target target( + UUID tenantId, String worldSlug, long pointerVersion, Instant observedAt) { + UUID realm = UUID.randomUUID(); + UUID playableNamespace = UUID.randomUUID(); + UUID instance = UUID.randomUUID(); + UUID version = UUID.randomUUID(); + UUID holdId = UUID.randomUUID(); + UUID holdFence = UUID.randomUUID(); + String initialRequest = UUID.randomUUID().toString(); + String initialDigest = "a".repeat(64); + var request = + new WorldCanonicalInitialAdmissionHold.Request( + NAMESPACE, + tenantId, + worldSlug, + realm, + playableNamespace, + "SHARED", + instance, + version, + 1, + initialRequest, + initialDigest, + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + 1, + null); + var hold = new WorldCanonicalInitialAdmissionHold.HoldIdentity(request, holdId, holdFence); + return new Target( + NAMESPACE, + "tenant-" + tenantId, + tenantId, + worldSlug, + "World " + worldSlug, + realm, + "main", + "Main", + 1, + 2, + playableNamespace, + "SHARED", + instance, + version, + 3, + 1, + pointerVersion, + "b".repeat(64), + 1, + initialRequest, + initialDigest, + OriginKind.NO_PRIOR_POINTER, + null, + holdId, + holdFence, + hold.holdBindingDigest(), + 1, + "sha256:" + "c".repeat(64), + OwnerProofOutcome.COMMITTED, + false, + observedAt, + "PRESEEDED_ONLY"); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClientMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClientMtlsTest.java new file mode 100644 index 0000000000..ec70086ff8 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClientMtlsTest.java @@ -0,0 +1,275 @@ +package net.firedevops.firemud.accountservice.client; + +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 io.grpc.Context; +import io.grpc.Deadline; +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.file.Path; +import java.util.List; +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.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.DiscoveryRequest; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.VisiblePublicProductionTargets; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayAdmissionDecisionReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.ListVisiblePublicProductionAdmissionTargetsRequest; +import net.firedevops.firemud.gamesession.v1.ListVisiblePublicProductionAdmissionTargetsResponse; +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 loopback mTLS proof for the Account public-target source client only. */ +class CanonicalGameplayAdmissionDecisionReadClientMtlsTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + + @TempDir static Path directory; + private static LoopbackMtlsTestPki.Pki pki; + + @BeforeAll + static void createLoopbackWorkloadCertificates() throws Exception { + pki = + LoopbackMtlsTestPki.create( + directory, + "Canonical public-target client test CA", + new IdentitySpec("account", ACCOUNT_URI, false), + new IdentitySpec( + "game-session", "spiffe://firemud/ns/test/sa/game-session-service", true), + new IdentitySpec( + "wrong-service-server", + "spiffe://firemud/ns/test/sa/world-management-service", + true), + new IdentitySpec( + "wrong-namespace-server", + "spiffe://firemud/ns/other/sa/game-session-service", + true)); + } + + @AfterEach + void clearAmbientSecurityAndTransactionContext() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void exactSameNamespaceGameSessionPeerAcceptsAccountIdentityAndCompleteEmptyCollection() + throws Exception { + var service = new DiscoveryProbeService(); + try (var server = startServer("game-session", service); + var client = newClient(server.port(), "account")) { + client.init(); + UUID readRequestId = UUID.randomUUID(); + + VisiblePublicProductionTargets result = + client.listVisiblePublicProductionAdmissionTargets(readRequestId); + + assertThat(result.request()).isEqualTo(new DiscoveryRequest(readRequestId, NAMESPACE)); + assertThat(result.targets()).isEmpty(); + assertThat(service.calls()).hasValue(1); + assertThat(service.observedPeer()) + .hasValue(new GrpcPeerIdentity(ACCOUNT_URI, NAMESPACE, "account-service")); + assertThat(service.observedRequest()) + .hasValue(new DiscoveryRequest(readRequestId, NAMESPACE)); + assertThat(service.observedDeadline()).isNotNull(); + long deadlineNanos = service.observedDeadline().timeRemaining(TimeUnit.NANOSECONDS); + assertThat(deadlineNanos).isPositive().isLessThanOrEqualTo(TimeUnit.SECONDS.toNanos(5)); + } + } + + @Test + void wrongServerServiceOrNamespaceIsRejectedBeforeTheApplicationHandler() throws Exception { + for (String serverIdentity : List.of("wrong-service-server", "wrong-namespace-server")) { + var service = new DiscoveryProbeService(); + try (var server = startServer(serverIdentity, service); + var client = newClient(server.port(), "account")) { + client.init(); + + assertThatThrownBy( + () -> client.listVisiblePublicProductionAdmissionTargets(UUID.randomUUID())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(service.calls()).hasValue(0); + } + } + } + + @Test + void staleCorrelationAndMalformedCompleteResponseRemainRefusals() throws Exception { + var service = new DiscoveryProbeService(); + try (var server = startServer("game-session", service); + var client = newClient(server.port(), "account")) { + client.init(); + service.respondWith( + request -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( + new DiscoveryRequest(UUID.randomUUID(), request.targetNamespace()), List.of())); + + assertThatThrownBy( + () -> client.listVisiblePublicProductionAdmissionTargets(UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid canonical discovery evidence"); + + service.respondWith( + ignored -> ListVisiblePublicProductionAdmissionTargetsResponse.getDefaultInstance()); + assertThatThrownBy( + () -> client.listVisiblePublicProductionAdmissionTargets(UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid canonical discovery evidence"); + assertThat(service.calls()).hasValue(2); + } + } + + @Test + void oversizedAuthenticatedResponsePreservesResourceExhaustedFromInboundLimit() throws Exception { + var service = new DiscoveryProbeService(); + service.respondWith( + request -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse(request, List.of()) + .toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 100, + UnknownFieldSet.Field.newBuilder() + .addLengthDelimited(ByteString.copyFrom(new byte[4 * 1024 * 1024])) + .build()) + .build()) + .build()); + try (var server = startServer("game-session", service); + var client = newClient(server.port(), "account")) { + client.init(); + assertThatThrownBy( + () -> client.listVisiblePublicProductionAdmissionTargets(UUID.randomUUID())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.RESOURCE_EXHAUSTED)); + assertThat(service.calls()).hasValue(1); + } + } + + private static LoopbackServer startServer(String identityAlias, DiscoveryProbeService service) + throws Exception { + var identity = pki.identity(identityAlias); + 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())) + .build() + .start(); + return new LoopbackServer(server); + } + + private static CanonicalGameplayAdmissionDecisionReadClient newClient( + int port, String identityAlias) throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameSessionService("127.0.0.1:" + port); + CommonGrpcClientProperties tls = pki.clientProperties(directory, pki.identity(identityAlias)); + return new CanonicalGameplayAdmissionDecisionReadClient( + endpoints, tls, new GrpcChannelFactory(), NAMESPACE); + } + + private record LoopbackServer(Server server) implements AutoCloseable { + private int port() { + return server.getPort(); + } + + @Override + public void close() throws InterruptedException { + server.shutdownNow(); + if (!server.awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback public-target server did not terminate"); + } + } + } + + private static final class DiscoveryProbeService + extends CanonicalGameplayAdmissionDecisionReadServiceGrpc + .CanonicalGameplayAdmissionDecisionReadServiceImplBase { + private final AtomicInteger calls = new AtomicInteger(); + private final AtomicReference observedPeer = new AtomicReference<>(); + private final AtomicReference observedRequest = new AtomicReference<>(); + private final AtomicReference observedDeadline = new AtomicReference<>(); + private final AtomicReference< + Function> + responseFactory = + new AtomicReference<>( + request -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( + request, List.of())); + + @Override + public void listVisiblePublicProductionAdmissionTargets( + ListVisiblePublicProductionAdmissionTargetsRequest request, + StreamObserver observer) { + calls.incrementAndGet(); + observedPeer.set(GrpcPeerIdentity.current()); + observedDeadline.set(Context.current().getDeadline()); + try { + DiscoveryRequest parsed = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseDiscoveryRequest(request); + observedRequest.set(parsed); + observer.onNext(responseFactory.get().apply(parsed)); + observer.onCompleted(); + } catch (RuntimeException failure) { + observer.onError(Status.INTERNAL.withCause(failure).asRuntimeException()); + } + } + + private AtomicInteger calls() { + return calls; + } + + private AtomicReference observedPeer() { + return observedPeer; + } + + private AtomicReference observedRequest() { + return observedRequest; + } + + private Deadline observedDeadline() { + return observedDeadline.get(); + } + + private void respondWith( + Function factory) { + responseFactory.set(factory); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClientTest.java new file mode 100644 index 0000000000..a9982c18b7 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClientTest.java @@ -0,0 +1,361 @@ +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.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.lang.reflect.Field; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient.ClientUnavailableException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +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.security.SessionContext; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayAdmissionDecisionReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.GetPublishedRealmAdmissionOwnerReadResponse; +import net.firedevops.firemud.gamesession.v1.ListVisiblePublicProductionAdmissionTargetsResponse; +import net.firedevops.firemud.gamesession.v1.ResolvePublishedRealmAdmissionTargetResponse; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +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; + +/** Controlled channel/codec tests; no physical mTLS, owner execution or custody is claimed. */ +class CanonicalGameplayAdmissionDecisionReadClientTest { + @TempDir static Path tlsDirectory; + private static LoopbackMtlsTestPki.Pki pki; + private final List initializedClients = + new ArrayList<>(); + + @BeforeAll + static void createFileBackedTlsMaterial() throws Exception { + pki = + LoopbackMtlsTestPki.create( + tlsDirectory, + "Controlled canonical discovery client CA", + new LoopbackMtlsTestPki.IdentitySpec( + "account", "spiffe://firemud/ns/test/sa/account-service", false)); + } + + @AfterEach + void closeClientsAndClearContexts() throws Exception { + try { + for (var client : initializedClients) { + client.close(); + } + } finally { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + } + + private Fixture fixture() throws Exception { + return fixture(true); + } + + private Fixture fixture(boolean initialize) throws Exception { + Fixture fixture = new Fixture(initialize); + initializedClients.add(fixture.client); + return fixture; + } + + @Test + void sourceReadsUseTypedUnavailableBeforeInitializationAndAfterClose() throws Exception { + for (boolean closed : new boolean[] {false, true}) { + Fixture f = fixture(false); + if (closed) { + f.client.init(); + f.client.close(); + } + + assertThatThrownBy( + () -> f.client.listVisiblePublicProductionAdmissionTargets(UUID.randomUUID())) + .isInstanceOf(ClientUnavailableException.class); + assertThatThrownBy(() -> f.client.resolvePublishedRealmAdmissionTarget(f.selector)) + .isInstanceOf(ClientUnavailableException.class); + assertThatThrownBy(() -> f.client.readPublishedRealmAdmissionOwner(f.strictSelector())) + .isInstanceOf(ClientUnavailableException.class); + verifyNoInteractions(f.stub); + } + } + + @Test + void discoveryUsesExactFourMiBBoundAndFiniteDeadlineAndAcceptsAuthenticatedEmptyCollection() + throws Exception { + Fixture f = fixture(); + UUID readId = UUID.randomUUID(); + var expected = + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.DiscoveryRequest(readId, "test"); + var request = CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryRequest(expected); + when(f.stub.listVisiblePublicProductionAdmissionTargets(request)) + .thenReturn( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( + expected, List.of())); + var result = f.client.listVisiblePublicProductionAdmissionTargets(readId); + assertThat(result.request()).isEqualTo(expected); + assertThat(result.targets()).isEmpty(); + verify(f.stub).withMaxInboundMessageSize(4 * 1024 * 1024); + verify(f.stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(f.stub).listVisiblePublicProductionAdmissionTargets(request); + } + + @Test + void discoveryNeverConvertsTransportOrMalformedResponseIntoEmptySuccess() throws Exception { + for (var status : + List.of(Status.UNAVAILABLE, Status.DEADLINE_EXCEEDED, Status.RESOURCE_EXHAUSTED)) { + Fixture f = fixture(); + when(f.stub.listVisiblePublicProductionAdmissionTargets(any())) + .thenThrow(status.asRuntimeException()); + assertThatThrownBy( + () -> f.client.listVisiblePublicProductionAdmissionTargets(UUID.randomUUID())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(status.getCode())); + } + Fixture f = fixture(); + when(f.stub.listVisiblePublicProductionAdmissionTargets(any())) + .thenReturn(ListVisiblePublicProductionAdmissionTargetsResponse.getDefaultInstance()); + assertThatThrownBy( + () -> f.client.listVisiblePublicProductionAdmissionTargets(UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .isNotInstanceOf(ClientUnavailableException.class); + } + + @Test + void discoveryRefusesPlayerInternalAndAmbientSqlContextsBeforeTransport() throws Exception { + Fixture f = fixture(); + SessionContext.setContext("account", List.of(), Map.of()); + assertThatThrownBy( + () -> f.client.listVisiblePublicProductionAdmissionTargets(UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .isNotInstanceOf(ClientUnavailableException.class); + SessionContext.setContext(null, List.of(), Map.of(), true, "account-service", "instance"); + assertThatThrownBy( + () -> f.client.listVisiblePublicProductionAdmissionTargets(UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .isNotInstanceOf(ClientUnavailableException.class); + SessionContext.clear(); + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy( + () -> f.client.listVisiblePublicProductionAdmissionTargets(UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .isNotInstanceOf(ClientUnavailableException.class); + TransactionSynchronizationManager.clear(); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy( + () -> f.client.listVisiblePublicProductionAdmissionTargets(UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .isNotInstanceOf(ClientUnavailableException.class); + verifyNoInteractions(f.stub); + } + + @Test + void resolverUsesItsOwnFiniteDeadlineAndResponseBoundAndReturnsOnlyDecodedOwnerResult() + throws Exception { + Fixture f = fixture(); + var request = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionRequest(f.selector); + var response = ResolvePublishedRealmAdmissionTargetResponse.getDefaultInstance(); + var result = + mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.ResolvedPublishedTarget.class); + when(f.stub.resolvePublishedRealmAdmissionTarget(request)).thenReturn(response); + try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { + codec + .when( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionRequest( + f.selector)) + .thenReturn(request); + codec + .when( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromTargetResolutionResponse( + f.selector, response)) + .thenReturn(result); + assertThat(f.client.resolvePublishedRealmAdmissionTarget(f.selector)).isSameAs(result); + } + verify(f.stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(f.stub) + .withMaxInboundMessageSize( + CanonicalGameplayAdmissionDecisionReadGrpcCodec + .MAX_TARGET_RESOLUTION_RESPONSE_WIRE_BYTES); + } + + @Test + void publishedReadRetainsItsFullPurposeBoundAndFiniteCompleteSourceDeadline() throws Exception { + Fixture f = fixture(); + var selector = f.strictSelector(); + var request = CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmRequest(selector); + var parsed = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest(request); + var response = GetPublishedRealmAdmissionOwnerReadResponse.getDefaultInstance(); + var result = mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class); + when(f.stub.getPublishedRealmAdmissionOwnerRead(request)).thenReturn(response); + try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { + codec + .when( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmRequest(selector)) + .thenReturn(request); + codec + .when( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( + request)) + .thenReturn(parsed); + codec + .when( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + parsed, response)) + .thenReturn(result); + assertThat(f.client.readPublishedRealmAdmissionOwner(selector)).isSameAs(result); + } + verify(f.stub).withDeadlineAfter(30L, TimeUnit.SECONDS); + verify(f.stub) + .withMaxInboundMessageSize( + CanonicalGameplayAdmissionDecisionReadGrpcCodec + .MAX_PUBLISHED_REALM_RESPONSE_WIRE_BYTES); + } + + @Test + void timeoutAndUnavailableAreNeverReinterpretedAsAbsence() throws Exception { + for (var status : List.of(Status.UNAVAILABLE, Status.DEADLINE_EXCEEDED)) { + Fixture f = fixture(); + when(f.stub.resolvePublishedRealmAdmissionTarget(any())) + .thenThrow(status.asRuntimeException()); + assertThatThrownBy(() -> f.client.resolvePublishedRealmAdmissionTarget(f.selector)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(status.getCode())); + when(f.stub.getPublishedRealmAdmissionOwnerRead(any())) + .thenThrow(status.asRuntimeException()); + assertThatThrownBy(() -> f.client.readPublishedRealmAdmissionOwner(f.strictSelector())) + .isInstanceOf(StatusRuntimeException.class); + } + } + + @Test + void emptyResponsesAreContractFailuresRatherThanMissingTargets() throws Exception { + Fixture f = fixture(); + when(f.stub.resolvePublishedRealmAdmissionTarget(any())) + .thenReturn(ResolvePublishedRealmAdmissionTargetResponse.getDefaultInstance()); + when(f.stub.getPublishedRealmAdmissionOwnerRead(any())) + .thenReturn(GetPublishedRealmAdmissionOwnerReadResponse.getDefaultInstance()); + assertThatThrownBy(() -> f.client.resolvePublishedRealmAdmissionTarget(f.selector)) + .isInstanceOf(IllegalStateException.class) + .isNotInstanceOf(ClientUnavailableException.class); + assertThatThrownBy(() -> f.client.readPublishedRealmAdmissionOwner(f.strictSelector())) + .isInstanceOf(IllegalStateException.class) + .isNotInstanceOf(ClientUnavailableException.class); + } + + @Test + void callerContextOrAmbientSqlRejectsBeforeTransport() throws Exception { + Fixture f = fixture(); + SessionContext.setContext("account", List.of(), Map.of()); + assertThatThrownBy(() -> f.client.resolvePublishedRealmAdmissionTarget(f.selector)) + .isInstanceOf(IllegalStateException.class) + .isNotInstanceOf(ClientUnavailableException.class); + assertThatThrownBy(() -> f.client.readPublishedRealmAdmissionOwner(f.strictSelector())) + .isInstanceOf(IllegalStateException.class) + .isNotInstanceOf(ClientUnavailableException.class); + SessionContext.clear(); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> f.client.resolvePublishedRealmAdmissionTarget(f.selector)) + .isInstanceOf(IllegalStateException.class) + .isNotInstanceOf(ClientUnavailableException.class); + assertThatThrownBy(() -> f.client.readPublishedRealmAdmissionOwner(f.strictSelector())) + .isInstanceOf(IllegalStateException.class) + .isNotInstanceOf(ClientUnavailableException.class); + verifyNoInteractions(f.stub); + } + + private static final class Fixture { + private final CanonicalGameplayAdmissionDecisionReadServiceGrpc + .CanonicalGameplayAdmissionDecisionReadServiceBlockingStub + stub = + mock( + CanonicalGameplayAdmissionDecisionReadServiceGrpc + .CanonicalGameplayAdmissionDecisionReadServiceBlockingStub.class); + private final RetainedTargetSelector selector = + new RetainedTargetSelector( + UUID.randomUUID(), + UUID.randomUUID(), + "test", + UUID.randomUUID(), + "tenant", + "earth", + UUID.randomUUID(), + "main", + UUID.randomUUID(), + "SHARED", + UUID.randomUUID(), + 3, + 5); + private final CanonicalGameplayAdmissionDecisionReadClient client; + + private Fixture(boolean initialize) throws Exception { + var tls = pki.clientProperties(tlsDirectory, pki.identity("account")); + var channels = mock(GrpcChannelFactory.class); + when(channels.buildChannel( + any(String.class), anyInt(), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(mock(ManagedChannel.class)); + client = + new CanonicalGameplayAdmissionDecisionReadClient( + new ServiceEndpointsProperties(), tls, channels, "test"); + // Exercise the real explicit initialization/close lifecycle, then supply a controlled stub. + // Neither the mocked channel nor these request-mapping cases prove a TLS handshake. + if (initialize) { + client.init(); + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + field.set(client, stub); + } + when(stub.withDeadlineAfter(anyLong(), eq(TimeUnit.SECONDS))).thenReturn(stub); + when(stub.withMaxInboundMessageSize(anyInt())).thenReturn(stub); + } + + private CanonicalGameplayRosterOwnerReadEvidence.Request strictSelector() { + return new CanonicalGameplayRosterOwnerReadEvidence.Request( + selector.readRequestId(), + selector.accountId(), + "test", + selector.tenantId(), + selector.worldSlug(), + selector.realmId(), + selector.realmSlug(), + selector.playableStateNamespaceId(), + "SHARED", + selector.gameInstanceId(), + UUID.randomUUID(), + selector.catalogRevision(), + selector.pointerVersion(), + 7); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserverTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserverTest.java new file mode 100644 index 0000000000..580cda3e13 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserverTest.java @@ -0,0 +1,564 @@ +package net.firedevops.firemud.accountservice.client; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +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.mock; + +import com.stripe.exception.ApiConnectionException; +import com.stripe.exception.RateLimitException; +import com.stripe.exception.StripeException; +import com.stripe.model.StripeObject; +import com.stripe.net.ApiMode; +import com.stripe.net.ApiResource; +import com.stripe.net.ApiResource.RequestMethod; +import com.stripe.net.BaseAddress; +import com.stripe.net.HttpClient; +import com.stripe.net.RequestOptions; +import com.stripe.net.StripeRequest; +import com.stripe.net.StripeResponse; +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.Map; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class StripeHostingSubscriptionObserverTest { + private static final String PROVIDER_SUBSCRIPTION_ID = "sub_expected"; + private static final String PROVIDER_CUSTOMER_ID = "cus_expected"; + private static final String PROVIDER_PAYMENT_METHOD_ID = "pm_expected"; + private static final String PROVIDER_PRICE_ID = "price_expected"; + private static final String OPERATION_ID = "4e2af076-4a10-4aaf-93a0-e5df29271310"; + private static final String SUBSCRIPTION_ID = "0c9ee07d-0e6d-4f66-9a87-54110acbc611"; + private static final Instant READ_STARTED_AT = Instant.parse("2026-11-01T00:00:00Z"); + private static final Instant OBSERVED_AT = Instant.parse("2026-11-01T00:00:01Z"); + private static final String VALID_RESPONSE = validResponse(); + + @Test + void retrievesAndParsesExactSdkSubscriptionIntoImmutableProviderEvidence() { + ControlledStripeTransport transport = new ControlledStripeTransport(VALID_RESPONSE); + + StripeHostingSubscriptionObserver.ObservedSubscription result = + assertInstanceOf( + StripeHostingSubscriptionObserver.ObservedSubscription.class, + observer(transport).observe(expected())); + + assertEquals(PROVIDER_SUBSCRIPTION_ID, result.providerSubscriptionId()); + assertEquals(PROVIDER_CUSTOMER_ID, result.providerCustomerId()); + assertEquals(PROVIDER_PAYMENT_METHOD_ID, result.providerPaymentMethodId()); + assertEquals("si_expected", result.providerSubscriptionItemId()); + assertEquals(PROVIDER_PRICE_ID, result.providerPriceId()); + assertEquals(1L, result.providerQuantity()); + assertEquals(Instant.ofEpochSecond(1_778_000_000), result.currentPeriodStart().orElseThrow()); + assertEquals(Instant.ofEpochSecond(1_780_592_000), result.currentPeriodEnd().orElseThrow()); + assertEquals("active", result.providerStatus()); + assertFalse(result.providerStatusIsCanceled()); + assertFalse(result.cancelAtPeriodEnd()); + assertEquals(false, result.livemode()); + assertEquals("stripe.subscriptions.retrieve", result.source()); + assertEquals(READ_STARTED_AT, result.readStartedAt()); + assertEquals(OBSERVED_AT, result.observedAt()); + assertEquals( + StripeHostingSubscriptionObserver.OperationType.SUBSCRIPTION_PROVISIONING, + result.correlation().operationType()); + assertEquals(UUID.fromString(OPERATION_ID), result.correlation().operationId()); + assertEquals(UUID.fromString(SUBSCRIPTION_ID), result.correlation().subscriptionId()); + assertEquals(OPERATION_ID, result.providerMetadata().get("firemud_operation_id")); + assertThrows( + UnsupportedOperationException.class, + () -> result.providerMetadata().put("unexpected", "mutation")); + assertEquals(250, transport.requestOptions.getConnectTimeout()); + assertEquals(1000, transport.requestOptions.getReadTimeout()); + assertEquals(0, transport.requestOptions.getMaxNetworkRetries()); + assertEquals(1, transport.callCount()); + assertEquals(RequestMethod.GET, transport.method()); + assertEquals("/v1/subscriptions/" + PROVIDER_SUBSCRIPTION_ID, transport.path()); + } + + @Test + void sdkOverridesClientDefaultsAndDoesNotRetryTransportTimeout() { + var calls = new java.util.ArrayList(); + var failure = + new ApiConnectionException("read timed out", new java.net.SocketTimeoutException()); + var http = + new HttpClient() { + @Override + public StripeResponse request(StripeRequest request) throws StripeException { + calls.add(request); + throw failure; + } + }; + var client = + com.stripe.StripeClient.builder() + .setApiKey("sk_test_observation_fixture") + .setConnectTimeout(30_000) + .setReadTimeout(80_000) + .setMaxNetworkRetries(3) + .setHttpClient(http) + .build(); + var observer = + new StripeHostingSubscriptionObserver( + client, + Clock.fixed(READ_STARTED_AT, ZoneOffset.UTC), + Duration.ofMillis(250), + Duration.ofSeconds(1)); + + var result = + assertInstanceOf( + StripeHostingSubscriptionObserver.UnresolvedObservation.class, + observer.observe(expected())); + + assertSame(failure, result.providerFailure()); + assertEquals(1, calls.size()); + assertEquals(250, calls.getFirst().options().getConnectTimeout()); + assertEquals(1000, calls.getFirst().options().getReadTimeout()); + assertEquals(0, calls.getFirst().options().getMaxNetworkRetries()); + } + + @Test + void requiresExplicitFiniteWholeMillisecondTimeouts() { + var client = new com.stripe.StripeClient(new ControlledStripeTransport(VALID_RESPONSE)); + var clock = Clock.fixed(READ_STARTED_AT, ZoneOffset.UTC); + for (Duration invalid : + java.util.List.of( + Duration.ZERO, + Duration.ofMillis(-1), + Duration.ofNanos(1), + Duration.ofNanos(1_000_001), + Duration.ofMillis((long) Integer.MAX_VALUE + 1), + Duration.ofSeconds(Long.MAX_VALUE))) { + assertThrows( + IllegalArgumentException.class, + () -> + new StripeHostingSubscriptionObserver(client, clock, invalid, Duration.ofSeconds(1))); + assertThrows( + IllegalArgumentException.class, + () -> + new StripeHostingSubscriptionObserver(client, clock, Duration.ofSeconds(1), invalid)); + } + assertThrows( + NullPointerException.class, + () -> new StripeHostingSubscriptionObserver(client, clock, null, Duration.ofSeconds(1))); + assertThrows( + NullPointerException.class, + () -> new StripeHostingSubscriptionObserver(client, clock, Duration.ofSeconds(1), null)); + } + + @Test + void rejectsMismatchedProviderSubscriptionCustomerInstrumentAndPriceBindings() { + assertInvalid( + VALID_RESPONSE.replace(PROVIDER_SUBSCRIPTION_ID, "sub_other"), + StripeHostingSubscriptionObserver.InvalidReason.SUBSCRIPTION_ID_MISMATCH); + assertInvalid( + VALID_RESPONSE.replace(PROVIDER_CUSTOMER_ID, "cus_other"), + StripeHostingSubscriptionObserver.InvalidReason.CUSTOMER_ID_MISMATCH); + assertInvalid( + VALID_RESPONSE.replace(PROVIDER_PAYMENT_METHOD_ID, "pm_other"), + StripeHostingSubscriptionObserver.InvalidReason.PAYMENT_METHOD_ID_MISMATCH); + assertInvalid( + VALID_RESPONSE.replace(PROVIDER_PRICE_ID, "price_other"), + StripeHostingSubscriptionObserver.InvalidReason.PRICE_ID_MISMATCH); + } + + @Test + void requiresExactPositiveServerExpectedSubscriptionItemQuantity() { + assertInvalid( + VALID_RESPONSE.replace("\"quantity\":1,", ""), + StripeHostingSubscriptionObserver.InvalidReason.ITEM_QUANTITY_MISSING); + assertInvalid( + VALID_RESPONSE.replace("\"quantity\":1", "\"quantity\":0"), + StripeHostingSubscriptionObserver.InvalidReason.ITEM_QUANTITY_INVALID); + assertInvalid( + VALID_RESPONSE.replace("\"quantity\":1", "\"quantity\":2"), + StripeHostingSubscriptionObserver.InvalidReason.ITEM_QUANTITY_MISMATCH); + assertThrows(IllegalArgumentException.class, () -> expected(PROVIDER_SUBSCRIPTION_ID, 0)); + } + + @Test + void rejectsWrongProviderObjectsAndItemSubscriptionIdentity() { + assertInvalid( + VALID_RESPONSE.replace("\"object\":\"subscription\"", "\"object\":\"customer\""), + StripeHostingSubscriptionObserver.InvalidReason.SUBSCRIPTION_OBJECT_MISMATCH); + assertInvalid( + VALID_RESPONSE.replace("\"object\":\"subscription_item\"", "\"object\":\"price\""), + StripeHostingSubscriptionObserver.InvalidReason.ITEM_OBJECT_MISMATCH); + assertInvalid( + VALID_RESPONSE.replace( + "\"subscription\":\"sub_expected\"", "\"subscription\":\"sub_other\""), + StripeHostingSubscriptionObserver.InvalidReason.ITEM_SUBSCRIPTION_MISMATCH); + } + + @Test + void rejectsMissingMismatchedAndNoncanonicalTypedCorrelation() { + assertInvalid( + VALID_RESPONSE.replace("\"firemud_operation_id\":\"" + OPERATION_ID + "\",", ""), + StripeHostingSubscriptionObserver.InvalidReason.METADATA_UUID_INVALID); + assertInvalid( + VALID_RESPONSE.replace(OPERATION_ID, "6f66ef0d-a8ec-46eb-901e-e795e21d3d0a"), + StripeHostingSubscriptionObserver.InvalidReason.OPERATION_ID_MISMATCH); + assertInvalid( + VALID_RESPONSE.replace(SUBSCRIPTION_ID, "00000000-0000-0000-0000-000000000000"), + StripeHostingSubscriptionObserver.InvalidReason.METADATA_UUID_INVALID); + assertInvalid( + VALID_RESPONSE.replace("firemud_operation_type", "firemud_untyped_operation"), + StripeHostingSubscriptionObserver.InvalidReason.OPERATION_TYPE_INVALID); + assertInvalid( + VALID_RESPONSE.replace( + "\"firemud_metadata_schema_version\":\"1\"", + "\"firemud_metadata_schema_version\":\"2\""), + StripeHostingSubscriptionObserver.InvalidReason.METADATA_SCHEMA_UNSUPPORTED); + } + + @Test + void rejectsIncompleteOrMultipleSubscriptionItems() { + assertInvalid( + VALID_RESPONSE.replace("\"has_more\":false", "\"has_more\":true"), + StripeHostingSubscriptionObserver.InvalidReason.ITEMS_INCOMPLETE); + assertInvalid( + replaceItemData(VALID_RESPONSE, ""), + StripeHostingSubscriptionObserver.InvalidReason.ITEM_CARDINALITY_UNSUPPORTED); + String secondItem = + "{\"id\":\"si_second\",\"object\":\"subscription_item\"," + + "\"subscription\":\"sub_expected\",\"quantity\":1," + + "\"current_period_start\":1778000000," + + "\"current_period_end\":1780592000,\"price\":{\"id\":\"price_expected\"," + + "\"object\":\"price\"}}"; + String twoItems = replaceItemData(VALID_RESPONSE, singleItemData() + "," + secondItem); + assertInvalid( + twoItems, StripeHostingSubscriptionObserver.InvalidReason.ITEM_CARDINALITY_UNSUPPORTED); + } + + @Test + void neverFallsBackToCustomerOrLegacyDefaultPaymentInstrument() { + String noExplicitMethod = + VALID_RESPONSE.replace( + "\"default_payment_method\":\"pm_expected\"", + "\"default_payment_method\":null,\"default_source\":\"src_legacy\""); + + assertInvalid( + noExplicitMethod, + StripeHostingSubscriptionObserver.InvalidReason.EXPLICIT_PAYMENT_METHOD_MISSING); + } + + @Test + void rejectsUnexpectedModeUnsupportedStatusAndMalformedPeriodEvidence() { + assertInvalid( + VALID_RESPONSE.replace("\"livemode\":false", "\"livemode\":true"), + StripeHostingSubscriptionObserver.InvalidReason.LIVEMODE_MISMATCH); + assertInvalid( + VALID_RESPONSE.replace("\"status\":\"active\"", "\"status\":\"future_state\""), + StripeHostingSubscriptionObserver.InvalidReason.UNSUPPORTED_PROVIDER_STATUS); + assertInvalid( + VALID_RESPONSE.replace("\"current_period_start\":1778000000", "\"current_period_start\":0"), + StripeHostingSubscriptionObserver.InvalidReason.PERIOD_INVALID); + assertInvalid( + VALID_RESPONSE.replace( + "\"current_period_end\":1780592000", "\"current_period_end\":1778000000"), + StripeHostingSubscriptionObserver.InvalidReason.PERIOD_INVALID); + assertInvalid( + VALID_RESPONSE.replace("\"current_period_start\":1778000000,", ""), + StripeHostingSubscriptionObserver.InvalidReason.PERIOD_MISSING); + } + + @Test + void retainsCanceledTerminalEvidenceWithoutRequiringCurrentPeriodBoundaries() { + String canceled = + VALID_RESPONSE + .replace("\"status\":\"active\"", "\"status\":\"canceled\"") + .replace("\"current_period_start\":1778000000", "\"current_period_start\":null") + .replace("\"current_period_end\":1780592000", "\"current_period_end\":null") + .replace("\"ended_at\":null", "\"ended_at\":1780592000") + .replace("\"canceled_at\":null", "\"canceled_at\":1780592000"); + + StripeHostingSubscriptionObserver.ObservedSubscription result = + assertInstanceOf( + StripeHostingSubscriptionObserver.ObservedSubscription.class, + observer(new ControlledStripeTransport(canceled)).observe(expected())); + + assertEquals("canceled", result.providerStatus()); + assertTrue(result.providerStatusIsCanceled()); + assertTrue(result.currentPeriodStart().isEmpty()); + assertTrue(result.currentPeriodEnd().isEmpty()); + assertEquals(Instant.ofEpochSecond(1_780_592_000), result.endedAt().orElseThrow()); + assertEquals(Instant.ofEpochSecond(1_780_592_000), result.canceledAt().orElseThrow()); + } + + @Test + void rejectsContradictoryCanceledPeriodBoundariesWhenBothArePresent() { + String reversed = + VALID_RESPONSE + .replace("\"status\":\"active\"", "\"status\":\"canceled\"") + .replace( + "\"current_period_start\":1778000000", "\"current_period_start\":__PERIOD_START__") + .replace("\"current_period_end\":1780592000", "\"current_period_end\":1778000000") + .replace("__PERIOD_START__", "1780592000"); + String equal = + VALID_RESPONSE + .replace("\"status\":\"active\"", "\"status\":\"canceled\"") + .replace("\"current_period_end\":1780592000", "\"current_period_end\":1778000000"); + + assertInvalid(reversed, StripeHostingSubscriptionObserver.InvalidReason.PERIOD_INVALID); + assertInvalid(equal, StripeHostingSubscriptionObserver.InvalidReason.PERIOD_INVALID); + } + + @Test + void rejectsReversedLocalReadIntervalAsInvalidEvidence() { + StripeHostingSubscriptionObserver.InvalidObservation result = + assertInstanceOf( + StripeHostingSubscriptionObserver.InvalidObservation.class, + observer( + new ControlledStripeTransport(VALID_RESPONSE), + tickingClock(OBSERVED_AT, READ_STARTED_AT)) + .observe(expected())); + + assertEquals( + StripeHostingSubscriptionObserver.InvalidReason.READ_INTERVAL_REVERSED, result.reason()); + assertEquals(OBSERVED_AT, result.readStartedAt()); + assertEquals(READ_STARTED_AT, result.observedAt()); + } + + @Test + void rejectsMalformedCancellationTimestampAndMissingCancelMetadata() { + String badTimestamp = VALID_RESPONSE.replace("\"ended_at\":null", "\"ended_at\":-1"); + assertInvalid( + badTimestamp, StripeHostingSubscriptionObserver.InvalidReason.CANCEL_TIMESTAMP_INVALID); + assertInvalid( + VALID_RESPONSE.replace("\"cancel_at_period_end\":false,", ""), + StripeHostingSubscriptionObserver.InvalidReason.CANCEL_METADATA_MISSING); + } + + @Test + void timeoutAndRateLimitRemainUnresolvedWithoutObserverRetry() { + for (StripeException failure : + java.util.List.of( + new ApiConnectionException("read timed out", new java.net.SocketTimeoutException()), + new RateLimitException("rate limited", null, "req_test", "rate_limit", 429, null))) { + var transport = new ControlledStripeTransport(failure); + var result = + assertInstanceOf( + StripeHostingSubscriptionObserver.UnresolvedObservation.class, + observer(transport).observe(expected())); + assertSame(failure, result.providerFailure()); + assertTrue(result.retryable()); + assertEquals(1, transport.callCount()); + assertEquals(250, transport.requestOptions.getConnectTimeout()); + assertEquals(1000, transport.requestOptions.getReadTimeout()); + assertEquals(0, transport.requestOptions.getMaxNetworkRetries()); + } + } + + @Test + void unknownProviderIdAndProviderReadFailureRemainUnresolvedWithTypedCause() { + StripeException unknownIdFailure = mock(StripeException.class); + ControlledStripeTransport transport = new ControlledStripeTransport(unknownIdFailure); + + StripeHostingSubscriptionObserver.UnresolvedObservation result = + assertInstanceOf( + StripeHostingSubscriptionObserver.UnresolvedObservation.class, + observer(transport).observe(expected("sub_unknown"))); + + assertEquals("sub_unknown", result.providerSubscriptionId()); + assertTrue(result.retryable()); + assertSame(unknownIdFailure, result.providerFailure()); + assertEquals(250, transport.requestOptions.getConnectTimeout()); + assertEquals(1000, transport.requestOptions.getReadTimeout()); + assertEquals(0, transport.requestOptions.getMaxNetworkRetries()); + assertEquals(1, transport.callCount()); + } + + @Test + void rejectsNilExpectedInternalIdentity() { + assertThrows( + IllegalArgumentException.class, + () -> + new StripeHostingSubscriptionObserver.ExpectedBinding( + PROVIDER_SUBSCRIPTION_ID, + new UUID(0, 0), + PROVIDER_CUSTOMER_ID, + PROVIDER_PAYMENT_METHOD_ID, + PROVIDER_PRICE_ID, + 1, + StripeHostingSubscriptionObserver.OperationType.SUBSCRIPTION_PROVISIONING, + UUID.fromString(OPERATION_ID), + false)); + } + + private static void assertInvalid( + String response, StripeHostingSubscriptionObserver.InvalidReason expectedReason) { + StripeHostingSubscriptionObserver.InvalidObservation invalid = + assertInstanceOf( + StripeHostingSubscriptionObserver.InvalidObservation.class, + observer(new ControlledStripeTransport(response)).observe(expected())); + assertEquals(expectedReason, invalid.reason()); + } + + private static StripeHostingSubscriptionObserver observer(ControlledStripeTransport transport) { + return observer(transport, tickingClock()); + } + + private static Clock tickingClock() { + return tickingClock(READ_STARTED_AT, OBSERVED_AT); + } + + private static Clock tickingClock(Instant firstInstant, Instant secondInstant) { + return new Clock() { + private int calls; + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return calls++ == 0 ? firstInstant : secondInstant; + } + }; + } + + private static StripeHostingSubscriptionObserver observer( + ControlledStripeTransport transport, Clock clock) { + return new StripeHostingSubscriptionObserver( + new com.stripe.StripeClient(transport), + clock, + Duration.ofMillis(250), + Duration.ofSeconds(1)); + } + + private static StripeHostingSubscriptionObserver.ExpectedBinding expected() { + return expected(PROVIDER_SUBSCRIPTION_ID); + } + + private static StripeHostingSubscriptionObserver.ExpectedBinding expected( + String providerSubscriptionId) { + return expected(providerSubscriptionId, 1); + } + + private static StripeHostingSubscriptionObserver.ExpectedBinding expected( + String providerSubscriptionId, long expectedQuantity) { + return new StripeHostingSubscriptionObserver.ExpectedBinding( + providerSubscriptionId, + UUID.fromString(SUBSCRIPTION_ID), + PROVIDER_CUSTOMER_ID, + PROVIDER_PAYMENT_METHOD_ID, + PROVIDER_PRICE_ID, + expectedQuantity, + StripeHostingSubscriptionObserver.OperationType.SUBSCRIPTION_PROVISIONING, + UUID.fromString(OPERATION_ID), + false); + } + + private static String validResponse() { + return """ + {"id":"sub_expected","object":"subscription","customer":"cus_expected", + "default_payment_method":"pm_expected","default_source":"src_ignored", + "livemode":false,"status":"active","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":"4e2af076-4a10-4aaf-93a0-e5df29271310", + "firemud_subscription_id":"0c9ee07d-0e6d-4f66-9a87-54110acbc611", + "retained_marker":"evidence"}, + "items":{"object":"list","data":[{"id":"si_expected","object":"subscription_item", + "subscription":"sub_expected","quantity":1,"current_period_start":1778000000, + "current_period_end":1780592000,"price":{"id":"price_expected","object":"price"}}], + "has_more":false}} + """; + } + + private static String singleItemData() { + return "{\"id\":\"si_expected\",\"object\":\"subscription_item\"," + + "\"subscription\":\"sub_expected\",\"quantity\":1," + + "\"current_period_start\":1778000000," + + "\"current_period_end\":1780592000,\"price\":{\"id\":\"price_expected\"," + + "\"object\":\"price\"}}"; + } + + private static String replaceItemData(String response, String itemData) { + String dataMarker = "\"data\":["; + int dataStart = response.indexOf(dataMarker); + int dataEnd = response.indexOf("],", dataStart); + if (dataStart < 0 || dataEnd < 0) { + throw new IllegalStateException("test response has no subscription item data list"); + } + return response.substring(0, dataStart) + dataMarker + itemData + response.substring(dataEnd); + } + + private static final class ControlledStripeTransport implements StripeResponseGetter { + private final String responseJson; + private final StripeException failure; + private int callCount; + private RequestMethod method; + private String path; + private RequestOptions requestOptions; + + private ControlledStripeTransport(String responseJson) { + this.responseJson = responseJson; + this.failure = null; + } + + private ControlledStripeTransport(StripeException failure) { + this.responseJson = null; + this.failure = failure; + } + + @Override + @SuppressWarnings("unchecked") + public T request( + BaseAddress baseAddress, + RequestMethod requestMethod, + String requestPath, + Map params, + Type type, + RequestOptions options, + ApiMode apiMode) + throws StripeException { + callCount++; + requestOptions = options; + method = requestMethod; + path = requestPath; + if (failure != null) { + throw failure; + } + return (T) ApiResource.GSON.fromJson(responseJson, type); + } + + @Override + public InputStream requestStream( + BaseAddress baseAddress, + RequestMethod requestMethod, + String requestPath, + Map params, + RequestOptions options, + ApiMode apiMode) + throws StripeException { + throw new AssertionError("subscription retrieve must not use a streaming request"); + } + + private int callCount() { + return callCount; + } + + private RequestMethod method() { + return method; + } + + private String path() { + return path; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingBillingStreamReadTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingBillingStreamReadTest.java new file mode 100644 index 0000000000..eecfa54281 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingBillingStreamReadTest.java @@ -0,0 +1,182 @@ +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.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.Consumer; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.json.JsonMapper; + +/** Actual hosting envelope codec with controlled ledger projections; no paid SQL owner proof. */ +class AccountHostingBillingStreamReadTest { + private static final UUID TENANT = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID REQUEST = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID EVENT = TenantAuthorityEventV1Codec.tenantBillingEventId(REQUEST); + private static final String REQUEST_DIGEST = "sha256:" + "a".repeat(64); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void actualHostingEncoderRoundTripsBothCutoffProfilesThroughSharedCheckpointWithoutDemoDecode() { + for (boolean cutoff : new boolean[] {false, true}) { + var event = hosting(cutoff); + var decoded = AccountHostingSubscriptionLifecycleEvidence.verifyBilling(event.payload()); + assertThat(decoded.matches(event.payload(), event.digest())).isTrue(); + assertThat(decoded.requestDigest).isEqualTo(REQUEST_DIGEST); + DSLContext dsl = mock(DSLContext.class); + doReturn(stream(7L), row(event)).when(dsl).fetchOne(anyString(), any(Object[].class)); + TransactionSynchronizationManager.setActualTransactionActive(true); + var repository = new AccountTenantEntitlementOutboxRepository(dsl); + + assertThat(repository.readCheckpoint(TENANT)) + .contains( + new AccountTenantEntitlementOutboxRepository.Checkpoint( + AccountTenantEntitlementOutboxRepository.streamKey(TENANT), + 7L, + EVENT, + event.digest())); + + // A hosting event remains incompatible with the deliberately DEMO-only Event API. + doReturn(row(event)).when(dsl).fetchOne(anyString(), any(Object[].class)); + assertThatThrownBy(() -> repository.readEvent(TENANT, 7L)) + .isInstanceOf(IllegalArgumentException.class); + verify(dsl, never()).execute(anyString(), any(Object[].class)); + } + } + + @Test + void sharedCheckpointRejectsChangedPersistedIdentitySequenceOrDigest() { + for (String field : + List.of( + "tenant_uuid", "tenant_billing_sequence", "request_id", "event_id", "event_digest")) { + var event = hosting(false); + Record row = row(event); + switch (field) { + case "tenant_billing_sequence" -> row.set(DSL.field(field, Long.class), 8L); + case "event_digest" -> row.set(DSL.field(field, String.class), "sha256:" + "b".repeat(64)); + default -> row.set(DSL.field(field, UUID.class), UUID.randomUUID()); + } + DSLContext dsl = mock(DSLContext.class); + doReturn(stream(7L), row).when(dsl).fetchOne(anyString(), any(Object[].class)); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy( + () -> new AccountTenantEntitlementOutboxRepository(dsl).readCheckpoint(TENANT)) + .as("changed %s", field) + .isInstanceOf(IllegalStateException.class); + } + } + + @Test + void inverseRejectsUnknownNoncanonicalDuplicateOversizedAndContradictoryEnvelopes() { + byte[] original = hosting(true).payload(); + for (Consumer> mutation : + List.>>of( + fields -> fields.put("schemaVersion", "unknown/v1"), + fields -> fields.put("unknown", true), + fields -> fields.remove("requestDigest"), + fields -> fields.put("tenantBillingSequence", "07"), + fields -> fields.put("eventId", "55555555-5555-4555-8555-555555555555"), + fields -> fields.put("tenantId", new UUID(0L, 0L).toString()), + fields -> fields.put("tenantBillingStateChanged", false), + fields -> fields.put("eventTypes", List.of("SubscriptionStatusChanged")), + fields -> fields.put("receipt", Map.of("hardCutoff", false)))) { + Map fields = JSON.readValue(original, new TypeReference<>() {}); + mutation.accept(fields); + assertThatThrownBy( + () -> + AccountHostingSubscriptionLifecycleEvidence.verifyBilling( + AccountHostingSubscriptionLifecycleEvidence.encode(fields))) + .isInstanceOf(IllegalArgumentException.class); + } + String text = new String(original, StandardCharsets.UTF_8); + for (byte[] invalid : + List.of( + (" " + text).getBytes(StandardCharsets.UTF_8), + (text + " {}").getBytes(StandardCharsets.UTF_8), + text.replaceFirst("\\{", "{\"eventType\":\"SubscriptionStatusChanged\",") + .getBytes(StandardCharsets.UTF_8), + new byte[32769])) { + assertThatThrownBy(() -> AccountHostingSubscriptionLifecycleEvidence.verifyBilling(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + // Unknown and tampered serialized envelopes are also refused at the shared reader boundary. + for (byte[] invalid : + List.of( + text.replace("account-hosting-subscription-event/v1", "unknown/v1") + .getBytes(StandardCharsets.UTF_8), + text.replace("SubscriptionStatusChanged", "OtherEvent") + .getBytes(StandardCharsets.UTF_8))) { + Record row = row(hosting(true)); + row.set(DSL.field("payload", byte[].class), invalid); + row.set( + DSL.field("event_digest", String.class), + AccountHostingSubscriptionLifecycleEvidence.digest(invalid)); + DSLContext dsl = mock(DSLContext.class); + doReturn(stream(7L), row).when(dsl).fetchOne(anyString(), any(Object[].class)); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy( + () -> new AccountTenantEntitlementOutboxRepository(dsl).readCheckpoint(TENANT)) + .isInstanceOfAny(IllegalStateException.class, IllegalArgumentException.class); + } + } + + private static AccountHostingSubscriptionLifecycleEvidence.BillingEvent hosting(boolean cutoff) { + Map receipt = new LinkedHashMap<>(); + receipt.put("schemaVersion", "account-hosting-current-receipt/v1"); + receipt.put("tenantId", TENANT.toString()); + receipt.put("requestId", REQUEST.toString()); + receipt.put("requestDigest", REQUEST_DIGEST); + receipt.put("hardCutoff", cutoff); + return AccountHostingSubscriptionLifecycleEvidence.billing( + TENANT, REQUEST, REQUEST_DIGEST, 7L, EVENT, receipt); + } + + private static Record stream(long value) { + var sequence = DSL.field("last_sequence", Long.class); + Record row = DSL.using(SQLDialect.POSTGRES).newRecord(sequence); + row.set(sequence, value); + return row; + } + + private static Record row(AccountHostingSubscriptionLifecycleEvidence.BillingEvent event) { + var tenant = DSL.field("tenant_uuid", UUID.class); + var sequence = DSL.field("tenant_billing_sequence", Long.class); + var request = DSL.field("request_id", UUID.class); + var id = DSL.field("event_id", UUID.class); + var digest = DSL.field("event_digest", String.class); + var payload = DSL.field("payload", byte[].class); + Record row = + DSL.using(SQLDialect.POSTGRES).newRecord(tenant, sequence, request, id, digest, payload); + row.set(tenant, event.tenantId); + row.set(sequence, event.sequence); + row.set(request, event.requestId); + row.set(id, event.eventId); + row.set(digest, event.digest()); + row.set(payload, event.payload()); + return row; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalogTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalogTest.java new file mode 100644 index 0000000000..f8e58a0a74 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalogTest.java @@ -0,0 +1,128 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import net.firedevops.firemud.accountservice.repository.AccountHostingPlanCatalog.ConfiguredPlan; +import org.junit.jupiter.api.Test; + +class AccountHostingPlanCatalogTest { + @Test + void onlyExplicitConfigurationResolvesAndTheConfigurationAndQuoteBytesCannotBeMutated() { + var entry = configuration("basic-hosting", "price_explicit"); + var source = new ArrayList<>(List.of(entry)); + var catalog = new AccountHostingPlanCatalog(source); + source.clear(); + var quote = catalog.resolve("basic-hosting"); + assertThat(quote) + .isEqualTo( + new AccountHostingPlanQuote("basic-hosting", "price_explicit", 3, 100, 2, 1048576)); + assertThat(quote.digest()).startsWith("sha256:").hasSize(71); + byte[] original = quote.payload(); + byte[] escaped = quote.payload(); + escaped[0] ^= 1; + assertThat(quote.payload()).containsExactly(original); + assertThat(quote.payload().length).isLessThanOrEqualTo(4096); + quote.requireRetained(original, quote.digest()); + assertThatThrownBy(() -> quote.requireRetained(escaped, quote.digest())) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> quote.requireRetained(original, "sha256:" + "f".repeat(64))) + .isInstanceOf(IllegalStateException.class); + var alteredFields = + new AccountHostingPlanQuote("basic-hosting", "price_other", 3, 100, 2, 1048576); + assertThatThrownBy(() -> alteredFields.requireRetained(original, quote.digest())) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void noDefaultPlanOrAmbiguousDuplicateCanBecomeAQuote() { + var empty = new AccountHostingPlanCatalog(List.of()); + assertThatThrownBy(() -> empty.resolve("basic-hosting")) + .isInstanceOf(AccountHostingPlanCatalog.PlanUnavailableException.class); + assertThatThrownBy(() -> new AccountHostingPlanCatalog(null)) + .isInstanceOf(IllegalArgumentException.class); + var entry = configuration("basic-hosting", "price_explicit"); + assertThatThrownBy(() -> new AccountHostingPlanCatalog(List.of(entry, entry))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Ambiguous"); + assertThatThrownBy( + () -> + new AccountHostingPlanCatalog( + List.of(entry, configuration("basic-hosting", "price_other")))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new AccountHostingPlanCatalog(Arrays.asList(entry, null))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void integralConfigurationRejectsIncompleteFractionalNegativeAndOverflowValuesWithoutFallback() { + for (String malformed : + Arrays.asList(null, "", "-1", "+1", "01", "1.5", "1e3", " 1", "9223372036854775808")) { + for (int position = 0; position < 4; position++) { + String[] fields = {"1", "100", "2", "1048576"}; + fields[position] = malformed; + var invalid = + new ConfiguredPlan( + "basic-hosting", "price_explicit", fields[0], fields[1], fields[2], fields[3]); + assertThatThrownBy(() -> new AccountHostingPlanCatalog(List.of(invalid))) + .isInstanceOf(IllegalArgumentException.class); + } + } + assertThatThrownBy( + () -> + new AccountHostingPlanCatalog( + List.of( + new ConfiguredPlan( + "basic-hosting", "price_explicit", "0", "100", "2", "1048576")))) + .isInstanceOf(IllegalArgumentException.class); + var maximum = + new AccountHostingPlanCatalog( + List.of( + new ConfiguredPlan( + "exact", + "price_max", + Long.toString(Long.MAX_VALUE), + "0", + "0", + Long.toString(Long.MAX_VALUE)))) + .resolve("exact"); + assertThat(maximum.providerQuantity()).isEqualTo(Long.MAX_VALUE); + assertThat(maximum.maxActiveSessions()) + .isZero(); // Explicit zero is a bound, never an unlimited default. + assertThat(new String(maximum.payload(), StandardCharsets.UTF_8)) + .contains( + "\"providerQuantity\":\"9223372036854775807\"", + "\"maxStorageBytes\":\"9223372036854775807\""); + } + + @Test + void planCodesRetainExactUnicodeAndNeverIntroduceUuidOrNormalizationFallbacks() { + String composed = "hébergement"; + String decomposed = "he\u0301bergement"; + var catalog = + new AccountHostingPlanCatalog( + List.of(configuration(composed, "price_one"), configuration(decomposed, "price_two"))); + assertThat(catalog.resolve(composed).planCode()).isEqualTo(composed); + assertThat(catalog.resolve(decomposed).planCode()).isEqualTo(decomposed); + assertThat(catalog.resolve(composed).digest()) + .isNotEqualTo(catalog.resolve(decomposed).digest()); + for (String bad : Arrays.asList(null, "", " basic", "basic ", "\uD800", "a".repeat(256))) { + assertThatThrownBy( + () -> new AccountHostingPlanCatalog(List.of(configuration(bad, "price_one")))) + .isInstanceOf(IllegalArgumentException.class); + } + for (String price : Arrays.asList(null, "", "prod_notAPrice", "price_contains-dash")) { + assertThatThrownBy( + () -> new AccountHostingPlanCatalog(List.of(configuration("basic-hosting", price)))) + .isInstanceOf(IllegalArgumentException.class); + } + } + + private static ConfiguredPlan configuration(String code, String price) { + return new ConfiguredPlan(code, price, "3", "100", "2", "1048576"); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecyclePolicyTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecyclePolicyTest.java new file mode 100644 index 0000000000..045105d786 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecyclePolicyTest.java @@ -0,0 +1,211 @@ +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.ZoneOffset; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy.Reason; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy.RecoveryTiming; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy.Status; +import org.junit.jupiter.api.Test; + +/** Real Stripe SDK deserialization over controlled transport; no remote Stripe requests. */ +class AccountHostingSubscriptionLifecyclePolicyTest { + private static final Instant NOW = Instant.ofEpochSecond(1_778_000_010); + private static final Instant END = Instant.ofEpochSecond(1_780_592_000); + private static final UUID SUBSCRIPTION = UUID.fromString("0c9ee07d-0e6d-4f66-9a87-54110acbc611"); + private static final UUID OPERATION = UUID.fromString("4e2af076-4a10-4aaf-93a0-e5df29271310"); + private static final String RESPONSE = + """ + {"id":"sub_expected","object":"subscription","customer":"cus_expected", + "default_payment_method":"pm_expected","livemode":false,"status":"active", + "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":"4e2af076-4a10-4aaf-93a0-e5df29271310", + "firemud_subscription_id":"0c9ee07d-0e6d-4f66-9a87-54110acbc611"}, + "items":{"object":"list","data":[{"id":"si_expected","object":"subscription_item", + "subscription":"sub_expected","quantity":1,"current_period_start":1778000000, + "current_period_end":1780592000,"price":{"id":"price_expected","object":"price"}}], + "has_more":false}} + """; + + @Test + void mapsActiveAndTrialOnlyFromActualSdkEvidenceAndExpiresAtStrictReadStartDeadline() { + var active = observed(RESPONSE, NOW); + var decision = policy().evaluate(active, NOW, null); + assertThat(decision.status()).isEqualTo(Status.ACTIVE); + assertThat(decision.validUntil()).isEqualTo(NOW.plusSeconds(15)); + assertThat(decision.receiptValidUntil()).isEqualTo(END); + assertThat(policy().evaluate(active, NOW.plusSeconds(14), null).resolved()).isTrue(); + assertThat(policy().evaluate(active, NOW.plusSeconds(15), null).reason()) + .isEqualTo(Reason.OBSERVATION_EXPIRED); + assertThat(policy().evaluate(active, NOW.minusNanos(1), null).reason()) + .isEqualTo(Reason.UNSAFE_READ_INTERVAL); + var trial = observed(RESPONSE.replace("\"active\"", "\"trialing\""), NOW); + assertThat(policy().evaluate(trial, NOW, null).status()).isEqualTo(Status.TRIALING); + } + + @Test + void pastDueUsesRetainedEpisodeAndExactConfiguredBoundariesWithoutRestartingGrace() { + String response = RESPONSE.replace("\"active\"", "\"past_due\""); + assertThat(policy().evaluate(observed(response, NOW), NOW, null).reason()) + .isEqualTo(Reason.RECOVERY_ORIGIN_UNRESOLVED); + assertThat(policy().evaluate(observed(response, NOW), NOW, NOW.plusNanos(1)).resolved()) + .isFalse(); + Instant delayedRead = NOW.plusSeconds(600); + assertThat(policy().evaluate(observed(response, delayedRead), delayedRead, null).reason()) + .isEqualTo(Reason.RECOVERY_ORIGIN_UNRESOLVED); + assertThat(policy().evaluate(observed(response, delayedRead), delayedRead, NOW).status()) + .isEqualTo(Status.SUSPENDED); + Instant warningEnd = NOW.plusSeconds(60); + assertThat(policy().evaluate(observed(response, NOW), NOW, NOW).status()) + .isEqualTo(Status.PAST_DUE); + assertThat(policy().evaluate(observed(response, warningEnd), warningEnd, NOW).status()) + .isEqualTo(Status.GRACE); + Instant graceEnd = warningEnd.plusSeconds(120); + var cutoff = policy().evaluate(observed(response, graceEnd), graceEnd, NOW); + assertThat(cutoff.status()).isEqualTo(Status.SUSPENDED); + assertThat(cutoff.cutoffAt()).isEqualTo(graceEnd); + assertThat(policy().evaluate(observed(response, NOW), NOW, NOW).validUntil()) + .isEqualTo(NOW.plusSeconds(15)); + assertThat(policy().evaluate(observed(response, NOW), NOW, NOW).receiptValidUntil()) + .isEqualTo(warningEnd); + assertThat( + policy().evaluate(observed(response, warningEnd), warningEnd, NOW).receiptValidUntil()) + .isEqualTo(graceEnd); + assertThat(cutoff.receiptValidUntil()).isEqualTo(END); + } + + @Test + void scheduledCancellationKeepsPaidPeriodAndDoesNotUseCanceledAtAsEffectiveCutoff() { + String response = + RESPONSE + .replace("\"cancel_at_period_end\":false", "\"cancel_at_period_end\":true") + .replace("\"canceled_at\":null", "\"canceled_at\":1778000005"); + var scheduled = policy().evaluate(observed(response, NOW), NOW, null); + assertThat(scheduled.status()).isEqualTo(Status.ACTIVE); + assertThat(scheduled.receiptValidUntil()).isEqualTo(END); + var atBoundary = policy().evaluate(observed(response, END), END, null); + assertThat(atBoundary.status()).isEqualTo(Status.CANCELED); + assertThat(atBoundary.cutoffAt()).isEqualTo(END); + assertThat(policy().evaluate(observed(RESPONSE, END), END, null).reason()) + .isEqualTo(Reason.PERIOD_UNRESOLVED); + } + + @Test + void confirmedCanceledMayOmitPeriodButFutureTerminationCannotAuthorizeAMapping() { + String response = + RESPONSE + .replace("\"active\"", "\"canceled\"") + .replace("\"current_period_start\":1778000000", "\"current_period_start\":null") + .replace("\"current_period_end\":1780592000", "\"current_period_end\":null"); + assertThat(policy().evaluate(observed(response, NOW), NOW, null).status()) + .isEqualTo(Status.CANCELED); + var contradictory = + observed(response.replace("\"ended_at\":null", "\"ended_at\":1780592000"), NOW); + assertThat(policy().evaluate(contradictory, NOW, null).reason()) + .isEqualTo(Reason.CONTRADICTORY_PROVIDER_FACTS); + } + + @Test + void unsupportedIncompletePausedAndUnpaidNeverAcquireAnInventedPositiveOrGraceState() { + for (String status : + new String[] {"incomplete", "incomplete_expired", "paused", "unpaid", "future_status"}) { + var result = observed(RESPONSE.replace("\"active\"", "\"" + status + "\""), NOW); + assertThat(policy().evaluate(result, NOW, NOW).resolved()).as(status).isFalse(); + } + var wrongBinding = observed(RESPONSE.replace("cus_expected", "cus_other"), NOW); + assertThat(policy().evaluate(wrongBinding, NOW, null).reason()) + .isEqualTo(Reason.PROVIDER_UNRESOLVED); + } + + @Test + void requiresExplicitFinitePositiveTimingInsteadOfDefaultRecoveryOrObservationWindows() { + assertThatThrownBy(() -> new RecoveryTiming(Duration.ZERO, Duration.ofMinutes(1))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new RecoveryTiming(Duration.ofMinutes(1), Duration.ofSeconds(-1))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> new RecoveryTiming(Duration.ofSeconds(Long.MAX_VALUE), Duration.ofSeconds(1))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new AccountHostingSubscriptionLifecyclePolicy(null, timing())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> new AccountHostingSubscriptionLifecyclePolicy(Duration.ofSeconds(1), null)) + .isInstanceOf(NullPointerException.class); + } + + private static AccountHostingSubscriptionLifecyclePolicy policy() { + return new AccountHostingSubscriptionLifecyclePolicy(Duration.ofSeconds(15), timing()); + } + + private static RecoveryTiming timing() { + return new RecoveryTiming(Duration.ofSeconds(60), Duration.ofSeconds(120)); + } + + private static StripeHostingSubscriptionObserver.Result observed(String json, Instant readAt) { + var observer = + new StripeHostingSubscriptionObserver( + new com.stripe.StripeClient(new ControlledTransport(json)), + Clock.fixed(readAt, ZoneOffset.UTC), + Duration.ofMillis(250), + Duration.ofSeconds(1)); + return observer.observe( + new StripeHostingSubscriptionObserver.ExpectedBinding( + "sub_expected", + SUBSCRIPTION, + "cus_expected", + "pm_expected", + "price_expected", + 1, + StripeHostingSubscriptionObserver.OperationType.SUBSCRIPTION_PROVISIONING, + OPERATION, + false)); + } + + private record ControlledTransport(String json) implements StripeResponseGetter { + @Override + @SuppressWarnings("unchecked") + public T request( + BaseAddress address, + RequestMethod method, + String path, + Map params, + Type type, + RequestOptions options, + ApiMode mode) + throws StripeException { + assertThat(method).isEqualTo(RequestMethod.GET); + assertThat(path).isEqualTo("/v1/subscriptions/sub_expected"); + return (T) new com.stripe.StripeClient(this).deserialize(json, mode); + } + + @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 mutation is allowed"); + } + } +} 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 new file mode 100644 index 0000000000..29f6e4fa35 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java @@ -0,0 +1,128 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReconciliationLimits; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountHostingSubscriptionLifecycleRepositoryTest { + private final DSLContext dsl = mock(DSLContext.class); + private final AccountSubscriptionIntentRepository intents = + new AccountSubscriptionIntentRepository(dsl, new AccountHostingPlanCatalog(List.of())); + private final AccountHostingSubscriptionLifecycleRepository repository = + new AccountHostingSubscriptionLifecycleRepository( + dsl, + intents, + Clock.systemUTC(), + new ReconciliationLimits( + 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); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } + + @Test + void recoveryOriginIsOnlyRetainedEpisodeHistoryAndMissingHistoryStaysUnresolved() { + assertThat(AccountHostingSubscriptionLifecycleRepository.retainedPastDueOrigin(null)).isNull(); + var receipt = mock(org.jooq.Record.class); + assertThat(AccountHostingSubscriptionLifecycleRepository.retainedPastDueOrigin(receipt)) + .isNull(); + Instant original = Instant.parse("2026-05-05T00:00:00Z"); + when(receipt.get("past_due_since", OffsetDateTime.class)) + .thenReturn(original.atOffset(ZoneOffset.UTC)); + assertThat(AccountHostingSubscriptionLifecycleRepository.retainedPastDueOrigin(receipt)) + .isEqualTo(original); + assertThat(AccountHostingSubscriptionLifecycleRepository.retainedPastDueOrigin(receipt)) + .isEqualTo(original); + } + + @Test + void claimAndSettlementRequireWritableOwnerTransactionBeforeSql() { + assertTransactionRefusal(); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertTransactionRefusal(); + verifyNoInteractions(dsl); + } + + private void assertTransactionRefusal() { + assertThatThrownBy(() -> repository.claim(UUID.randomUUID(), 1, UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable Account transaction"); + assertThatThrownBy(() -> repository.deferUnresolved(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable Account transaction"); + } + + @Test + void malformedClaimInputsCannotBecomeSqlLookups() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> repository.claim(null, 1, UUID.randomUUID())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> repository.claim(UUID.randomUUID(), 1, new UUID(0, 0))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> repository.claim(UUID.randomUUID(), 0, UUID.randomUUID())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> repository.claim(UUID.randomUUID(), Long.MAX_VALUE, UUID.randomUUID())) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(dsl); + } + + @Test + void reconciliationRequiresExplicitFiniteNonzeroBudgetsAndRepresentableDurations() { + assertThatThrownBy( + () -> limits(0, 1, Duration.ofSeconds(1), Duration.ofSeconds(1), Duration.ofHours(1))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> limits(1, 0, Duration.ofSeconds(1), Duration.ofSeconds(1), Duration.ofHours(1))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> limits(1, 1, Duration.ZERO, Duration.ofSeconds(1), Duration.ofHours(1))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> limits(1, 1, Duration.ofNanos(1), Duration.ofSeconds(1), Duration.ofHours(1))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> limits(1, 1, Duration.ofSeconds(1), null, Duration.ofHours(1))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> limits(1, 1, Duration.ofHours(2), Duration.ofSeconds(1), Duration.ofHours(1))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + limits( + 1, + 1, + Duration.ofSeconds(1), + Duration.ofSeconds(1), + Duration.ofSeconds(Long.MAX_VALUE))) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(dsl); + } + + private static ReconciliationLimits limits( + int attempts, int stalled, Duration lease, Duration backoff, Duration deadline) { + return new ReconciliationLimits(attempts, stalled, lease, backoff, deadline); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSubscriptionCreateDigestTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSubscriptionCreateDigestTest.java new file mode 100644 index 0000000000..ea5dd01038 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSubscriptionCreateDigestTest.java @@ -0,0 +1,96 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class AccountSubscriptionCreateDigestTest { + private static final UUID TENANT = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID OWNER = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID INSTRUMENT = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID OTHER = UUID.fromString("44444444-4444-4444-8444-444444444444"); + + @Test + void canonicalVersionOneGoldenVectorBindsTheResolvedCreateTuple() { + var encoded = + AccountSubscriptionCreateDigest.encode(TENANT, OWNER, "basic-hosting", INSTRUMENT); + + assertThat(new String(encoded.payload(), StandardCharsets.UTF_8)) + .isEqualTo( + "{\"instrumentSelection\":{\"kind\":\"EXACT_SAVED_INSTRUMENT\"," + + "\"paymentInstrumentId\":\"33333333-3333-4333-8333-333333333333\"}," + + "\"ownerAccountId\":\"22222222-2222-4222-8222-222222222222\"," + + "\"planCode\":\"basic-hosting\"," + + "\"schemaVersion\":\"account-subscription-create-request/v1\"," + + "\"tenantId\":\"11111111-1111-4111-8111-111111111111\"}"); + assertThat(encoded.digest()) + .isEqualTo("sha256:1b9e07bcbec705fc21fad3395ef9239ec5e5fb5d08899db9f9dbc07190053b70"); + assertThat( + AccountSubscriptionCreateDigest.encode(TENANT, OWNER, "basic-hosting", INSTRUMENT) + .digest()) + .isEqualTo(encoded.digest()); + assertThat( + AccountSubscriptionCreateDigest.encode(OTHER, OWNER, "basic-hosting", INSTRUMENT) + .digest()) + .isNotEqualTo(encoded.digest()); + assertThat( + AccountSubscriptionCreateDigest.encode(TENANT, OTHER, "basic-hosting", INSTRUMENT) + .digest()) + .isNotEqualTo(encoded.digest()); + assertThat( + AccountSubscriptionCreateDigest.encode(TENANT, OWNER, "pro-hosting", INSTRUMENT) + .digest()) + .isNotEqualTo(encoded.digest()); + assertThat( + AccountSubscriptionCreateDigest.encode(TENANT, OWNER, "basic-hosting", OTHER).digest()) + .isNotEqualTo(encoded.digest()); + } + + @Test + void malformedOrUnnormalizedPlanCannotCollideThroughLossyEncoding() { + for (String plan : + new String[] {null, "", " ", " basic-hosting", "basic-hosting ", "bad\uD800"}) { + assertThatThrownBy( + () -> AccountSubscriptionCreateDigest.encode(TENANT, OWNER, plan, INSTRUMENT)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void missingCanonicalIdentityCannotBecomeRequestEvidence() { + for (UUID identity : new UUID[] {null, new UUID(0, 0)}) { + assertThatThrownBy( + () -> + AccountSubscriptionCreateDigest.encode( + identity, OWNER, "basic-hosting", INSTRUMENT)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountSubscriptionCreateDigest.encode( + TENANT, identity, "basic-hosting", INSTRUMENT)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountSubscriptionCreateDigest.encode(TENANT, OWNER, "basic-hosting", identity)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void returnedBytesCannotChangeRetainedRequestEvidence() { + var encoded = + AccountSubscriptionCreateDigest.encode(TENANT, OWNER, "basic-hosting", INSTRUMENT); + byte[] original = encoded.payload(); + byte[] supplied = encoded.payload(); + var retained = new AccountSubscriptionCreateDigest.EncodedRequest(supplied, encoded.digest()); + supplied[0] = '!'; + encoded.payload()[0] = '!'; + retained.payload()[0] = '!'; + + assertThat(encoded.payload()).isEqualTo(original); + assertThat(retained.payload()).isEqualTo(original); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepositoryTest.java new file mode 100644 index 0000000000..7d79e6cc87 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepositoryTest.java @@ -0,0 +1,404 @@ +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.ArgumentMatchers.anyString; +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.OffsetDateTime; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +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 org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountSubscriptionIntentRepositoryTest { + private static final UUID ACCOUNT = UUID.randomUUID(); + private static final UUID TENANT = UUID.randomUUID(); + private static final UUID INSTRUMENT = UUID.randomUUID(); + private static final OwnerFence OWNER = new OwnerFence(ACCOUNT, 1, UUID.randomUUID()); + private static final ProducerEvidence PRODUCER = + new ProducerEvidence(ACCOUNT, UUID.randomUUID(), "sha256:" + "a".repeat(64)); + private final DSLContext dsl = mock(DSLContext.class); + private final AccountSubscriptionIntentRepository repository = + new AccountSubscriptionIntentRepository(dsl, new AccountHostingPlanCatalog(List.of())); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } + + @Test + void pendingWritesAndClaimReadsRefuseAbsentOrReadOnlyTransactionsBeforeSql() { + assertTransactionRefusal(); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertTransactionRefusal(); + verifyNoInteractions(dsl); + } + + private void assertTransactionRefusal() { + var request = request("basic-hosting", 1); + assertThatThrownBy(() -> repository.retainPending(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active writable Account transaction"); + assertThatThrownBy(() -> repository.lockPendingForClaim(request.requestId(), 1)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active writable Account transaction"); + } + + @Test + void exactNormalizedSavedInstrumentInputsAndAdvanceableVersionsAreRequired() { + assertThatThrownBy(() -> request(" basic-hosting", 1)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> request("", 1)).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> request("a".repeat(256), 1)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> request("basic-hosting", 0)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> request("basic-hosting", Long.MAX_VALUE)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new OwnerFence(ACCOUNT, 0, UUID.randomUUID())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new ReplacementFence(UUID.randomUUID(), Long.MAX_VALUE)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new ProducerEvidence(ACCOUNT, UUID.randomUUID(), "unverified claim")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountSubscriptionCreateRequest( + new UUID(0L, 0L), + TENANT, + OWNER, + "basic-hosting", + INSTRUMENT, + 1, + PRODUCER, + null)) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(dsl); + } + + @Test + void invalidReadIdentitiesCannotBecomeSqlLookupsOrProviderMappings() { + assertThatThrownBy(() -> repository.findCreation(new UUID(0L, 0L))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> repository.findCurrentByTenant(null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> repository.lookupProviderId("customer-or-latest-subscription")) + .isInstanceOf(IllegalArgumentException.class); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> repository.lockPendingForClaim(UUID.randomUUID(), 0)) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(dsl); + } + + @Test + void lifecycleRetainsOriginalBindingAcrossCurrentVersionDisplayUpdatesAndUnavailability() { + for (String observation : List.of("original", "updated-display", "unavailable")) { + BindingFixture f = new BindingFixture(); + if (!observation.equals("original")) { + f.instrument.put("row_version", 4L); + f.instrument.put("display_last_four", "4242"); + f.instrument.put("display_expiry_year", 2031); + } + if (observation.equals("unavailable")) f.instrument.put("state", "UNAVAILABLE"); + TransactionSynchronizationManager.setActualTransactionActive(true); + + var current = f.repository.lockForLifecycle(f.requestId, 7L); + + assertThat(current.subscriptionId()).isEqualTo(f.subscriptionId); + assertThat(current.paymentInstrumentId()).isEqualTo(INSTRUMENT); + assertThat(current.reservedInstrumentVersion()).isEqualTo(3L); + assertThat(current.providerCustomerId()).isEqualTo("cus_original"); + assertThat(f.reservation.get("instrument_version")).isEqualTo(3L); + assertThat(f.reservation.get("released_at")).isNull(); + assertThat(f.reads).hasSize(7); + assertThat(f.reads.get(1)).contains("FROM accounts", "FOR UPDATE"); + assertThat(f.reads.get(2)).contains("FROM billing_customer", "FOR UPDATE"); + assertThat(f.reads.get(3)).contains("FROM payment_instrument", "FOR UPDATE"); + assertThat(f.reads.get(4)).contains("FROM account_tenant_billing_owners", "FOR UPDATE"); + assertThat(f.reads.get(5)).contains("FROM subscription s", "FOR UPDATE OF s"); + assertThat(f.reads.get(6)) + .contains("FROM subscription_instrument_reservations", "FOR UPDATE OF r"); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + } + + @Test + void lifecycleRejectsRolledBackWalletVersionAndChangedImmutableInstrumentBinding() { + for (String changed : + List.of( + "row_version", + "instrument_uuid", + "account_uuid", + "provider_customer_id", + "customer_provisioning_request_id")) { + BindingFixture f = new BindingFixture(); + switch (changed) { + case "row_version" -> f.instrument.put(changed, 2L); + case "provider_customer_id" -> f.instrument.put(changed, "cus_other"); + default -> f.instrument.put(changed, UUID.randomUUID()); + } + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> f.repository.lockForLifecycle(f.requestId, 7L)) + .as("changed %s", changed) + .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class); + + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + } + + @Test + void lifecycleRejectsChangedSubscriptionIdentityExpectedVersionAndOriginalReservation() { + for (String changed : + List.of( + "subscription_id", + "tenant_id", + "account_uuid", + "owner_version", + "creation_request_id", + "payment_instrument_id", + "reserved_instrument_version", + "customer_provisioning_request_id", + "provider_customer_id", + "row_version", + "superseded_at")) { + BindingFixture f = new BindingFixture(); + switch (changed) { + case "owner_version", "reserved_instrument_version", "row_version" -> + f.current.put(changed, 8L); + case "provider_customer_id" -> f.current.put(changed, "cus_other"); + case "superseded_at" -> f.current.put(changed, f.time); + default -> f.current.put(changed, UUID.randomUUID()); + } + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> f.repository.lockForLifecycle(f.requestId, 7L)) + .as("changed current %s", changed) + .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + for (String changed : + List.of( + "missing", + "subscription_id", + "payment_instrument_id", + "instrument_version", + "released_at")) { + BindingFixture f = new BindingFixture(); + switch (changed) { + case "missing" -> f.missingReservation = true; + case "instrument_version" -> f.reservation.put(changed, 4L); + case "released_at" -> f.reservation.put(changed, f.time); + default -> f.reservation.put(changed, UUID.randomUUID()); + } + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> f.repository.lockForLifecycle(f.requestId, 7L)) + .as("changed reservation %s", changed) + .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + } + + @Test + void canceledLifecycleReadRetainsOnlyItsExactTerminalReservationAfterWalletUnavailability() { + BindingFixture f = new BindingFixture(); + UUID terminal = UUID.randomUUID(); + f.current.put("status", "canceled"); + f.current.put("terminal_resolution_id", terminal); + f.instrument.put("row_version", 4L); + f.instrument.put("state", "UNAVAILABLE"); + f.reservation.put("released_at", f.time); + f.reservation.put("terminal_resolution_id", terminal); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThat(f.repository.lockForLifecycle(f.requestId, 7L).terminalResolutionId()) + .isEqualTo(terminal); + assertThat(f.reservation.get("instrument_version")).isEqualTo(3L); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + + f.reservation.put("terminal_resolution_id", UUID.randomUUID()); + assertThatThrownBy(() -> f.repository.lockForLifecycle(f.requestId, 7L)) + .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class); + } + + @Test + void provisioningClaimAndRecoveryStillRequireExactReservedVersionAndAttachableState() { + for (boolean recovery : new boolean[] {false, true}) { + BindingFixture original = new BindingFixture(); + original.current.put("status", recovery ? "provisioning" : "pending"); + TransactionSynchronizationManager.setActualTransactionActive(true); + var accepted = + recovery + ? original.repository.lockForProvisioningRecovery(original.requestId, 7L) + : original.repository.lockPendingForClaim(original.requestId, 7L); + assertThat(accepted.reservedInstrumentVersion()).isEqualTo(3L); + verify(original.dsl, never()).execute(anyString(), any(Object[].class)); + + for (String changed : List.of("version", "state", "both")) { + BindingFixture f = new BindingFixture(); + f.current.put("status", recovery ? "provisioning" : "pending"); + if (!changed.equals("state")) f.instrument.put("row_version", 4L); + if (!changed.equals("version")) f.instrument.put("state", "UNAVAILABLE"); + assertThatThrownBy( + () -> { + if (recovery) f.repository.lockForProvisioningRecovery(f.requestId, 7L); + else f.repository.lockPendingForClaim(f.requestId, 7L); + }) + .as("%s updated %s", recovery ? "recovery" : "claim", changed) + .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + } + } + + /** Real row decoders over controlled SQL projections; no paid schema or provider proof. */ + private static final class BindingFixture { + private final DSLContext dsl = mock(DSLContext.class); + private final AccountSubscriptionIntentRepository repository = + new AccountSubscriptionIntentRepository(dsl, new AccountHostingPlanCatalog(List.of())); + private final UUID requestId = UUID.randomUUID(); + private final UUID subscriptionId = UUID.randomUUID(); + private final UUID customerRequest = UUID.randomUUID(); + private final OffsetDateTime time = OffsetDateTime.parse("2026-11-03T00:00:00Z"); + private final Map current = new LinkedHashMap<>(); + private final Map instrument = new LinkedHashMap<>(); + private final Map reservation = new LinkedHashMap<>(); + private final List reads = new ArrayList<>(); + private boolean missingReservation; + + private BindingFixture() { + var quote = new AccountHostingPlanQuote("basic-hosting", "price_basic", 1L, 3L, 2L, 4096L); + Map creation = new LinkedHashMap<>(); + creation.put("request_id", requestId); + creation.put( + "request_digest", + AccountSubscriptionCreateDigest.encode(TENANT, ACCOUNT, "basic-hosting", INSTRUMENT) + .digest()); + creation.put("subscription_id", subscriptionId); + creation.put("tenant_id", TENANT); + creation.put("account_uuid", ACCOUNT); + creation.put("owner_version", OWNER.version()); + creation.put("owner_generation", OWNER.generation()); + creation.put("plan_code", quote.planCode()); + creation.put("provider_price_id", quote.providerPriceId()); + creation.put("provider_quantity", quote.providerQuantity()); + creation.put("max_active_sessions", quote.maxActiveSessions()); + creation.put("max_concurrent_game_instances", quote.maxConcurrentGameInstances()); + creation.put("max_storage_bytes", quote.maxStorageBytes()); + creation.put("plan_quote_payload", quote.payload()); + creation.put("plan_quote_digest", quote.digest()); + creation.put("payment_instrument_id", INSTRUMENT); + creation.put("reserved_instrument_version", 3L); + creation.put("customer_provisioning_request_id", customerRequest); + creation.put("provider_customer_id", "cus_original"); + creation.put("subscription_provisioning_request_id", UUID.randomUUID()); + creation.put("cleanup_provider_identity", UUID.randomUUID()); + creation.put("result_status", "pending"); + creation.put("result_row_version", 1L); + creation.put("created_at", time); + current.putAll(creation); + current.put("creation_request_id", requestId); + current.put("row_version", 7L); + current.put("status", "active"); + current.put("provider_subscription_id", "sub_original"); + instrument.put("instrument_uuid", INSTRUMENT); + instrument.put("account_uuid", ACCOUNT); + instrument.put("customer_provisioning_request_id", customerRequest); + instrument.put("provider_customer_id", "cus_original"); + instrument.put("provider_payment_method_id", "pm_original"); + instrument.put("attachment_request_id", UUID.randomUUID()); + instrument.put("row_version", 3L); + instrument.put("state", "ATTACHABLE"); + instrument.put("display_brand", "visa"); + instrument.put("display_last_four", "1234"); + instrument.put("display_expiry_month", 12); + instrument.put("display_expiry_year", 2030); + instrument.put("change_request_id", UUID.randomUUID()); + instrument.put("evidence_digest", "sha256:" + "a".repeat(64)); + instrument.put("created_at", time); + instrument.put("updated_at", time); + Map customer = new LinkedHashMap<>(); + customer.put("account_uuid", ACCOUNT); + customer.put("customer_provisioning_request_id", customerRequest); + customer.put("provider_idempotency_id", UUID.randomUUID()); + customer.put("row_version", 2L); + customer.put("state", "CONFIRMED"); + customer.put("provider_customer_id", "cus_original"); + customer.put("change_request_id", UUID.randomUUID()); + customer.put("observation", "CONFIRMED"); + customer.put("evidence_digest", "sha256:" + "b".repeat(64)); + customer.put("created_at", time); + customer.put("updated_at", time); + reservation.put("subscription_id", subscriptionId); + reservation.put("payment_instrument_id", INSTRUMENT); + reservation.put("instrument_version", 3L); + Record creationRow = projection(creation); + Record currentRow = projection(current); + Record instrumentRow = projection(instrument); + Record customerRow = projection(customer); + Record ownerRow = + projection( + Map.of( + "owner_account_uuid", + ACCOUNT, + "owner_version", + OWNER.version(), + "owner_generation", + OWNER.generation())); + Record reservationRow = projection(reservation); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0, String.class); + reads.add(sql); + if (sql.startsWith("SELECT * FROM subscription_create_operations")) + return creationRow; + if (sql.contains("FROM accounts")) return ownerRow; + if (sql.contains("FROM billing_customer")) return customerRow; + if (sql.contains("FROM payment_instrument")) return instrumentRow; + if (sql.contains("FROM account_tenant_billing_owners")) return ownerRow; + if (sql.contains("FROM subscription s")) return currentRow; + if (sql.contains("FROM subscription_instrument_reservations")) + return missingReservation ? null : reservationRow; + throw new AssertionError("Unexpected original binding SQL: " + sql); + }); + } + } + + @SuppressWarnings("unchecked") + private static Record projection(Map fields) { + Record row = mock(Record.class); + doAnswer( + invocation -> + invocation + .getArgument(1, Class.class) + .cast(fields.get(invocation.getArgument(0, String.class)))) + .when(row) + .get(anyString(), any(Class.class)); + when(row.get(anyString())) + .thenAnswer(invocation -> fields.get(invocation.getArgument(0, String.class))); + return row; + } + + private static AccountSubscriptionCreateRequest request(String plan, long instrumentVersion) { + return new AccountSubscriptionCreateRequest( + UUID.randomUUID(), TENANT, OWNER, plan, INSTRUMENT, instrumentVersion, PRODUCER, null); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java index 657a8d16ce..3e3f844c13 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java @@ -1,15 +1,22 @@ package unit.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.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +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.lang.reflect.Method; +import java.util.List; +import java.util.Map; import java.util.UUID; import java.util.function.LongFunction; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; @@ -24,6 +31,7 @@ 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.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import org.jooq.DSLContext; @@ -33,6 +41,7 @@ import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; class AccountTenantAuthorityEventRepositoryTest { private static final String NAMESPACE = "prod"; @@ -137,6 +146,256 @@ void appendBindsBillingEventIdAsUuidAndAuthorityEventIdAsVarcharText() { } } + @Test + void genericCurrentReadReturnsTheExactSelectedFamilyCheckpointOnce() throws Exception { + for (var kind : AccountTenantAuthorityEventRepository.SourceKind.values()) { + SelectionFixture f = new SelectionFixture(true); + doReturn(new AccountTenantAuthorityEventRepository.SourceSelection(kind, f.authority)) + .when(f.repository) + .readCurrentSourceSelection(TENANT_ID); + + assertThat(f.repository.readCurrentByTenant(TENANT_ID)).isSameAs(f.authority); + + verify(f.repository).readCurrentSourceSelection(TENANT_ID); + verifyNoInteractions( + f.dsl, f.billingOutbox, f.authorityOutbox, f.generations, f.tenantIdentity); + } + } + + @Test + void actualPaidSourceSelectionUsesHostingReceiptWithoutEnteringTheDemoCurrentReader() + throws Exception { + SelectionFixture f = new SelectionFixture(true); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + var selected = f.repository.readCurrentByTenant(TENANT_ID); + + assertThat(selected).isSameAs(f.authority); + verify(f.repository).readHostingCheckpoint(TENANT_ID, REQUEST_ID); + verify(f.billingOutbox, never()).readEvent(any(), org.mockito.ArgumentMatchers.anyLong()); + verifyNoInteractions(f.tenantIdentity, f.authorityOutbox); + } finally { + TransactionSynchronizationManager.clear(); + } + } + + @Test + void demoSelectionEntersItsPrivateCurrentReaderWithoutRecursingThroughGenericDispatch() + throws Exception { + SelectionFixture f = new SelectionFixture(false); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + // This controlled graph deliberately omits the fresh association. The DEMO private reader + // must reach that exact Account SQL guard, rather than re-entering the generic selector. + assertThatThrownBy(() -> f.repository.readCurrentByTenant(TENANT_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Exact fresh Account tenant source association is unavailable"); + verify(f.repository).readCurrentSourceSelection(TENANT_ID); + verify(f.repository, never()).readHostingCheckpoint(any(), any()); + } finally { + TransactionSynchronizationManager.clear(); + } + } + + @Test + void paidSelectorStillRejectsChangedAuthorityHeadOrCommittedReceipt() throws Exception { + for (boolean changedReceipt : new boolean[] {false, true}) { + SelectionFixture f = new SelectionFixture(true); + if (changedReceipt) { + doReturn("{}".getBytes(java.nio.charset.StandardCharsets.UTF_8)) + .when(f.receipt) + .get("receipt_payload", byte[].class); + } else { + doReturn("sha256:" + "f".repeat(64)).when(f.head).get("last_event_digest", String.class); + } + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> f.repository.readCurrentByTenant(TENANT_ID)) + .isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.clear(); + } + } + } + + /** Controlled ledger/hosting-checkpoint inputs; not paid-table or lifecycle-owner proof. */ + private static final class SelectionFixture { + private final DSLContext dsl = mock(DSLContext.class); + private final AccountAuthorityOutboxRepository authorityOutbox = + mock(AccountAuthorityOutboxRepository.class); + private final AccountTenantEntitlementOutboxRepository billingOutbox = + mock(AccountTenantEntitlementOutboxRepository.class); + private final FreshTenantIdentityAssociationRepository tenantIdentity = + mock(FreshTenantIdentityAssociationRepository.class); + private final AccountAuthorityGenerationRepository generations = + mock(AccountAuthorityGenerationRepository.class); + private final AccountTenantAuthorityEventRepository repository = + spy( + new AccountTenantAuthorityEventRepository( + dsl, authorityOutbox, billingOutbox, tenantIdentity, generations)); + private final TenantAuthorityEventV1Codec.Event authority; + private final Record head; + private final Record receipt; + + private SelectionFixture(boolean hosting) throws Exception { + var source = freshTenantEvidence(); + var request = + new DemoTenantEntitlementRequest( + REQUEST_ID, + TENANT_ID, + SOURCE_REQUEST_ID, + SOURCE_REQUEST_DIGEST, + null, + null, + null, + true, + false, + false, + true, + new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)); + var demo = DemoTenantEntitlementEventV1Codec.seal(request, source, 1L, 2L, 2L, 1L); + String requestDigest = demo.requestDigest(); + UUID billingEventId = TenantAuthorityEventV1Codec.tenantBillingEventId(REQUEST_ID); + var json = JsonMapper.builder().build(); + Map receiptFields = + Map.of( + "schemaVersion", + "account-hosting-current-receipt/v1", + "tenantId", + TENANT_ID.toString(), + "requestId", + REQUEST_ID.toString(), + "requestDigest", + requestDigest, + "hardCutoff", + false); + byte[] receiptBytes = + Rfc8785CanonicalJson.canonicalizeUtf8(json.writeValueAsString(receiptFields)); + byte[] payload; + String digest; + if (hosting) { + // Exact public serialized profile. The dedicated repository-package codec tests use the + // actual hosting writer; this unit only controls the committed source-selection ledger. + Map fields = + Map.of( + "schemaVersion", + "account-hosting-subscription-event/v1", + "eventType", + "SubscriptionStatusChanged", + "tenantBillingStateChanged", + false, + "eventTypes", + List.of("SubscriptionStatusChanged"), + "tenantId", + TENANT_ID.toString(), + "requestId", + REQUEST_ID.toString(), + "requestDigest", + requestDigest, + "tenantBillingSequence", + "1", + "eventId", + billingEventId.toString(), + "receipt", + receiptFields); + payload = Rfc8785CanonicalJson.canonicalizeUtf8(json.writeValueAsString(fields)); + digest = + "sha256:" + + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(payload)); + } else { + payload = demo.payload(); + digest = demo.eventDigest(); + billingEventId = demo.eventId(); + } + authority = + TenantAuthorityEventV1Codec.seal( + new TenantAuthorityEventV1Codec.AuthorityRequest( + REQUEST_ID, requestDigest, TENANT_ID, SOURCE_REQUEST_ID, SOURCE_REQUEST_DIGEST), + source, + 2L, + 2L, + 1L, + new TenantAuthorityEventV1Codec.BillingReceipt( + TENANT_ID, + REQUEST_ID, + requestDigest, + AccountTenantEntitlementOutboxRepository.streamKey(TENANT_ID), + 1L, + billingEventId, + digest)); + head = + projection( + Map.of( + "tenant_billing_sequence", + 1L, + "last_request_id", + REQUEST_ID, + "tenant_billing_event_id", + billingEventId, + "tenant_billing_event_digest", + digest, + "last_request_digest", + requestDigest, + "current_generation", + 2L, + "current_source_version", + 2L, + "last_outbox_sequence", + 1L, + "last_event_id", + authority.eventId().toString(), + "last_event_digest", + authority.eventDigest())); + Record billing = + projection( + Map.of( + "last_sequence", + 1L, + "tenant_billing_sequence", + 1L, + "request_id", + REQUEST_ID, + "event_id", + billingEventId, + "event_digest", + digest, + "payload", + payload)); + receipt = projection(Map.of("receipt_payload", receiptBytes)); + when(generations.read(AuthorityScope.tenant(TENANT_ID))) + .thenReturn(new ScopeState(AuthorityScope.tenant(TENANT_ID), 2L, 2L, null)); + if (hosting) + doReturn(authority).when(repository).readHostingCheckpoint(TENANT_ID, REQUEST_ID); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0, String.class); + if (sql.contains("FROM account_tenant_authority_source_records")) return head; + if (sql.contains("JOIN account_tenant_entitlement_outbox_streams")) return billing; + if (sql.contains("SELECT receipt_payload FROM subscription_lifecycle_receipts")) + return receipt; + if (sql.contains( + "SELECT canonical_tenant_id FROM account_fresh_tenant_identity_associations")) + return null; + throw new AssertionError("Unexpected source-selection SQL: " + sql); + }); + } + } + + @SuppressWarnings("unchecked") + private static Record projection(Map fields) { + Record row = mock(Record.class); + doAnswer( + invocation -> + invocation + .getArgument(1, Class.class) + .cast(fields.get(invocation.getArgument(0, String.class)))) + .when(row) + .get(anyString(), any(Class.class)); + return row; + } + private static FreshTenantCreationEvidence freshTenantEvidence() { String sourceTenantKey = "tenant-source-44444444"; String evidenceDigest = diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityHostingEventTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityHostingEventTest.java new file mode 100644 index 0000000000..532278ce15 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityHostingEventTest.java @@ -0,0 +1,313 @@ +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.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.when; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.LongFunction; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver.ObservedSubscription; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver.OperationType; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Preparation; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReconciliationLimits; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.OwnerFence; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.Answers; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** Controlled storage proves the actual producer/codec boundary, not a durable SQL commit. */ +class AccountTenantAuthorityHostingEventTest { + private static final UUID TENANT_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID CREATION_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID ATTEMPT_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final String REQUEST_DIGEST = "sha256:" + "b".repeat(64); + private static final Instant NOW = Instant.parse("2026-10-31T12:00:00Z"); + + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void lifecycleEmitsExactBillingIdentityConsumedByCanonicalTenantCodec() throws Exception { + DSLContext dsl = mock(DSLContext.class); + AccountSubscriptionIntentRepository intents = mock(AccountSubscriptionIntentRepository.class); + Record operation = mock(Record.class); + when(operation.get("state", String.class)).thenReturn("PENDING"); + when(operation.get("request_id", UUID.class)).thenReturn(REQUEST_ID); + when(operation.get("request_digest", String.class)).thenReturn(REQUEST_DIGEST); + when(operation.get("creation_request_id", UUID.class)).thenReturn(CREATION_ID); + when(operation.get("reserved_row_version", Long.class)).thenReturn(1L); + when(operation.get("last_attempt_id", UUID.class)).thenReturn(ATTEMPT_ID); + when(operation.get("provider_subscription_id", String.class)).thenReturn("sub_exact"); + when(operation.get("deadline_at", OffsetDateTime.class)) + .thenReturn(NOW.plusSeconds(60).atOffset(ZoneOffset.UTC)); + when(operation.get("observation_age_millis", Long.class)).thenReturn(15000L); + when(operation.get("warning_millis", Long.class)).thenReturn(60000L); + when(operation.get("grace_millis", Long.class)).thenReturn(120000L); + Record attempt = mock(Record.class); + when(attempt.get("started_at", OffsetDateTime.class)) + .thenReturn(NOW.minusSeconds(1).atOffset(ZoneOffset.UTC)); + when(attempt.get("expires_at", OffsetDateTime.class)) + .thenReturn(NOW.plusSeconds(10).atOffset(ZoneOffset.UTC)); + Record links = mock(Record.class); + when(links.get("lifecycle_inflight_request_id", UUID.class)).thenReturn(REQUEST_ID); + Record sourceHead = mock(Record.class); + when(sourceHead.get("current_generation", Long.class)).thenReturn(4L); + when(sourceHead.get("current_source_version", Long.class)).thenReturn(4L); + when(sourceHead.get("last_outbox_sequence", Long.class)).thenReturn(3L); + Record version = mock(Record.class); + when(version.get("next_version", Long.class)).thenReturn(8L); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0); + if (sql.contains("FROM subscription_lifecycle_operations")) { + return operation; + } + if (sql.contains("FROM subscription_lifecycle_attempts")) { + return attempt; + } + if (sql.contains("FROM subscription WHERE")) { + return links; + } + if (sql.contains("FROM account_tenant_authority_source_records")) { + return sourceHead; + } + if (sql.startsWith("SELECT greatest(")) { + return version; + } + throw new AssertionError("Unexpected producer read: " + sql); + }); + var receiptBindings = new AtomicReference(); + var reachedReceipt = new IllegalStateException("Stop after both actual event producers"); + when(dsl.execute(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0); + if (sql.startsWith("INSERT INTO subscription_lifecycle_receipts")) { + receiptBindings.set((Object[]) invocation.getRawArguments()[1]); + throw reachedReceipt; + } + return 1; + }); + + UUID subscriptionId = UUID.fromString("55555555-5555-4555-8555-555555555555"); + var owner = new OwnerFence(ATTEMPT_ID, 1L, ATTEMPT_ID); + var quote = new AccountHostingPlanQuote("basic", "price_exact", 1L, 3L, 2L, 4096L); + var original = + new AccountSubscriptionCreationRecord( + CREATION_ID, + REQUEST_DIGEST, + subscriptionId, + TENANT_ID, + owner, + "basic", + quote, + ATTEMPT_ID, + 1L, + ATTEMPT_ID, + "cus_exact", + ATTEMPT_ID, + ATTEMPT_ID, + "pending", + 1L, + NOW.minusSeconds(60)); + var current = + new AccountSubscriptionCurrentRecord( + subscriptionId, + TENANT_ID, + owner, + "basic", + quote, + ATTEMPT_ID, + 1L, + ATTEMPT_ID, + "cus_exact", + CREATION_ID, + 1L, + "pending", + null, + null, + null, + null); + when(intents.findCreation(CREATION_ID)).thenReturn(Optional.of(original)); + when(intents.lockForLifecycle(CREATION_ID, 1L)).thenReturn(current); + Preparation prepared = mock(Preparation.class); + when(prepared.requestId()).thenReturn(REQUEST_ID); + when(prepared.attemptId()).thenReturn(ATTEMPT_ID); + // Provider observation and upstream authority are controlled inputs; event encoding is real. + ObservedSubscription observed = mock(ObservedSubscription.class, Answers.RETURNS_DEEP_STUBS); + when(observed.providerSubscriptionId()).thenReturn("sub_exact"); + when(observed.providerCustomerId()).thenReturn("cus_exact"); + when(observed.providerPaymentMethodId()).thenReturn("pm_exact"); + when(observed.providerSubscriptionItemId()).thenReturn("si_exact"); + when(observed.providerPriceId()).thenReturn("price_exact"); + when(observed.providerQuantity()).thenReturn(1L); + when(observed.providerStatus()).thenReturn("active"); + when(observed.currentPeriodStart()).thenReturn(Optional.of(NOW.minusSeconds(60))); + when(observed.currentPeriodEnd()).thenReturn(Optional.of(NOW.plusSeconds(3600))); + when(observed.cancelAt()).thenReturn(Optional.empty()); + when(observed.canceledAt()).thenReturn(Optional.empty()); + when(observed.endedAt()).thenReturn(Optional.empty()); + when(observed.providerMetadata()).thenReturn(Map.of()); + when(observed.readStartedAt()).thenReturn(NOW); + when(observed.observedAt()).thenReturn(NOW); + when(observed.correlation().operationType()) + .thenReturn(OperationType.SUBSCRIPTION_PROVISIONING); + when(observed.correlation().operationId()).thenReturn(ATTEMPT_ID); + when(observed.correlation().subscriptionId()).thenReturn(subscriptionId); + FreshTenantCreationEvidence source = source(); + var prior = new ScopeState(AuthorityScope.tenant(TENANT_ID), 4L, 4L, null); + var next = new ScopeState(AuthorityScope.tenant(TENANT_ID), 5L, 5L, null); + var emittedBilling = + new AtomicReference(); + var emittedAuthority = new AtomicReference(); + try (var generationMocks = + mockConstruction( + AccountAuthorityGenerationRepository.class, + (repository, context) -> { + when(repository.read(AuthorityScope.tenant(TENANT_ID))).thenReturn(prior); + when(repository.advance(prior, null)).thenReturn(next); + }); + var sourceMocks = + mockConstruction( + FreshTenantIdentityAssociationRepository.class, + (repository, context) -> + when(repository.read(TENANT_ID)).thenReturn(Optional.of(source))); + var walletMocks = + mockConstruction( + AccountPaymentInstrumentRepository.class, + (repository, context) -> { + AccountPaymentInstrumentRecord wallet = + mock(AccountPaymentInstrumentRecord.class); + when(wallet.providerPaymentMethodId()).thenReturn("pm_exact"); + when(repository.findByOwner(owner.accountUuid(), ATTEMPT_ID)) + .thenReturn(Optional.of(wallet)); + }); + var billingMocks = + mockConstruction( + AccountTenantEntitlementOutboxRepository.class, + (repository, context) -> + when(repository.appendHosting(any(), any(), any())) + .thenAnswer( + invocation -> { + LongFunction + factory = invocation.getArgument(2); + var event = factory.apply(7L); + emittedBilling.set(event); + return event; + })); + var outboxMocks = + mockConstruction( + AccountAuthorityOutboxRepository.class, + (repository, context) -> + when(repository.append(anyString(), anyString(), any())) + .thenAnswer( + invocation -> { + LongFunction factory = + invocation.getArgument(2); + var evidence = factory.apply(4L); + emittedAuthority.set( + TenantAuthorityEventV1Codec.verify(evidence.payload())); + return new AccountAuthorityOutboxRepository.Event( + invocation.getArgument(0), + invocation.getArgument(1), + 4L, + evidence.eventId(), + evidence.eventDigest(), + evidence.payload()); + }))) { + var repository = + new AccountHostingSubscriptionLifecycleRepository( + dsl, + intents, + Clock.fixed(NOW, ZoneOffset.UTC), + new ReconciliationLimits( + 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(() -> repository.apply(prepared, observed)).isSameAs(reachedReceipt); + } + + var billing = emittedBilling.get(); + var authority = emittedAuthority.get(); + assertThat(billing).isNotNull(); + assertThat(authority).isNotNull(); + assertThat(billing.eventId) + .isEqualTo(TenantAuthorityEventV1Codec.tenantBillingEventId(REQUEST_ID)); + assertThat(authority.requestId()).isEqualTo(REQUEST_ID); + assertThat(authority.requestDigest()).isEqualTo(REQUEST_DIGEST); + assertThat(authority.sourceEvidence().requestDigest()).isNotEqualTo(REQUEST_DIGEST); + assertThat(authority.sourceEvidence()).isEqualTo(source); + assertThat(authority.tenantAuthorityGeneration()).isEqualTo(5L); + assertThat(authority.tenantAuthoritySourceVersion()).isEqualTo(5L); + assertThat(authority.outboxSequence()).isEqualTo(4L); + assertThat(authority.tenantBillingSequence()).isEqualTo(7L); + assertThat(authority.tenantBillingEventId()).isEqualTo(billing.eventId); + assertThat(authority.tenantBillingEventDigest()).isEqualTo(billing.digest()); + var billingWire = JsonMapper.builder().build().readTree(billing.payload()); + assertThat(billingWire.get("schemaVersion").asText()) + .isEqualTo("account-hosting-subscription-event/v1"); + assertThat(billingWire.get("eventId").asText()).isEqualTo(billing.eventId.toString()); + assertThat(billingWire.get("requestDigest").asText()).isEqualTo(REQUEST_DIGEST); + assertThat(receiptBindings.get()[18]).isEqualTo(7L); + assertThat(receiptBindings.get()[19]).isEqualTo(billing.eventId); + assertThat(receiptBindings.get()[20]).isEqualTo(billing.digest()); + assertThat(receiptBindings.get()[23]).isEqualTo(4L); + assertThat(receiptBindings.get()[24]).isEqualTo(authority.eventId().toString()); + assertThat(receiptBindings.get()[25]).isEqualTo(authority.eventDigest()); + } + + private static FreshTenantCreationEvidence source() { + String digest = "sha256:" + "a".repeat(64); + String evidenceDigest = + GameTenantCreationDigest.evidenceDigest( + "prod", + CREATION_ID, + ATTEMPT_ID, + digest, + TENANT_ID, + 7001L, + "tenant-source", + "NEW_GAME_ROW"); + return new FreshTenantCreationEvidence( + 1, + "prod", + CREATION_ID, + ATTEMPT_ID, + digest, + TENANT_ID, + 7001L, + "tenant-source", + "NEW_GAME_ROW", + evidenceDigest); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionTest.java new file mode 100644 index 0000000000..b31b507638 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionTest.java @@ -0,0 +1,255 @@ +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.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doCallRealMethod; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceKind; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Actual billing encoders and parsing, with controlled committed-source readback and SQL rows. */ +class AccountTenantAuthoritySourceSelectionTest { + private static final UUID TENANT = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID REQUEST = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID CREATION = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID OPERATION = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final String DIGEST = "sha256:" + "a".repeat(64); + + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void paidEnvelopeRoutesToExactHostingReceiptWithoutInterpretingRetainedDemo() { + Fixture f = new Fixture(true); + var selection = f.repository.readCurrentSourceSelection(TENANT); + assertThat(selection.kind()).isEqualTo(SourceKind.PAID_HOSTING); + assertThat(selection.matches(f.event)).isTrue(); + verify(f.repository).readHostingCheckpoint(TENANT, REQUEST); + verify(f.repository, never()).readCurrentDemoByTenant(any()); + } + + @Test + void explicitDemoEnvelopeRoutesToItsCommittedDemoSource() { + Fixture f = new Fixture(false); + assertThat(f.repository.readCurrentSourceSelection(TENANT).kind()) + .isEqualTo(SourceKind.NON_PAID_DEMO); + verify(f.repository).readCurrentDemoByTenant(TENANT); + verify(f.repository, never()).readHostingCheckpoint(any(), any()); + } + + @Test + void unknownEnvelopeFamilyFailsBeforeEitherOwningReader() { + Fixture f = new Fixture(true); + byte[] payload = + new String((byte[]) f.billing.get("payload"), java.nio.charset.StandardCharsets.UTF_8) + .replace("account-hosting-subscription-event/v1", "unknown-billing-source/v1") + .getBytes(java.nio.charset.StandardCharsets.UTF_8); + f.billing.put("payload", payload); + String digest = AccountHostingSubscriptionLifecycleEvidence.digest(payload); + f.billing.put("event_digest", digest); + f.head.put("tenant_billing_event_digest", digest); + assertThatThrownBy(() -> f.repository.readCurrentSourceSelection(TENANT)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("unknown"); + verify(f.repository, never()).readHostingCheckpoint(any(), any()); + verify(f.repository, never()).readCurrentDemoByTenant(any()); + } + + @Test + void nonlatestBillingCheckpointAndChangedAuthorityHeadFailClosed() { + Fixture f = new Fixture(true); + f.billing.put("last_sequence", 8L); + assertThatThrownBy(() -> f.repository.readCurrentSourceSelection(TENANT)) + .hasMessageContaining("billing checkpoint"); + f.billing.put("last_sequence", 7L); + f.head.put("last_event_digest", "sha256:" + "b".repeat(64)); + assertThatThrownBy(() -> f.repository.readCurrentSourceSelection(TENANT)) + .hasMessageContaining("changed"); + } + + @Test + void rejectsTamperedPayloadAndReadOnlyOwnerTransaction() { + Fixture f = new Fixture(true); + f.billing.put("event_digest", "sha256:" + "b".repeat(64)); + f.head.put("tenant_billing_event_digest", "sha256:" + "b".repeat(64)); + assertThatThrownBy(() -> f.repository.readCurrentSourceSelection(TENANT)) + .hasMessageContaining("digest"); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertThatThrownBy(() -> f.repository.readCurrentSourceSelection(TENANT)) + .hasMessageContaining("writable"); + doCallRealMethod().when(f.repository).readCurrentDemoByTenant(TENANT); + assertThatThrownBy(() -> f.repository.readCurrentDemoByTenant(TENANT)) + .hasMessageContaining("writable"); + } + + private static final class Fixture { + private final Map head = new LinkedHashMap<>(); + private final Map billing = new LinkedHashMap<>(); + private final AccountTenantAuthorityEventRepository repository; + private final TenantAuthorityEventV1Codec.Event event; + private final byte[] hostingReceipt; + + private Fixture(boolean paid) { + var source = + new FreshTenantCreationEvidence( + 1, + "prod", + CREATION, + OPERATION, + DIGEST, + TENANT, + 71L, + "tenant", + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "prod", CREATION, OPERATION, DIGEST, TENANT, 71L, "tenant", "NEW_GAME_ROW")); + byte[] payload; + String requestDigest; + UUID billingId; + String billingDigest; + if (paid) { + // Controlled committed-receipt projection, not a provider observation or paid SQL proof. + Map receipt = + Map.of( + "schemaVersion", + "account-hosting-current-receipt/v1", + "tenantId", + TENANT.toString(), + "requestId", + REQUEST.toString(), + "requestDigest", + DIGEST, + "hardCutoff", + false); + hostingReceipt = AccountHostingSubscriptionLifecycleEvidence.encode(receipt); + var encoded = + AccountHostingSubscriptionLifecycleEvidence.billing( + TENANT, + REQUEST, + DIGEST, + 7L, + TenantAuthorityEventV1Codec.tenantBillingEventId(REQUEST), + receipt); + payload = encoded.payload(); + requestDigest = DIGEST; + billingId = encoded.eventId; + billingDigest = encoded.digest(); + } else { + hostingReceipt = null; + var request = + new DemoTenantEntitlementRequest( + REQUEST, + TENANT, + CREATION, + DIGEST, + null, + null, + null, + true, + true, + true, + true, + new DemoTenantEntitlementRequest.Quotas(2L, 2L, 1024L)); + var encoded = DemoTenantEntitlementEventV1Codec.seal(request, source, 3L, 5L, 5L, 7L); + payload = encoded.payload(); + requestDigest = encoded.requestDigest(); + billingId = encoded.eventId(); + billingDigest = encoded.eventDigest(); + } + event = + TenantAuthorityEventV1Codec.seal( + new TenantAuthorityEventV1Codec.AuthorityRequest( + REQUEST, requestDigest, TENANT, CREATION, DIGEST), + source, + 5L, + 5L, + 4L, + new TenantAuthorityEventV1Codec.BillingReceipt( + TENANT, + REQUEST, + requestDigest, + TenantAuthorityEventV1Codec.tenantBillingStreamKey(TENANT), + 7L, + billingId, + billingDigest)); + head.put("tenant_billing_sequence", 7L); + head.put("last_request_id", REQUEST); + head.put("last_request_digest", requestDigest); + head.put("tenant_billing_event_id", billingId); + head.put("tenant_billing_event_digest", billingDigest); + head.put("current_generation", 5L); + head.put("current_source_version", 5L); + head.put("last_outbox_sequence", 4L); + head.put("last_event_id", event.eventId().toString()); + head.put("last_event_digest", event.eventDigest()); + billing.put("last_sequence", 7L); + billing.put("tenant_billing_sequence", 7L); + billing.put("request_id", REQUEST); + billing.put("event_id", billingId); + billing.put("event_digest", billingDigest); + billing.put("payload", payload); + DSLContext dsl = mock(DSLContext.class); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0); + if (sql.contains("account_tenant_authority_source_records")) return row(head); + if (sql.contains("account_tenant_entitlement_outbox_events")) return row(billing); + if (sql.contains("subscription_lifecycle_receipts")) { + return row(Map.of("receipt_payload", hostingReceipt)); + } + throw new AssertionError(sql); + }); + AccountAuthorityGenerationRepository generations = + mock(AccountAuthorityGenerationRepository.class); + when(generations.read(AccountAuthorityGenerationRepository.AuthorityScope.tenant(TENANT))) + .thenReturn( + new AccountAuthorityGenerationRepository.ScopeState( + AccountAuthorityGenerationRepository.AuthorityScope.tenant(TENANT), + 5L, + 5L, + null)); + repository = + spy( + new AccountTenantAuthorityEventRepository( + dsl, + mock(AccountAuthorityOutboxRepository.class), + mock(AccountTenantEntitlementOutboxRepository.class), + mock(FreshTenantIdentityAssociationRepository.class), + generations)); + doReturn(event).when(repository).readHostingCheckpoint(TENANT, REQUEST); + doReturn(event).when(repository).readCurrentDemoByTenant(TENANT); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } + } + + private static Record row(Map fields) { + Record record = mock(Record.class); + when(record.get(anyString(), any(Class.class))) + .thenAnswer(invocation -> fields.get(invocation.getArgument(0))); + return record; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepositoryTest.java index f73645b728..2d5bb51a48 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepositoryTest.java @@ -109,6 +109,25 @@ void exactRequestReplayWithChangedPayloadRemainsAnIdempotencyConflict() { any(Object[].class)); } + @Test + void sharedCheckpointPreservesTheExactDemoEventAndTypedDemoReader() { + DSLContext dsl = mock(DSLContext.class); + Event committed = event(true); + doReturn(streamProjection(1L), eventProjection(committed), eventProjection(committed)) + .when(dsl) + .fetchOne(anyString(), any(Object[].class)); + var repository = new AccountTenantEntitlementOutboxRepository(dsl); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThat(repository.readCheckpoint(TENANT_ID)) + .contains( + new AccountTenantEntitlementOutboxRepository.Checkpoint( + committed.outboxStreamKey(), 1L, committed.eventId(), committed.eventDigest())); + assertThat(repository.readEvent(TENANT_ID, 1L).orElseThrow().payload()) + .containsExactly(committed.payload()); + verify(dsl, never()).execute(anyString(), any(Object[].class)); + } + private static Event event(boolean gameplayAvailable) { FreshTenantCreationEvidence source = sourceEvidence(); DemoTenantEntitlementRequest request = @@ -162,13 +181,16 @@ private static Record streamProjection(long sequence) { } private static Record eventProjection(Event event) { + var tenant = DSL.field("tenant_uuid", UUID.class); var sequence = DSL.field("tenant_billing_sequence", Long.class); var requestId = DSL.field("request_id", UUID.class); var eventId = DSL.field("event_id", UUID.class); var digest = DSL.field("event_digest", String.class); var payload = DSL.field("payload", byte[].class); Record projection = - DSL.using(SQLDialect.POSTGRES).newRecord(sequence, requestId, eventId, digest, payload); + DSL.using(SQLDialect.POSTGRES) + .newRecord(tenant, sequence, requestId, eventId, digest, payload); + projection.set(tenant, event.canonicalTenantId()); projection.set(sequence, event.tenantBillingSequence()); projection.set(requestId, event.requestId()); projection.set(eventId, event.eventId()); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java new file mode 100644 index 0000000000..7964545d21 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java @@ -0,0 +1,910 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +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 io.grpc.Status; +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jws; +import io.jsonwebtoken.JwtException; +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.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient.ClientUnavailableException; +import net.firedevops.firemud.accountservice.config.AccountTokenProperties; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +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.repository.AccountRepository; +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.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.AccountCanonicalPublicRealmScopeOwner; +import net.firedevops.firemud.accountservice.service.AccountPublicBootstrapEntitlementOwner; +import net.firedevops.firemud.accountservice.service.AccountPublicBootstrapEntitlementOwner.Evaluation; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.session.AccountPlayerBootstrapCallerVerifier; +import net.firedevops.firemud.accountservice.service.session.SessionService; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.DiscoveryRequest; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.OriginKind; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; +import net.firedevops.firemud.common.security.JwtClaims; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +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.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Real local JWT signing/verifier with controlled Account/GS/entitlement/transaction sources. These + * tests prove orchestration and refusal, not SQL rollback, mTLS provenance, issuer custody, + * registry durability, a World hold or gameplay admission. + */ +class AccountCanonicalPublicRealmScopeOwnerTest { + 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 long PRIVATE_ACCOUNT = 41L; + private static final String NAMESPACE = "prod"; + private static final String HASH = "a".repeat(64); + + @AfterEach + void clearContexts() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void genuineAbsenceAndClosedEnrollmentStillProduceOnlyACanonicalPublicSelectorScope() { + Fixture f = new Fixture(300000L); + + var result = f.owner.listRealmScopes(f.token, "tenant", "world").getFirst(); + + assertThat(result.target()).isEqualTo(f.target); + assertThat(result.membership().accountId()).isEqualTo(ACCOUNT); + assertThat(result.membership().tenantId()).isEqualTo(TENANT); + assertThat(result.membership().current()).isEmpty(); + assertThat(result.entitlement()).isSameAs(f.evaluation); + assertThat(result.entitlement().allowPublicJoin()).isFalse(); + var scope = result.scope(); + assertThat(scope.accountId()).isEqualTo(ACCOUNT); + assertThat(scope.tenantId()).isEqualTo(TENANT); + assertThat(scope.gameInstanceId()).isEqualTo(f.target.canonicalGameInstanceId()); + assertThat(scope.playableStateScope()).isEqualTo("SHARED"); + var signed = f.jwt.parseToken(scope.connectScopeId()).getPayload(); + assertThat(signed.getSubject()).isEqualTo(ACCOUNT.toString()); + assertThat(signed.get("accountId")).isEqualTo(ACCOUNT.toString()); + assertThat(JwtClaims.requireText(signed.get("aud"), "aud")) + .isEqualTo("bootstrap-connect-scope"); + assertThat(signed.get("tenantId")).isEqualTo(TENANT.toString()); + assertThat(signed.get("gameInstanceId")) + .isEqualTo(f.target.canonicalGameInstanceId().toString()); + assertThat(signed.get("evaluatedAt")).isEqualTo(scope.evaluatedAt()); + assertThat(signed.getExpiration().toInstant()) + .isEqualTo(Instant.parse(scope.connectScopeExpiresAt())); + assertThat(f.retainedEvidence.get().scopeDigest()).isEqualTo(AccountJoinDigest.scopeV2(scope)); + assertThat(f.retainedEvidence.get().tenantProvenance()).isEqualTo(f.provenance()); + assertThat(result.toString()).doesNotContain(scope.connectScopeId(), f.token); + assertThat(f.transactions.commits).isEqualTo(2); + assertThat(f.registryChecks.get()).isEqualTo(3); + verify(f.scopes).insertCanonical(PRIVATE_ACCOUNT, scope, f.provenance()); + verify(f.memberships, never()).createFreshMembershipForJoin(any(), any()); + } + + @ParameterizedTest + @ValueSource(strings = {"ACTIVE", "INACTIVE"}) + void closedEnrollmentPreservesCurrentMembershipFactsWithoutRepairOrAdmission(String lifecycle) { + Fixture f = new Fixture(300000L); + AccountTenantMembership membership = f.membership(lifecycle); + f.member.set(Optional.of(membership)); + + var result = f.owner.listRealmScopes(f.token, "tenant", "world").getFirst(); + + var current = result.membership().current().orElseThrow(); + assertThat(current.lifecycleState()).isEqualTo(lifecycle); + assertThat(current.gameplayAdmissionAllowed()).isEqualTo(lifecycle.equals("ACTIVE")); + assertThat(current.membershipVersion()).isEqualTo(7L); + assertThat(current.membershipAuthorityGeneration()).isEqualTo(3L); + assertThat(result.entitlement().allowPublicJoin()).isFalse(); + verify(f.memberships, never()).createFreshMembershipForJoin(any(), any()); + } + + @Test + void scopeExpiryIsCappedByTheActualBootstrapExpiryAndSignedExactly() { + Fixture f = new Fixture(60000L); + var bootstrapExpiry = f.jwt.parseToken(f.token).getPayload().getExpiration().toInstant(); + + var scope = f.owner.listRealmScopes(f.token, "tenant", "world").getFirst().scope(); + + assertThat(Instant.parse(scope.connectScopeExpiresAt())).isEqualTo(bootstrapExpiry); + assertThat(f.jwt.absoluteExpiration).isEqualTo(bootstrapExpiry); + assertThat(f.jwt.parseToken(scope.connectScopeId()).getPayload().getExpiration().toInstant()) + .isEqualTo(bootstrapExpiry); + } + + @Test + void callerAuthenticationPrecedesAllTargetAndAccountSourceWork() { + Fixture f = new Fixture(300000L); + + assertCode( + "CONNECT_CONTEXT_INVALID", () -> f.owner.listRealmScopes("malformed", "tenant", "world")); + + verifyNoInteractions(f.targets, f.entitlements, f.tenants, f.heads, f.memberships, f.scopes); + assertThat(f.transactions.started).isZero(); + } + + @Test + void invalidJwtFromScopeOwnerParsingIsMappedWithoutCause() { + Fixture f = new Fixture(300000L); + f.jwt.ownerParseFailure = new JwtException("invalid bootstrap JWT"); + + assertThatThrownBy(() -> f.owner.listRealmScopes(f.token, "tenant", "world")) + .isInstanceOf(AuthenticationException.class) + .satisfies( + failure -> { + assertThat(((AuthenticationException) failure).getCode()) + .isEqualTo("CONNECT_CONTEXT_INVALID"); + assertThat(failure.getCause()).isNull(); + }); + } + + @Test + void operationalBootstrapCallerFailureIsRetainedAsUnavailableCause() { + Fixture f = new Fixture(300000L); + RuntimeException failure = new IllegalStateException("caller authority unavailable"); + doThrow(failure).when(f.sessions).isAccountSessionActive(PRIVATE_ACCOUNT, f.token); + + assertThatThrownBy(() -> f.owner.listRealmScopes(f.token, "tenant", "world")) + .isInstanceOf(AuthenticationException.class) + .satisfies( + wrapped -> { + assertThat(((AuthenticationException) wrapped).getCode()) + .isEqualTo("AUTH_UNAVAILABLE"); + assertThat(wrapped.getCause()).isSameAs(failure); + }); + } + + @Test + void absoluteExpirySigningFailureIsRetainedAsUnavailableCause() { + Fixture f = new Fixture(300000L); + IllegalArgumentException failure = new IllegalArgumentException("signing expiry unavailable"); + f.jwt.absoluteExpiryFailure = failure; + + assertThatThrownBy(() -> f.owner.listRealmScopes(f.token, "tenant", "world")) + .isInstanceOf(AuthenticationException.class) + .satisfies( + wrapped -> { + assertThat(((AuthenticationException) wrapped).getCode()) + .isEqualTo("AUTH_UNAVAILABLE"); + assertThat(wrapped.getCause()).isSameAs(failure); + }); + } + + @Test + void bootstrapExpiryAtTheOwnerClockRefusesBeforeTargetOrScopeSources() { + Fixture f = new Fixture(300000L); + f.clock.offset.set(Duration.ofSeconds(301)); + + assertCode( + "CONNECT_CONTEXT_INVALID", () -> f.owner.listRealmScopes(f.token, "tenant", "world")); + + verifyNoInteractions(f.targets, f.entitlements, f.scopes, f.memberships); + } + + @Test + void gameplayDenialOmitsTheRealmWithoutReadingOrWritingMembershipAndScopes() { + Fixture f = new Fixture(300000L); + when(f.entitlements.evaluate(TENANT)).thenReturn(f.evaluation(false)); + + assertThat(f.owner.listRealmScopes(f.token, "tenant", "world")).isEmpty(); + + verifyNoInteractions(f.memberships, f.scopes, f.tenants, f.heads); + } + + @Test + void exactTenantWorldSelectionNeverUsesABareGlobalWorldOrAnotherTenant() { + Fixture f = new Fixture(300000L); + + assertThat(f.owner.listRealmScopes(f.token, "other-tenant", "world")).isEmpty(); + + verifyNoInteractions(f.entitlements, f.memberships, f.scopes); + } + + @Test + void changedIndependentTargetReadRefusesBeforeAnyScopeWrite() { + Fixture f = new Fixture(300000L); + f.secondTarget = target(2L); + + assertCode( + "ADMISSION_POINTER_UNAVAILABLE", () -> f.owner.listRealmScopes(f.token, "tenant", "world")); + + verifyNoInteractions(f.scopes); + } + + @Test + void unavailableTransportIsNotAnEmptyRealmAndCannotRetainAScope() { + Fixture f = new Fixture(300000L); + doThrow(Status.DEADLINE_EXCEEDED.asRuntimeException()) + .when(f.targets) + .listVisiblePublicProductionAdmissionTargets(any()); + + assertCode("AUTH_UNAVAILABLE", () -> f.owner.listRealmScopes(f.token, "tenant", "world")); + + verifyNoInteractions(f.entitlements, f.scopes); + } + + @Test + void typedClientLifecycleAndUnavailableTransportRefuseBeforeScopeOrEntitlementSources() { + for (RuntimeException failure : + List.of( + new ClientUnavailableException(new IllegalStateException()), + Status.UNAVAILABLE.asRuntimeException(), + Status.DEADLINE_EXCEEDED.asRuntimeException(), + Status.CANCELLED.asRuntimeException(), + Status.ABORTED.asRuntimeException())) { + Fixture f = new Fixture(300000L); + doThrow(failure).when(f.targets).listVisiblePublicProductionAdmissionTargets(any()); + + assertCode("AUTH_UNAVAILABLE", () -> f.owner.listRealmScopes(f.token, "tenant", "world")); + + verifyNoInteractions(f.entitlements, f.tenants, f.heads, f.memberships, f.scopes); + assertThat(f.transactions.started).isZero(); + } + } + + @Test + void malformedUnsupportedAndOtherSemanticSourceFailuresCannotRetainAScope() { + for (RuntimeException failure : + List.of( + new IllegalStateException("Malformed or mismatched source response"), + new IllegalArgumentException("Unsupported source value"), + new IllegalStateException( + "Malformed source content", Status.UNAVAILABLE.asRuntimeException()), + Status.RESOURCE_EXHAUSTED + .withDescription("gRPC message exceeds maximum size") + .asRuntimeException(), + Status.INVALID_ARGUMENT.asRuntimeException(), + Status.FAILED_PRECONDITION.asRuntimeException(), + Status.UNIMPLEMENTED.asRuntimeException(), + Status.PERMISSION_DENIED.asRuntimeException())) { + Fixture f = new Fixture(300000L); + doThrow(failure).when(f.targets).listVisiblePublicProductionAdmissionTargets(any()); + + assertCode( + "ADMISSION_POINTER_UNAVAILABLE", + () -> f.owner.listRealmScopes(f.token, "tenant", "world")); + + verifyNoInteractions(f.entitlements, f.tenants, f.heads, f.memberships, f.scopes); + assertThat(f.transactions.started).isZero(); + } + } + + @Test + void changedBillingHeadRefusesRatherThanRefreshingTheOriginalEntitlement() { + Fixture f = new Fixture(300000L); + doReturn(f.head, new SourceSelection(SourceKind.NON_PAID_DEMO, f.event(2L))) + .when(f.heads) + .readCurrentSourceSelection(TENANT); + + assertCode( + "ENTITLEMENT_UNAVAILABLE", () -> f.owner.listRealmScopes(f.token, "tenant", "world")); + + verify(f.entitlements).evaluate(TENANT); + verifyNoInteractions(f.scopes); + } + + @Test + void missingTenantSourceAndMalformedMembershipAreNotConvertedToGenuineAbsence() { + Fixture missingSource = new Fixture(300000L); + doReturn(Optional.empty()).when(missingSource.tenants).read(TENANT); + assertCode( + "AUTH_UNAVAILABLE", + () -> missingSource.owner.listRealmScopes(missingSource.token, "tenant", "world")); + verifyNoInteractions(missingSource.scopes); + + Fixture malformed = new Fixture(300000L); + AccountTenantMembership member = malformed.membership("ACTIVE"); + member.setMembershipAuthorityGeneration(0L); + malformed.member.set(Optional.of(member)); + assertCode( + "AUTH_UNAVAILABLE", + () -> malformed.owner.listRealmScopes(malformed.token, "tenant", "world")); + verifyNoInteractions(malformed.scopes); + } + + @Test + void changedMembershipAndAccountStateRefuseBeforeSigningOrRetainingScope() { + Fixture changedMember = new Fixture(300000L); + changedMember.onSecondTargetRead = + () -> changedMember.member.set(Optional.of(changedMember.membership("ACTIVE"))); + assertCode( + "AUTH_UNAVAILABLE", + () -> changedMember.owner.listRealmScopes(changedMember.token, "tenant", "world")); + verifyNoInteractions(changedMember.scopes); + + Fixture changedAccount = new Fixture(300000L); + changedAccount.onSecondTargetRead = + () -> + changedAccount.account.setLifecycleState( + AccountLifecycleState.DEACTIVATED_PENDING_DELETE); + assertCode( + "AUTH_UNAVAILABLE", + () -> changedAccount.owner.listRealmScopes(changedAccount.token, "tenant", "world")); + verifyNoInteractions(changedAccount.scopes); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void registryLossBeforePersistenceOrDuringCommitNeverPublishesScope(boolean duringCommit) { + Fixture f = new Fixture(300000L); + if (duringCommit) f.transactions.afterFinalCommit = () -> f.active.set(false); + else f.onSecondTargetRead = () -> f.active.set(false); + + assertCode( + "CONNECT_CONTEXT_INVALID", () -> f.owner.listRealmScopes(f.token, "tenant", "world")); + + if (!duringCommit) verifyNoInteractions(f.scopes); + else assertThat(f.transactions.commits).isEqualTo(2); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void entitlementExpiryBeforePersistenceOrDuringCommitCannotBeRestamped(boolean duringCommit) { + Fixture f = new Fixture(300000L); + if (duringCommit) + f.transactions.afterFinalCommit = () -> f.clock.offset.set(Duration.ofSeconds(20)); + else f.onSecondTargetRead = () -> f.clock.offset.set(Duration.ofSeconds(20)); + + assertCode( + "ENTITLEMENT_UNAVAILABLE", () -> f.owner.listRealmScopes(f.token, "tenant", "world")); + + verify(f.entitlements).evaluate(TENANT); + if (!duringCommit) verifyNoInteractions(f.scopes); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void alteredV2ScopeOrDigestReadbackProducesNoReturnedValue(boolean digestOnly) { + Fixture f = new Fixture(300000L); + f.corruptReadback = !digestOnly; + f.corruptDigest = digestOnly; + + assertCode("AUTH_UNAVAILABLE", () -> f.owner.listRealmScopes(f.token, "tenant", "world")); + + assertThat(f.transactions.rollbacks).isEqualTo(1); + } + + @Test + void failedFinalCommitDoesNotExposeTheSignedSelector() { + Fixture f = new Fixture(300000L); + f.transactions.failFinalCommit = true; + + assertCode("AUTH_UNAVAILABLE", () -> f.owner.listRealmScopes(f.token, "tenant", "world")); + + assertThat(f.transactions.commitAttempts).isEqualTo(2); + } + + @Test + void ambientSqlAndPlayerContextRefuseWithoutClearingContextOrReadingSources() { + Fixture f = new Fixture(300000L); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> f.owner.listRealmScopes(f.token, "tenant", "world")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient SQL"); + TransactionSynchronizationManager.clear(); + SessionContext.setContext(ACCOUNT.toString(), List.of(), Map.of()); + assertThatThrownBy(() -> f.owner.listRealmScopes(f.token, "tenant", "world")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("workload-only"); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isTrue(); + verifyNoInteractions(f.targets, f.entitlements, f.scopes); + } + + private static void assertCode(String expected, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(AuthenticationException.class) + .extracting(failure -> ((AuthenticationException) failure).getCode()) + .isEqualTo(expected); + } + + private static final class Fixture { + private final AccountRepository accounts = mock(AccountRepository.class); + private final AccountTenantMembershipRepository memberships = + mock(AccountTenantMembershipRepository.class); + private final FreshTenantIdentityAssociationRepository tenants = + mock(FreshTenantIdentityAssociationRepository.class); + private final AccountTenantAuthorityEventRepository heads = + mock(AccountTenantAuthorityEventRepository.class); + private final AccountConnectScopeRepository scopes = mock(AccountConnectScopeRepository.class); + private final CanonicalGameplayAdmissionDecisionReadClient targets = + mock(CanonicalGameplayAdmissionDecisionReadClient.class); + private final AccountPublicBootstrapEntitlementOwner entitlements = + mock(AccountPublicBootstrapEntitlementOwner.class); + private final SessionService sessions = mock(SessionService.class); + private final RecordingJwtUtil jwt = + new RecordingJwtUtil("controlled-local-canonical-scope-key-01234567890123456789", 300000L); + private final AtomicBoolean active = new AtomicBoolean(true); + private final AtomicInteger registryChecks = new AtomicInteger(); + private final AtomicInteger targetReads = new AtomicInteger(); + private final AtomicReference> member = + new AtomicReference<>(Optional.empty()); + private final AtomicReference retained = new AtomicReference<>(); + private final AtomicReference retainedEvidence = + new AtomicReference<>(); + private final RecordingTransactions transactions = new RecordingTransactions(); + private final OffsetClock clock = new OffsetClock(); + private final FreshTenantCreationEvidence source = source(); + private final SourceSelection head = new SourceSelection(SourceKind.NON_PAID_DEMO, event(1L)); + private final Account account = account(); + private final Target target = target(1L); + private final Evaluation evaluation = evaluation(true); + private final String token; + private final AccountCanonicalPublicRealmScopeOwner owner; + private Target secondTarget = target; + private Runnable onSecondTargetRead = () -> {}; + private boolean corruptReadback; + private boolean corruptDigest; + + private Fixture(long bootstrapLifetime) { + token = + jwt.generateToken( + ACCOUNT.toString(), + bootstrapLifetime, + Map.of( + "aud", + "player-bootstrap", + "accountId", + ACCOUNT.toString(), + "jti", + UUID.randomUUID().toString())); + when(accounts.findByAccountUuid(ACCOUNT)) + .thenAnswer( + invocation -> { + assertOutsideSql(); + return Optional.of(account); + }); + when(accounts.findByAccountUuidForUpdate(ACCOUNT)) + .thenAnswer( + invocation -> { + assertInsideSql(); + return Optional.of(account); + }); + when(sessions.isAccountSessionActive(PRIVATE_ACCOUNT, token)) + .thenAnswer( + invocation -> { + assertOutsideSql(); + registryChecks.incrementAndGet(); + return active.get(); + }); + when(tenants.read(TENANT)) + .thenAnswer( + invocation -> { + assertInsideSql(); + return Optional.of(source); + }); + when(heads.readCurrentSourceSelection(TENANT)) + .thenAnswer( + invocation -> { + assertInsideSql(); + return head; + }); + when(memberships.findFreshMembershipForUpdate(ACCOUNT, TENANT)) + .thenAnswer( + invocation -> { + assertInsideSql(); + return member.get(); + }); + when(entitlements.evaluate(TENANT)) + .thenAnswer( + invocation -> { + assertOutsideSql(); + return evaluation; + }); + when(targets.listVisiblePublicProductionAdmissionTargets(any())) + .thenAnswer( + invocation -> { + assertOutsideSql(); + int count = targetReads.incrementAndGet(); + if (count == 2) onSecondTargetRead.run(); + var request = + new DiscoveryRequest(invocation.getArgument(0, UUID.class), NAMESPACE); + List values = List.of(count == 1 ? target : secondTarget); + return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + request, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( + request, values)); + }); + doAnswer( + invocation -> { + assertInsideSql(); + CanonicalJoinScopeV2 scope = invocation.getArgument(1); + retained.set(scope); + retainedEvidence.set(evidence(scope)); + return null; + }) + .when(scopes) + .insertCanonical(anyLong(), any(), any()); + when(scopes.findCanonical(any())) + .thenAnswer( + invocation -> { + assertInsideSql(); + CanonicalJoinScopeV2 original = retained.get(); + if (corruptReadback) + return Optional.of( + new CanonicalJoinScopeV2( + original.connectScopeId(), + original.accountId(), + original.tenantId(), + UUID.randomUUID(), + original.tenantSlug(), + original.worldSlug(), + original.realmSlug(), + original.playableStateNamespaceId(), + original.playableStateScope(), + original.gameInstanceId(), + original.catalogRevision(), + original.pointerVersion(), + original.evaluatedAt(), + original.connectScopeExpiresAt())); + return Optional.of(original); + }); + when(scopes.findCanonicalEvidenceByTokenHash(any())) + .thenAnswer( + invocation -> { + assertInsideSql(); + CanonicalConnectScopeEvidence original = retainedEvidence.get(); + if (corruptDigest) + return Optional.of( + new CanonicalConnectScopeEvidence( + original.scopeTokenHash(), + original.privateAccountId(), + original.targetClass(), + original.accountUuid(), + original.tenantUuid(), + original.realmId(), + original.tenantSlug(), + original.worldSlug(), + original.realmSlug(), + original.playableStateNamespaceUuid(), + original.playableStateScope(), + original.gameInstanceUuid(), + original.catalogRevision(), + original.pointerVersion(), + original.evaluatedAt(), + original.connectScopeExpiresAt(), + 2, + "sha256:" + "b".repeat(64), + original.tenantProvenance())); + return Optional.of(original); + }); + var properties = new AccountTokenProperties(); + properties.setConnectScopeExpirationMs(120000L); + var caller = new AccountPlayerBootstrapCallerVerifier(jwt, accounts, sessions); + owner = + new AccountCanonicalPublicRealmScopeOwner( + caller, + targets, + entitlements, + accounts, + memberships, + tenants, + heads, + scopes, + jwt, + properties, + clock, + transactions, + NAMESPACE); + } + + private Evaluation evaluation(boolean gameplay) { + Instant observed = clock.instant().minusSeconds(1); + return new Evaluation( + TENANT, + SourceKind.NON_PAID_DEMO, + gameplay, + false, + 1, + 1, + observed, + observed.plusSeconds(15)); + } + + private VerifiedTenantProvenance provenance() { + return new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + source.operationId(), + source.evidenceDigest()); + } + + private CanonicalConnectScopeEvidence evidence(CanonicalJoinScopeV2 scope) { + return new CanonicalConnectScopeEvidence( + AccountJoinDigest.tokenHash(scope.connectScopeId()), + PRIVATE_ACCOUNT, + "PUBLIC_PRODUCTION", + ACCOUNT, + TENANT, + 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), + provenance()); + } + + private AccountTenantMembership membership(String lifecycle) { + AccountTenantMembership value = new AccountTenantMembership(); + value.setId(52L); + value.setAccount(account); + value.setTenantUuid(TENANT); + value.setTenantProvenanceKind(TenantProvenanceKind.FRESH_GAME_DESIGN.name()); + value.setTenantSourceOperationId(source.operationId()); + value.setTenantProvenanceDigest(source.evidenceDigest()); + value.setLifecycleState(lifecycle); + value.setGameplayAdmissionAllowed(lifecycle.equals("ACTIVE")); + value.setMembershipVersion(7L); + value.setMembershipAuthorityGeneration(3L); + return value; + } + + private TenantAuthorityEventV1Codec.Event event(long sequence) { + 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), + sequence, + TenantAuthorityEventV1Codec.tenantBillingEventId(requestId), + "sha256:" + HASH); + return TenantAuthorityEventV1Codec.seal( + request, source, sequence + 1, sequence + 1, sequence, receipt); + } + } + + private static Account account() { + Account account = new Account(); + account.setId(PRIVATE_ACCOUNT); + account.setAccountUuid(ACCOUNT); + account.setAccountUuidSourceNumericId(PRIVATE_ACCOUNT); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + account.setLifecycleState(AccountLifecycleState.ACTIVE); + return account; + } + + private static FreshTenantCreationEvidence source() { + UUID creation = UUID.randomUUID(); + UUID operation = UUID.randomUUID(); + String digest = + GameTenantCreationDigest.requestDigest( + NAMESPACE, creation, "controlled-world", "World", null); + return new FreshTenantCreationEvidence( + 1, + NAMESPACE, + creation, + operation, + digest, + TENANT, + 91L, + "controlled-world", + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + NAMESPACE, + creation, + operation, + digest, + TENANT, + 91L, + "controlled-world", + "NEW_GAME_ROW")); + } + + private static Target target(long pointer) { + UUID realm = UUID.randomUUID(); + UUID playableNamespace = UUID.randomUUID(); + UUID instance = UUID.randomUUID(); + UUID version = UUID.randomUUID(); + UUID holdId = UUID.randomUUID(); + UUID holdFence = UUID.randomUUID(); + String initial = UUID.randomUUID().toString(); + var request = + new WorldCanonicalInitialAdmissionHold.Request( + NAMESPACE, + TENANT, + "world", + realm, + playableNamespace, + "SHARED", + instance, + version, + 1, + initial, + HASH, + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + 1, + null); + var hold = new WorldCanonicalInitialAdmissionHold.HoldIdentity(request, holdId, holdFence); + return new Target( + NAMESPACE, + "tenant", + TENANT, + "world", + "World", + realm, + "main", + "Main", + 11, + 44, + playableNamespace, + "SHARED", + instance, + version, + 1, + 1, + pointer, + HASH, + 1, + initial, + HASH, + OriginKind.NO_PRIOR_POINTER, + null, + holdId, + holdFence, + hold.holdBindingDigest(), + 1, + "sha256:" + HASH, + OwnerProofOutcome.COMMITTED, + false, + Instant.now(), + "PRESEEDED_ONLY"); + } + + private static void assertOutsideSql() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } + + private static void assertInsideSql() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + } + + private static final class RecordingTransactions implements PlatformTransactionManager { + private int started; + private int commitAttempts; + private int commits; + private int rollbacks; + private boolean failFinalCommit; + private Runnable afterFinalCommit = () -> {}; + + @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.isReadOnly()).isFalse(); + started++; + TransactionSynchronizationManager.setActualTransactionActive(true); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + commitAttempts++; + TransactionSynchronizationManager.setActualTransactionActive(false); + if (commitAttempts == 2 && failFinalCommit) + throw new IllegalStateException("controlled commit failure"); + commits++; + if (commitAttempts == 2) afterFinalCommit.run(); + } + + @Override + public void rollback(TransactionStatus status) { + rollbacks++; + TransactionSynchronizationManager.setActualTransactionActive(false); + } + } + + private static final class OffsetClock extends Clock { + private final AtomicReference offset = new AtomicReference<>(Duration.ZERO); + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return Clock.offset(Clock.system(zone), offset.get()); + } + + @Override + public Instant instant() { + return Instant.now().plus(offset.get()); + } + } + + private static final class RecordingJwtUtil extends JwtUtil { + private Instant absoluteExpiration; + private IllegalArgumentException absoluteExpiryFailure; + private JwtException ownerParseFailure; + private int parseCalls; + + private RecordingJwtUtil(String secret, long expirationMillis) { + super(secret, expirationMillis); + } + + @Override + public String generateToken(String subject, Instant expiresAt, Map claims) { + absoluteExpiration = expiresAt; + if (absoluteExpiryFailure != null) throw absoluteExpiryFailure; + return super.generateToken(subject, expiresAt, claims); + } + + @Override + public Jws parseToken(String token) { + if (++parseCalls == 2 && ownerParseFailure != null) throw ownerParseFailure; + return super.parseToken(token); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleServiceTest.java new file mode 100644 index 0000000000..da86c5f95e --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleServiceTest.java @@ -0,0 +1,60 @@ +package net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.UUID; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountHostingSubscriptionLifecycleServiceTest { + private final AccountHostingSubscriptionLifecycleRepository repository = + mock(AccountHostingSubscriptionLifecycleRepository.class); + private final StripeHostingSubscriptionObserver observer = + mock(StripeHostingSubscriptionObserver.class); + private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + private final AccountHostingSubscriptionLifecycleService service = + new AccountHostingSubscriptionLifecycleService(repository, observer, transactions); + + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void ambientTransactionCannotSpanSdkReadOrImplicitlyCommitClaims() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertRefusal(); + verifyNoInteractions(repository, observer, transactions); + } + + @Test + void ambientSynchronizationAlsoRefusesBeforeAnyProviderOrSqlCall() { + TransactionSynchronizationManager.initSynchronization(); + assertRefusal(); + verifyNoInteractions(repository, observer, transactions); + } + + private void assertRefusal() { + assertThatThrownBy(() -> service.claimProvisioning(UUID.randomUUID(), 1, UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient SQL transaction"); + assertThatThrownBy( + () -> + service.reconcile( + UUID.randomUUID(), UUID.randomUUID(), 2, "sub_controlled", UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient SQL transaction"); + assertThatThrownBy(() -> service.readCurrent(UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient SQL transaction"); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwnerTest.java new file mode 100644 index 0000000000..436c96b67f --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwnerTest.java @@ -0,0 +1,270 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +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.Arrays; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; +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.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.AccountHostingSubscriptionLifecycleService; +import net.firedevops.firemud.accountservice.service.AccountPublicBootstrapEntitlementOwner; +import net.firedevops.firemud.accountservice.service.AccountPublicBootstrapEntitlementOwner.Evaluation; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec.Event; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +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 owners exercise routing and final-transaction projection, not provider or SQL proof. + */ +class AccountPublicBootstrapEntitlementOwnerTest { + private static final UUID TENANT = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID EVENT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final String DIGEST = "sha256:" + "a".repeat(64); + private static final Instant NOW = Instant.parse("2026-11-02T00:00:00Z"); + + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void paidFactsKeepTheirActualObservationAndDeadlineWithoutReadingDemo() { + Fixture f = new Fixture(SourceKind.PAID_HOSTING); + var value = f.owner.evaluate(TENANT); + assertThat(value.sourceKind()).isEqualTo(SourceKind.PAID_HOSTING); + assertThat(value.gameplayAvailable()).isTrue(); + assertThat(value.allowPublicJoin()).isFalse(); + assertThat(value.entitlementVersion()).isEqualTo(3L); + assertThat(value.evaluatedAt()).isEqualTo(NOW.minusSeconds(2)); + assertThat(value.validUntil()).isEqualTo(NOW.plusSeconds(4)); + verifyNoInteractions(f.demos); + assertThat(Arrays.stream(Evaluation.class.getRecordComponents()).map(c -> c.getName())) + .containsExactly( + "canonicalTenantId", + "sourceKind", + "gameplayAvailable", + "allowPublicJoin", + "entitlementVersion", + "tenantBillingSequence", + "evaluatedAt", + "validUntil"); + } + + @Test + void demoRevalidationCannotRenewTheOriginalObservationDeadline() { + Fixture f = new Fixture(SourceKind.NON_PAID_DEMO); + when(f.demos.revalidate(f.demo)) + .thenAnswer( + invocation -> { + f.time.set(NOW.plusSeconds(7)); + return f.demo; + }); + var value = f.owner.evaluate(TENANT); + assertThat(value.sourceKind()).isEqualTo(SourceKind.NON_PAID_DEMO); + assertThat(value.evaluatedAt()).isEqualTo(NOW); + assertThat(value.validUntil()).isEqualTo(NOW.plusSeconds(15)); + verifyNoInteractions(f.hosting); + } + + @Test + void changedHeadOrUnavailableSelectionReturnsNoEvaluation() { + Fixture f = new Fixture(SourceKind.PAID_HOSTING); + Event changed = mock(Event.class); + when(changed.tenantId()).thenReturn(TENANT); + when(changed.eventId()).thenReturn(UUID.fromString("33333333-3333-4333-8333-333333333333")); + when(f.sources.readCurrentSourceSelection(TENANT)) + .thenReturn(f.selection, new SourceSelection(SourceKind.PAID_HOSTING, changed)); + assertThatThrownBy(() -> f.owner.evaluate(TENANT)) + .isInstanceOf(AccountPublicBootstrapEntitlementOwner.UnavailableException.class); + verifyNoInteractions(f.demos); + when(f.sources.readCurrentSourceSelection(TENANT)) + .thenThrow(new IllegalStateException("unknown head")); + assertThatThrownBy(() -> f.owner.evaluate(TENANT)) + .isInstanceOf(AccountPublicBootstrapEntitlementOwner.UnavailableException.class); + } + + @Test + void paidFailureNeverFallsBackToRetainedDemo() { + Fixture f = new Fixture(SourceKind.PAID_HOSTING); + doThrow(new IllegalStateException("provider unavailable")) + .when(f.hosting) + .readCurrentAndCapture(eq(TENANT), any()); + assertThatThrownBy(() -> f.owner.evaluate(TENANT)) + .isInstanceOf(AccountPublicBootstrapEntitlementOwner.UnavailableException.class); + verifyNoInteractions(f.demos); + } + + @Test + void expiredDemoObservationAndFinalCommitFailureExposeNoValue() { + Fixture f = new Fixture(SourceKind.NON_PAID_DEMO); + when(f.demos.revalidate(f.demo)) + .thenAnswer( + invocation -> { + f.time.set(NOW.plusSeconds(15)); + return f.demo; + }); + assertThatThrownBy(() -> f.owner.evaluate(TENANT)) + .isInstanceOf(AccountPublicBootstrapEntitlementOwner.UnavailableException.class); + Fixture failedCommit = new Fixture(SourceKind.NON_PAID_DEMO); + failedCommit.transactions.failFinalCommit = true; + assertThatThrownBy(() -> failedCommit.owner.evaluate(TENANT)) + .isInstanceOf(AccountPublicBootstrapEntitlementOwner.UnavailableException.class); + verifyNoInteractions(f.hosting, failedCommit.hosting); + } + + @Test + void sourceRefusalAndAmbientSqlFailWithoutUsingAnotherFamily() { + Fixture f = new Fixture(SourceKind.NON_PAID_DEMO); + when(f.demos.readCurrent(TENANT)).thenThrow(new IllegalStateException("stale demo")); + assertThatThrownBy(() -> f.owner.evaluate(TENANT)) + .isInstanceOf(AccountPublicBootstrapEntitlementOwner.UnavailableException.class); + verifyNoInteractions(f.hosting); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> f.owner.evaluate(TENANT)).hasMessageContaining("ambient SQL"); + } + + private static final class Fixture { + private final AccountTenantAuthorityEventRepository sources = + mock(AccountTenantAuthorityEventRepository.class); + private final AccountHostingSubscriptionLifecycleService hosting = + mock(AccountHostingSubscriptionLifecycleService.class); + private final AccountDemoTenantEntitlementRepository demos = + mock(AccountDemoTenantEntitlementRepository.class); + private final DemoTenantEntitlementSnapshot demo = mock(DemoTenantEntitlementSnapshot.class); + private final AtomicReference time = new AtomicReference<>(NOW); + private final Transactions transactions = new Transactions(); + private final SourceSelection selection; + private final AccountPublicBootstrapEntitlementOwner owner; + + private Fixture(SourceKind kind) { + Event event = mock(Event.class); + when(event.tenantId()).thenReturn(TENANT); + when(event.eventId()).thenReturn(EVENT); + when(event.eventDigest()).thenReturn(DIGEST); + when(event.payload()).thenReturn(new byte[] {1, 2}); + when(event.tenantBillingSequence()).thenReturn(7L); + when(event.tenantBillingEventId()).thenReturn(EVENT); + when(event.tenantBillingEventDigest()).thenReturn(DIGEST); + when(event.tenantAuthorityGeneration()).thenReturn(5L); + when(event.tenantAuthoritySourceVersion()).thenReturn(5L); + selection = new SourceSelection(kind, event); + when(sources.readCurrentSourceSelection(TENANT)).thenReturn(selection); + when(demo.canonicalTenantId()).thenReturn(TENANT); + when(demo.tenantBillingSequence()).thenReturn(7L); + when(demo.eventId()).thenReturn(EVENT); + when(demo.eventDigest()).thenReturn(DIGEST); + when(demo.tenantAuthorityEventId()).thenReturn(EVENT); + when(demo.tenantAuthorityEventDigest()).thenReturn(DIGEST); + when(demo.tenantAuthorityGeneration()).thenReturn(5L); + when(demo.tenantAuthoritySourceVersion()).thenReturn(5L); + when(demo.entitlementVersion()).thenReturn(3L); + when(demo.gameplayAvailable()).thenReturn(true); + when(demo.allowPublicJoin()).thenReturn(false); + when(demos.readCurrent(TENANT)).thenReturn(demo); + when(demos.revalidate(demo)).thenReturn(demo); + AccountSubscriptionCurrentRecord current = mock(AccountSubscriptionCurrentRecord.class); + when(current.tenantId()).thenReturn(TENANT); + var receipt = + new AccountHostingSubscriptionCurrentReceipt( + current, + EVENT, + null, + true, + false, + false, + false, + 3L, + 7L, + EVENT, + DIGEST, + event, + "active", + null, + null, + false, + null, + null, + NOW.minusSeconds(2), + NOW.plusSeconds(4)); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + Function capture = + invocation.getArgument(1); + TransactionStatus status = transactions.getTransaction(definition()); + try { + Evaluation result = capture.apply(receipt); + transactions.commit(status); + return result; + } catch (RuntimeException exception) { + transactions.rollback(status); + throw exception; + } + }) + .when(hosting) + .readCurrentAndCapture(eq(TENANT), any()); + Clock clock = mock(Clock.class); + when(clock.instant()).thenAnswer(invocation -> time.get()); + when(clock.getZone()).thenReturn(ZoneOffset.UTC); + owner = + new AccountPublicBootstrapEntitlementOwner(sources, hosting, demos, transactions, clock); + } + } + + private static TransactionDefinition definition() { + var definition = new org.springframework.transaction.support.DefaultTransactionDefinition(); + definition.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + return definition; + } + + private static final class Transactions implements PlatformTransactionManager { + private int commits; + private boolean failFinalCommit; + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + TransactionDefinition actual = + definition == null ? TransactionDefinition.withDefaults() : definition; + assertThat(actual.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_SERIALIZABLE); + assertThat(actual.isReadOnly()).isFalse(); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + TransactionSynchronizationManager.setActualTransactionActive(false); + if (++commits == 2 && failFinalCommit) throw new IllegalStateException("commit failed"); + } + + @Override + public void rollback(TransactionStatus status) { + 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 new file mode 100644 index 0000000000..f66f27186a --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java @@ -0,0 +1,505 @@ +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.mock; +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.Status; +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jws; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Optional; +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.AtomicReference; +import java.util.stream.IntStream; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient.ClientUnavailableException; +import net.firedevops.firemud.accountservice.dto.BootstrapWorldDto; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceKind; +import net.firedevops.firemud.accountservice.service.AccountPublicBootstrapEntitlementOwner; +import net.firedevops.firemud.accountservice.service.AccountPublicBootstrapEntitlementOwner.Evaluation; +import net.firedevops.firemud.accountservice.service.AccountPublicBootstrapWorldsOwner; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.session.AccountPlayerBootstrapCallerVerifier; +import net.firedevops.firemud.accountservice.service.session.SessionService; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.OriginKind; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.VisiblePublicProductionTargets; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.security.SessionContext; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Controlled owner composition; no genuine JWT custody, Game Session transport, or PostgreSQL. */ +class AccountPublicBootstrapWorldsOwnerTest { + private static final Instant NOW = Instant.parse("2026-11-02T00:00:00Z"); + private static final UUID ACCOUNT_UUID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_A = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID TENANT_B = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final long ACCOUNT_ID = 41L; + private static final String TOKEN = "controlled-bootstrap-token"; + + @AfterEach + void clearThreadContexts() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void returnsSortedPublicWorldsAfterCompleteStableReorderedSourceAndFinalCallerCheck() { + Fixture f = new Fixture(); + Target zulu = target(TENANT_A, "tenant-a", "zulu", "Zulu", 1); + Target alpha = target(TENANT_B, "tenant-b", "alpha", "Alpha", 1); + f.stubTargetReads(List.of(zulu, alpha), List.of(alpha, zulu)); + 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))); + + List worlds = f.owner.listWorlds(TOKEN); + + assertThat(worlds) + .containsExactly( + new BootstrapWorldDto("alpha", "Alpha"), new BootstrapWorldDto("zulu", "Zulu")); + verify(f.targets, times(2)).listVisiblePublicProductionAdmissionTargets(any()); + verify(f.entitlements).evaluate(TENANT_A); + verify(f.entitlements).evaluate(TENANT_B); + verify(f.accounts, times(2)).findByAccountUuid(ACCOUNT_UUID); + verify(f.sessions, times(2)).isAccountSessionActive(ACCOUNT_ID, TOKEN); + } + + @Test + void denialFiltersGameplayUnavailableTenantButDoesNotRequireJoinEligibility() { + Fixture f = new Fixture(); + Target denied = target(TENANT_A, "tenant-a", "closed", "Closed", 1); + f.stubTargetReads(List.of(denied), List.of(denied)); + when(f.entitlements.evaluate(TENANT_A)) + .thenReturn( + new Evaluation( + TENANT_A, SourceKind.NON_PAID_DEMO, false, true, 1, 1, NOW, NOW.plusSeconds(30))); + + assertThat(f.owner.listWorlds(TOKEN)).isEmpty(); + + verify(f.targets, times(2)).listVisiblePublicProductionAdmissionTargets(any()); + verify(f.entitlements).evaluate(TENANT_A); + verify(f.accounts, times(2)).findByAccountUuid(ACCOUNT_UUID); + } + + @Test + void changedCompleteTargetRefusesTheWholeList() { + Fixture f = new Fixture(); + Target original = target(TENANT_A, "tenant-a", "world", "World", 1); + Target changedPointer = target(TENANT_A, "tenant-a", "world", "World", 2); + f.stubTargetReads(List.of(original), List.of(changedPointer)); + when(f.entitlements.evaluate(TENANT_A)) + .thenReturn(evaluation(TENANT_A, true, NOW.plusSeconds(30))); + + assertCode("ADMISSION_POINTER_UNAVAILABLE", () -> f.owner.listWorlds(TOKEN)); + + verify(f.accounts).findByAccountUuid(ACCOUNT_UUID); + } + + @Test + void ambiguousWorldSlugAcrossTenantsRefusesWithoutReturningEitherWorld() { + Fixture f = new Fixture(); + Target first = target(TENANT_A, "tenant-a", "same-slug", "First", 1); + Target second = target(TENANT_B, "tenant-b", "same-slug", "Second", 1); + f.stubTargetReads(List.of(first, second), List.of(second, first)); + 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))); + + assertCode("ADMISSION_POINTER_UNAVAILABLE", () -> f.owner.listWorlds(TOKEN)); + } + + @Test + void expiredEntitlementDuringFinalCollectionReadRefusesTheWholeList() { + Fixture f = new Fixture(); + Target target = target(TENANT_A, "tenant-a", "world", "World", 1); + when(f.targets.listVisiblePublicProductionAdmissionTargets(any())) + .thenAnswer( + invocation -> { + f.readCount++; + if (f.readCount == 1) return f.evidence(List.of(target)); + f.time.set(NOW.plusSeconds(15)); + return f.evidence(List.of(target)); + }); + when(f.entitlements.evaluate(TENANT_A)) + .thenReturn(evaluation(TENANT_A, true, NOW.plusSeconds(15))); + + assertCode("ENTITLEMENT_UNAVAILABLE", () -> f.owner.listWorlds(TOKEN)); + } + + @Test + void changedCallerIdentityDuringSourceReadsRefusesTheWholeList() { + Fixture f = new Fixture(); + Target target = target(TENANT_A, "tenant-a", "world", "World", 1); + f.stubTargetReads(List.of(target), List.of(target)); + when(f.entitlements.evaluate(TENANT_A)) + .thenReturn(evaluation(TENANT_A, true, NOW.plusSeconds(30))); + when(f.accounts.findByAccountUuid(ACCOUNT_UUID)) + .thenReturn(Optional.of(account(ACCOUNT_ID)), Optional.of(account(ACCOUNT_ID + 1))); + when(f.sessions.isAccountSessionActive(ACCOUNT_ID + 1, TOKEN)).thenReturn(true); + + assertCode("CONNECT_CONTEXT_INVALID", () -> f.owner.listWorlds(TOKEN)); + + verify(f.accounts, times(2)).findByAccountUuid(ACCOUNT_UUID); + verify(f.sessions).isAccountSessionActive(ACCOUNT_ID, TOKEN); + verify(f.sessions).isAccountSessionActive(ACCOUNT_ID + 1, TOKEN); + } + + @Test + void entitlementSourceFailureIsNotReplacedWithAnotherSourceOrPartialSuccess() { + Fixture f = new Fixture(); + Target target = target(TENANT_A, "tenant-a", "world", "World", 1); + f.stubTargetReads(List.of(target), List.of(target)); + when(f.entitlements.evaluate(TENANT_A)) + .thenThrow( + new AccountPublicBootstrapEntitlementOwner.UnavailableException( + new IllegalStateException("source unavailable"))); + + assertCode("ENTITLEMENT_UNAVAILABLE", () -> f.owner.listWorlds(TOKEN)); + + verify(f.targets, times(1)).listVisiblePublicProductionAdmissionTargets(any()); + } + + @Test + void unreachableGameSessionAuthorityIsAuthUnavailable() { + for (Status failure : + new Status[] { + Status.UNAVAILABLE, Status.DEADLINE_EXCEEDED, Status.CANCELLED, Status.ABORTED + }) { + Fixture f = new Fixture(); + when(f.targets.listVisiblePublicProductionAdmissionTargets(any())) + .thenThrow(failure.asRuntimeException()); + assertCode("AUTH_UNAVAILABLE", () -> f.owner.listWorlds(TOKEN)); + verify(f.entitlements, never()).evaluate(any()); + } + } + + @Test + void typedClientLifecycleFailureIsUnavailableWithoutReadingEntitlements() { + Fixture f = new Fixture(); + when(f.targets.listVisiblePublicProductionAdmissionTargets(any())) + .thenThrow(new ClientUnavailableException(new IllegalStateException())); + + assertCode("AUTH_UNAVAILABLE", () -> f.owner.listWorlds(TOKEN)); + + verifyNoInteractions(f.entitlements); + } + + @Test + void malformedUnsupportedAndOtherSemanticSourceFailuresRemainPointerUnavailable() { + for (RuntimeException failure : + List.of( + new IllegalStateException("Malformed or mismatched source response"), + new IllegalArgumentException("Unsupported source value"), + new IllegalStateException( + "Malformed source content", Status.UNAVAILABLE.asRuntimeException()), + Status.RESOURCE_EXHAUSTED + .withDescription("gRPC message exceeds maximum size") + .asRuntimeException(), + Status.INVALID_ARGUMENT.asRuntimeException(), + Status.FAILED_PRECONDITION.asRuntimeException(), + Status.UNIMPLEMENTED.asRuntimeException(), + Status.PERMISSION_DENIED.asRuntimeException())) { + Fixture f = new Fixture(); + when(f.targets.listVisiblePublicProductionAdmissionTargets(any())).thenThrow(failure); + + assertCode("ADMISSION_POINTER_UNAVAILABLE", () -> f.owner.listWorlds(TOKEN)); + + verifyNoInteractions(f.entitlements); + } + } + + @Test + void ambientSqlOrCallerSessionContextRefusesBeforeAnyAuthorityRead() { + Fixture ambientSql = new Fixture(); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> ambientSql.owner.listWorlds(TOKEN)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient SQL"); + verifyNoInteractions(ambientSql.targets, ambientSql.entitlements, ambientSql.accounts); + + TransactionSynchronizationManager.clear(); + Fixture callerContext = new Fixture(); + SessionContext.setContext("account", List.of(), java.util.Map.of()); + assertThatThrownBy(() -> callerContext.owner.listWorlds(TOKEN)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("workload-only"); + verifyNoInteractions(callerContext.targets, callerContext.entitlements, callerContext.accounts); + } + + @Test + void independentTenantEvaluationsOverlapWithEightWorkerBoundAndNoAmbientContexts() { + Fixture f = new Fixture(); + var tenants = IntStream.range(0, 24).mapToObj(index -> UUID.randomUUID()).toList(); + var targets = + IntStream.range(0, tenants.size()) + .mapToObj( + index -> + target( + tenants.get(index), + "tenant-" + index, + "world-" + index, + "World " + index, + 1)) + .toList(); + f.stubTargetReads(targets, targets.reversed()); + var firstWave = new CountDownLatch(8); + var entered = new AtomicInteger(); + var active = new AtomicInteger(); + var peak = new AtomicInteger(); + when(f.entitlements.evaluate(any())) + .thenAnswer( + invocation -> { + int current = active.incrementAndGet(); + peak.accumulateAndGet(current, Math::max); + try { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + if (entered.incrementAndGet() <= 8) { + firstWave.countDown(); + assertThat(firstWave.await(5, TimeUnit.SECONDS)).isTrue(); + } + return evaluation(invocation.getArgument(0), true, NOW.plusSeconds(15)); + } finally { + active.decrementAndGet(); + } + }); + assertThat(f.owner.listWorlds(TOKEN)).hasSize(24); + assertThat(peak.get()).isEqualTo(8); + assertThat(entered.get()).isEqualTo(24); + for (UUID tenant : tenants) verify(f.entitlements, times(1)).evaluate(tenant); + verify(f.targets, times(2)).listVisiblePublicProductionAdmissionTargets(any()); + verify(f.accounts, times(2)).findByAccountUuid(ACCOUNT_UUID); + } + + @Test + void parallelEvaluationForAnotherTenantRefusesInsteadOfReturningPartialList() { + Fixture f = new Fixture(); + var first = target(TENANT_A, "tenant-a", "alpha", "Alpha", 1); + var second = target(TENANT_B, "tenant-b", "beta", "Beta", 1); + f.stubTargetReads(List.of(first, second), List.of(first, second)); + when(f.entitlements.evaluate(TENANT_A)) + .thenReturn(evaluation(TENANT_A, true, NOW.plusSeconds(15))); + when(f.entitlements.evaluate(TENANT_B)) + .thenReturn(evaluation(TENANT_A, true, NOW.plusSeconds(15))); + assertCode("ENTITLEMENT_UNAVAILABLE", () -> f.owner.listWorlds(TOKEN)); + verify(f.targets, times(1)).listVisiblePublicProductionAdmissionTargets(any()); + } + + @Test + void simultaneousDiscoveryCallsAcrossOwnerInstancesShareTheEightEvaluationLimit() + throws Exception { + Fixture first = new Fixture(); + Fixture second = new Fixture(); + var tenants = IntStream.range(0, 16).mapToObj(index -> UUID.randomUUID()).toList(); + var targets = + IntStream.range(0, tenants.size()) + .mapToObj( + index -> + target( + tenants.get(index), + "tenant-" + index, + "world-" + index, + "World " + index, + 1)) + .toList(); + first.stubTargetReads(targets, targets); + second.stubTargetReads(targets, targets); + var firstEight = new CountDownLatch(8); + var release = new CountDownLatch(1); + var exceeded = new CountDownLatch(1); + var active = new AtomicInteger(); + var peak = new AtomicInteger(); + org.mockito.stubbing.Answer evaluation = + invocation -> { + int count = active.incrementAndGet(); + peak.accumulateAndGet(count, Math::max); + if (count > 8) exceeded.countDown(); + firstEight.countDown(); + try { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(release.await(5, TimeUnit.SECONDS)).isTrue(); + return evaluation(invocation.getArgument(0), true, NOW.plusSeconds(30)); + } finally { + active.decrementAndGet(); + } + }; + when(first.entitlements.evaluate(any())).thenAnswer(evaluation); + when(second.entitlements.evaluate(any())).thenAnswer(evaluation); + try (var callers = Executors.newFixedThreadPool(2)) { + var left = callers.submit(() -> first.owner.listWorlds(TOKEN)); + var right = callers.submit(() -> second.owner.listWorlds(TOKEN)); + try { + assertThat(firstEight.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat(exceeded.await(200, TimeUnit.MILLISECONDS)).isFalse(); + } finally { + release.countDown(); + } + assertThat(left.get(5, TimeUnit.SECONDS)).hasSize(16); + assertThat(right.get(5, TimeUnit.SECONDS)).hasSize(16); + } + assertThat(peak.get()).isEqualTo(8); + for (UUID tenant : tenants) { + verify(first.entitlements, times(1)).evaluate(tenant); + verify(second.entitlements, times(1)).evaluate(tenant); + } + } + + private static void assertCode(String expectedCode, ThrowingCallable action) { + assertThatThrownBy(action) + .isInstanceOf(AuthenticationException.class) + .extracting(failure -> ((AuthenticationException) failure).getCode()) + .isEqualTo(expectedCode); + } + + private static Evaluation evaluation(UUID tenantId, boolean available, Instant validUntil) { + return new Evaluation( + tenantId, SourceKind.NON_PAID_DEMO, available, false, 1, 1, NOW, validUntil); + } + + private static Target target( + UUID tenantId, String tenantSlug, String worldSlug, String displayName, long pointerVersion) { + String suffix = tenantId.toString(); + return new Target( + "prod", + tenantSlug, + tenantId, + worldSlug, + displayName, + UUID.nameUUIDFromBytes( + ("realm:" + suffix).getBytes(java.nio.charset.StandardCharsets.UTF_8)), + "main", + "Main Realm", + 1, + 2, + UUID.nameUUIDFromBytes( + ("namespace:" + suffix).getBytes(java.nio.charset.StandardCharsets.UTF_8)), + "SHARED", + UUID.nameUUIDFromBytes( + ("instance:" + suffix).getBytes(java.nio.charset.StandardCharsets.UTF_8)), + UUID.nameUUIDFromBytes( + ("version:" + suffix).getBytes(java.nio.charset.StandardCharsets.UTF_8)), + 3, + 4, + pointerVersion, + "a".repeat(64), + 1, + "initial-request-" + tenantSlug, + "b".repeat(64), + OriginKind.NO_PRIOR_POINTER, + null, + UUID.nameUUIDFromBytes( + ("hold:" + suffix).getBytes(java.nio.charset.StandardCharsets.UTF_8)), + UUID.nameUUIDFromBytes( + ("fence:" + suffix).getBytes(java.nio.charset.StandardCharsets.UTF_8)), + "hold-binding-" + tenantSlug, + 5, + "owner-proof-" + tenantSlug, + OwnerProofOutcome.COMMITTED, + false, + NOW, + "PRESEEDED_ONLY"); + } + + private static Account account(long id) { + Account account = new Account(); + account.setId(id); + account.setAccountUuid(ACCOUNT_UUID); + account.setAccountUuidSourceNumericId(id); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + return account; + } + + private static final class Fixture { + private final JwtUtil jwtUtil = mock(JwtUtil.class); + private final AccountRepository accounts = mock(AccountRepository.class); + private final SessionService sessions = mock(SessionService.class); + private final CanonicalGameplayAdmissionDecisionReadClient targets = + mock(CanonicalGameplayAdmissionDecisionReadClient.class); + private final AccountPublicBootstrapEntitlementOwner entitlements = + mock(AccountPublicBootstrapEntitlementOwner.class); + private final Jws signedToken = mock(Jws.class); + private final Claims claims = mock(Claims.class); + private final AtomicReference time = new AtomicReference<>(NOW); + private final MutableClock clock = new MutableClock(time); + private final AccountPlayerBootstrapCallerVerifier callerVerifier; + private final AccountPublicBootstrapWorldsOwner owner; + private int readCount; + + private Fixture() { + when(jwtUtil.parseToken(TOKEN)).thenReturn(signedToken); + when(signedToken.getPayload()).thenReturn(claims); + when(claims.get("aud")).thenReturn("player-bootstrap"); + when(claims.get("sub")).thenReturn(ACCOUNT_UUID.toString()); + when(claims.get("accountId")).thenReturn(ACCOUNT_UUID.toString()); + when(accounts.findByAccountUuid(ACCOUNT_UUID)).thenReturn(Optional.of(account(ACCOUNT_ID))); + when(sessions.isAccountSessionActive(ACCOUNT_ID, TOKEN)).thenReturn(true); + callerVerifier = new AccountPlayerBootstrapCallerVerifier(jwtUtil, accounts, sessions); + owner = new AccountPublicBootstrapWorldsOwner(callerVerifier, targets, entitlements, clock); + } + + private void stubTargetReads(List before, List after) { + VisiblePublicProductionTargets initial = evidence(before); + VisiblePublicProductionTargets current = evidence(after); + when(targets.listVisiblePublicProductionAdmissionTargets(any())).thenReturn(initial, current); + } + + private VisiblePublicProductionTargets evidence(List evidenceTargets) { + VisiblePublicProductionTargets evidence = + mock( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.VisiblePublicProductionTargets.class); + when(evidence.targets()).thenReturn(evidenceTargets); + return evidence; + } + } + + private static final class MutableClock extends Clock { + private final AtomicReference time; + + private MutableClock(AtomicReference time) { + this.time = time; + } + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return time.get(); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPlayerBootstrapCallerVerifierTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPlayerBootstrapCallerVerifierTest.java new file mode 100644 index 0000000000..5be8e81608 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPlayerBootstrapCallerVerifierTest.java @@ -0,0 +1,292 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +import static org.junit.jupiter.api.Assertions.assertEquals; +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.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jws; +import io.jsonwebtoken.JwtException; +import java.util.Optional; +import java.util.UUID; +import java.util.stream.Stream; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.session.AccountPlayerBootstrapCallerVerifier; +import net.firedevops.firemud.accountservice.service.session.SessionService; +import net.firedevops.firemud.common.security.JwtUtil; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +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.NullAndEmptySource; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.dao.DataAccessResourceFailureException; + +/** Controlled collaborators exercise the verifier; this is not cryptographic or Redis proof. */ +@ExtendWith(MockitoExtension.class) +class AccountPlayerBootstrapCallerVerifierTest { + private static final UUID ACCOUNT_UUID = UUID.fromString("7c9b1c20-e15c-4809-b6fb-d2ecc253460b"); + private static final UUID OTHER_UUID = UUID.fromString("e16c4af2-c203-4f1a-a0a8-ab1163234e46"); + private static final long ACCOUNT_ID = 41L; + private static final String TOKEN = "exact-bootstrap-token"; + + @Mock private JwtUtil jwtUtil; + @Mock private AccountRepository accountRepository; + @Mock private SessionService sessionService; + @Mock private Jws signedToken; + @Mock private Claims claims; + + private AccountPlayerBootstrapCallerVerifier verifier; + + @BeforeEach + void setUp() { + verifier = new AccountPlayerBootstrapCallerVerifier(jwtUtil, accountRepository, sessionService); + } + + @ParameterizedTest + @EnumSource(AccountIdentityProvenance.class) + void verifiesExactPersistedOwnerAndAccountSession(AccountIdentityProvenance provenance) { + stubIdentityClaims(ACCOUNT_UUID.toString(), ACCOUNT_UUID.toString()); + Account account = account(); + account.setAccountUuidProvenance(provenance); + when(accountRepository.findByAccountUuid(ACCOUNT_UUID)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive(ACCOUNT_ID, TOKEN)).thenReturn(true); + + var caller = verifier.requireCaller(TOKEN); + + assertEquals(ACCOUNT_ID, caller.accountId()); + assertEquals(ACCOUNT_UUID, caller.accountUuid()); + verify(jwtUtil).parseToken(TOKEN); + verify(accountRepository).findByAccountUuid(ACCOUNT_UUID); + verify(sessionService).isAccountSessionActive(ACCOUNT_ID, TOKEN); + verifyNoMoreInteractions(accountRepository, sessionService); + } + + @ParameterizedTest + @NullAndEmptySource + @ValueSource(strings = {" ", "\t"}) + void missingTokenNeverReachesAnyAuthority(String token) { + AuthenticationException failure = + assertThrows(AuthenticationException.class, () -> verifier.requireCaller(token)); + + assertEquals("CONNECT_CONTEXT_INVALID", failure.getCode()); + assertEquals("Missing bootstrap token", failure.getMessage()); + verifyNoInteractions(jwtUtil, accountRepository, sessionService); + } + + @Test + void invalidSignatureOrExpiredJwtNeverReadsAccountOrSession() { + JwtException unavailable = new JwtException("invalid signed token"); + when(jwtUtil.parseToken(TOKEN)).thenThrow(unavailable); + + AuthenticationException failure = requireInvalidCaller(); + + assertNull(failure.getCause()); + verifyNoInteractions(accountRepository, sessionService); + } + + @Test + void malformedJwtNeverReadsAccountOrSession() { + IllegalArgumentException malformed = new IllegalArgumentException("malformed token"); + when(jwtUtil.parseToken(TOKEN)).thenThrow(malformed); + + assertNull(requireInvalidCaller().getCause()); + verifyNoInteractions(accountRepository, sessionService); + } + + @Test + void malformedAudienceClaimNeverReadsAccountOrSessionAndHasNoCause() { + stubSignedClaims(); + when(claims.get("aud")).thenReturn(17); + + AuthenticationException failure = requireInvalidCaller(); + + assertNull(failure.getCause()); + verifyNoInteractions(accountRepository, sessionService); + } + + @ParameterizedTest + @NullAndEmptySource + @ValueSource(strings = {"control-ui", "gameplay-connect", "account-service"}) + void wrongAudienceNeverReadsAccountOrSession(String audience) { + stubSignedClaims(); + when(claims.get("aud")).thenReturn(audience); + + requireInvalidCaller(); + + verifyNoInteractions(accountRepository, sessionService); + } + + @ParameterizedTest + @MethodSource("invalidIdentityClaims") + void rejectsNoncanonicalOrUnboundIdentity(Object subject, Object accountUuid) { + stubIdentityClaims(subject, accountUuid); + + requireInvalidCaller(); + + verifyNoInteractions(accountRepository, sessionService); + } + + static Stream invalidIdentityClaims() { + String canonical = ACCOUNT_UUID.toString(); + return Stream.of( + Arguments.of(OTHER_UUID.toString(), canonical), + Arguments.of(null, canonical), + Arguments.of(canonical, null), + Arguments.of(ACCOUNT_ID, canonical), + Arguments.of(canonical, ACCOUNT_ID), + Arguments.of(canonical.toUpperCase(java.util.Locale.ROOT), canonical), + Arguments.of(canonical, canonical.toUpperCase(java.util.Locale.ROOT)), + Arguments.of(" " + canonical, canonical), + Arguments.of(canonical, "00000000-0000-0000-0000-000000000000"), + Arguments.of("not-a-uuid", canonical), + Arguments.of("1-1-1-1-1", "1-1-1-1-1")); + } + + @Test + void missingAccountIsUnavailableAndNeverReadsSession() { + stubIdentityClaims(ACCOUNT_UUID.toString(), ACCOUNT_UUID.toString()); + when(accountRepository.findByAccountUuid(ACCOUNT_UUID)).thenReturn(Optional.empty()); + + requireUnavailableCaller(); + + verifyNoInteractions(sessionService); + } + + @ParameterizedTest + @MethodSource("invalidAccountRows") + void rejectsMismatchedOrUnprovenPersistedRow(String description, Account account) { + stubIdentityClaims(ACCOUNT_UUID.toString(), ACCOUNT_UUID.toString()); + when(accountRepository.findByAccountUuid(ACCOUNT_UUID)).thenReturn(Optional.of(account)); + + requireUnavailableCaller(); + + verifyNoInteractions(sessionService); + } + + static Stream invalidAccountRows() { + Account wrongUuid = account(); + wrongUuid.setAccountUuid(OTHER_UUID); + Account absentUuid = account(); + absentUuid.setAccountUuid(null); + Account nilUuid = account(); + nilUuid.setAccountUuid(new UUID(0L, 0L)); + Account absentId = account(); + absentId.setId(null); + Account zeroId = account(); + zeroId.setId(0L); + Account negativeId = account(); + negativeId.setId(-1L); + Account wrongSource = account(); + wrongSource.setAccountUuidSourceNumericId(ACCOUNT_ID + 1L); + Account absentSource = account(); + absentSource.setAccountUuidSourceNumericId(null); + Account absentProvenance = account(); + absentProvenance.setAccountUuidProvenance(null); + return Stream.of( + Arguments.of("wrong UUID", wrongUuid), + Arguments.of("absent UUID", absentUuid), + Arguments.of("nil UUID", nilUuid), + Arguments.of("absent private ID", absentId), + Arguments.of("zero private ID", zeroId), + Arguments.of("negative private ID", negativeId), + Arguments.of("source ID mismatch", wrongSource), + Arguments.of("absent source ID", absentSource), + Arguments.of("absent provenance", absentProvenance)); + } + + @Test + void repositoryFailureIsUnavailableAndNeverReadsSession() { + stubIdentityClaims(ACCOUNT_UUID.toString(), ACCOUNT_UUID.toString()); + DataAccessResourceFailureException unavailable = + new DataAccessResourceFailureException("account database unavailable"); + when(accountRepository.findByAccountUuid(ACCOUNT_UUID)).thenThrow(unavailable); + + assertSame(unavailable, requireUnavailableCaller().getCause()); + verifyNoInteractions(sessionService); + } + + @Test + void invalidRepositoryProvenanceReadbackIsUnavailable() { + stubIdentityClaims(ACCOUNT_UUID.toString(), ACCOUNT_UUID.toString()); + IllegalStateException invalid = new IllegalStateException("Unknown Account UUID provenance"); + when(accountRepository.findByAccountUuid(ACCOUNT_UUID)).thenThrow(invalid); + + assertSame(invalid, requireUnavailableCaller().getCause()); + verifyNoInteractions(sessionService); + } + + @Test + void inactiveExactSessionIsInvalidRatherThanUnavailable() { + stubIdentityClaims(ACCOUNT_UUID.toString(), ACCOUNT_UUID.toString()); + when(accountRepository.findByAccountUuid(ACCOUNT_UUID)).thenReturn(Optional.of(account())); + when(sessionService.isAccountSessionActive(ACCOUNT_ID, TOKEN)).thenReturn(false); + + AuthenticationException failure = requireInvalidCaller(); + + assertEquals("Bootstrap token expired", failure.getMessage()); + verify(sessionService).isAccountSessionActive(ACCOUNT_ID, TOKEN); + } + + @Test + void sessionOutagePreservesExistingUnavailableExceptionRatherThanInvalidToken() { + stubIdentityClaims(ACCOUNT_UUID.toString(), ACCOUNT_UUID.toString()); + when(accountRepository.findByAccountUuid(ACCOUNT_UUID)).thenReturn(Optional.of(account())); + DataAccessResourceFailureException unavailable = + new DataAccessResourceFailureException("account session unavailable"); + when(sessionService.isAccountSessionActive(ACCOUNT_ID, TOKEN)).thenThrow(unavailable); + + assertSame( + unavailable, + assertThrows( + DataAccessResourceFailureException.class, () -> verifier.requireCaller(TOKEN))); + } + + private AuthenticationException requireInvalidCaller() { + AuthenticationException failure = + assertThrows(AuthenticationException.class, () -> verifier.requireCaller(TOKEN)); + assertEquals("CONNECT_CONTEXT_INVALID", failure.getCode()); + return failure; + } + + private AuthenticationException requireUnavailableCaller() { + AuthenticationException failure = + assertThrows(AuthenticationException.class, () -> verifier.requireCaller(TOKEN)); + assertEquals("AUTH_UNAVAILABLE", failure.getCode()); + return failure; + } + + private void stubSignedClaims() { + when(jwtUtil.parseToken(TOKEN)).thenReturn(signedToken); + when(signedToken.getPayload()).thenReturn(claims); + } + + private void stubIdentityClaims(Object subject, Object accountUuid) { + stubSignedClaims(); + when(claims.get("aud")).thenReturn("player-bootstrap"); + when(claims.get("sub")).thenReturn(subject); + when(claims.get("accountId")).thenReturn(accountUuid); + } + + private static Account account() { + Account account = new Account(); + account.setId(ACCOUNT_ID); + account.setAccountUuid(ACCOUNT_UUID); + account.setAccountUuidSourceNumericId(ACCOUNT_ID); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + return account; + } +} 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 944fd27754..5d382dce16 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 @@ -1,6 +1,7 @@ package net.firedevops.firemud.common.gamesession; import com.google.protobuf.ByteString; +import com.google.protobuf.CodedOutputStream; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; @@ -8,11 +9,18 @@ import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.Arrays; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Set; import java.util.UUID; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; import net.firedevops.firemud.common.security.AccountJwtExactValues; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; @@ -20,6 +28,7 @@ import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProofCodec; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayAdmissionCandidate; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayAdmissionDecisionStatus; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayAdmissionOriginKind; @@ -31,6 +40,10 @@ import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadResponse; import net.firedevops.firemud.gamesession.v1.GetPublishedRealmAdmissionOwnerReadRequest; import net.firedevops.firemud.gamesession.v1.GetPublishedRealmAdmissionOwnerReadResponse; +import net.firedevops.firemud.gamesession.v1.ListVisiblePublicProductionAdmissionTargetsRequest; +import net.firedevops.firemud.gamesession.v1.ListVisiblePublicProductionAdmissionTargetsResponse; +import net.firedevops.firemud.gamesession.v1.ResolvePublishedRealmAdmissionTargetRequest; +import net.firedevops.firemud.gamesession.v1.ResolvePublishedRealmAdmissionTargetResponse; /** * Closed, purpose-specific wire mapping for Account-only Game Session owner reads. @@ -42,15 +55,338 @@ public final class CanonicalGameplayAdmissionDecisionReadGrpcCodec { public static final int MAX_REQUEST_WIRE_BYTES = AccountGameplayAdmissionLeaseEvidence.MAX_EVIDENCE_BYTES + 1024; public static final int MAX_RESPONSE_WIRE_BYTES = 256 * 1024; + public static final int MAX_DISCOVERY_REQUEST_WIRE_BYTES = 16 * 1024; + public static final int MAX_DISCOVERY_RESPONSE_WIRE_BYTES = 4 * 1024 * 1024; + public static final int MAX_TARGET_RESOLUTION_REQUEST_WIRE_BYTES = 16 * 1024; + public static final int MAX_TARGET_RESOLUTION_RESPONSE_WIRE_BYTES = 64 * 1024; public static final int MAX_PUBLISHED_REALM_REQUEST_WIRE_BYTES = CanonicalGameplayRosterOwnerReadGrpcCodec.MAX_REQUEST_BYTES + 256; + // WorldCanonicalInstanceLifecycleClient and GrpcChannelFactory have no inbound override: the + // existing upstream RPC admits at most the ordinary 4 MiB complete Protobuf response. The World + // value itself has no intrinsic byte/count bound; this is its current transport budget, not a new + // source-content limit. A returned resolver target fits its existing complete 64 KiB response. public static final int MAX_PUBLISHED_REALM_RESPONSE_WIRE_BYTES = - CanonicalGameplayRosterOwnerReadGrpcCodec.MAX_RESPONSE_BYTES + 1024 * 1024; + framedFieldBytes(1, 1) + + framedFieldBytes(2, CanonicalGameplayRosterOwnerReadGrpcCodec.MAX_RESPONSE_BYTES) + + framedFieldBytes(3, MAX_TARGET_RESOLUTION_RESPONSE_WIRE_BYTES) + + framedFieldBytes(4, GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES); private static final int SCHEMA_VERSION = 1; private static final UUID NIL_UUID = new UUID(0L, 0L); private CanonicalGameplayAdmissionDecisionReadGrpcCodec() {} + // Schema version is one packed uint32 with a one-byte payload. Each remaining value is one + // length-delimited field. Budget the entire admitted upstream World response even though only + // its canonical evidence payload is copied, preserving conservative framing headroom. + private static int framedFieldBytes(int fieldNumber, int maximumPayloadBytes) { + return CodedOutputStream.computeTagSize(fieldNumber) + + CodedOutputStream.computeUInt32SizeNoTag(maximumPayloadBytes) + + maximumPayloadBytes; + } + + /** Workload-only correlation; no player or admission authority is supplied. */ + public record DiscoveryRequest(UUID readRequestId, String targetNamespace) { + public DiscoveryRequest { + requireNonNil(readRequestId, "readRequestId"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw invalid("Canonical discovery namespace required"); + } + } + } + + /** Closed complete collection; authenticated transport and owner reads establish provenance. */ + public static final class VisiblePublicProductionTargets { + private final DiscoveryRequest request; + private final List targets; + + private VisiblePublicProductionTargets(DiscoveryRequest request, List targets) { + this.request = request; + this.targets = List.copyOf(targets); + } + + public DiscoveryRequest request() { + return request; + } + + public List targets() { + return targets; + } + } + + public static ListVisiblePublicProductionAdmissionTargetsRequest toDiscoveryRequest( + DiscoveryRequest request) { + Objects.requireNonNull(request, "request"); + var wire = + ListVisiblePublicProductionAdmissionTargetsRequest.newBuilder() + .addSchemaVersion(SCHEMA_VERSION) + .addReadRequestUuid(request.readRequestId().toString()) + .addTargetNamespace(request.targetNamespace()) + .build(); + requireWireSize( + wire.getSerializedSize(), MAX_DISCOVERY_REQUEST_WIRE_BYTES, "discovery request"); + return wire; + } + + public static DiscoveryRequest parseDiscoveryRequest( + ListVisiblePublicProductionAdmissionTargetsRequest request) { + Objects.requireNonNull(request, "request"); + requireWireSize( + request.getSerializedSize(), MAX_DISCOVERY_REQUEST_WIRE_BYTES, "discovery request"); + if (!request.getUnknownFields().asMap().isEmpty() + || one(request.getSchemaVersionList(), "discovery schemaVersion") != SCHEMA_VERSION) { + throw invalid("Unsupported or unknown discovery request"); + } + return new DiscoveryRequest( + uuid(one(request.getReadRequestUuidList(), "readRequestId")), + one(request.getTargetNamespaceList(), "targetNamespace")); + } + + public static ListVisiblePublicProductionAdmissionTargetsResponse toDiscoveryResponse( + DiscoveryRequest request, List targets) { + Objects.requireNonNull(targets, "targets"); + var response = + ListVisiblePublicProductionAdmissionTargetsResponse.newBuilder() + .addSchemaVersion(SCHEMA_VERSION) + .addRequest(toDiscoveryRequest(request)); + int encodedSize = response.build().getSerializedSize(); + for (Target target : targets) { + var wire = toTargetEvidence(target); + requireWireSize( + wire.getSerializedSize(), MAX_TARGET_RESOLUTION_RESPONSE_WIRE_BYTES, "discovery target"); + encodedSize += framedFieldBytes(3, wire.getSerializedSize()); + requireWireSize(encodedSize, MAX_DISCOVERY_RESPONSE_WIRE_BYTES, "discovery response"); + response.addCurrentTargets(wire); + } + var built = response.build(); + fromDiscoveryResponse(request, built); + return built; + } + + public static VisiblePublicProductionTargets fromDiscoveryResponse( + DiscoveryRequest expected, ListVisiblePublicProductionAdmissionTargetsResponse response) { + Objects.requireNonNull(expected, "expected"); + Objects.requireNonNull(response, "response"); + requireWireSize( + response.getSerializedSize(), MAX_DISCOVERY_RESPONSE_WIRE_BYTES, "discovery response"); + if (!response.getUnknownFields().asMap().isEmpty() + || one(response.getSchemaVersionList(), "discovery schemaVersion") != SCHEMA_VERSION + || !toDiscoveryRequest(expected) + .equals(one(response.getRequestList(), "discovery request"))) { + throw invalid("Discovery response changed the closed original request"); + } + Set tenants = new HashSet<>(); + Set tenantSlugs = new HashSet<>(); + Set realms = new HashSet<>(); + List targets = + response.getCurrentTargetsList().stream() + .map( + wire -> { + requireWireSize( + wire.getSerializedSize(), + MAX_TARGET_RESOLUTION_RESPONSE_WIRE_BYTES, + "discovery target"); + Target target = parseTargetEvidence(wire); + if (!expected.targetNamespace().equals(target.targetNamespace()) + || !"SHARED".equals(target.playableStateScope()) + || !"PRESEEDED_ONLY".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"); + } + return target; + }) + .toList(); + return new VisiblePublicProductionTargets(expected, targets); + } + + /** Comparison selectors only; constructing this value authenticates neither Account nor scope. */ + public record RetainedTargetSelector( + UUID readRequestId, + UUID accountId, + String targetNamespace, + UUID tenantId, + String tenantSlug, + String worldSlug, + UUID realmId, + String realmSlug, + UUID playableStateNamespaceId, + String playableStateScope, + UUID gameInstanceId, + long catalogRevision, + long pointerVersion) { + public RetainedTargetSelector { + requireNonNil(readRequestId, "readRequestId"); + requireNonNil(accountId, "accountId"); + requireNonNil(tenantId, "tenantId"); + requireNonNil(realmId, "realmId"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + requireNonNil(gameInstanceId, "gameInstanceId"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace) + || !RealmEntryPolicy.isCanonicalSlug(tenantSlug) + || !RealmEntryPolicy.isCanonicalSlug(worldSlug) + || !RealmEntryPolicy.isCanonicalSlug(realmSlug) + || !"SHARED".equals(playableStateScope)) { + throw invalid("Exact canonical public SHARED target selectors required"); + } + positiveLong(catalogRevision, "catalogRevision"); + positiveLong(pointerVersion, "pointerVersion"); + } + } + + /** + * Structurally verified resolver result; protected transport establishes its owner provenance. + */ + public static final class ResolvedPublishedTarget { + private final RetainedTargetSelector selector; + private final Target currentTarget; + + private ResolvedPublishedTarget(RetainedTargetSelector selector, Target currentTarget) { + this.selector = selector; + this.currentTarget = currentTarget; + } + + public RetainedTargetSelector selector() { + return selector; + } + + public Target currentTarget() { + return currentTarget; + } + + /** Derives both previously missing selectors exclusively from the returned owner target. */ + public CanonicalGameplayRosterOwnerReadEvidence.Request strictSelector() { + return new CanonicalGameplayRosterOwnerReadEvidence.Request( + selector.readRequestId(), + selector.accountId(), + currentTarget.targetNamespace(), + currentTarget.canonicalTenantId(), + currentTarget.worldSlug(), + currentTarget.realmId(), + currentTarget.realmSlug(), + currentTarget.playableStateNamespaceId(), + currentTarget.playableStateScope(), + currentTarget.canonicalGameInstanceId(), + currentTarget.canonicalVersionId(), + currentTarget.catalogRevision(), + currentTarget.pointerVersion(), + currentTarget.activeWorldEpoch()); + } + } + + public static ResolvePublishedRealmAdmissionTargetRequest toTargetResolutionRequest( + RetainedTargetSelector selector) { + Objects.requireNonNull(selector, "selector"); + var request = + ResolvePublishedRealmAdmissionTargetRequest.newBuilder() + .addSchemaVersion(SCHEMA_VERSION) + .addReadRequestUuid(selector.readRequestId().toString()) + .addAccountUuid(selector.accountId().toString()) + .addTargetNamespace(selector.targetNamespace()) + .addCanonicalTenantUuid(selector.tenantId().toString()) + .addTenantSlug(selector.tenantSlug()) + .addWorldSlug(selector.worldSlug()) + .addRealmUuid(selector.realmId().toString()) + .addRealmSlug(selector.realmSlug()) + .addPlayableStateNamespaceUuid(selector.playableStateNamespaceId().toString()) + .addPlayableStateScope(selector.playableStateScope()) + .addCanonicalGameInstanceUuid(selector.gameInstanceId().toString()) + .addCatalogRevision(Long.toString(selector.catalogRevision())) + .addPointerVersion(Long.toString(selector.pointerVersion())) + .build(); + requireWireSize( + request.getSerializedSize(), + MAX_TARGET_RESOLUTION_REQUEST_WIRE_BYTES, + "target resolution request"); + return request; + } + + public static RetainedTargetSelector parseTargetResolutionRequest( + ResolvePublishedRealmAdmissionTargetRequest request) { + Objects.requireNonNull(request, "request"); + requireWireSize( + request.getSerializedSize(), + MAX_TARGET_RESOLUTION_REQUEST_WIRE_BYTES, + "target resolution request"); + if (!request.getUnknownFields().asMap().isEmpty() + || one(request.getSchemaVersionList(), "resolver schemaVersion") != SCHEMA_VERSION) { + throw invalid("Closed schema-1 target resolution request required"); + } + return new RetainedTargetSelector( + uuid(one(request.getReadRequestUuidList(), "readRequestId")), + uuid(one(request.getAccountUuidList(), "accountId")), + one(request.getTargetNamespaceList(), "targetNamespace"), + uuid(one(request.getCanonicalTenantUuidList(), "tenantId")), + one(request.getTenantSlugList(), "tenantSlug"), + one(request.getWorldSlugList(), "worldSlug"), + uuid(one(request.getRealmUuidList(), "realmId")), + one(request.getRealmSlugList(), "realmSlug"), + uuid(one(request.getPlayableStateNamespaceUuidList(), "playableStateNamespaceId")), + one(request.getPlayableStateScopeList(), "playableStateScope"), + uuid(one(request.getCanonicalGameInstanceUuidList(), "gameInstanceId")), + positiveLongDecimal( + one(request.getCatalogRevisionList(), "catalogRevision"), "catalogRevision"), + positiveLongDecimal( + one(request.getPointerVersionList(), "pointerVersion"), "pointerVersion")); + } + + public static ResolvePublishedRealmAdmissionTargetResponse toTargetResolutionResponse( + RetainedTargetSelector selector, Target target) { + var response = + ResolvePublishedRealmAdmissionTargetResponse.newBuilder() + .addSchemaVersion(SCHEMA_VERSION) + .addRequest(toTargetResolutionRequest(selector)) + .addCurrentTarget(toTargetEvidence(target)) + .build(); + fromTargetResolutionResponse(selector, response); + return response; + } + + public static ResolvedPublishedTarget fromTargetResolutionResponse( + RetainedTargetSelector expected, ResolvePublishedRealmAdmissionTargetResponse response) { + Objects.requireNonNull(expected, "expected"); + Objects.requireNonNull(response, "response"); + requireWireSize( + response.getSerializedSize(), + MAX_TARGET_RESOLUTION_RESPONSE_WIRE_BYTES, + "target resolution response"); + if (!response.getUnknownFields().asMap().isEmpty() + || one(response.getSchemaVersionList(), "resolver schemaVersion") != SCHEMA_VERSION + || !toTargetResolutionRequest(expected) + .equals(one(response.getRequestList(), "resolver request"))) { + throw invalid("Target resolution response changed the exact closed original request"); + } + Target target = + parseTargetEvidence(one(response.getCurrentTargetList(), "resolver currentTarget")); + requireRetainedTargetMatches(expected, target); + return new ResolvedPublishedTarget(expected, target); + } + + public static void requireRetainedTargetMatches(RetainedTargetSelector expected, Target current) { + Objects.requireNonNull(expected, "expected"); + Objects.requireNonNull(current, "current"); + if (!expected.targetNamespace().equals(current.targetNamespace()) + || !expected.tenantId().equals(current.canonicalTenantId()) + || !expected.tenantSlug().equals(current.tenantSlug()) + || !expected.worldSlug().equals(current.worldSlug()) + || !expected.realmId().equals(current.realmId()) + || !expected.realmSlug().equals(current.realmSlug()) + || !expected.playableStateNamespaceId().equals(current.playableStateNamespaceId()) + || !expected.playableStateScope().equals(current.playableStateScope()) + || !expected.gameInstanceId().equals(current.canonicalGameInstanceId()) + || expected.catalogRevision() != current.catalogRevision() + || expected.pointerVersion() != current.pointerVersion() + || !"PRESEEDED_ONLY".equals(current.characterCreationPolicy()) + || current.ownerProofOutcome() != OwnerProofOutcome.COMMITTED + || current.positiveDurableAbort()) { + throw invalid( + "Current owner target differs from the exact retained public PRESEEDED_ONLY target"); + } + } + /** Locally retained request identity; construction is restricted to this codec. */ public static final class RequestEvidence { private final UUID bindingDecisionId; @@ -161,14 +497,17 @@ public static final class PublishedRealmEvidence { private final CanonicalGameplayRosterOwnerReadEvidence.Request selector; private final CanonicalGameplayRosterOwnerReadEvidence sourceEvidence; private final Target currentTarget; + private final WorldCanonicalInstanceLifecycleEvidence worldLifecycleEvidence; private PublishedRealmEvidence( CanonicalGameplayRosterOwnerReadEvidence.Request selector, CanonicalGameplayRosterOwnerReadEvidence sourceEvidence, - Target currentTarget) { + Target currentTarget, + WorldCanonicalInstanceLifecycleEvidence worldLifecycleEvidence) { this.selector = selector; this.sourceEvidence = sourceEvidence; this.currentTarget = currentTarget; + this.worldLifecycleEvidence = worldLifecycleEvidence; } public CanonicalGameplayRosterOwnerReadEvidence.Request selector() { @@ -182,6 +521,10 @@ public CanonicalGameplayRosterOwnerReadEvidence sourceEvidence() { public Target currentTarget() { return currentTarget; } + + public WorldCanonicalInstanceLifecycleEvidence worldLifecycleEvidence() { + return worldLifecycleEvidence; + } } /** Complete CanonicalGameplayBindingIdentity in Account-independent common types. */ @@ -324,11 +667,14 @@ public static PublishedRealmRequest parsePublishedRealmRequest( public static GetPublishedRealmAdmissionOwnerReadResponse toPublishedRealmResponse( PublishedRealmRequest request, CanonicalGameplayRosterOwnerReadEvidence sourceEvidence, - Target currentTarget) { + Target currentTarget, + WorldCanonicalInstanceLifecycleEvidence worldLifecycleEvidence) { Objects.requireNonNull(request, "request"); Objects.requireNonNull(sourceEvidence, "sourceEvidence"); Objects.requireNonNull(currentTarget, "currentTarget"); requirePublishedTargetMatchesSource(currentTarget, request.selector(), sourceEvidence); + requirePublishedWorldLifecycle( + request.selector(), currentTarget, sourceEvidence, worldLifecycleEvidence); GetCanonicalGameplayRosterOwnerReadResponse sourceResponse = CanonicalGameplayRosterOwnerReadGrpcCodec.toResponse(request.selector(), sourceEvidence); GetPublishedRealmAdmissionOwnerReadResponse response = @@ -336,6 +682,7 @@ public static GetPublishedRealmAdmissionOwnerReadResponse toPublishedRealmRespon .addSchemaVersion(SCHEMA_VERSION) .addPublishedSource(sourceResponse) .addCurrentTarget(toTargetEvidence(currentTarget)) + .addWorldLifecycleEvidence(ByteString.copyFrom(worldLifecycleEvidence.canonicalBytes())) .build(); requireWireSize( response.getSerializedSize(), @@ -363,8 +710,82 @@ public static PublishedRealmEvidence fromPublishedRealmResponse( request.selector(), one(response.getPublishedSourceList(), "published source")); Target currentTarget = parseTargetEvidence(one(response.getCurrentTargetList(), "current target")); + WorldCanonicalInstanceLifecycleEvidence lifecycle = + WorldCanonicalInstanceLifecycleEvidence.fromStored( + one(response.getWorldLifecycleEvidenceList(), "World lifecycle evidence") + .toByteArray()); requirePublishedTargetMatchesSource(currentTarget, request.selector(), sourceEvidence); - return new PublishedRealmEvidence(request.selector(), sourceEvidence, currentTarget); + requirePublishedWorldLifecycle(request.selector(), currentTarget, sourceEvidence, lifecycle); + return new PublishedRealmEvidence(request.selector(), sourceEvidence, currentTarget, lifecycle); + } + + private static void requirePublishedWorldLifecycle( + CanonicalGameplayRosterOwnerReadEvidence.Request selector, + Target target, + CanonicalGameplayRosterOwnerReadEvidence source, + WorldCanonicalInstanceLifecycleEvidence lifecycle) { + Objects.requireNonNull(lifecycle, "Fresh World lifecycle evidence is required"); + var request = lifecycle.request(); + var binding = lifecycle.launchBinding(); + var descriptor = binding.descriptor(); + var release = binding.releaseAttestation(); + var published = source.publishedPolicySetEvidence(); + var terminal = + GameDesignPublicationTerminalEvidence.fromStored(published.terminalEvidenceBytes()); + var content = terminal.releaseContent(); + var participants = + content.participantDigests().stream() + .map( + participant -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionId() != null, + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + participant.digestSchemaVersion(), + participant.abilitySchemaDigest() != null, + participant.abilitySchemaDigest())) + .toList(); + int attestationSchema = + switch (content.attestationSchemaVersion()) { + case "v2" -> AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION; + case "v3" -> AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION; + case "v4" -> AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION; + default -> throw invalid("Published release has no supported full attestation schema"); + }; + if (!selector.requestUuid().equals(request.readRequestId()) + || !selector.targetNamespace().equals(request.targetNamespace()) + || !selector.canonicalTenantUuid().equals(request.canonicalTenantId()) + || !selector.worldSlug().equals(request.worldSlug()) + || !selector.canonicalGameInstanceUuid().equals(request.canonicalGameInstanceId()) + || !selector.playableStateNamespaceUuid().equals(request.playableStateNamespaceId()) + || !selector.playableStateScope().equals(request.playableStateScope()) + || !request.publicProduction() + || !selector.canonicalVersionUuid().equals(request.canonicalVersionId()) + || !"ACTIVE".equals(lifecycle.lifecycleStatus()) + || lifecycle.lifecycleEpoch() != target.activeWorldEpoch() + || descriptor.versionId() != target.runtimeVersionId() + || !release.canonicalTenantId().equals(target.canonicalTenantId()) + || !release.canonicalVersionId().equals(target.canonicalVersionId()) + || !release.worldSlug().equals(target.worldSlug()) + || !release.commitId().equals(published.sourceCommitId().toString()) + || !release.publishWorkflowId().equals(published.publishWorkflowId()) + || !release.manifestHash().equals(published.manifestHash()) + || release.versionStateEpoch() != published.publicationVersionStateEpoch() + || !release.publishedReleaseBundleRef().equals(published.publishedReleaseBundleRef()) + || release.schemaVersion() != attestationSchema + || release.manifestSchemaVersion() != content.manifestSchemaVersion() + || !release.artifactDigests().equals(content.artifactDigests()) + || !release.requiredManifestAssetKeys().equals(content.requiredManifestAssetKeys()) + || !release.commandDefinitions().equals(content.commandDefinitions()) + || !release.generationConfigRevision().equals(content.generationConfigRevision()) + || !release.participantDigests().equals(participants) + || !Objects.equals(release.worldStartLocationEvidence(), terminal.worldEvidence())) { + throw invalid( + "Fresh World ACTIVE lifecycle differs from the exact published target and launch source"); + } } /** diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/JwtUtil.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/JwtUtil.java index d10ceb2234..3b3c56126c 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/JwtUtil.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/JwtUtil.java @@ -5,8 +5,11 @@ import io.jsonwebtoken.Jwts; import io.jsonwebtoken.security.Keys; import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.Date; import java.util.Map; +import java.util.Objects; /** Helper for generating and verifying JWT tokens. */ public class JwtUtil { @@ -26,14 +29,40 @@ public String generateToken( String subject, long tokenExpirationMillis, Map claims) { long now = System.currentTimeMillis(); return Jwts.builder() - .subject(subject) .claims(claims) + .subject(subject) .issuedAt(new Date(now)) .expiration(new Date(now + tokenExpirationMillis)) .signWith(Keys.hmacShaKeyFor(key)) .compact(); } + /** + * Signs with an owner-selected absolute expiration at JWT NumericDate precision. The issuance + * timestamp is sampled once; expiration must be whole-second precision and later than issuance. + */ + public String generateToken(String subject, Instant expiresAt, Map claims) { + Objects.requireNonNull(subject, "Token subject required"); + Objects.requireNonNull(expiresAt, "Absolute token expiration required"); + Objects.requireNonNull(claims, "Token claims required"); + if (!expiresAt.equals(expiresAt.truncatedTo(ChronoUnit.SECONDS))) { + throw new IllegalArgumentException("Absolute JWT expiration must use whole-second precision"); + } + + Date issuedAt = new Date(System.currentTimeMillis()); + Date expiration = Date.from(expiresAt); + if (!expiration.after(issuedAt)) { + throw new IllegalArgumentException("Absolute JWT expiration must be after issuance"); + } + return Jwts.builder() + .claims(claims) + .subject(subject) + .issuedAt(issuedAt) + .expiration(expiration) + .signWith(Keys.hmacShaKeyFor(key)) + .compact(); + } + public Jws parseToken(String token) { return Jwts.parser().verifyWith(Keys.hmacShaKeyFor(key)).build().parseSignedClaims(token); } diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/ReloadableJwtUtil.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/ReloadableJwtUtil.java index 66535d4a0e..bbc5f37bf8 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/ReloadableJwtUtil.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/ReloadableJwtUtil.java @@ -2,6 +2,7 @@ import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jws; +import java.time.Instant; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; @@ -38,6 +39,11 @@ public String generateToken( return delegate.get().generateToken(subject, tokenExpirationMillis, claims); } + @Override + public String generateToken(String subject, Instant expiresAt, Map claims) { + return delegate.get().generateToken(subject, expiresAt, claims); + } + @Override public Jws parseToken(String token) { return delegate.get().parseToken(token); 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 3ef303e6ca..2d1298723e 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 @@ -10,12 +10,15 @@ import java.nio.charset.StandardCharsets; import java.time.Instant; import java.time.OffsetDateTime; +import java.util.LinkedHashMap; 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.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Participant; @@ -25,6 +28,7 @@ import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.OriginKind; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; +import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; @@ -38,6 +42,9 @@ import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleGrpcCodec; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayAdmissionCandidate; import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayAdmissionDecisionResponse; @@ -59,6 +66,491 @@ class CanonicalGameplayAdmissionDecisionReadGrpcCodecTest { private static final String DIGEST = "sha256:" + "a".repeat(64); private static final tools.jackson.databind.ObjectMapper JSON = JsonMapper.builder().build(); + @Test + void discoveryRoundTripsCompleteOwnerTargetsAndAuthenticatedEmptyCollection() { + var target = target(lease(), "PRESEEDED_ONLY"); + var request = + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.DiscoveryRequest( + DECISION_ID, target.targetNamespace()); + assertThat( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseDiscoveryRequest( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryRequest(request))) + .isEqualTo(request); + var response = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( + request, List.of(target)); + var decoded = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse(request, response); + assertThat(decoded.request()).isEqualTo(request); + assertThat(decoded.targets()).containsExactly(target); + assertThat(decoded.targets().getFirst().canonicalTenantId().toString()) + .isNotEqualTo(Long.toString(target.gameSessionTenantId())); + assertThatThrownBy(() -> decoded.targets().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThat( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + request, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( + request, List.of())) + .targets()) + .isEmpty(); + } + + @Test + void discoveryRejectsOpenRequestShapeAndChangedResponseCorrelation() { + var request = + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.DiscoveryRequest(DECISION_ID, "test"); + var wire = CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryRequest(request); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + var oversizedUnknown = + UnknownFieldSet.newBuilder() + .addField( + 99, + UnknownFieldSet.Field.newBuilder() + .addLengthDelimited(ByteString.copyFrom(new byte[16 * 1024])) + .build()) + .build(); + for (var malformed : + List.of( + wire.toBuilder().addSchemaVersion(1).build(), + wire.toBuilder().setSchemaVersion(0, 2).build(), + wire.toBuilder().addReadRequestUuid(DECISION_ID.toString()).build(), + wire.toBuilder().setUnknownFields(oversizedUnknown).build(), + wire.toBuilder().clearReadRequestUuid().build(), + wire.toBuilder().setReadRequestUuid(0, "1").build(), + wire.toBuilder().setReadRequestUuid(0, new UUID(0, 0).toString()).build(), + wire.toBuilder().setTargetNamespace(0, "bad/namespace").build(), + wire.toBuilder().setUnknownFields(unknown).build())) { + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseDiscoveryRequest(malformed)) + .isInstanceOf(IllegalArgumentException.class); + } + var response = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse(request, List.of()); + for (var malformed : + List.of( + response.toBuilder().clearSchemaVersion().build(), + response.toBuilder().addRequest(wire).build(), + response.toBuilder() + .setRequest(0, wire.toBuilder().setReadRequestUuid(0, OTHER.toString())) + .build(), + response.toBuilder().setRequest(0, wire.toBuilder().addTargetNamespace("test")).build(), + response.toBuilder().setUnknownFields(unknown).build())) { + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + request, malformed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void discoveryRejectsDuplicateTenantAuthorityAndUnsupportedOrIncompleteTargets() { + var target = target(lease(), "PRESEEDED_ONLY"); + var request = + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.DiscoveryRequest( + DECISION_ID, target.targetNamespace()); + var response = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( + request, List.of(target)); + var wire = response.getCurrentTargets(0); + for (var malformed : + List.of( + response.toBuilder().addCurrentTargets(wire).build(), + response.toBuilder() + .setCurrentTargets(0, wire.toBuilder().setTargetNamespace(0, "foreign")) + .build(), + response.toBuilder() + .setCurrentTargets(0, wire.toBuilder().setPlayableStateScope(0, "ISOLATED")) + .build(), + response.toBuilder() + .setCurrentTargets( + 0, wire.toBuilder().setCharacterCreationPolicy(0, "PLAYER_CREATED")) + .build(), + response.toBuilder() + .setCurrentTargets(0, wire.toBuilder().clearCanonicalGameInstanceUuid()) + .build(), + response.toBuilder() + .setCurrentTargets(0, wire.toBuilder().setCatalogRevision(0, "01")) + .build(), + response.toBuilder() + .setCurrentTargets(0, wire.toBuilder().addTenantSlug("duplicate")) + .build(), + response.toBuilder() + .setCurrentTargets( + 0, wire.toBuilder().setHoldBindingDigest(0, "sha256:" + "f".repeat(64))) + .build())) { + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + request, malformed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void discoveryEnforcesCompleteTargetAndFourMiBEnvelopeBounds() { + var target = target(lease(), "PRESEEDED_ONLY"); + var request = + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.DiscoveryRequest( + DECISION_ID, target.targetNamespace()); + var response = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( + request, List.of(target)); + var oversizedTarget = + response.getCurrentTargets(0).toBuilder() + .setWorldDisplayName(0, "x".repeat(64 * 1024)) + .build(); + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + request, response.toBuilder().setCurrentTargets(0, oversizedTarget).build())) + .isInstanceOf(IllegalArgumentException.class); + var boundary = response.toBuilder().clearCurrentTargets(); + for (int index = 0; index < 63; index++) { + boundary.addCurrentTargets(discoveryBoundaryTarget(target, index, 64 * 1024)); + } + // Field 3 framing for this final roughly 64 KiB target is one tag plus a three-byte length. + int finalTargetSize = 4 * 1024 * 1024 - boundary.build().getSerializedSize() - 4; + boundary.addCurrentTargets(discoveryBoundaryTarget(target, 63, finalTargetSize)); + var complete = boundary.build(); + assertThat(complete.getSerializedSize()).isEqualTo(4 * 1024 * 1024); + var accepted = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse(request, complete); + assertThat(accepted.targets()).hasSize(64); + assertThat( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( + request, accepted.targets())) + .isEqualTo(complete); + var last = complete.getCurrentTargets(63).toBuilder(); + last.setWorldDisplayName(0, last.getWorldDisplayName(0) + "x"); + var oversized = complete.toBuilder().setCurrentTargets(63, last).build(); + assertThat(oversized.getSerializedSize()).isEqualTo(4 * 1024 * 1024 + 1); + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + request, oversized)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("discovery response"); + var oneMore = CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseTargetEvidence(last.build()); + var tooLargeTargets = new java.util.ArrayList<>(accepted.targets()); + tooLargeTargets.set(63, oneMore); + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( + request, tooLargeTargets)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("discovery response"); + assertThat(CanonicalGameplayAdmissionDecisionReadGrpcCodec.MAX_DISCOVERY_RESPONSE_WIRE_BYTES) + .isEqualTo(4 * 1024 * 1024); + } + + private static net.firedevops.firemud.gamesession.v1.CanonicalPlayableTargetEvidence + discoveryBoundaryTarget(Target source, int index, int targetSize) { + UUID tenant = + UUID.nameUUIDFromBytes(("discovery-tenant-" + index).getBytes(StandardCharsets.UTF_8)); + UUID realm = + UUID.nameUUIDFromBytes(("discovery-realm-" + index).getBytes(StandardCharsets.UTF_8)); + var holdRequest = + new WorldCanonicalInitialAdmissionHold.Request( + source.targetNamespace(), + tenant, + source.worldSlug(), + realm, + source.playableStateNamespaceId(), + source.playableStateScope(), + source.canonicalGameInstanceId(), + source.canonicalVersionId(), + source.activeWorldEpoch(), + source.initialAdmissionRequestId(), + source.initialAdmissionRequestDigest(), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + source.catalogRevision(), + null); + var hold = + new WorldCanonicalInitialAdmissionHold.HoldIdentity( + holdRequest, source.holdId(), source.holdFence()); + var wire = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetEvidence(source).toBuilder() + .setCanonicalTenantUuid(0, tenant.toString()) + .setRealmUuid(0, realm.toString()) + .setTenantSlug(0, "tenant-" + index) + .setHoldBindingDigest(0, hold.holdBindingDigest()) + .setWorldDisplayName(0, "x"); + int characters = targetSize - wire.build().getSerializedSize() + 1; + wire.setWorldDisplayName(0, "x".repeat(characters)); + characters += targetSize - wire.build().getSerializedSize(); + wire.setWorldDisplayName(0, "x".repeat(characters)); + assertThat(wire.build().getSerializedSize()).isEqualTo(targetSize); + return wire.build(); + } + + @Test + void resolverAcceptsOnlyRetainedSelectorsAndDerivesVersionAndEpochFromOwnerTarget() + throws Exception { + var source = publishedRealmEvidence(); + var target = publishedTarget(source); + var selector = retainedSelector(target, source.request()); + var request = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionRequest(selector); + assertThat( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseTargetResolutionRequest(request)) + .isEqualTo(selector); + assertThat(request.getDescriptorForType().findFieldByName("canonical_version_uuid")).isNull(); + assertThat(request.getDescriptorForType().findFieldByName("active_world_epoch")).isNull(); + var response = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionResponse( + selector, target); + var resolved = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromTargetResolutionResponse( + selector, response); + assertThat(resolved.currentTarget()).isEqualTo(target); + assertThat(resolved.strictSelector()).isEqualTo(source.request()); + } + + @Test + void resolverRejectsUnknownDuplicateMissingAndChangedOriginalValues() throws Exception { + var source = publishedRealmEvidence(); + var target = publishedTarget(source); + var selector = retainedSelector(target, source.request()); + var request = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionRequest(selector); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + for (var malformed : + List.of( + request.toBuilder().addPointerVersion("1").build(), + request.toBuilder().clearAccountUuid().build(), + request.toBuilder().setUnknownFields(unknown).build(), + request.toBuilder().setCatalogRevision(0, "01").build(), + request.toBuilder().setPlayableStateScope(0, "ISOLATED").build())) { + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseTargetResolutionRequest( + malformed)) + .isInstanceOf(IllegalArgumentException.class); + } + var response = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionResponse( + selector, target); + for (var malformed : + List.of( + response.toBuilder().addSchemaVersion(1).build(), + response.toBuilder() + .setRequest(0, request.toBuilder().setAccountUuid(0, OTHER.toString())) + .build(), + response.toBuilder().setUnknownFields(unknown).build())) { + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromTargetResolutionResponse( + selector, malformed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void resolverRejectsEveryRetainedTargetMismatchAndPlayerCreatedSubstitution() throws Exception { + var source = publishedRealmEvidence(); + var target = publishedTarget(source); + var selector = retainedSelector(target, source.request()); + var response = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionResponse( + selector, target); + List< + java.util.function.Consumer< + net.firedevops.firemud.gamesession.v1.CanonicalPlayableTargetEvidence.Builder>> + changes = + List.of( + builder -> builder.setTargetNamespace(0, "foreign"), + builder -> builder.setCanonicalTenantUuid(0, OTHER.toString()), + builder -> builder.setTenantSlug(0, "another"), + builder -> builder.setWorldSlug(0, "another"), + builder -> builder.setRealmUuid(0, OTHER.toString()), + builder -> builder.setRealmSlug(0, "another"), + builder -> builder.setPlayableStateNamespaceUuid(0, OTHER.toString()), + builder -> builder.setPlayableStateScope(0, "ISOLATED"), + builder -> builder.setCanonicalGameInstanceUuid(0, OTHER.toString()), + builder -> builder.setCatalogRevision(0, "1"), + builder -> builder.setPointerVersion(0, "1"), + builder -> builder.setCharacterCreationPolicy(0, "PLAYER_CREATED")); + for (var change : changes) { + var changed = response.getCurrentTarget(0).toBuilder(); + change.accept(changed); + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromTargetResolutionResponse( + selector, response.toBuilder().setCurrentTarget(0, changed).build())) + .isInstanceOf(IllegalArgumentException.class); + } + } + + private static CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector + retainedSelector( + Target target, CanonicalGameplayRosterOwnerReadEvidence.Request correlation) { + return new CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector( + correlation.requestUuid(), + correlation.canonicalAccountUuid(), + target.targetNamespace(), + target.canonicalTenantId(), + target.tenantSlug(), + target.worldSlug(), + target.realmId(), + target.realmSlug(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + target.catalogRevision(), + target.pointerVersion()); + } + + @Test + void strictPublishedReadRequiresOneExactFreshActiveWorldCapture() throws Exception { + var source = publishedRealmEvidence(); + var target = publishedTarget(source); + var request = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmRequest( + source.request())); + var lifecycle = worldLifecycle(source, target); + var response = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmResponse( + request, source, target, lifecycle); + for (var malformed : + List.of( + response.toBuilder().clearWorldLifecycleEvidence().build(), + response.toBuilder() + .addWorldLifecycleEvidence(response.getWorldLifecycleEvidence(0)) + .build(), + response.toBuilder() + .setWorldLifecycleEvidence(0, ByteString.copyFromUtf8("{}")) + .build())) { + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + request, malformed)) + .isInstanceOf(IllegalArgumentException.class); + } + var original = lifecycle.request(); + var changedRequest = + new WorldCanonicalInstanceLifecycleEvidence.Request( + 1, + OTHER, + original.targetNamespace(), + original.canonicalTenantId(), + original.worldSlug(), + original.canonicalGameInstanceId(), + original.playableStateNamespaceId(), + original.playableStateScope(), + true, + original.controlPlaneRequestId(), + original.canonicalVersionId(), + original.expectedDescriptorRequestDigest(), + original.expectedDescriptorResultDigest(), + original.expectedReleaseAttestationDigest()); + for (var changed : + List.of( + copyWorld(lifecycle, original, "TERMINATING", lifecycle.lifecycleEpoch()), + copyWorld(lifecycle, original, "ACTIVE", lifecycle.lifecycleEpoch() + 1), + copyWorld(lifecycle, changedRequest, "ACTIVE", lifecycle.lifecycleEpoch()))) { + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + request, + response.toBuilder() + .setWorldLifecycleEvidence( + 0, ByteString.copyFrom(changed.canonicalBytes())) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + assertThat( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + request, response) + .worldLifecycleEvidence()) + .isEqualTo(lifecycle); + } + + private static WorldCanonicalInstanceLifecycleEvidence copyWorld( + WorldCanonicalInstanceLifecycleEvidence source, + WorldCanonicalInstanceLifecycleEvidence.Request request, + String status, + long epoch) { + return new WorldCanonicalInstanceLifecycleEvidence( + request, + source.launchBinding(), + source.startLocation(), + source.runtimeRoomInstanceId(), + status, + epoch, + source.rowVersion(), + source.captureId(), + source.graphSha256(), + source.preparationInputDigest(), + source.operationalRegionAssignments()); + } + + @Test + void strictEnvelopeRetainsCompleteWorldEvidenceAtTheExistingUpstreamTransportBoundary() + throws Exception { + var source = publishedRealmEvidence(); + var target = publishedTarget(source); + var small = worldLifecycle(source, target); + assertThat(small.operationalRegionAssignments()).hasSize(1); + // World uses one bytes field: near 4 MiB its tag and length occupy five bytes. Every additional + // canonical UUID-to-UUID JSON entry adds exactly 78 ASCII bytes, including its comma. + int upstreamBudget = GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES; + int entries = 1 + (upstreamBudget - 5 - small.canonicalBytes().length) / 78; + assertThat(entries).isGreaterThan(1); + Map assignments = new LinkedHashMap<>(); + for (int index = 1; index <= entries; index++) { + assignments.put(new UUID(1L, index), new UUID(2L, index)); + } + var complete = + new WorldCanonicalInstanceLifecycleEvidence( + small.request(), + small.launchBinding(), + small.startLocation(), + small.runtimeRoomInstanceId(), + small.lifecycleStatus(), + small.lifecycleEpoch(), + small.rowVersion(), + small.captureId(), + small.graphSha256(), + small.preparationInputDigest(), + assignments); + var upstream = + WorldCanonicalInstanceLifecycleGrpcCodec.toResponse(complete.request(), complete); + assertThat(upstream.getSerializedSize()) + .isLessThanOrEqualTo(upstreamBudget) + .isGreaterThan(upstreamBudget - 78); + var request = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmRequest( + source.request())); + var response = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmResponse( + request, source, target, complete); + assertThat(response.getSerializedSize()) + .isGreaterThan(upstreamBudget) + .isLessThanOrEqualTo( + CanonicalGameplayAdmissionDecisionReadGrpcCodec + .MAX_PUBLISHED_REALM_RESPONSE_WIRE_BYTES); + assertThat(response.getWorldLifecycleEvidence(0)) + .isEqualTo(upstream.getCanonicalResponseBytes()); + var decoded = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + request, response); + assertThat(decoded.worldLifecycleEvidence().canonicalBytes()) + .containsExactly(complete.canonicalBytes()); + assertThat(decoded.worldLifecycleEvidence().operationalRegionAssignments()) + .containsExactlyEntriesOf(assignments); + } + @Test void roundTripsCompleteProvisionalReadAndPreservesOriginalLeaseBytes() { var lease = lease(); @@ -237,13 +729,14 @@ void roundTripsClosedPublishedRealmSelectorAndCompleteCurrentTarget() throws Exc var target = publishedTarget(source); var response = CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmResponse( - parsedRequest, source, target); + parsedRequest, source, target, worldLifecycle(source, target)); var evidence = CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( parsedRequest, response); assertThat(evidence.selector()).isEqualTo(selector); assertThat(evidence.sourceEvidence()).isEqualTo(source); assertThat(evidence.currentTarget()).isEqualTo(target); + assertThat(evidence.worldLifecycleEvidence().lifecycleStatus()).isEqualTo("ACTIVE"); UnknownFieldSet unknown = UnknownFieldSet.newBuilder() @@ -367,7 +860,7 @@ void rejectsPublishedTargetSourceAndSelectorSubstitutions() throws Exception { var target = publishedTarget(source); var response = CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmResponse( - request, source, target); + request, source, target, worldLifecycle(source, target)); var targetEvidence = response.getCurrentTarget(0); for (var changed : List.of( @@ -417,7 +910,10 @@ void enforcesPublishedRealmWireBoundsOnRequestAndResponse() throws Exception { CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest(request); var response = CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmResponse( - parsedRequest, source, publishedTarget(source)); + parsedRequest, + source, + publishedTarget(source), + worldLifecycle(source, publishedTarget(source))); var oversizedResponse = response.toBuilder() .setPublishedSource( @@ -585,6 +1081,113 @@ private static CanonicalGameplayRosterOwnerReadEvidence publishedRealmEvidence() return new CanonicalGameplayRosterOwnerReadEvidence(request, "1".repeat(64), proof, policySet); } + private static WorldCanonicalInstanceLifecycleEvidence worldLifecycle( + CanonicalGameplayRosterOwnerReadEvidence source, Target target) { + var published = source.publishedPolicySetEvidence(); + var content = + GameDesignPublicationTerminalEvidence.fromStored(published.terminalEvidenceBytes()) + .releaseContent(); + var selected = content.worldStartLocationEvidence(); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + target.targetNamespace(), + "controlled-launch", + target.canonicalTenantId(), + target.worldSlug(), + HOLD_ID, + DIGEST, + 19L, + false, + null, + false, + null, + false, + null, + false, + null); + var descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "controlled-descriptor", + target.runtimeVersionId(), + false, + null, + "{}", + content.generationConfigRevision(), + published.publicationVersionStateEpoch(), + 1L, + published.publishedReleaseBundleRef(), + false, + null); + var participants = + content.participantDigests().stream() + .map( + p -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + p.participantKey(), + p.scopeValue(), + p.baseVersionId() != null, + p.baseVersionId(), + p.appliedCommitId(), + p.contentDigest(), + p.digestSchemaVersion(), + p.abilitySchemaDigest() != null, + p.abilitySchemaDigest())) + .toList(); + var release = + AuthoredWorldReleaseAttestationEvidence.create( + target.targetNamespace(), + descriptor.resultDigest(), + target.canonicalTenantId(), + target.canonicalVersionId(), + target.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + published.publishedReleaseBundleRef(), + published.publicationVersionStateEpoch(), + published.publishWorkflowId(), + published.sourceCommitId().toString(), + participants, + content.manifestHash(), + content.manifestSchemaVersion(), + content.requiredManifestAssetKeys(), + content.artifactDigests(), + content.commandDefinitions(), + content.generationConfigRevision(), + selected); + var binding = new CompleteLaunchBindingEvidence(descriptor, release); + var request = + new WorldCanonicalInstanceLifecycleEvidence.Request( + 1, + source.request().requestUuid(), + target.targetNamespace(), + target.canonicalTenantId(), + target.worldSlug(), + target.canonicalGameInstanceId(), + target.playableStateNamespaceId(), + "SHARED", + true, + descriptor.controlPlaneRequestId(), + target.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + var start = WorldDraftStartLocationEvidence.fromStored(selected.selectorReceiptBytes()); + return new WorldCanonicalInstanceLifecycleEvidence( + request, + binding, + start.startLocation(), + 1L, + "ACTIVE", + target.activeWorldEpoch(), + 1L, + HOLD_ID, + start.graphDigest().substring(7), + DIGEST, + Map.of(HOLD_ID, HOLD_FENCE)); + } + private static Target publishedTarget(CanonicalGameplayRosterOwnerReadEvidence evidence) { var request = evidence.request(); var proof = evidence.gameSessionOwnerProof(); @@ -604,7 +1207,7 @@ private static Target publishedTarget(CanonicalGameplayRosterOwnerReadEvidence e request.playableStateScope(), request.canonicalGameInstanceUuid(), request.canonicalVersionUuid(), - 99L, + evidence.publishedPolicySetEvidence().target().gameDesignVersionRowId(), request.expectedCatalogRevision(), request.expectedPointerVersion(), evidence.admissionPointerSnapshotDigest(), diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/JwtUtilTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/JwtUtilTest.java index e041043945..2d5b9f8e6e 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/JwtUtilTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/JwtUtilTest.java @@ -1,11 +1,15 @@ package net.firedevops.firemud.common.security; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jws; +import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.Date; +import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; @@ -27,7 +31,8 @@ void generateTokenWithExplicitExpirationUsesSuppliedLifetime() { long defaultExpirationMillis = 3_600_000L; long requestedExpirationMillis = 4_000L; JwtUtil util = new JwtUtil("mysecretkey123456789012345678901", defaultExpirationMillis); - Map suppliedClaims = Map.of("role", "admin", "tenantId", "7"); + Map suppliedClaims = + Map.of("role", "admin", "tenantId", "7", "sub", "claims-subject"); long beforeGeneration = System.currentTimeMillis(); String token = util.generateToken("demo", requestedExpirationMillis, suppliedClaims); @@ -49,4 +54,58 @@ void generateTokenWithExplicitExpirationUsesSuppliedLifetime() { <= afterGeneration + requestedExpirationMillis + clockPrecisionToleranceMillis, () -> "expiration was later than the explicit lifetime: " + expiration); } + + @Test + void generateTokenWithAbsoluteExpirationSignsTheExactExpiryAndOwnsRegisteredClaims() { + JwtUtil util = new JwtUtil("mysecretkey123456789012345678901", 3600000L); + Instant expiresAt = Instant.now().plusSeconds(30).truncatedTo(ChronoUnit.SECONDS); + Map suppliedClaims = new HashMap<>(); + suppliedClaims.put("role", "admin"); + suppliedClaims.put("sub", "claims-subject"); + suppliedClaims.put("iat", 1L); + suppliedClaims.put("exp", 2L); + + long beforeGeneration = System.currentTimeMillis(); + String token = util.generateToken("demo", expiresAt, suppliedClaims); + long afterGeneration = System.currentTimeMillis(); + + Claims payload = util.parseToken(token).getPayload(); + assertEquals("demo", payload.getSubject()); + assertEquals("admin", payload.get("role")); + assertEquals(expiresAt, payload.getExpiration().toInstant()); + assertTrue( + !payload + .getIssuedAt() + .toInstant() + .isBefore(Instant.ofEpochMilli(beforeGeneration).truncatedTo(ChronoUnit.SECONDS))); + assertTrue(payload.getIssuedAt().getTime() <= afterGeneration); + } + + @Test + void absoluteExpirationRejectsExpiredAndSubsecondValues() { + JwtUtil util = new JwtUtil("mysecretkey123456789012345678901", 3600000L); + + assertThrows( + IllegalArgumentException.class, + () -> util.generateToken("demo", Instant.EPOCH, Map.of("role", "admin"))); + assertThrows( + IllegalArgumentException.class, + () -> + util.generateToken( + "demo", Instant.parse("2030-01-01T00:00:30.000000001Z"), Map.of("role", "admin"))); + } + + @Test + void reloadableJwtUtilDelegatesAbsoluteExpiryToTheCurrentSigner() { + ReloadableJwtUtil util = new ReloadableJwtUtil("mysecretkey123456789012345678901", 3600000L); + util.updateSecret("rotatedsecretkey12345678901234567890"); + Instant expiresAt = Instant.now().plusSeconds(30).truncatedTo(ChronoUnit.SECONDS); + + String token = util.generateToken("demo", expiresAt, Map.of("role", "admin")); + + Claims payload = util.parseToken(token).getPayload(); + assertEquals("demo", payload.getSubject()); + assertEquals("admin", payload.get("role")); + assertEquals(expiresAt, payload.getExpiration().toInstant()); + } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/security/CanonicalGameplayAdmissionDecisionReadWorkloadGuard.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/security/CanonicalGameplayAdmissionDecisionReadWorkloadGuard.java index 177e9a4dfb..856558e99c 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/security/CanonicalGameplayAdmissionDecisionReadWorkloadGuard.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/security/CanonicalGameplayAdmissionDecisionReadWorkloadGuard.java @@ -19,6 +19,13 @@ public final class CanonicalGameplayAdmissionDecisionReadWorkloadGuard public static final String NEVER_ADMITTED_METHOD = "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/" + "GetOriginalNewNeverAdmittedDecision"; + public static final String TARGET_RESOLUTION_METHOD = + "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/ResolvePublishedRealmAdmissionTarget"; + public static final String PUBLISHED_REALM_METHOD = + "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetPublishedRealmAdmissionOwnerRead"; + + public static final String DISCOVERY_METHOD = + "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/ListVisiblePublicProductionAdmissionTargets"; private final String workloadNamespace; @@ -38,6 +45,8 @@ public void requireAccountCaller() { } if (SessionContext.hasAuthenticatedCallerContext() || SessionContext.isInternalService() + || SessionContext.getServiceName() != null + || SessionContext.getServiceInstanceId() != null || !"account-service".equals(peer.service()) || !workloadNamespace.equals(peer.namespace()) || !("spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service") @@ -53,7 +62,11 @@ public ServerCall.Listener interceptCall( ServerCall call, Metadata headers, ServerCallHandler next) { Objects.requireNonNull(call, "gRPC server call required"); String method = call.getMethodDescriptor().getFullMethodName(); - if (!METHOD.equals(method) && !NEVER_ADMITTED_METHOD.equals(method)) { + if (!METHOD.equals(method) + && !NEVER_ADMITTED_METHOD.equals(method) + && !TARGET_RESOLUTION_METHOD.equals(method) + && !PUBLISHED_REALM_METHOD.equals(method) + && !DISCOVERY_METHOD.equals(method)) { call.close( Status.PERMISSION_DENIED.withDescription("Exact Account decision-read method required"), new Metadata()); 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 54ea646741..d450e1041f 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 @@ -6,30 +6,49 @@ import io.lettuce.core.RedisCommandTimeoutException; import io.lettuce.core.RedisConnectionException; import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; import java.util.Objects; +import java.util.UUID; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionNeverAdmittedGrpcCodec; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; import net.firedevops.firemud.gamesession.repository.CanonicalGameplayBindingInventoryConflictException; import net.firedevops.firemud.gamesession.repository.CanonicalGameplayBindingInventoryRepository; import net.firedevops.firemud.gamesession.repository.CanonicalGameplayOriginalNewCandidateClosureRedisOwner; 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.v1.CanonicalGameplayAdmissionDecisionReadServiceGrpc; import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayAdmissionDecisionRequest; import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayAdmissionDecisionResponse; import net.firedevops.firemud.gamesession.v1.GetOriginalNewNeverAdmittedDecisionRequest; import net.firedevops.firemud.gamesession.v1.GetOriginalNewNeverAdmittedDecisionResponse; +import net.firedevops.firemud.gamesession.v1.GetPublishedRealmAdmissionOwnerReadRequest; +import net.firedevops.firemud.gamesession.v1.GetPublishedRealmAdmissionOwnerReadResponse; +import net.firedevops.firemud.gamesession.v1.ListVisiblePublicProductionAdmissionTargetsRequest; +import net.firedevops.firemud.gamesession.v1.ListVisiblePublicProductionAdmissionTargetsResponse; +import net.firedevops.firemud.gamesession.v1.ResolvePublishedRealmAdmissionTargetRequest; +import net.firedevops.firemud.gamesession.v1.ResolvePublishedRealmAdmissionTargetResponse; import org.jooq.exception.DataAccessException; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.dao.TransientDataAccessException; import org.springframework.transaction.CannotCreateTransactionException; import org.springframework.transaction.support.TransactionSynchronizationManager; -/** Unregistered, non-admitting Account-only read of one exact retained PROVISIONAL decision. */ +/** Unregistered Account-only current-target, published-source and retained-decision reads. */ public final class CanonicalGameplayAdmissionDecisionReadGrpcService extends CanonicalGameplayAdmissionDecisionReadServiceGrpc .CanonicalGameplayAdmissionDecisionReadServiceImplBase { @@ -37,6 +56,10 @@ public final class CanonicalGameplayAdmissionDecisionReadGrpcService private final CanonicalGameplayAdmissionDecisionReadWorkloadGuard workloadGuard; private final String workloadNamespace; private final CanonicalGameplayOriginalNewCandidateClosureRedisOwner closureOwner; + private final CanonicalPlayerRouteReadService routeReader; + private final CanonicalPublishedPlayerRouteReadService publishedReader; + private final CanonicalGameInstanceLaunchAssociationRepository launchReader; + private final WorldCanonicalInstanceLifecycleClient world; public CanonicalGameplayAdmissionDecisionReadGrpcService( CanonicalGameplayBindingInventoryRepository repository, @@ -50,6 +73,19 @@ public CanonicalGameplayAdmissionDecisionReadGrpcService( CanonicalGameplayAdmissionDecisionReadWorkloadGuard workloadGuard, String workloadNamespace, CanonicalGameplayOriginalNewCandidateClosureRedisOwner closureOwner) { + this(repository, workloadGuard, workloadNamespace, closureOwner, null, null, null, null); + } + + /** Complete strict-source composition; no default registration or World hold is acquired. */ + public CanonicalGameplayAdmissionDecisionReadGrpcService( + CanonicalGameplayBindingInventoryRepository repository, + CanonicalGameplayAdmissionDecisionReadWorkloadGuard workloadGuard, + String workloadNamespace, + CanonicalGameplayOriginalNewCandidateClosureRedisOwner closureOwner, + CanonicalPlayerRouteReadService routeReader, + CanonicalPublishedPlayerRouteReadService publishedReader, + CanonicalGameInstanceLaunchAssociationRepository launchReader, + WorldCanonicalInstanceLifecycleClient world) { this.repository = Objects.requireNonNull(repository, "Game Session decision owner required"); this.workloadGuard = Objects.requireNonNull(workloadGuard, "Account-only decision-read guard required"); @@ -58,6 +94,361 @@ public CanonicalGameplayAdmissionDecisionReadGrpcService( } this.workloadNamespace = workloadNamespace; this.closureOwner = closureOwner; + this.routeReader = routeReader; + this.publishedReader = publishedReader; + this.launchReader = launchReader; + this.world = world; + } + + /** Complete canonical discovery only; this manually composed receiver grants no admission. */ + @Override + public void listVisiblePublicProductionAdmissionTargets( + ListVisiblePublicProductionAdmissionTargetsRequest request, + StreamObserver observer) { + Objects.requireNonNull(observer); + if (!requireSourceCallerOutsideSql(observer)) return; + final CanonicalGameplayAdmissionDecisionReadGrpcCodec.DiscoveryRequest parsed; + try { + if (request == null) { + fail(observer, Status.INVALID_ARGUMENT); + return; + } + parsed = CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseDiscoveryRequest(request); + } catch (IllegalArgumentException malformed) { + fail(observer, Status.INVALID_ARGUMENT); + return; + } catch (RuntimeException unexpectedParserFailure) { + fail(observer, Status.INTERNAL); + return; + } + if (!workloadNamespace.equals(parsed.targetNamespace())) { + fail(observer, Status.PERMISSION_DENIED); + return; + } + if (routeReader == null) { + fail(observer, Status.UNAVAILABLE); + return; + } + final ListVisiblePublicProductionAdmissionTargetsResponse response; + try { + var before = readPreseededDiscoveryTargets(); + // Validate the complete first read before treating it as an expected collection. + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse(parsed, before); + var after = readPreseededDiscoveryTargets(); + response = CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse(parsed, after); + if (!new HashSet<>(before).equals(new HashSet<>(after))) { + fail(observer, Status.FAILED_PRECONDITION); + return; + } + } catch (RuntimeException failure) { + failSource(observer, failure); + return; + } + sendSource(observer, response); + } + + @Override + public void resolvePublishedRealmAdmissionTarget( + ResolvePublishedRealmAdmissionTargetRequest request, + StreamObserver observer) { + Objects.requireNonNull(observer); + if (!requireSourceCallerOutsideSql(observer)) return; + if (request == null) { + fail(observer, Status.INVALID_ARGUMENT); + return; + } + final CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector selector; + try { + selector = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseTargetResolutionRequest(request); + } catch (IllegalArgumentException malformed) { + fail(observer, Status.INVALID_ARGUMENT); + return; + } catch (RuntimeException unexpectedParserFailure) { + fail(observer, Status.INTERNAL); + return; + } + if (!workloadNamespace.equals(selector.targetNamespace())) { + fail(observer, Status.PERMISSION_DENIED); + return; + } + if (routeReader == null) { + fail(observer, Status.UNAVAILABLE); + return; + } + final ResolvePublishedRealmAdmissionTargetResponse response; + try { + var before = routeReader.readCurrentTarget(selector.tenantId()); + CanonicalGameplayAdmissionDecisionReadGrpcCodec.requireRetainedTargetMatches( + selector, toTarget(before)); + var after = routeReader.readCurrentTarget(selector.tenantId()); + if (!before.equals(after)) { + fail(observer, Status.FAILED_PRECONDITION); + return; + } + response = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionResponse( + selector, toTarget(after)); + } catch (RuntimeException failure) { + failSource(observer, failure); + return; + } + sendSource(observer, response); + } + + private List readPreseededDiscoveryTargets() { + 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. + var target = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseTargetEvidence( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetEvidence(toTarget(route))); + if (!workloadNamespace.equals(target.targetNamespace()) + || !"SHARED".equals(target.playableStateScope()) + || target.ownerProofOutcome() != OwnerProofOutcome.COMMITTED + || target.positiveDurableAbort() + || !tenants.add(target.canonicalTenantId()) + || !tenantSlugs.add(target.tenantSlug()) + || !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())) { + throw new IllegalArgumentException("Discovery source has unsupported character policy"); + } + } + return List.copyOf(selected); + } + + @Override + public void getPublishedRealmAdmissionOwnerRead( + GetPublishedRealmAdmissionOwnerReadRequest request, + StreamObserver observer) { + Objects.requireNonNull(observer); + if (!requireSourceCallerOutsideSql(observer)) return; + if (request == null) { + fail(observer, Status.INVALID_ARGUMENT); + return; + } + final CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmRequest parsed; + try { + parsed = CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest(request); + } catch (IllegalArgumentException malformed) { + fail(observer, Status.INVALID_ARGUMENT); + return; + } catch (RuntimeException unexpectedParserFailure) { + fail(observer, Status.INTERNAL); + return; + } + if (!workloadNamespace.equals(parsed.selector().targetNamespace())) { + fail(observer, Status.PERMISSION_DENIED); + return; + } + if (routeReader == null || publishedReader == null || launchReader == null || world == null) { + fail(observer, Status.UNAVAILABLE); + return; + } + final GetPublishedRealmAdmissionOwnerReadResponse response; + try { + var before = routeReader.readCurrentTarget(parsed.selector().canonicalTenantUuid()); + if (!matchesPublishedRoute(before, parsed.selector())) { + fail(observer, Status.FAILED_PRECONDITION); + return; + } + var launchBefore = readCurrentLaunch(before); + var sourceBefore = publishedReader.readCurrent(parsed.selector()); + var association = launchBefore.association(); + var descriptor = association.launchBindingEvidence().descriptor(); + var lifecycleRequest = + new WorldCanonicalInstanceLifecycleEvidence.Request( + 1, + parsed.selector().requestUuid(), + workloadNamespace, + before.canonicalTenantId(), + before.worldSlug(), + before.canonicalGameInstanceId(), + before.playableStateNamespaceId(), + before.playableStateScope(), + true, + association.controlPlaneRequestId(), + before.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + association.launchBindingEvidence().releaseAttestation().evidenceDigest()); + requireOutsideSourceSql(); + var lifecycle = readWorld(lifecycleRequest); + if (lifecycle == null + || !lifecycleRequest.equals(lifecycle.request()) + || !"ACTIVE".equals(lifecycle.lifecycleStatus()) + || lifecycle.lifecycleEpoch() != before.activeWorldEpoch() + || !association.launchBindingEvidence().equals(lifecycle.launchBinding())) { + fail(observer, Status.FAILED_PRECONDITION); + return; + } + var sourceAfter = publishedReader.readCurrent(parsed.selector()); + var after = routeReader.readCurrentTarget(parsed.selector().canonicalTenantUuid()); + if (!before.equals(after)) { + fail(observer, Status.FAILED_PRECONDITION); + return; + } + var launchAfter = readCurrentLaunch(after); + if (!launchBefore.equals(launchAfter) || !sourceBefore.equals(sourceAfter)) { + fail(observer, Status.FAILED_PRECONDITION); + return; + } + response = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmResponse( + parsed, sourceAfter, toTarget(after), lifecycle); + } catch (RuntimeException failure) { + failSource(observer, failure); + return; + } + sendSource(observer, response); + } + + private static boolean matchesPublishedRoute( + CanonicalPlayableTarget route, CanonicalGameplayRosterOwnerReadEvidence.Request selector) { + return selector.targetNamespace().equals(route.targetNamespace()) + && selector.canonicalTenantUuid().equals(route.canonicalTenantId()) + && selector.worldSlug().equals(route.worldSlug()) + && selector.realmUuid().equals(route.realmId()) + && selector.realmSlug().equals(route.realmSlug()) + && selector.playableStateNamespaceUuid().equals(route.playableStateNamespaceId()) + && selector.playableStateScope().equals(route.playableStateScope()) + && selector.canonicalGameInstanceUuid().equals(route.canonicalGameInstanceId()) + && selector.canonicalVersionUuid().equals(route.canonicalVersionId()) + && selector.expectedCatalogRevision() == route.catalogRevision() + && selector.expectedPointerVersion() == route.pointerVersion() + && selector.expectedActiveWorldEpoch() == route.activeWorldEpoch(); + } + + private CanonicalInitialAdmissionLaunchTarget readCurrentLaunch(CanonicalPlayableTarget route) { + var launch = + launchReader + .readForInitialAdmission( + workloadNamespace, + route.canonicalTenantId(), + route.realmId(), + route.canonicalGameInstanceId()) + .orElseThrow( + () -> + new CanonicalPublishedPlayerRouteReadService.StaleAuthorityException( + "Current launch source is absent")); + var association = launch.association(); + if (!workloadNamespace.equals(association.targetNamespace()) + || !route.canonicalTenantId().equals(association.canonicalTenantId()) + || !route.realmId().equals(launch.realmId()) + || !route.worldSlug().equals(association.worldSlug()) + || !route.canonicalGameInstanceId().equals(association.gameInstanceUuid()) + || !route.playableStateNamespaceId().equals(association.playableStateNamespaceId()) + || !route.playableStateScope().equals(association.playableStateScope().name()) + || !association.publicProduction() + || association.currentGameInstanceStatus() + != CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.RUNNING + || !route.canonicalVersionId().equals(launch.canonicalVersionId()) + || route.gameInstanceId() != launch.gameInstanceId() + || route.runtimeVersionId() != launch.runtimeVersionId() + || route.gameSessionTenantId() != association.gameSessionTenantId()) { + throw new CanonicalPublishedPlayerRouteReadService.StaleAuthorityException( + "Current launch differs from pointer source"); + } + return launch; + } + + private WorldCanonicalInstanceLifecycleEvidence readWorld( + WorldCanonicalInstanceLifecycleEvidence.Request request) { + try { + return world.read(request); + } catch (IllegalStateException failure) { + if (failure.getCause() instanceof IllegalArgumentException malformed) { + throw new CanonicalPublishedPlayerRouteReadService.InvalidAuthorityException( + "World lifecycle response is invalid", malformed); + } + throw new WorldReadUnavailableException(failure); + } + } + + private static void requireOutsideSourceSql() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new CanonicalPublishedPlayerRouteReadService.InvalidAuthorityException( + "Independent World source read requires no SQL"); + } + } + + private static final class WorldReadUnavailableException extends RuntimeException { + private WorldReadUnavailableException(Throwable cause) { + super(cause); + } + } + + private boolean requireSourceCallerOutsideSql(StreamObserver observer) { + try { + workloadGuard.requireAccountCaller(); + } catch (StatusRuntimeException denied) { + fail(observer, denied.getStatus()); + return false; + } catch (RuntimeException unexpectedGuardFailure) { + fail(observer, Status.INTERNAL); + return false; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + fail(observer, Status.FAILED_PRECONDITION); + return false; + } + return true; + } + + private static void failSource(StreamObserver observer, RuntimeException failure) { + if (failure instanceof CanonicalPlayerRouteReadService.ReadUnavailableException + || failure instanceof WorldReadUnavailableException + || failure instanceof CanonicalPublishedPlayerRouteReadService.StorageUnavailableException + || failure + instanceof CanonicalPublishedPlayerRouteReadService.GameDesignUnavailableException + || failure instanceof CannotCreateTransactionException + || failure instanceof DataAccessResourceFailureException + || failure instanceof TransientDataAccessException) { + fail(observer, Status.UNAVAILABLE); + } else if (failure instanceof StatusRuntimeException transport) { + var code = transport.getStatus().getCode(); + fail( + observer, + switch (code) { + case UNAVAILABLE, DEADLINE_EXCEEDED, RESOURCE_EXHAUSTED, ABORTED -> Status.UNAVAILABLE; + case NOT_FOUND, + FAILED_PRECONDITION, + INVALID_ARGUMENT, + PERMISSION_DENIED, + UNAUTHENTICATED -> + Status.FAILED_PRECONDITION; + default -> Status.INTERNAL; + }); + } else if (failure instanceof CanonicalPlayerRouteReadService.InvalidAuthorityException + || failure instanceof CanonicalPublishedPlayerRouteReadService.InvalidAuthorityException + || failure instanceof CanonicalPublishedPlayerRouteReadService.StaleAuthorityException + || failure instanceof IllegalArgumentException) { + fail(observer, Status.FAILED_PRECONDITION); + } else if (failure instanceof DataAccessException + || failure instanceof org.springframework.dao.DataAccessException) { + fail(observer, hasConnectionFailureSqlState(failure) ? Status.UNAVAILABLE : Status.INTERNAL); + } else { + fail(observer, Status.INTERNAL); + } + } + + private static void sendSource(StreamObserver observer, T response) { + try { + observer.onNext(response); + } catch (RuntimeException callbackFailure) { + fail(observer, Status.INTERNAL); + return; + } + observer.onCompleted(); } @Override diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture.java index cdaa806670..09c5401071 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture.java @@ -301,13 +301,15 @@ public void getPublishedRealmAdmissionOwnerRead( } observer.onNext( CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmResponse( - parsed, controlledPublishedEvidence(expected), target())); + parsed, + controlledPublishedEvidence(expected), + target(), + controlledWorldLifecycle(expected))); observer.onCompleted(); } }; - // Both handlers authenticate first; the actual decision-only interceptor intentionally - // refuses the separate published-source purpose and cannot guard this test-only combined - // adapter. + // Both handlers authenticate first. The upstream publication and World lifecycle captures + // remain explicitly controlled; the actual retained-decision receiver is unchanged. factory.addService( ServerInterceptors.interceptForward( controlledPublishedSource, new GrpcPeerIdentityInterceptor())); @@ -424,6 +426,123 @@ public void getPublishedRealmAdmissionOwnerRead( selector, target.admissionPointerSnapshotDigest(), controlledProof, complete); } + /** Retained launch descriptor and publication selector with controlled World capture facts. */ + private net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence + controlledWorldLifecycle( + net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence.Request + selector) { + var target = target(); + var launch = + new CanonicalGameInstanceLaunchAssociationRepository(binding.dsl(), "test") + .readForInitialAdmission( + "test", + target.canonicalTenantId(), + target.realmId(), + target.canonicalGameInstanceId()) + .orElseThrow() + .association(); + var descriptor = launch.launchBindingEvidence().descriptor(); + // The stored Game Session launch release is intentionally minimal. Rebuild the controlled + // World binding from this target's retained complete publication, keeping the actual launch + // descriptor and using its retained start-location selector rather than a guessed room. + byte[] policyBytes = + java.util.Objects.requireNonNull( + binding + .dsl() + .fetchSingle( + "SELECT complete_policy_set_evidence FROM game_session_canonical_realm_catalog " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ?", + "test", + target.canonicalTenantId(), + target.realmId()) + .get(0, byte[].class), + "Controlled complete publication fixture is required"); + var publishedSet = + net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidenceCodec.decode( + policyBytes); + var publishedRelease = + net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.fromStored( + publishedSet.terminalEvidenceBytes()) + .releaseContent(); + var worldSelector = publishedRelease.worldStartLocationEvidence(); + var participants = + publishedRelease.participantDigests().stream() + .map( + participant -> + new net.firedevops.firemud.common.gamedesign + .AuthoredWorldReleaseAttestationEvidence.Participant( + participant.participantKey(), + participant.scopeValue(), + false, + null, + participant.appliedCommitId(), + participant.contentDigest(), + participant.digestSchemaVersion(), + participant.abilitySchemaDigest() != null, + participant.abilitySchemaDigest())) + .toList(); + var release = + net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + publishedRelease.canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + publishedRelease.publishWorkflowId(), + worldSelector.request().appliedCommitId(), + participants, + publishedRelease.manifestHash(), + publishedRelease.manifestSchemaVersion(), + publishedRelease.requiredManifestAssetKeys(), + publishedRelease.artifactDigests(), + publishedRelease.commandDefinitions(), + descriptor.generationConfigRevision(), + worldSelector); + var complete = + new net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence( + descriptor, release); + var start = + net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence.fromStored( + worldSelector.selectorReceiptBytes()); + var request = + new net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence.Request( + 1, + selector.requestUuid(), + "test", + target.canonicalTenantId(), + target.worldSlug(), + target.canonicalGameInstanceId(), + target.playableStateNamespaceId(), + target.playableStateScope(), + true, + launch.controlPlaneRequestId(), + target.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + return new net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence( + request, + complete, + start.startLocation(), + 1L, + "ACTIVE", + target.activeWorldEpoch(), + 1L, + UUID.nameUUIDFromBytes( + ("controlled-world-capture:" + selector.requestUuid()) + .getBytes(StandardCharsets.UTF_8)), + start.graphDigest().substring(7), + "sha256:" + "a".repeat(64), + java.util.Map.of( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"))); + } + public void installActualCandidate(AccountGameplayAdmissionLeaseEvidence actualLease) { decision = new CanonicalGameplayAdmissionDecision( 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 18cb1ea23c..391e6129fe 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 @@ -2,6 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; @@ -9,6 +10,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; 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; @@ -20,8 +22,11 @@ import io.lettuce.core.RedisClient; import io.lettuce.core.RedisCommandTimeoutException; import io.lettuce.core.RedisConnectionException; +import java.nio.charset.StandardCharsets; import java.sql.SQLException; +import java.time.Instant; import java.util.HexFormat; +import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; @@ -30,13 +35,20 @@ import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionNeverAdmittedGrpcCodec; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; import net.firedevops.firemud.gamesession.security.CanonicalGameplayAdmissionDecisionReadWorkloadGuard; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; import net.firedevops.firemud.gamesession.service.impl.CanonicalGameplayAdmissionDecisionReadGrpcService; import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayAdmissionDecisionRequest; import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayAdmissionDecisionResponse; import net.firedevops.firemud.gamesession.v1.GetOriginalNewNeverAdmittedDecisionRequest; import net.firedevops.firemud.gamesession.v1.GetOriginalNewNeverAdmittedDecisionResponse; +import net.firedevops.firemud.gamesession.v1.ListVisiblePublicProductionAdmissionTargetsRequest; +import net.firedevops.firemud.gamesession.v1.ListVisiblePublicProductionAdmissionTargetsResponse; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.springframework.dao.DataAccessResourceFailureException; @@ -50,6 +62,364 @@ * separate PostgreSQL test. */ class CanonicalGameplayAdmissionDecisionReadGrpcServiceTest { + @Test + void discoveryReturnsOnlyCompleteUnchangedOwnerCollectionRegardlessOfIterationOrder() { + var routes = mock(CanonicalPlayerRouteReadService.class); + var first = discoveryTarget("first", "First world"); + var second = discoveryTarget("second", "Second world"); + when(routes.readVisiblePublicProductionTargets()) + .thenReturn(List.of(first, second), List.of(second, first)); + var observer = discoveryObserver(); + discoveryService(routes, mock(CanonicalGameplayAdmissionDecisionReadWorkloadGuard.class)) + .listVisiblePublicProductionAdmissionTargets(discoveryRequest(), observer); + var captured = + ArgumentCaptor.forClass(ListVisiblePublicProductionAdmissionTargetsResponse.class); + verify(observer).onNext(captured.capture()); + verify(observer).onCompleted(); + verify(observer, never()).onError(any()); + var result = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseDiscoveryRequest( + discoveryRequest()), + captured.getValue()); + assertThat(result.targets()) + .extracting( + target -> target.canonicalTenantId(), + target -> target.canonicalGameInstanceId(), + target -> target.ownerProofDigest()) + .containsExactlyInAnyOrder( + tuple( + first.canonicalTenantId(), + first.canonicalGameInstanceId(), + first.ownerProofDigest()), + tuple( + second.canonicalTenantId(), + second.canonicalGameInstanceId(), + second.ownerProofDigest())); + verify(routes, org.mockito.Mockito.times(2)).readVisiblePublicProductionTargets(); + } + + @Test + void discoveryExcludesValidPlayerCreatedTargetsOnBothReads() { + 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))) { + var routes = mock(CanonicalPlayerRouteReadService.class); + var reversed = new java.util.ArrayList<>(initial); + java.util.Collections.reverse(reversed); + when(routes.readVisiblePublicProductionTargets()).thenReturn(initial, reversed); + var observer = discoveryObserver(); + discoveryService(routes, mock(CanonicalGameplayAdmissionDecisionReadWorkloadGuard.class)) + .listVisiblePublicProductionAdmissionTargets(discoveryRequest(), observer); + var captured = + ArgumentCaptor.forClass(ListVisiblePublicProductionAdmissionTargetsResponse.class); + verify(observer).onNext(captured.capture()); + verify(observer).onCompleted(); + verify(observer, never()).onError(any()); + var result = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseDiscoveryRequest( + discoveryRequest()), + captured.getValue()); + assertThat(result.targets()).hasSize(initial.size() - 1); + assertThat(result.targets()) + .allMatch(target -> target.characterCreationPolicy().equals("PRESEEDED_ONLY")); + verify(routes, times(2)).readVisiblePublicProductionTargets(); + } + } + + @Test + void discoveryDoesNotHideMalformedPlayerCreatedAuthority() { + var created = discoveryTarget("created", "World", "PLAYER_CREATED"); + var malformed = + mock(CanonicalPlayableTarget.class, org.mockito.AdditionalAnswers.delegatesTo(created)); + org.mockito.Mockito.doReturn("not-a-proof-digest").when(malformed).ownerProofDigest(); + var routes = mock(CanonicalPlayerRouteReadService.class); + when(routes.readVisiblePublicProductionTargets()).thenReturn(List.of(malformed)); + var observer = discoveryObserver(); + discoveryService(routes, mock(CanonicalGameplayAdmissionDecisionReadWorkloadGuard.class)) + .listVisiblePublicProductionAdmissionTargets(discoveryRequest(), observer); + assertDiscoveryFailure(observer, Status.Code.FAILED_PRECONDITION); + verify(routes).readVisiblePublicProductionTargets(); + } + + @Test + void discoveryDoesNotHideDuplicateAuthorityBehindPlayerCreatedFiltering() { + var preseeded = discoveryTarget("same", "World"); + var created = discoveryTarget("same", "World", "PLAYER_CREATED"); + for (var targets : List.of(List.of(preseeded, created), List.of(created, created))) { + var routes = mock(CanonicalPlayerRouteReadService.class); + when(routes.readVisiblePublicProductionTargets()).thenReturn(targets); + var observer = discoveryObserver(); + discoveryService(routes, mock(CanonicalGameplayAdmissionDecisionReadWorkloadGuard.class)) + .listVisiblePublicProductionAdmissionTargets(discoveryRequest(), observer); + assertDiscoveryFailure(observer, Status.Code.FAILED_PRECONDITION); + verify(routes).readVisiblePublicProductionTargets(); + } + } + + @Test + void discoveryAllowsGenuineEmptyCollectionButNeverDependencyAbsenceAsEmptySuccess() { + var routes = mock(CanonicalPlayerRouteReadService.class); + when(routes.readVisiblePublicProductionTargets()).thenReturn(List.of()); + var observer = discoveryObserver(); + discoveryService(routes, mock(CanonicalGameplayAdmissionDecisionReadWorkloadGuard.class)) + .listVisiblePublicProductionAdmissionTargets(discoveryRequest(), observer); + var captured = + ArgumentCaptor.forClass(ListVisiblePublicProductionAdmissionTargetsResponse.class); + verify(observer).onNext(captured.capture()); + assertThat(captured.getValue().getCurrentTargetsList()).isEmpty(); + verify(observer).onCompleted(); + var absent = discoveryObserver(); + discoveryService(null, mock(CanonicalGameplayAdmissionDecisionReadWorkloadGuard.class)) + .listVisiblePublicProductionAdmissionTargets(discoveryRequest(), absent); + assertDiscoveryFailure(absent, Status.Code.UNAVAILABLE); + when(routes.readVisiblePublicProductionTargets()) + .thenThrow( + new CanonicalPlayerRouteReadService.ReadUnavailableException("private storage detail")); + var unavailable = discoveryObserver(); + discoveryService(routes, mock(CanonicalGameplayAdmissionDecisionReadWorkloadGuard.class)) + .listVisiblePublicProductionAdmissionTargets(discoveryRequest(), unavailable); + assertDiscoveryFailure(unavailable, Status.Code.UNAVAILABLE); + } + + @Test + void discoveryRejectsChangedContentsMembershipAndDuplicates() { + var first = discoveryTarget("first", "First world"); + var second = discoveryTarget("second", "Second world"); + for (var changed : + List.of( + List.of(), + List.of(first, second), + List.of(discoveryTarget("first", "Changed display")), + List.of(first, first))) { + var routes = mock(CanonicalPlayerRouteReadService.class); + when(routes.readVisiblePublicProductionTargets()).thenReturn(List.of(first), changed); + var observer = discoveryObserver(); + discoveryService(routes, mock(CanonicalGameplayAdmissionDecisionReadWorkloadGuard.class)) + .listVisiblePublicProductionAdmissionTargets(discoveryRequest(), observer); + assertDiscoveryFailure(observer, Status.Code.FAILED_PRECONDITION); + } + } + + @Test + void discoveryRejectsAnUnchangedOversizedTargetBeforeTheSecondSourceRead() { + var oversized = discoveryTarget("first", "x".repeat(64 * 1024)); + var routes = mock(CanonicalPlayerRouteReadService.class); + when(routes.readVisiblePublicProductionTargets()).thenReturn(List.of(oversized)); + var observer = discoveryObserver(); + discoveryService(routes, mock(CanonicalGameplayAdmissionDecisionReadWorkloadGuard.class)) + .listVisiblePublicProductionAdmissionTargets(discoveryRequest(), observer); + assertDiscoveryFailure(observer, Status.Code.FAILED_PRECONDITION); + verify(routes, times(1)).readVisiblePublicProductionTargets(); + } + + @Test + void discoveryAuthenticatesAndRejectsSqlBeforeParsingOrOwnerAccess() { + var routes = mock(CanonicalPlayerRouteReadService.class); + var guard = mock(CanonicalGameplayAdmissionDecisionReadWorkloadGuard.class); + doThrow(Status.PERMISSION_DENIED.asRuntimeException()).when(guard).requireAccountCaller(); + var denied = discoveryObserver(); + discoveryService(routes, guard) + .listVisiblePublicProductionAdmissionTargets( + ListVisiblePublicProductionAdmissionTargetsRequest.getDefaultInstance(), denied); + assertDiscoveryFailure(denied, Status.Code.PERMISSION_DENIED); + verifyNoInteractions(routes); + for (boolean synchronization : new boolean[] {false, true}) { + var observer = discoveryObserver(); + var allowed = mock(CanonicalGameplayAdmissionDecisionReadWorkloadGuard.class); + try { + if (synchronization) TransactionSynchronizationManager.initSynchronization(); + else TransactionSynchronizationManager.setActualTransactionActive(true); + discoveryService(routes, allowed) + .listVisiblePublicProductionAdmissionTargets( + ListVisiblePublicProductionAdmissionTargetsRequest.getDefaultInstance(), observer); + assertDiscoveryFailure(observer, Status.Code.FAILED_PRECONDITION); + verify(allowed).requireAccountCaller(); + } finally { + TransactionSynchronizationManager.clear(); + } + } + verifyNoInteractions(routes); + } + + @Test + void discoveryRejectsMalformedOrForeignNamespaceBeforeOwnerAccess() { + var routes = mock(CanonicalPlayerRouteReadService.class); + for (var request : + List.of( + ListVisiblePublicProductionAdmissionTargetsRequest.getDefaultInstance(), + discoveryRequest().toBuilder().setTargetNamespace(0, "foreign").build())) { + var observer = discoveryObserver(); + discoveryService(routes, mock(CanonicalGameplayAdmissionDecisionReadWorkloadGuard.class)) + .listVisiblePublicProductionAdmissionTargets(request, observer); + assertDiscoveryFailure( + observer, + request.getSchemaVersionCount() == 0 + ? Status.Code.INVALID_ARGUMENT + : Status.Code.PERMISSION_DENIED); + } + verifyNoInteractions(routes); + } + + private static CanonicalGameplayAdmissionDecisionReadGrpcService discoveryService( + CanonicalPlayerRouteReadService routes, + CanonicalGameplayAdmissionDecisionReadWorkloadGuard guard) { + return new CanonicalGameplayAdmissionDecisionReadGrpcService( + mock(CanonicalGameplayBindingInventoryRepository.class), + guard, + "test", + null, + routes, + null, + null, + null); + } + + private static ListVisiblePublicProductionAdmissionTargetsRequest discoveryRequest() { + return CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryRequest( + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.DiscoveryRequest( + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), "test")); + } + + @SuppressWarnings("unchecked") + private static StreamObserver + discoveryObserver() { + return mock(StreamObserver.class); + } + + @Test + void discoveryUnexpectedSourceFailuresUseTheSourceContractsSanitizedStatus() { + for (RuntimeException failure : + List.of( + new UnsupportedOperationException("private storage detail"), + new IllegalStateException("private storage detail"), + new IllegalArgumentException("private storage detail"))) { + var routes = mock(CanonicalPlayerRouteReadService.class); + when(routes.readVisiblePublicProductionTargets()).thenThrow(failure); + var observer = discoveryObserver(); + discoveryService(routes, mock(CanonicalGameplayAdmissionDecisionReadWorkloadGuard.class)) + .listVisiblePublicProductionAdmissionTargets(discoveryRequest(), observer); + assertDiscoveryFailure( + observer, + failure instanceof IllegalArgumentException + ? Status.Code.FAILED_PRECONDITION + : Status.Code.INTERNAL); + } + } + + @Test + void discoveryObserverFailuresNeverProduceASecondTerminalSignal() { + for (boolean completionFailure : List.of(false, true)) { + var routes = mock(CanonicalPlayerRouteReadService.class); + when(routes.readVisiblePublicProductionTargets()).thenReturn(List.of()); + var observer = discoveryObserver(); + var failure = new IllegalStateException("private observer detail"); + if (completionFailure) doThrow(failure).when(observer).onCompleted(); + else doThrow(failure).when(observer).onNext(any()); + Runnable receive = + () -> + discoveryService( + routes, mock(CanonicalGameplayAdmissionDecisionReadWorkloadGuard.class)) + .listVisiblePublicProductionAdmissionTargets(discoveryRequest(), observer); + if (completionFailure) assertThatThrownBy(receive::run).isSameAs(failure); + else receive.run(); + verify(observer).onNext(any()); + if (completionFailure) { + verify(observer).onCompleted(); + verify(observer, never()).onError(any()); + } else { + var error = ArgumentCaptor.forClass(Throwable.class); + verify(observer).onError(error.capture()); + assertThat(Status.fromThrowable(error.getValue()).getCode()) + .isEqualTo(Status.Code.INTERNAL); + assertThat(error.getValue()) + .hasMessageNotContaining("private observer detail") + .hasNoCause(); + verify(observer, never()).onCompleted(); + } + } + } + + private static void assertDiscoveryFailure( + StreamObserver observer, + Status.Code expected) { + var error = ArgumentCaptor.forClass(Throwable.class); + verify(observer).onError(error.capture()); + assertThat(Status.fromThrowable(error.getValue()).getCode()).isEqualTo(expected); + assertThat(error.getValue()).hasMessageNotContaining("private storage detail"); + verify(observer, never()).onNext(any()); + verify(observer, never()).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) { + 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"); + UUID instance = UUID.nameUUIDFromBytes(("instance-" + slug).getBytes(StandardCharsets.UTF_8)); + UUID version = UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + UUID holdId = UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + UUID holdFence = UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + String requestId = + UUID.nameUUIDFromBytes(("admission-" + slug).getBytes(StandardCharsets.UTF_8)).toString(); + String digest = "a".repeat(64); + var request = + new WorldCanonicalInitialAdmissionHold.Request( + "test", + tenant, + "earth", + realm, + namespace, + "SHARED", + instance, + version, + 7, + requestId, + digest, + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + 2, + null); + var hold = new WorldCanonicalInitialAdmissionHold.HoldIdentity(request, holdId, holdFence); + return new CanonicalPlayableTarget( + "test", + slug, + tenant, + "earth", + displayName, + realm, + "production", + "Production", + 11, + 71, + namespace, + "SHARED", + instance, + version, + 99, + 2, + 3, + "d".repeat(64), + 7, + requestId, + digest, + CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER, + null, + holdId, + holdFence, + hold.holdBindingDigest(), + 101, + "sha256:" + digest, + CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + false, + Instant.parse("2026-10-25T00:00:00Z"), + policy); + } + @Test void deniesNonAccountCallerBeforeParsingOrRepositoryRead() { var repository = mock(CanonicalGameplayBindingInventoryRepository.class); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionPublishedReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionPublishedReadGrpcServiceTest.java new file mode 100644 index 0000000000..3e7673a4aa --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionPublishedReadGrpcServiceTest.java @@ -0,0 +1,680 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.AdditionalAnswers.delegatesTo; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +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.Status; +import io.grpc.stub.StreamObserver; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +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 net.firedevops.firemud.gamesession.v1.GetPublishedRealmAdmissionOwnerReadRequest; +import net.firedevops.firemud.gamesession.v1.GetPublishedRealmAdmissionOwnerReadResponse; +import net.firedevops.firemud.gamesession.v1.ResolvePublishedRealmAdmissionTargetRequest; +import net.firedevops.firemud.gamesession.v1.ResolvePublishedRealmAdmissionTargetResponse; +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.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Controlled collaborator/codec tests; source-content and physical owner proof remain separate. */ +class CanonicalGameplayAdmissionPublishedReadGrpcServiceTest { + private static final UUID TENANT = UUID.fromString("11111111-1111-4111-8111-111111111111"); + + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void certificateDenialPrecedesBothParsersAndEveryOwnerRead() { + Fixture f = new Fixture(); + doThrow(Status.PERMISSION_DENIED.asRuntimeException()).when(f.guard).requireAccountCaller(); + try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { + f.service.resolvePublishedRealmAdmissionTarget( + ResolvePublishedRealmAdmissionTargetRequest.getDefaultInstance(), f.resolverObserver); + f.service.getPublishedRealmAdmissionOwnerRead( + GetPublishedRealmAdmissionOwnerReadRequest.getDefaultInstance(), f.publishedObserver); + codec.verifyNoInteractions(); + } + assertFailure(f.resolverObserver, Status.Code.PERMISSION_DENIED); + assertFailure(f.publishedObserver, Status.Code.PERMISSION_DENIED); + verifyNoInteractions(f.routes, f.published, f.inventory); + } + + @Test + void synchronizationRefusalPrecedesBothParsersAndEveryOwnerRead() { + Fixture f = new Fixture(); + TransactionSynchronizationManager.initSynchronization(); + try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { + f.service.resolvePublishedRealmAdmissionTarget( + ResolvePublishedRealmAdmissionTargetRequest.getDefaultInstance(), f.resolverObserver); + f.service.getPublishedRealmAdmissionOwnerRead( + GetPublishedRealmAdmissionOwnerReadRequest.getDefaultInstance(), f.publishedObserver); + codec.verifyNoInteractions(); + } + assertFailure(f.resolverObserver, Status.Code.FAILED_PRECONDITION); + assertFailure(f.publishedObserver, Status.Code.FAILED_PRECONDITION); + verifyNoInteractions(f.routes, f.published, f.inventory); + } + + @Test + void resolverReadsActualTenantOwnerTwiceAndPassesItsUnchangedTargetToClosedEncoder() { + Fixture f = new Fixture(); + var request = ResolvePublishedRealmAdmissionTargetRequest.getDefaultInstance(); + var response = + ResolvePublishedRealmAdmissionTargetResponse.newBuilder().addSchemaVersion(1).build(); + var route = route(); + when(f.routes.readCurrentTarget(TENANT)).thenReturn(route); + try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { + codec + .when( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseTargetResolutionRequest( + request)) + .thenReturn(f.selector); + codec + .when( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionResponse( + eq(f.selector), any())) + .thenReturn(response); + f.service.resolvePublishedRealmAdmissionTarget(request, f.resolverObserver); + var encoded = + org.mockito.ArgumentCaptor.forClass( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target.class); + codec.verify( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionResponse( + eq(f.selector), encoded.capture())); + assertThat(encoded.getValue()) + .usingRecursiveComparison() + .withComparatorForFields( + java.util.Comparator.comparing(Object::toString), + "initialAdmissionOriginKind", + "ownerProofOutcome") + .isEqualTo(route); + codec.verify( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.requireRetainedTargetMatches( + eq(f.selector), eq(encoded.getValue()))); + } + verify(f.routes, times(2)).readCurrentTarget(TENANT); + verify(f.resolverObserver).onNext(response); + verify(f.resolverObserver).onCompleted(); + verify(f.resolverObserver, never()).onError(any()); + verifyNoInteractions(f.published, f.inventory); + } + + @Test + void resolverTargetChangeAndUnavailableStorageReturnNoSelectionEvidence() { + for (boolean unavailable : new boolean[] {false, true}) { + Fixture f = new Fixture(); + var request = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionRequest(f.selector); + if (unavailable) { + when(f.routes.readCurrentTarget(TENANT)) + .thenThrow( + new CanonicalPlayerRouteReadService.ReadUnavailableException("private failure")); + } else { + var before = route(); + var changed = route(); + when(f.routes.readCurrentTarget(TENANT)).thenReturn(before, changed); + } + try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { + codec + .when( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseTargetResolutionRequest( + request)) + .thenReturn(f.selector); + f.service.resolvePublishedRealmAdmissionTarget(request, f.resolverObserver); + } + assertFailure( + f.resolverObserver, + unavailable ? Status.Code.UNAVAILABLE : Status.Code.FAILED_PRECONDITION); + verifyNoInteractions(f.published, f.inventory); + } + } + + @Test + void strictReadUsesPublishedOwnerBetweenCompleteRouteReadsAndReturnsItsExactSource() { + Fixture f = new Fixture(); + var request = GetPublishedRealmAdmissionOwnerReadRequest.getDefaultInstance(); + var parsed = mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmRequest.class); + var selector = strictSelector(f.selector); + when(parsed.selector()).thenReturn(selector); + var source = mock(CanonicalGameplayRosterOwnerReadEvidence.class); + var response = + GetPublishedRealmAdmissionOwnerReadResponse.newBuilder().addSchemaVersion(1).build(); + var route = f.configureStrictRoute(selector); + when(f.published.readCurrent(selector)).thenReturn(source); + var worldResult = new AtomicReference(); + doAnswer( + invocation -> { + var evidence = f.worldEvidence(invocation.getArgument(0), "ACTIVE", 7); + worldResult.set(evidence); + return evidence; + }) + .when(f.world) + .read(any()); + var encodedTarget = + ArgumentCaptor.forClass(CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target.class); + var encodedWorld = ArgumentCaptor.forClass(WorldCanonicalInstanceLifecycleEvidence.class); + try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { + codec + .when( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( + request)) + .thenReturn(parsed); + codec + .when( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmResponse( + eq(parsed), eq(source), any(), any())) + .thenReturn(response); + f.service.getPublishedRealmAdmissionOwnerRead(request, f.publishedObserver); + codec.verify( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmResponse( + eq(parsed), eq(source), encodedTarget.capture(), encodedWorld.capture())); + } + assertThat(encodedTarget.getValue()) + .usingRecursiveComparison() + .withComparatorForFields( + java.util.Comparator.comparing(Object::toString), + "initialAdmissionOriginKind", + "ownerProofOutcome") + .isEqualTo(route); + assertThat(encodedWorld.getValue()).isSameAs(worldResult.get()); + var worldRequest = + ArgumentCaptor.forClass(WorldCanonicalInstanceLifecycleEvidence.Request.class); + var order = org.mockito.Mockito.inOrder(f.routes, f.published, f.world); + order.verify(f.routes).readCurrentTarget(TENANT); + order.verify(f.published).readCurrent(selector); + order.verify(f.world).read(worldRequest.capture()); + order.verify(f.published).readCurrent(selector); + order.verify(f.routes).readCurrentTarget(TENANT); + assertThat(worldRequest.getValue()) + .usingRecursiveComparison() + .isEqualTo(encodedWorld.getValue().request()); + assertThat(worldRequest.getValue().readRequestId()).isEqualTo(selector.requestUuid()); + assertThat(worldRequest.getValue().targetNamespace()).isEqualTo("test"); + assertThat(worldRequest.getValue().canonicalTenantId()).isEqualTo(TENANT); + assertThat(worldRequest.getValue().worldSlug()).isEqualTo(selector.worldSlug()); + assertThat(worldRequest.getValue().canonicalGameInstanceId()) + .isEqualTo(selector.canonicalGameInstanceUuid()); + assertThat(worldRequest.getValue().playableStateNamespaceId()) + .isEqualTo(selector.playableStateNamespaceUuid()); + assertThat(worldRequest.getValue().playableStateScope()).isEqualTo("SHARED"); + assertThat(worldRequest.getValue().canonicalVersionId()) + .isEqualTo(selector.canonicalVersionUuid()); + assertThat(worldRequest.getValue().publicProduction()).isTrue(); + assertThat(encodedWorld.getValue().lifecycleStatus()).isEqualTo("ACTIVE"); + assertThat(encodedWorld.getValue().lifecycleEpoch()).isEqualTo(7); + verify(f.publishedObserver).onNext(response); + verify(f.publishedObserver).onCompleted(); + verifyNoInteractions(f.inventory); + } + + @ParameterizedTest + @ValueSource( + strings = { + "namespace", + "tenant", + "world", + "realm", + "realm-slug", + "playable-namespace", + "scope", + "instance", + "version", + "catalog", + "pointer", + "epoch" + }) + void staleRouteRefusesBeforeLaunchPublicationAndWorldEvenWhenDependencyIsUnavailable( + String changed) { + Fixture f = new Fixture(); + var selector = strictSelector(f.selector); + var route = f.configureStrictRoute(selector); + switch (changed) { + case "namespace" -> when(route.targetNamespace()).thenReturn("other"); + case "tenant" -> when(route.canonicalTenantId()).thenReturn(UUID.randomUUID()); + case "world" -> when(route.worldSlug()).thenReturn("other"); + case "realm" -> when(route.realmId()).thenReturn(UUID.randomUUID()); + case "realm-slug" -> when(route.realmSlug()).thenReturn("other"); + case "playable-namespace" -> + when(route.playableStateNamespaceId()).thenReturn(UUID.randomUUID()); + case "scope" -> when(route.playableStateScope()).thenReturn("ISOLATED"); + case "instance" -> when(route.canonicalGameInstanceId()).thenReturn(UUID.randomUUID()); + case "version" -> when(route.canonicalVersionId()).thenReturn(UUID.randomUUID()); + case "catalog" -> + when(route.catalogRevision()).thenReturn(selector.expectedCatalogRevision() + 1); + case "pointer" -> + when(route.pointerVersion()).thenReturn(selector.expectedPointerVersion() + 1); + case "epoch" -> + when(route.activeWorldEpoch()).thenReturn(selector.expectedActiveWorldEpoch() + 1); + default -> throw new IllegalArgumentException(changed); + } + when(f.published.readCurrent(selector)) + .thenThrow( + new CanonicalPublishedPlayerRouteReadService.StorageUnavailableException( + "private source")); + f.service.getPublishedRealmAdmissionOwnerRead( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmRequest(selector), + f.publishedObserver); + assertFailure(f.publishedObserver, Status.Code.FAILED_PRECONDITION); + verify(f.routes).readCurrentTarget(TENANT); + verifyNoInteractions(f.launches, f.published, f.world, f.inventory); + } + + @Test + void strictReadPreservesUnavailableAndRejectsChangedRouteWithoutReturningSource() { + for (boolean unavailable : new boolean[] {false, true}) { + Fixture f = new Fixture(); + var request = GetPublishedRealmAdmissionOwnerReadRequest.getDefaultInstance(); + var parsed = + mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmRequest.class); + var selector = strictSelector(f.selector); + when(parsed.selector()).thenReturn(selector); + var before = f.configureStrictRoute(selector); + var changed = route(); + when(f.routes.readCurrentTarget(TENANT)).thenReturn(before, changed); + if (unavailable) { + when(f.published.readCurrent(selector)) + .thenThrow( + new CanonicalPublishedPlayerRouteReadService.StorageUnavailableException( + "private source")); + } + try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { + codec + .when( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( + request)) + .thenReturn(parsed); + f.service.getPublishedRealmAdmissionOwnerRead(request, f.publishedObserver); + } + assertFailure( + f.publishedObserver, + unavailable ? Status.Code.UNAVAILABLE : Status.Code.FAILED_PRECONDITION); + } + } + + @Test + void strictReadRejectsMissingInactiveWrongEpochAndUnavailableWorldWithoutPositiveEvidence() { + for (String outcome : + java.util.List.of( + "MISSING", + "TERMINATING", + "WRONG_EPOCH", + "WRONG_REQUEST", + "WRONG_BINDING", + "UNAVAILABLE")) { + Fixture f = new Fixture(); + var request = GetPublishedRealmAdmissionOwnerReadRequest.getDefaultInstance(); + var parsed = + mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmRequest.class); + var selector = strictSelector(f.selector); + when(parsed.selector()).thenReturn(selector); + f.configureStrictRoute(selector); + if ("UNAVAILABLE".equals(outcome)) { + doThrow(Status.UNAVAILABLE.asRuntimeException()).when(f.world).read(any()); + } else if ("MISSING".equals(outcome)) { + doReturn(null).when(f.world).read(any()); + } else { + doAnswer( + invocation -> { + var evidence = + f.worldEvidence( + invocation.getArgument(0), + "TERMINATING".equals(outcome) ? "TERMINATING" : "ACTIVE", + "WRONG_EPOCH".equals(outcome) ? 8 : 7); + if ("WRONG_REQUEST".equals(outcome)) + when(evidence.request()) + .thenReturn(mock(WorldCanonicalInstanceLifecycleEvidence.Request.class)); + if ("WRONG_BINDING".equals(outcome)) + when(evidence.launchBinding()) + .thenReturn(mock(CompleteLaunchBindingEvidence.class)); + return evidence; + }) + .when(f.world) + .read(any()); + } + try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { + codec + .when( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( + request)) + .thenReturn(parsed); + f.service.getPublishedRealmAdmissionOwnerRead(request, f.publishedObserver); + } + assertFailure( + f.publishedObserver, + "UNAVAILABLE".equals(outcome) + ? Status.Code.UNAVAILABLE + : Status.Code.FAILED_PRECONDITION); + verify(f.published, times(1)).readCurrent(selector); + } + } + + @ParameterizedTest + @ValueSource( + strings = { + "absent", + "namespace", + "tenant", + "realm", + "world", + "instance-uuid", + "state-namespace", + "state-scope", + "non-production", + "stopped", + "version", + "instance-id", + "runtime-version", + "numeric-tenant", + "changed-after" + }) + void strictReadRefusesAbsentMismatchedOrChangedLaunchAuthority(String change) { + Fixture f = new Fixture(); + var request = GetPublishedRealmAdmissionOwnerReadRequest.getDefaultInstance(); + var parsed = mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmRequest.class); + var selector = strictSelector(f.selector); + when(parsed.selector()).thenReturn(selector); + f.configureStrictRoute(selector); + var launch = + f.launches + .readForInitialAdmission( + "test", TENANT, selector.realmUuid(), selector.canonicalGameInstanceUuid()) + .orElseThrow(); + var association = launch.association(); + switch (change) { + case "absent" -> + when(f.launches.readForInitialAdmission( + "test", TENANT, selector.realmUuid(), selector.canonicalGameInstanceUuid())) + .thenReturn(Optional.empty()); + case "namespace" -> when(association.targetNamespace()).thenReturn("other"); + case "tenant" -> when(association.canonicalTenantId()).thenReturn(UUID.randomUUID()); + case "realm" -> when(launch.realmId()).thenReturn(UUID.randomUUID()); + case "world" -> when(association.worldSlug()).thenReturn("other"); + case "instance-uuid" -> when(association.gameInstanceUuid()).thenReturn(UUID.randomUUID()); + case "state-namespace" -> + when(association.playableStateNamespaceId()).thenReturn(UUID.randomUUID()); + case "state-scope" -> + when(association.playableStateScope()).thenReturn(RealmEntryPolicy.StateScope.ISOLATED); + case "non-production" -> when(association.publicProduction()).thenReturn(false); + case "stopped" -> + when(association.currentGameInstanceStatus()) + .thenReturn(CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.STOPPED); + case "version" -> when(launch.canonicalVersionId()).thenReturn(UUID.randomUUID()); + case "instance-id" -> when(launch.gameInstanceId()).thenReturn(72L); + case "runtime-version" -> when(launch.runtimeVersionId()).thenReturn(10L); + case "numeric-tenant" -> when(association.gameSessionTenantId()).thenReturn(12L); + case "changed-after" -> { + var changed = mock(CanonicalInitialAdmissionLaunchTarget.class); + when(association.currentRowVersion()).thenReturn(1L); + var changedAssociation = + mock(CanonicalGameInstanceLaunchAssociation.class, delegatesTo(association)); + when(changedAssociation.currentRowVersion()).thenReturn(2L); + when(changed.association()).thenReturn(changedAssociation); + doReturn(launch.realmId()).when(changed).realmId(); + doReturn(launch.canonicalVersionId()).when(changed).canonicalVersionId(); + doReturn(launch.gameInstanceId()).when(changed).gameInstanceId(); + doReturn(launch.runtimeVersionId()).when(changed).runtimeVersionId(); + when(f.launches.readForInitialAdmission( + "test", TENANT, selector.realmUuid(), selector.canonicalGameInstanceUuid())) + .thenReturn(Optional.of(launch), Optional.of(changed)); + } + default -> throw new AssertionError(change); + } + try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { + codec + .when( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( + request)) + .thenReturn(parsed); + f.service.getPublishedRealmAdmissionOwnerRead(request, f.publishedObserver); + } + assertFailure(f.publishedObserver, Status.Code.FAILED_PRECONDITION); + if ("changed-after".equals(change)) { + verify(f.world).read(any()); + verify(f.published, times(2)).readCurrent(selector); + } else { + verifyNoInteractions(f.world, f.published); + } + verifyNoInteractions(f.inventory); + } + + @Test + void strictReadRefusesPublicationChangeAfterTheHealthyWorldRead() { + Fixture f = new Fixture(); + var request = GetPublishedRealmAdmissionOwnerReadRequest.getDefaultInstance(); + var parsed = mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmRequest.class); + var selector = strictSelector(f.selector); + when(parsed.selector()).thenReturn(selector); + f.configureStrictRoute(selector); + when(f.published.readCurrent(selector)) + .thenReturn( + mock(CanonicalGameplayRosterOwnerReadEvidence.class), + mock(CanonicalGameplayRosterOwnerReadEvidence.class)); + try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { + codec + .when( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( + request)) + .thenReturn(parsed); + f.service.getPublishedRealmAdmissionOwnerRead(request, f.publishedObserver); + } + verify(f.world).read(any()); + verify(f.published, times(2)).readCurrent(selector); + assertFailure(f.publishedObserver, Status.Code.FAILED_PRECONDITION); + } + + @Test + void closedInvalidRequestAndAbsentCompositionFailWithoutSourceReads() { + Fixture f = new Fixture(); + f.service.resolvePublishedRealmAdmissionTarget( + ResolvePublishedRealmAdmissionTargetRequest.getDefaultInstance(), f.resolverObserver); + assertFailure(f.resolverObserver, Status.Code.INVALID_ARGUMENT); + var observer = resolverObserver(); + new CanonicalGameplayAdmissionDecisionReadGrpcService(f.inventory, f.guard, "test") + .resolvePublishedRealmAdmissionTarget( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionRequest(f.selector), + observer); + assertFailure(observer, Status.Code.UNAVAILABLE); + verifyNoInteractions(f.routes, f.published, f.inventory); + } + + private static CanonicalGameplayRosterOwnerReadEvidence.Request strictSelector( + RetainedTargetSelector selector) { + return new CanonicalGameplayRosterOwnerReadEvidence.Request( + selector.readRequestId(), + selector.accountId(), + "test", + TENANT, + selector.worldSlug(), + selector.realmId(), + selector.realmSlug(), + selector.playableStateNamespaceId(), + "SHARED", + selector.gameInstanceId(), + UUID.randomUUID(), + selector.catalogRevision(), + selector.pointerVersion(), + 7); + } + + private static CanonicalPlayableTarget route() { + var route = mock(CanonicalPlayableTarget.class); + when(route.initialAdmissionOriginKind()) + .thenReturn(CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER); + when(route.ownerProofOutcome()) + .thenReturn(CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); + return route; + } + + private static void assertFailure(StreamObserver observer, Status.Code code) { + var error = ArgumentCaptor.forClass(Throwable.class); + verify(observer).onError(error.capture()); + assertThat(Status.fromThrowable(error.getValue()).getCode()).isEqualTo(code); + assertThat(error.getValue()).hasMessageNotContaining("private"); + verify(observer, never()).onNext(any()); + verify(observer, never()).onCompleted(); + } + + @SuppressWarnings("unchecked") + private static StreamObserver resolverObserver() { + return mock(StreamObserver.class); + } + + private static final class Fixture { + private final CanonicalGameplayBindingInventoryRepository inventory = + mock(CanonicalGameplayBindingInventoryRepository.class); + private final CanonicalGameplayAdmissionDecisionReadWorkloadGuard guard = + mock(CanonicalGameplayAdmissionDecisionReadWorkloadGuard.class); + private final CanonicalPlayerRouteReadService routes = + mock(CanonicalPlayerRouteReadService.class); + private final CanonicalPublishedPlayerRouteReadService published = + mock(CanonicalPublishedPlayerRouteReadService.class); + private final CanonicalGameInstanceLaunchAssociationRepository launches = + mock(CanonicalGameInstanceLaunchAssociationRepository.class); + private final WorldCanonicalInstanceLifecycleClient world = + mock(WorldCanonicalInstanceLifecycleClient.class); + private final CompleteLaunchBindingEvidence binding = mock(CompleteLaunchBindingEvidence.class); + private final RetainedTargetSelector selector = + new RetainedTargetSelector( + UUID.randomUUID(), + UUID.randomUUID(), + "test", + TENANT, + "tenant", + "earth", + UUID.randomUUID(), + "main", + UUID.randomUUID(), + "SHARED", + UUID.randomUUID(), + 3, + 5); + private final StreamObserver resolverObserver = + resolverObserver(); + + @SuppressWarnings("unchecked") + private final StreamObserver publishedObserver = + mock(StreamObserver.class); + + private final CanonicalGameplayAdmissionDecisionReadGrpcService service = + new CanonicalGameplayAdmissionDecisionReadGrpcService( + inventory, guard, "test", null, routes, published, launches, world); + + private CanonicalPlayableTarget configureStrictRoute( + CanonicalGameplayRosterOwnerReadEvidence.Request selector) { + var current = route(); + when(current.targetNamespace()).thenReturn("test"); + when(current.canonicalTenantId()).thenReturn(TENANT); + when(current.realmId()).thenReturn(selector.realmUuid()); + when(current.realmSlug()).thenReturn(selector.realmSlug()); + when(current.worldSlug()).thenReturn(selector.worldSlug()); + when(current.canonicalGameInstanceId()).thenReturn(selector.canonicalGameInstanceUuid()); + when(current.playableStateNamespaceId()).thenReturn(selector.playableStateNamespaceUuid()); + when(current.playableStateScope()).thenReturn("SHARED"); + when(current.canonicalVersionId()).thenReturn(selector.canonicalVersionUuid()); + when(current.catalogRevision()).thenReturn(selector.expectedCatalogRevision()); + when(current.pointerVersion()).thenReturn(selector.expectedPointerVersion()); + when(current.activeWorldEpoch()).thenReturn(7L); + when(current.gameSessionTenantId()).thenReturn(11L); + when(current.gameInstanceId()).thenReturn(71L); + when(current.runtimeVersionId()).thenReturn(9L); + when(routes.readCurrentTarget(TENANT)).thenReturn(current); + var target = mock(CanonicalInitialAdmissionLaunchTarget.class); + var association = mock(CanonicalGameInstanceLaunchAssociation.class); + when(target.association()).thenReturn(association); + when(target.realmId()).thenReturn(selector.realmUuid()); + when(target.canonicalVersionId()).thenReturn(selector.canonicalVersionUuid()); + when(target.gameInstanceId()).thenReturn(71L); + when(target.runtimeVersionId()).thenReturn(9L); + when(association.targetNamespace()).thenReturn("test"); + when(association.canonicalTenantId()).thenReturn(TENANT); + when(association.worldSlug()).thenReturn(selector.worldSlug()); + when(association.gameInstanceUuid()).thenReturn(selector.canonicalGameInstanceUuid()); + when(association.playableStateNamespaceId()) + .thenReturn(selector.playableStateNamespaceUuid()); + when(association.playableStateScope()).thenReturn(RealmEntryPolicy.StateScope.SHARED); + when(association.publicProduction()).thenReturn(true); + when(association.currentGameInstanceStatus()) + .thenReturn(CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.RUNNING); + when(association.gameSessionTenantId()).thenReturn(11L); + when(association.controlPlaneRequestId()).thenReturn("controlled-launch"); + when(association.launchBindingEvidence()).thenReturn(binding); + var descriptor = mock(AuthoredWorldLaunchDescriptorEvidence.class); + var release = mock(AuthoredWorldReleaseAttestationEvidence.class); + when(binding.descriptor()).thenReturn(descriptor); + when(binding.releaseAttestation()).thenReturn(release); + when(descriptor.requestDigest()).thenReturn("sha256:" + "a".repeat(64)); + when(descriptor.resultDigest()).thenReturn("sha256:" + "b".repeat(64)); + when(release.evidenceDigest()).thenReturn("sha256:" + "c".repeat(64)); + when(launches.readForInitialAdmission( + "test", TENANT, selector.realmUuid(), selector.canonicalGameInstanceUuid())) + .thenReturn(Optional.of(target)); + when(published.readCurrent(selector)) + .thenReturn(mock(CanonicalGameplayRosterOwnerReadEvidence.class)); + when(world.read(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return worldEvidence(invocation.getArgument(0), "ACTIVE", 7); + }); + return current; + } + + private WorldCanonicalInstanceLifecycleEvidence worldEvidence( + WorldCanonicalInstanceLifecycleEvidence.Request request, String status, long epoch) { + var evidence = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(evidence.request()).thenReturn(request); + when(evidence.launchBinding()).thenReturn(binding); + when(evidence.lifecycleStatus()).thenReturn(status); + when(evidence.lifecycleEpoch()).thenReturn(epoch); + return evidence; + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayAdmissionDecisionReadWorkloadGuardTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayAdmissionDecisionReadWorkloadGuardTest.java index 5a428fefda..31661272f0 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayAdmissionDecisionReadWorkloadGuardTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayAdmissionDecisionReadWorkloadGuardTest.java @@ -56,6 +56,40 @@ void acceptsOnlyTheExactSameNamespaceAccountMethod() { } } + @Test + void publishedAndResolverMethodsRequireTheirExactAccountCertificateAndNoCallerContext() { + for (var method : + List.of( + CanonicalGameplayAdmissionDecisionReadServiceGrpc + .getListVisiblePublicProductionAdmissionTargetsMethod(), + CanonicalGameplayAdmissionDecisionReadServiceGrpc + .getResolvePublishedRealmAdmissionTargetMethod(), + CanonicalGameplayAdmissionDecisionReadServiceGrpc + .getGetPublishedRealmAdmissionOwnerReadMethod())) { + assertThat(invoke(method, peer(NAMESPACE, "account-service")).nextStarts()).isEqualTo(1); + assertRejected(invoke(method, null), Status.Code.UNAUTHENTICATED); + assertRejected( + invoke(method, peer(NAMESPACE, "entity-management-service")), + Status.Code.PERMISSION_DENIED); + assertRejected( + invoke(method, peer("foreign", "account-service")), Status.Code.PERMISSION_DENIED); + SessionContext.setContext("account", List.of(), Map.of()); + assertRejected( + invoke(method, peer(NAMESPACE, "account-service")), Status.Code.PERMISSION_DENIED); + SessionContext.setContext(null, List.of(), Map.of(), true, "account-service", "instance"); + assertRejected( + invoke(method, peer(NAMESPACE, "account-service")), Status.Code.PERMISSION_DENIED); + SessionContext.clear(); + assertRejected( + invoke( + method.toBuilder() + .setFullMethodName("other.Service/" + method.getBareMethodName()) + .build(), + peer(NAMESPACE, "account-service")), + Status.Code.PERMISSION_DENIED); + } + } + @Test void rejectsMissingForeignOrSessionContextIdentityBeforeHandler() { var method =