diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index bc7f07c849..fb73e9a561 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -233,7 +233,7 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - `ListPresenceVisibilityPolicies` – bounded internal bulk read of current tenant-scoped profile visibility policy for up to 100 canonical Account UUIDs. Account resolves known subjects through one local UUID batch query with the same persisted provenance and source-row checks as scalar identity reads, then returns policies keyed by UUID. Unknown or unproven entries are intentionally omitted so Social applies complete `PRIVATE` redaction. - `ExportAccount` – **target-state RPC** equivalent of `POST /accounts/{accountId}/exports`; starts or reads the persisted export operation for the caller's `requestId` and matching versioned `requestDigest`, returning the same stable `exportId` on replay and an idempotency conflict on digest mismatch. It gathers every required owning-service contribution and exposes a versioned portable-data manifest with explicit complete, partial, omitted, redacted, unavailable, retryable, failed, and separately retained owner outcomes; this is not a promise of every account-related record or secret. The current gRPC adapter returns `FAILED_PRECONDITION` before selector parsing or owner reads; this does not implement the target export operation. -- `CommitTenantCapacityAdmission` – **internal RPC with an unregistered receiving implementation** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the target contract's exact complete Account-authenticated entitlement bundle from `GetTenantEntitlementsForRuntime`, including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. The current numeric runtime endpoint returns `ENTITLEMENT_UNAVAILABLE` and is not qualified player evidence; the separately prepared `PLAYER_ADMISSION` evidence comes from Account's manually composed caller-bound `AccountPlayerAdmissionEntitlementOwner`/receiver and Game Session client. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry of the currently bound reservation attempt, fence, complete payload and digest replays its durably retained result. Outside proof-backed rearm, a change to a bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest conflicts before usage mutation when it differs from an existing retained binding. After transport validation, Account resolves exact replay/conflict first, then checks retained/current evidence, supported shape, and quota. Fresh authoritative billing or non-creating entitlement refusal returns the typed `TENANT_BILLING_BLOCKED` response. This billing refusal does not itself bind the attempt, consume the quota-refusal budget, or create a durable decision receipt; it remains available when no refusal-budget row exists. Fresh creation-eligible evidence with checked insufficient capacity returns the typed `CAPACITY_QUOTA_EXCEEDED` response only after the exact durable `NO_ACCEPT` decision commits. If its refusal budget is missing or exhausted, Account returns non-OK `ENTITLEMENT_UNAVAILABLE` instead; no quota receipt or settlement authority is issued. Each refusal response is correlated to the exact original attempt, mutation digest, snapshot and evaluation. A quota refusal includes the immutable Account decision UUID only after an exact durable `NO_ACCEPT` commits. A matching exact retry returns the retained receipt. A quota refusal without that receipt grants no evidence settlement authority. The response contains exactly one commitment or one typed refusal. A fresh positive reservation requires the exact retained evaluation to remain within its lifetime according to both the Account clock and the PostgreSQL owner clock. If both clocks establish expiry before quota or reservation mutation, Account can return `CAPACITY_EVALUATION_EXPIRED` for an exact creation-eligible original evaluation after committing its exact budgeted `NO_ACCEPT` receipt. This includes expiry during source qualification when the current membership source still matches and its billing cutoff remains exact. The receipt grants settlement only for the matching Game Session evidence charge. A stale evaluation without settled owner proof, including a superseded billing cutoff, still returns `CAPACITY_ADMISSION_STALE` with `UNAVAILABLE`. Missing or unqualified current entitlement owner evidence or its dependency returns `ENTITLEMENT_UNAVAILABLE`. The receiver preserves `AUTH_UNAVAILABLE` for authentication authority unavailability, `PERMISSION_DENIED` for an authenticated caller mismatch, `INVALID_ARGUMENT` for malformed requests, and `IDEMPOTENCY_CONFLICT` with `ALREADY_EXISTS` for a mismatch against an existing retained binding outside proof-backed rearm. The prepared receiver also rejects a structurally valid initial attempt whose `capacityRearmFence` is not `1`, even when no reservation exists; that rejection occurs before retained quota-denial lookup. The Game Session client validates the bounded details and preserves the gRPC outcome. These errors grant no release or rearm authority. Rearm, recovery, and execution still require creation-committable evidence. The shared proto/codec, bounded private mTLS receiver, Game Session adapter and Account durable owner are locally prepared but unqualified and unregistered. The current owner accepts only exact new player-binding shape; World lifecycle activation and zero-delta recovery remain held without genuine current producers. Current source and proof limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). +- `CommitTenantCapacityAdmission` – **internal RPC with an unregistered receiving implementation** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the target contract's exact complete Account-authenticated entitlement bundle from `GetTenantEntitlementsForRuntime`, including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. The current numeric runtime endpoint returns `ENTITLEMENT_UNAVAILABLE` and is not qualified player evidence; the separately prepared `PLAYER_ADMISSION` evidence comes from Account's manually composed caller-bound `AccountPlayerAdmissionEntitlementOwner`/receiver and Game Session client. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry of the currently bound reservation attempt, fence, complete payload and digest replays its durably retained result. Outside proof-backed rearm, a change to a bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest conflicts before usage mutation when it differs from an existing retained binding. After transport validation, Account resolves exact replay/conflict first, then checks retained/current evidence, supported shape, and quota. Fresh authoritative billing or non-creating entitlement refusal returns the typed `TENANT_BILLING_BLOCKED` response. This billing refusal does not itself bind the attempt, consume the quota-refusal budget, or create a durable decision receipt; it remains available when no refusal-budget row exists. Fresh creation-eligible evidence with checked insufficient capacity returns the typed `CAPACITY_QUOTA_EXCEEDED` response only after the exact durable `NO_ACCEPT` decision commits. If its refusal budget is missing or exhausted, Account returns non-OK `ENTITLEMENT_UNAVAILABLE` instead; no quota receipt or settlement authority is issued. Each refusal response is correlated to the exact original attempt, mutation digest, snapshot and evaluation. A quota refusal includes the immutable Account decision UUID only after an exact durable `NO_ACCEPT` commits. A matching exact retry returns the retained receipt. A quota refusal without that receipt grants no evidence settlement authority. The response contains exactly one commitment or one typed refusal. A fresh positive reservation requires the exact retained evaluation to remain current on PostgreSQL’s clock and the caller, scope, and applicable original paid authority deadlines to remain current on Account’s application clock. The owner rechecks these deadlines in the same transaction before requesting commit. If both clocks establish expiry before quota or reservation mutation, Account can return `CAPACITY_EVALUATION_EXPIRED` for an exact creation-eligible original evaluation after committing its exact budgeted `NO_ACCEPT` receipt. This includes expiry during source qualification when the current membership source still matches and its billing cutoff remains exact. The receipt grants settlement only for the matching Game Session evidence charge. A stale evaluation without settled owner proof, including a superseded billing cutoff, still returns `CAPACITY_ADMISSION_STALE` with `UNAVAILABLE`. Missing or unqualified current entitlement owner evidence or its dependency returns `ENTITLEMENT_UNAVAILABLE`. The receiver preserves `AUTH_UNAVAILABLE` for authentication authority unavailability, `PERMISSION_DENIED` for an authenticated caller mismatch, `INVALID_ARGUMENT` for malformed requests, and `IDEMPOTENCY_CONFLICT` with `ALREADY_EXISTS` for a mismatch against an existing retained binding outside proof-backed rearm. The prepared receiver also rejects a structurally valid initial attempt whose `capacityRearmFence` is not `1`, even when no reservation exists; that rejection occurs before retained quota-denial lookup. The Game Session client validates the bounded details and preserves the gRPC outcome. These errors grant no release or rearm authority. Rearm, recovery, and execution still require creation-committable evidence. The shared proto/codec, bounded private mTLS receiver, Game Session adapter and Account durable owner are locally prepared but unqualified and unregistered. The current owner accepts only exact new player-binding shape; World lifecycle activation and zero-delta recovery remain held without genuine current producers. Current source and proof limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). - `CommitTenantCapacityAdmission` reservation retries use one durable reservation. The initial attempt requires no rearm CAS and binds its fresh `admissionAttemptId`, current `capacityRearmFence`, exact payload, and digest. A fresh attempt is accepted only after an Account-owned atomic CAS over the same outer identity, the terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` predecessor and durable no-commit proof, the current fence, and the prior digest; the CAS advances the fence and binds the fresh attempt, payload, and digest without allocating a second reservation or capacity claim. Exact retries of the currently bound attempt, fence, complete payload and digest replay its durably retained reservation result; superseded pre-rearm attempts do not replay after a committed rearm. This reservation rule is separate from replay of an exact retained quota-denial decision, which has no reservation. A changed field without a matching rearm returns `IDEMPOTENCY_CONFLICT`, while a stale or losing fence returns `FENCE_REJECTED` only with the required no-accept/no-runtime-mutation proof and never rearms. Exact replay is guaranteed only for outcomes Account durably retained. A billing or non-creating entitlement refusal that did not retain a decision receipt is not a replayable outcome; a later retry rechecks current evidence freshness before deciding and cannot treat the earlier refusal as a retained result. @@ -545,6 +545,17 @@ Current implementation status: `GET /accounts/{accountId}/login-auth-modes` is a The private self-service game-creation reauthentication owner binds exact original request, Account, purpose and creation-operation identities to retained credential-MAC evidence. A wrong credential replay appends one immutable failed-attempt record and commits it before returning a credential denial. Five failures exhaust that original request; later attempts are denied before credential-MAC access. Successful replay preserves the original evidence and freshness deadline and never resets the budget or consumes another OTP. Missing custody or replay-proof dependencies remain unavailable and are not counted as bad credentials. This owner remains unregistered and supplies no factor-change or general billing authority. +### Hosting First-Invoice Checkout + +The Account-owned HTTPS owner surface is `/billing/hosting/subscriptions/{subscriptionId}/first-invoice`, externally prefixed by `/api/account`. It is an account-scoped billing-owner operation, not tenant-role authority: the exact current `control-ui` Account subject must own the subscription and selected instrument. Billing suspension does not remove this recovery surface. The isolated checkout receiving slice #3410 owns the HTTPS controller and browser composition. This Account producer keeps registration held. Route activation requires a physical Gateway-to-Account proof that Account observes a secure request through the authenticated owner transport. A direct Account TLS test supplies only the Account listener proof; the [Stripe owner contract](./stripe-integration.md#first-invoice-confirmation-and-completion) and existing retention, deletion, backup, custody and registration gates remain binding. + +- `GET` returns the exact existing invoice, PaymentIntent, selected instrument, amount, currency, immutable `tupleDigest`, expected current subscription row version, expiry, nullable retained `confirmationRequestId`, nullable retained `openingRequestId` before first consent, current `authorizationVersion` (zero before first consent) and `AWAITING_PAYMENT`, `COMMITTED`, or terminal unpaid `CANCELED` state. A canceled checkout offers no payment authorization. `amount` is a positive decimal integer string in Stripe minor units, not a floating-point or major-unit amount. No client secret appears in status, URLs, logs or audit. A null `confirmationRequestId` means only that no confirmation row is currently committed. When `openingRequestId` is present, explicit pre-row renewal must use that exact original operation. That absence does not authorize a replacement request or charge. Recovery semantics remain owned by the [Stripe contract](./stripe-integration.md#first-invoice-confirmation-and-completion). +- `POST /reauthenticate` takes distinct stable evidence `requestId` and `confirmationRequestId` plus one enabled ordinary login secret over HTTPS. A proof usable for new billing consent requires `billingBinding` with `originalRequestId`, `expectedRowVersion`, `expectedAuthorizationVersion`, `acceptedTupleDigest`, `invoiceExpiresAt`, and `authorizationPurpose`; `confirmationRequestId` names that binding's authorization request. Use `INITIAL_CONFIRMATION` with the original request ID and version zero for opening proof, `PRE_ROW_RENEWAL` with the retained original ID and a distinct authorization request at version zero for pre-row recovery, or `FOLLOWUP_RENEWAL` for a later retained authorization version. Account returns a newly bound proof only after actual primary authentication and exact owner binding. A replayed unbound historical `evidenceId` remains non-authorizing for new consent. `SELF_SERVICE_GAME_CREATION` evidence is rejected for payment. The [Stripe owner contract](./stripe-integration.md#durable-opening-proof-and-explicit-pre-row-renewal) defines the binding and recovery behavior. +- `POST /confirm` takes the immutable confirmation `requestId`, `expectedRowVersion`, `reauthenticationEvidenceId`, exact `acceptedTupleDigest` and explicit `acceptCharge=true`. The server resolves the retained commercial tuple; client amounts, instrument substitutions and provider defaults cannot change it. An exact retry retains the original operation and provider idempotency identity. Changed request fields conflict. +- `POST /renew` takes the original confirmation `requestId`, distinct fresh `authorizationRequestId`, `expectedAuthorizationVersion`, original `expectedRowVersion`, fresh `reauthenticationEvidenceId`, unchanged `acceptedTupleDigest` and explicit `acceptCharge=true`. For pre-row renewal, use expected authorization version zero and `PRE_ROW_RENEWAL` proof from `/reauthenticate`; after a retained first consent, use the exact current version and `FOLLOWUP_RENEWAL` proof. Exact renewal replay is read-only; changed evidence, consent, payment identity or losing authorization version conflicts. Renewal never resets invoice expiry or provider command history. The [Stripe owner contract](./stripe-integration.md#durable-opening-proof-and-explicit-pre-row-renewal) owns the recovery behavior and single-command boundary. +- The narrowly authorized owner response returns provider status and a client secret only for `requires_action`, with `Cache-Control: no-store`. Stripe.js `handleNextAction` completes provider authentication for that existing intent. A browser result never completes Account fulfillment; the owner polls status until the signed server completion has committed and independently read back. +- Transport or provider failures are uncertain, not evidence that no payment occurred. `FIRST_INVOICE_PROVIDER_UNCERTAIN` and `FIRST_INVOICE_EVIDENCE_REFUSED` preserve the original operation; clients must not create a replacement request or charge to escape an unknown result. + ### Sensitive Actions and Gameplay Handoff - Account identity/factor changes, new real-money charges, saved payment-instrument changes, global deletion, billing-owner transfer, and global administration are HTTPS-only account/control operations. Clients may be web, native, or CLI, but a Telnet gameplay connection cannot complete them or receive elevated authority. diff --git a/design/architecture/microservices/account-service/configuration.md b/design/architecture/microservices/account-service/configuration.md index da7982e6f6..c14a3d6e58 100644 --- a/design/architecture/microservices/account-service/configuration.md +++ b/design/architecture/microservices/account-service/configuration.md @@ -69,6 +69,10 @@ The source-only Control-UI issuance preparation reads the configured margin thro The gRPC schemas for this service live in [`protos/account/v1`](../../../../protos/account/v1). Use `./gradlew generateProto` to regenerate Java stubs when the definitions change. +## Held first-invoice checkout configuration + +The prepared [first-invoice owner](./stripe-integration.md#first-invoice-confirmation-and-completion) has no enabling flag or automatically registered bean/controller. Explicit composition requires the Account Stripe client, a protected webhook signing secret (`firemud.payment.hosting-webhook-secret`), a public Stripe publishable key for the provider-authentication client, finite provider transport limits and genuine current Account/control-ui owners. Secrets must not be logged or exposed through property diagnostics. Separate versioned billing-purpose reauthentication policies and exact commercial billing-policy rows are required; absent rows refuse and no migration seeds a default. Configuration alone does not clear registration or custody gates. + ## Canonical Gameplay LOGIN Receiving Canonical credential envelopes and exact-original retirement share the existing AccountService registration through `AccountGameplayAuthenticateReceiver`. The receiver, complete initial-LOGIN source graph and protected source selection all require `firemud.account.gameplay-login.enabled=true`; they are absent by default. `AccountGameplayLoginSourceConfiguration` composes the existing issuance/evidence/encrypted-response repositories, protected signer and trusted JWKS reader, issuer/account projection publisher, token registry, commit, activation and exact response-recovery owners. Registration supplies no synthetic owner evidence and performs no enrollment, key generation, publication or Redis mutation. diff --git a/design/architecture/microservices/account-service/operations.md b/design/architecture/microservices/account-service/operations.md index bb4895bcf7..646959d085 100644 --- a/design/architecture/microservices/account-service/operations.md +++ b/design/architecture/microservices/account-service/operations.md @@ -81,3 +81,9 @@ Expired connect-scope cleanup exposes `account.connect_scopes.cleanup.deleted` f The old disabled GHCR-based cross-service placeholder for Account Service was removed because it did not prove a meaningful current contract. The maintained local application smoke now lives under `src/test/java/integration` and should be treated as the canonical lightweight readiness check for this service. Higher-value cross-service behavior should be covered by targeted current-contract tests rather than by "other container exists" scaffolding. See [System Architecture Testing](../../system-architecture-testing.md) for the shared testing approach. + +### First-invoice recovery and held activation + +Use the [first-invoice owner contract](./stripe-integration.md#first-invoice-confirmation-and-completion) for payment and completion. Preserve the original invoice, PaymentIntent, consent, provider idempotency key, event intake and reservation after an uncertain provider response, expired client session or failed Account commit. Never repair an uncertain charge by provisioning a replacement or changing the selected method. Read-only signed-success reconciliation must not authorize new provider work. An owner may explicitly renew unchanged consent and primary reauthentication on the original operation through the owner contract. A durable command claim, including an uncertain claim/response or crash after claim but before POST, never permits another provider command; keep it nonterminal for exact observation or audited remediation. Paid-but-unfulfilled and policy/authority conflicts remain explicit unresolved billing work and continue to block deletion. + +Before registering this held source, execute physical migration/current-owner, crash/retry, signed tuple-mismatch, HTTPS owner isolation and provider next-action/SCA proof, together with the existing category-specific retention/minimization/deletion/backup and protected source-custody gates. Compiled Docker-backed definitions, skipped cases and controlled active-subscription fixtures are not proof of those boundaries. No live provider or financial action is authorized by this preparation. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 0c433d9f79..369c1b9558 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -86,7 +86,7 @@ Recovery/verification foundations are live. Password-reset completion now uses a Current public bootstrap, direct-scope, JOIN, connect-token and numeric entitlement receiving boundaries are defined by [Account API Contracts](./api-contracts.md#rest-apis) and its [gRPC inventory](./api-contracts.md#grpc-apis). The held boundary, preserved positive component obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Game Session text `REALMS`/`JOIN` dispatch remains unimplemented under #2898; unknown JOIN outcome recovery and Logging receipt receiver/readback remain #2848, and direct text-client end-to-end proof remains open. The target scope and transport contract remains in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). -Strict capacity follows the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). The prepared V1040 storage records immutable exact Account evaluation bytes, one stable outer request/reservation identity, the current attempt/digest and monotonic rearm/reservation fences, prior-attempt evidence, recovery claims, and durable held/used units. Deferred PostgreSQL constraints compare the complete reservation inventory with usage; eligibility reads and issuer-local counters cannot initialize or replace it. Zero usage is established only when the existing creator bootstrap commits against a genuinely new fresh-tenant association born in that same Account transaction, with the exact creation tuple and nonadmitting sequence-zero baseline. Earlier tenants are not backfilled. The actual player evaluator retains its complete bundle inside its final source transaction, so failed source commit exposes neither a capacity evaluation nor an entitlement result. Reservations use conservative microsecond expiry bounds without extending the evidence lifetime. The same prepared recovery schema retains its immutable read history and `capacity-recovery/1` retry budget. Deadline or budget exhaustion quarantines the original complete hold; it does not expire, release or replace it. No live recovery source/scheduler or quarantine-resolution authority is registered. +Strict capacity follows the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). The prepared V1040 storage records immutable exact Account evaluation bytes, one stable outer request/reservation identity, the current attempt/digest and monotonic rearm/reservation fences, prior-attempt evidence, recovery claims, and durable held/used units. Deferred PostgreSQL constraints require exact reservation-derived usage; eligibility reads and issuer-local counters cannot initialize or replace it. Forward installation audits the complete retained inventory once under a writer lock and refuses mismatches without repairing source rows. Thereafter a protected per-tenant/owner aggregate changes only with database-validated reservation insertions and state transitions. Deferred usage checks use primary-key point reads rather than summing lifetime finalized or released history. Fresh zero aggregates require the same new-tenant bootstrap authority; direct aggregate writes, deletion and truncation remain forbidden. Zero usage is established only when the existing creator bootstrap commits against a genuinely new fresh-tenant association born in that same Account transaction, with the exact creation tuple and nonadmitting sequence-zero baseline. Earlier tenants are not backfilled. The actual player evaluator retains its complete bundle inside its final source transaction, so failed source commit exposes neither a capacity evaluation nor an entitlement result. Reservations use conservative microsecond expiry bounds without extending the evidence lifetime. New-attempt current-source qualification follows the usage-row lock, with a fresh database-clock check before mutation. The additive V1046 deferred write guard also rejects original creation or rearm that is expired at transaction completion, rolling back any usage or history changes. Retained exact replay and same-attempt recovery do not renew authorization and remain available after expiry. The same prepared recovery schema retains its immutable read history and `capacity-recovery/1` retry budget. Deadline or budget exhaustion quarantines the original complete hold; it does not expire, release or replace it. No live recovery source/scheduler or quarantine-resolution authority is registered. V1040.1 serializes the exact Account `ACCEPTED` and `NO_ACCEPT` origin decisions against reservation creation and rearm. A pre-V1040.1 writer cannot create a reservation after the guard applies. The [database migration compatibility and writer-quiescence policy](../../system-architecture-database-migrations.md#version-aware-migration-checklist) governs deployment. A reset must preserve results for still-eligible retries. It may proceed only after all external-action intents have settled, their authoritative outcomes are known, and any receipts to be discarded have passed their retry and reconciliation window. V1040.2 retains an exact quota denial under an explicitly installed finite tenant refusal limit. The same serializable owner transaction checks quota and chooses between a reservation and a denial. The denial carries no reservation and permanently excludes acceptance for the exact original. Exact replay returns the same decision even after capacity becomes available. An unavailable refusal budget or uncertain outcome leaves Game Session's reserve active. Account neither frees nor rearms an accepted reservation through this path. Before enabling any admission producer, the Account operator must provision every supported canonical tenant through `AccountCapacityRefusalBudgetRepository.provision` and call `requireReady` with the same explicit lifetime limit and the bounded admission cohort headroom in one writable owner transaction while producers remain quiescent. Commit only after both succeed; otherwise roll back the undersized installation so it does not permanently bind an unusable limit. Sizing is explicit: the finite lifetime limit must cover retained denials plus the planned denial cohort; it is not the gameplay capacity quota or an automatically replenished rate limit. Exact provisioning retries preserve the row and its historical evidence; a different limit conflicts. Missing, mismatched or insufficient budgets fail readiness. Readiness is a local observation, not a reservation or authority to admit, and the SQL trigger remains the runtime concurrency authority. Exhaustion requires stopping new admission and an independently designed retention-safe lifecycle, never deleting denials or resetting/increasing this immutable budget. No exhaustion detector or admission-producer stop control is implemented by these private repositories: the positive reservation path does not consult refusal headroom. Qualifying that stop, including last-slot consumption followed by available capacity, is an unmet activation prerequisite; provisioning readiness alone cannot satisfy it. These private methods do not register an endpoint, seed tenants automatically or activate the default-off capacity component. @@ -330,7 +330,22 @@ Entitlement producer contract: - `provisioningStatus` is `pending`, `provisioning`, or null; while non-null, `subscriptionStatus` is null and all new gameplay/admission/instance-start flags are false. `tenantAuthorityGeneration` is opaque and may be compared only for exact equality, never ordered or used as an event identity. - The focused producer proof must show that every entitlement response is one Account-authenticated bundle from the same authoritative committed evaluation, that `tenantAuthorityGeneration` is the Account-committed fence rather than a value reconstructed from a later projection read, and that no caller reconstructs or separately sources bundle identities, tuple members, cutoff evidence, or checkpoints. -The numeric runtime entitlement endpoint follows the [Account API refusal boundary](./api-contracts.md#endpoint-authentication-classes). The separate manually composed PLAYER_ADMISSION owner/receiver and Game Session client preserve canonical V2 scope/current-owner evidence under the [private purpose contract](./api-contracts.md#private-player-admission-entitlement-read); their presence does not wire or qualify a runtime cutover. Canonical UUID billing and the distinct unregistered `TENANT_OPERATION` source are prepared separately; the complete public `PLAYER_ADMISSION` consumer is not yet qualified. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving) owns public receiving proof and gaps. `V1040` prepares immutable capacity-evaluation, attempt-history, and recovery-evidence records plus guarded reservations, but no capacity-family retention entry, horizon, or owner-safe cleanup/archive contract is defined under [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) and [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md). This remains an open Account activation limitation; existing guards and holds remain in force. +The numeric runtime entitlement endpoint follows the [Account API refusal boundary](./api-contracts.md#endpoint-authentication-classes). The separate manually composed PLAYER_ADMISSION owner/receiver and Game Session client preserve canonical V2 scope/current-owner evidence under the [private purpose contract](./api-contracts.md#private-player-admission-entitlement-read); their presence does not wire or qualify a runtime cutover. Canonical UUID billing and the distinct unregistered `TENANT_OPERATION` source are prepared separately; the complete public `PLAYER_ADMISSION` consumer is not yet qualified. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving) owns public receiving proof and gaps. The [capacity evidence lifecycle](#capacity-evidence-lifecycle) below owns the retention classes and safety predicates for the prepared capacity family. Complete operating schedules, authoritative hold inputs and cleanup remain an open Account activation limitation; existing guards and holds remain in force. + +### Capacity Evidence Lifecycle + +Account owns capacity evaluations, reservations, attempt history, recovery evidence, usage and their protected conservation aggregate under [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) and [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md). Evaluation expiry ends admission freshness; it is not an erasure grant. No universal duration, caller-supplied approval flag or tenant setting can replace the finite environment schedule and its privacy/finance approval. + +- Evaluations are purpose-bound authorization evidence. An expired evaluation can become a cleanup candidate only after its declared evidence horizon and every supported retry, replay, restore and investigation horizon end, with no hold or retained reference. References include prior evaluations retained inside immutable rearmed-attempt payloads, not only the current reservation foreign key. Until exact historical reference qualification exists, any retained reservation for the same tenant and owner conservatively blocks that scope's evaluations. Unreferenced non-admitting baselines still require the same policy and hold qualification. +- Reservations retain live or recoverable work and the stable outer retry identity. Pending, ambiguous and quarantined work is never age-expired. Finalized or released state alone does not end the supported replay/restore window, prove teardown, or authorize removal of a reservation or its evidence. +- Attempt history and recovery evidence are recovery/reconciliation lineage. All related attempts and owner observations must be terminal, reconciliation complete, and supported restore/replay unable to resurrect a dependency before bounded compaction or erasure is eligible. Compact identities, digests and outcomes must survive every applicable retry/deduplication window; an archive does not replace an online guard. +- Usage and conservation are live resource-accounting state, not expiring event history. Retiring used capacity requires the once-only authoritative teardown transition; absence of an evaluation or an old timestamp cannot decrease either counter. The conservation aggregate adds no deletion or terminal-retirement authority. + +Every category's environment entry must name its exact finite maximum duration, purpose, authorized Account roles, subject/tenant export treatment, terminal erasure or minimization action, backup/replica handling and legal holds. Cleanup is owner-local, uses a bounded batch and safe watermark, and fails closed when a required policy, hold, reference or restore input is absent or contradictory. No cross-schema reads, unqualified partition drops or arbitrary age-only deletion are permitted. Restore must retain the applicable evidence and erasure reconciliation before traffic opens. + +Read-only evaluation inspection uses a bounded oldest window and requires the exact environment schedule, current hold snapshot and safe watermark before reporting candidates. The [implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation) records the receiving owner, proof and remaining lifecycle work. + +For paid player admission, Account retains the original [subscription observation cutoff](./subscription-management.md#runtime-entitlement-contract) as immutable private metadata on the exact evaluation. Fresh reservation, quota denial, and rearm require both the original cutoff on Account's application clock and the translated evaluation expiry on PostgreSQL's clock. The Account owner rechecks both in the same transaction immediately before requesting commit. Paid evaluations without the original cutoff require a fresh evaluation before any new attempt. Account uses the existing exact replay path for retained outcomes. Retained player-admission version-1 evidence remains immutable and held for owner-governed retention. Player-admission version 2 is required for new capacity requests and their replay. Before activation or reuse of predecessor-populated storage, establish the retained Account and Game Session SQL and Redis inventory and resolve its outstanding confirmation, replay, recovery and restore obligations under the [objective compatibility gates](../../decisions/adr-0081-objective-compatibility-gates-for-database-evolution.md). @@ -418,3 +433,9 @@ Forward [V1004.2](../../../../services/account-service/src/main/resources/db/mig Forward [V1004.3](../../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql) requires all four Base64 carriers in the Account activation request to match the canonical encoding of their decoded tuple, projection, launch-read, and PREPARING bytes before protection acquisition. This prevents accepted whitespace spellings from being retained in an immutable request that later settlement must compare. It changes only the existing acquisition guard and does not backfill rows, authenticate World, or activate the source path. Current proof and limits are recorded in the [source-protection tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage). V1003 preserves canonical predecessor SQL and retained owner rows; it never backfills protection, adopts missing historical evidence, fabricates owner proof or registers runtime authority. Its scoped PostgreSQL fixtures explicitly stipulate upstream capture/redemption/World rows with upstream producer triggers disabled while leaving the protection and source-writer guards under test enabled. Such execution establishes storage integrity, exclusion and retained-history behavior only. Genuine current-owner acquisition, authenticated terminal reads/settlement, continuously protected admission and activation remain unproved. Forward [Account V1007](../../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql) provides preliminary selected-owner reservation and source-writer storage; forward V1008–V1010 prepare finalized owner authorization/recovery and exact terminal settlement, with focused owner-storage and upgrade proof. The receiving stage also prepares bounded recovery for expired abandoned preliminary reservations. Authenticated cross-owner composition, full-native qualification and registration remain open as recorded in the [selected-recipient tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-recipient-source-intake-preparation). + +### First-invoice completion ownership + +The [Stripe owner contract](./stripe-integration.md#first-invoice-confirmation-and-completion) owns the immutable provider-linked first invoice, explicit billing consent, signed success and separate completion journal. `provisioning`/`AWAITING_PAYMENT` is never positive runtime authority. The first authorizing receipt must carry exact signed paid-invoice fulfillment; its receipt, audit, billing outbox and tenant authority outbox commit atomically and require independent current-source readback. The webhook inbox remains immutable intake and is not a processing ledger. V1041 creates completion storage and guards without backfilling retained positive lifecycle rows; rows without exact first-payment and completion evidence remain unqualified. Forward V1046.1 refuses upgrade when any current `trialing`, `active`, `past_due` or `grace` subscription lacks its immutable first-invoice completion. It neither demotes the subscription nor synthesizes payment evidence. The migration takes a write-conflicting subscription-table lock before inspecting retained rows and installing a deferred final-row consistency trigger; positive state and its genuine completion can commit together, while later writers cannot commit a new gap. A blocked upgrade preserves existing rows and receipts and requires separately authorized evidence-preserving resolution before retry. Account V1047 remains the downstream control-ui replay-failure budget migration. The manually composed lifecycle owner provides a read-only, time-bounded prerequisite inspection; database failures and unresolved rows keep activation held. A clear inspection is only a snapshot: it does not fence concurrent writers, grant registration, reconstruct historical payment evidence or replace the remaining live-target qualification. See the [Stripe owner contract](./stripe-integration.md#first-invoice-confirmation-and-completion) and [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Retention, minimization, deletion, backup and source-custody registration holds continue to apply. + +The local additive [V1043 candidate](../../../../services/account-service/src/main/resources/db/migration/V1043__hosting_first_invoice_operation_fence.sql) extends Account's existing recent-reauthentication evidence with all-or-none typed billing-context fields and a canonical digest, and adds the immutable per-subscription `subscription_first_invoice_operation_fences` owner table. The fence retains the original operation, Account, invoice tuple digest, expected subscription-row version, original invoice expiry, opening evidence identity and binding digest; older evidence remains unbackfilled and unchanged, with no authority inferred from a null context. The migration follows the verified V1042 frontier and preserves V1041/V1042. The [Stripe owner contract](./stripe-integration.md#durable-opening-proof-and-explicit-pre-row-renewal) owns behavior; the [API contract](./api-contracts.md#hosting-first-invoice-checkout) records only its wire consequences. diff --git a/design/architecture/microservices/account-service/stripe-integration.md b/design/architecture/microservices/account-service/stripe-integration.md index cbb4a55e3d..964a0ec6c1 100644 --- a/design/architecture/microservices/account-service/stripe-integration.md +++ b/design/architecture/microservices/account-service/stripe-integration.md @@ -42,6 +42,32 @@ The hosting-subscription, provider-reconciliation, and account-deletion billing- The account-owned wallet contracts are also target state. Per-subscription instrument binding, replacement-before-detach, the single-use transfer proof and database transfer fence, immutable predecessor-provider history, and the audited `cross_tenant_billing_safe` ownership-transfer route remain absent or partial until the corresponding routes and enforcement are implemented; the [Authorization Route Matrix](../../system-architecture-authz-route-matrix.md) records that coverage drift. +## First-Invoice Confirmation and Completion + +Stripe may expose the already-bound original unpaid first-invoice PaymentIntent without an assigned payment method before confirmation. Account accepts this shape only for the exact original intent in `requires_payment_method` with zero received and no prior charge, on the matching open unpaid subscription-creation invoice and exact customer, subscription, mode, quote, amount and currency. Capture requires the provider subscription default to match the selected reserved instrument. Confirmation requires matching bound invoice and separately retrieved intent, a current Account claim for the retained original subscription and instrument version, and the existing one-shot authorization and idempotency key; the command explicitly supplies the reserved payment method. A conflicting non-null method or contradictory evidence fails closed. This exception grants no replay/redisclosure, SCA, signed-success or settlement authority: the confirmation response and later reads other than the terminal unpaid case below require the exact reserved method. This accepted evidence shape does not establish that live Stripe produces it. + +`DEFAULT_INCOMPLETE` creation and subscription polling do not confirm the initial PaymentIntent. Account first retains the exact existing first invoice, its sole existing PaymentIntent, canonical provider subscription/customer, explicitly selected saved instrument and reserved version, provider method, versioned commercial policy/quote, positive minor-unit amount, currency and provider mode. Provider linkage remains `provisioning` with durable `AWAITING_PAYMENT` work and grants no hosting authority. The instrument reservation remains held through Stripe's original 23-hour incomplete-subscription boundary and until explicit terminal cleanup; expiry never creates a replacement subscription, PaymentIntent or Checkout Session. + +The current commercial owner supports only an exact positive first-invoice amount/currency/quantity matching an explicitly installed versioned billing policy and the sole fully read invoice line's original quote price/quantity. Invoice total and due must agree, the starting balance is zero, and an unpaid invoice must retain its full amount remaining. A credit, balance adjustment, tax, discount, split payment or currency difference that changes that exact tuple is refused rather than inferred or absorbed into a permissive policy. The policy relations contain no seeded default. A policy change cannot rewrite a retained invoice or silently authorize another amount. + +Payment requires genuine billing-purpose recent ordinary reauthentication and explicit owner consent for the retained tuple through the [owner API](./api-contracts.md#hosting-first-invoice-checkout). An append-only authorization attempt and independent readback precede provider work. Confirmation retrieves that invoice and intent first, then atomically claims the operation's single durable command permission under current owner, reauthentication, policy, subscription-row and authorization-version fences before confirming the existing unconfirmed intent with the selected method and original retained idempotency key. The owner-only Stripe.js next-action handoff is disclosed only within the current authorization window. No provider charge is dispatched by provisioning. Customer defaults, default sources, new PaymentIntents and Checkout Sessions are prohibited. The held first-invoice composition uses a dedicated Stripe transport with a two-second connection timeout, a five-second whole-response deadline and bounded JSON body consumption. A deadline cancels the exchange and leaves any claimed command outcome uncertain under the original identity. + +Only a verified signed `payment_intent.succeeded` event, matched to the exact retained customer/method/amount/amount-received/currency/mode and independently re-read paid invoice/intent, may supply first-payment evidence. `invoice.paid` alone, an active subscription fixture, a browser callback or a client-supplied success flag is insufficient. The immutable webhook inbox remains intake only. Separate append-only success and completion journals retain the tuple, original consent, event digest and exact lifecycle receipt identity; processing never mutates the inbox or treats its `PENDING` marker as a completion flag. + +The Account lifecycle transaction atomically commits the exact completion, hosting receipt, audit/observation evidence, billing sequence/outbox and tenant authority-generation/outbox. Independent receipt/current-source and completion-journal reads follow commit. An exact replay of retained completion proves historical fulfillment from its original receipt and journal. Current hosting authority requires an independent current-source read. A lost provider response or local commit failure remains on the same operation. An exact owner retry is read-only and cannot send another confirmation; if the intent still requires confirmation, it reports `AUTHORIZED_NOT_CONFIRMED`. Recovery of that held outcome or expired client-secret disclosure requires a separately explicit fresh primary reauthentication and unchanged charge consent. Its distinct authorization request is append-only and compare-and-set against the current authorization version on the original payment operation. It preserves the original invoice, PaymentIntent, subscription, instrument, quote, amount/currency, provider idempotency key, lifecycle and audit identities. The new attempt supersedes older disclosure/command permissions without rewriting the original consent. It may recover a crash before any durable command claim, but it cannot repeat an already claimed command, even if the provider still reports `requires_confirmation`. A crash or ambiguous commit after that claim remains nonterminal and read-only until exact provider evidence or audited remediation resolves it. The same fresh authorization may redisclose the existing intent's `requires_action` secret; it does not create or confirm another intent. Authorization expiry never extends the original incomplete-subscription expiry. Read-only reconciliation and authorization expiry follow [ADR 0045's authorization-linearization contract](../../decisions/adr-0045-ordinary-login-factors-and-https-sensitive-action-step-up.md#handoff-authorization-linearization); neither a delayed event nor an expired handoff permits a new charge or changed tuple. A paid-but-unfulfilled result remains non-authorizing until that exact atomic fulfillment succeeds or audited remediation resolves it. + +An absent committed confirmation ID cannot authorize replacement consent, request identity, or charge. Retained subscription qualification remains an [activation prerequisite](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). + +If the invocation that won the committed command claim observes authorization expiry before entering the Stripe confirm call, Account retains that observation independently against the original claim. The claim permanently consumes the one-shot command permission. A failed or uncertain claim commit, process loss, provider timeout, or a later read of the intent cannot establish that the confirm call was never entered. + +### Durable opening proof and explicit pre-row renewal + +Before returning usable opening `HOSTING_FIRST_INVOICE_PAYMENT` reauthentication proof, Account durably retains one original-operation fence for the exact owned `AWAITING_PAYMENT` invoice. The immutable typed billing context and fence bind the authenticated Account, subscription and current subscription-row version, original operation ID, exact invoice tuple digest and original invoice expiry, authorization request identity and purpose, and expected authorization version. The current authenticated Account transaction verifies or exactly replays that context under the owner locks and retains the fence before returning the proof. New opening evidence and the exact operation fence commit in the same owner transaction. A failed fence bind rolls back that evidence and cannot redirect it to another invoice, operation, row version, or authorization purpose. Unbound historical billing evidence remains retained but cannot authorize a new first consent or pre-row renewal; a nullable confirmation ID from status is observational only. + +Original confirmation and an explicitly requested pre-row renewal serialize under the same Account owner/subscription locks and original-operation fence, preserving the established source/evidence/owner lock order. A pre-row renewal must name that exact original operation, a distinct authorization request, expected authorization version zero, fresh typed billing reauthentication for `PRE_ROW_RENEWAL`, and unchanged explicit charge consent. In one owner transaction, either the original confirmation or this renewal may create the sole first consent and first authorization/dispatch winner. If confirmation wins, renewal is stale and consumes nothing. If renewal wins, the original operation and opening evidence remain retained and unchanged, and the delayed original confirmation cannot replace the winning authorization. Losing, rolled-back, stale, changed, expired, or mismatched evidence consumes no reauthentication proof and authorizes no dispatch; rollback leaves the fence and original evidence intact. Exact retries replay the retained winner without another provider command, using the existing independent readback and single command claim/provider idempotency boundary. This path never creates a replacement subscription, invoice, PaymentIntent, charge, automatic renewal, or post-expiry activation. Existing post-row renewal remains the distinct follow-up path above, and old retained confirmations remain authoritative only for their existing scoped recovery. + +The held lifecycle owner may settle an exact provider-linked unpaid checkout only when the retained first invoice has no signed success evidence and fresh provider reads establish that the subscription is canceled, the exact original invoice is void with zero paid, and its independently read PaymentIntent is canceled with zero received. A claimed checkout additionally requires the exact durable expiry-before-confirm observation. The two views of that intent must agree on the reserved method or both show no method and no charge. The latter shape is accepted only for this read-only terminal unpaid decision when the exact winning invocation is durably proven never to have sent confirmation. Qualification against FireMUD’s pinned Stripe subscription flow remains pending. Signed success intake, first invoice capture, and unpaid settlement share one transaction-scoped ordering boundary keyed by provider mode and the exact PaymentIntent. Intake takes that lock even before the invoice mapping exists and never waits for a subscription row. Capture and settlement preserve the existing owner lock order and acquire the intent lock after the subscription row. Capture records only the immutable linkage. Settlement rechecks the claim and absence of exact signed success under those locks with a fresh READ COMMITTED evidence read after any wait, including events created before the original consent. Paid fulfillment and new links to a retained late-payment conflict still require an event at or after the original consent floor. The claimed path retains its typed evidence in the same transaction as the negative lifecycle receipt, terminal provisioning state and exact instrument reservation release. Before requesting a fresh cancellation commit, the owner compares the terminal invoice and intent observation cutoff with PostgreSQL wall time on the same transaction. An expired cutoff rolls back the cancellation and release. Exact replay returns the committed outcome independently of observation freshness. Ambiguous, stale, mismatched or paid evidence keeps the reservation held. A paid first invoice whose provider subscription was canceled before first fulfillment retains its payment evidence and produces exact lifecycle operator work before any hosting receipt or instrument release. A verified exact payment that arrives after an already committed unpaid cancellation is retained as a separate operator reconciliation conflict linked to that cancellation. Account retains each independently verified event identity it accepts for that exact conflict. Replay of any such event returns the retained conflict without new provider reads. An exact signed success for a canceled invoice without local confirmation stays pending reconciliation until the operator conflict owner is available. The conflict does not reopen fulfillment or authorize a refund. Registration remains held by the category-specific retention/minimization, deletion, backup, source-custody and provider qualification prerequisites above. Controlled SDK or SQL tests do not establish live Stripe/SCA support or deployment activation. + ## Domain Model The Account Service owns billing records and maps them to Stripe resources. Records use immutable internal IDs for stable identity; for `subscription`, the internal `subscriptionId` is the sole stable identity and `tenantId` is its immutable tenant-scope binding. `accountId` and `plan_code` are mutable lookup, authorization, and constraint fields, not key material. No generic update or billing-owner transfer may change `tenantId`. @@ -80,7 +106,7 @@ The provider-ID history mapping is immutable and separate from the current subsc - `subscription` (status lifecycle and plan-change timing are canonical in [Subscription Management](./subscription-management.md)) - Represents a recurring billing agreement between a creator (platform account) and the platform for a specific tenant’s hosting plan. - Key fields: immutable internal `subscriptionId`, immutable `tenantId`, `accountId`, `plan_code`, `status` (`pending`, `provisioning`, `trialing`, `active`, `past_due`, `grace`, `suspended`, `canceled`), current period start/end, `provider_subscription_id` (Stripe `subscription` ID), `provider_customer_id` (Stripe `customer` ID), an immutable `subscription_provisioning_request_id`/subscription-operation idempotency identity, the reserved payment-instrument version, a reference to the separately immutable customer-provisioning request identity, and a non-null persisted subscription-specific binding to the selected account-owned payment instrument. `accountId` and `plan_code` remain mutable lookup/constraint fields; only the explicit billing-owner handoff may replace `accountId`, and no supported operation relocates a subscription to another tenant. - - `pending` and `provisioning` are durable pre-activation states. `pending` means the local subscription intent and provider work item have committed but provider creation has not been claimed; `provisioning` means the provider call is in progress or awaiting recovery. Neither state grants hosting entitlements or permits billing. + - `pending` and `provisioning` are durable pre-activation states. `pending` means the local subscription intent and provider work item have committed but provider creation has not been claimed. `provisioning` means the provider call is in progress or awaiting recovery. A `pending` subscription cannot be charged. During `provisioning`, the only permitted charge is [owner-authorized first-invoice confirmation](#first-invoice-confirmation-and-completion). Hosting authority starts after exact first-invoice fulfillment commits. - Plan metadata defines quota-related attributes (for example, maximum active sessions, world size tiers) that the platform uses to drive per-tenant resource limits as described in [Multi-Tenancy](../../system-architecture-multi-tenancy.md#tenant-configuration--scaling). - `subscription_operation` @@ -162,7 +188,7 @@ Subscription creation, lifecycle, and entitlements are covered in more detail in 2. For a new subscription, before any Stripe customer or subscription provisioning, the Account Service resolves the authoritative billing owner for the tenant and captures the exact owner authority version/generation from that snapshot. It verifies that the actor is authorized to act for that owner or has an explicit billing-owner handoff. It allocates the immutable internal `subscriptionId`, then in the same local intent/outbox transaction locks or CAS-validates the resolved owner and the captured version/generation before committing a durable subscription operation/correlation record and outbox work item bound to the operation, authenticated caller, account owner, tenant, and caller request identity. An owner change or fence mismatch fails closed before any provider work. For an existing subscription update, it reads the current owner from the existing row. A cross-tenant `billingAdmin` or `platformAdmin` action must use the dedicated audited billing route. Account then links the subscription operation to that owner's separate durable account-keyed customer-provisioning operation, which must complete or reconcile to a confirmed Stripe customer identity before the subscription work item can transition to provider creation. The customer operation has its own immutable `customer_provisioning_request_id`; the subscription operation has a different immutable `subscription_provisioning_request_id`. Every retry recovers the existing operation of the relevant type and reuses only that operation's provider-resource identity. Customer recovery must not create a subscription, and subscription recovery must not create a second customer. The requested or deterministically selected `payment_instrument` must be owned by that same account and belong to that customer. 3. Account atomically persists the subscription’s immutable internal `subscriptionId`, owner, non-null subscription-specific instrument binding and reserved instrument version, durable `pending` status, the separate customer-operation reference, the immutable `subscription_provisioning_request_id`, and the outbox work item in one database transaction. The provider customer reference may remain null only while the subscription stays `pending`; a confirmed non-null customer reference is mandatory before the work item becomes eligible for `provisioning` or any provider-subscription call. The subscription-operation idempotency identity is reused for every retry or recovery of that subscription operation; it is never reused for customer provisioning or a later update to an existing subscription. Customer retries and reconciliation reuse only `customer_provisioning_request_id` and its provider customer identity. Every existing-subscription plan, instrument, cancellation, or other provider update has its own immutable operation-specific request ID and expected subscription row version/CAS; Account rejects a stale version, and retries reuse that same update identity and guard. The provider call must use the persisted customer, payment-method, and operation-specific idempotency identifiers; Stripe customer defaults and other provider defaults are prohibited. A missing, stale, or mismatched binding fails closed and cannot be repaired by a provider default. A permanent provider or local failure, intent expiry, or explicit abandonment enters one idempotent terminal cleanup keyed by a distinct immutable cleanup/cancellation operation identity. The creation/provisioning identity `subscription_provisioning_request_id` is retained only for lookup and attribution and is never reused as the cleanup provider-mutation idempotency key. Before local cancellation or reservation release, cleanup uses that distinct identity to reconcile and cancel or end any provider subscription object attributable to the operation; an ambiguous provider result keeps cleanup pending for retry. Only after provider absence or terminal cancellation is durably recorded does cleanup lock the subscription and instrument, validate the exact owner, binding, reserved instrument version, reservation identity, and row version, mark the local subscription `canceled` with the durable terminal outcome, advance the instrument version exactly once, and release the reservation in the same transaction and outbox boundary. No terminal response or detach that relies on the released instrument is returned before that cleanup commits. 4. A durable worker claims the work item only after an atomic transaction revalidates the persisted instrument owner, exact reserved instrument version, matching Stripe customer, and attachable state, then moves the row to `provisioning`. A pending or provisioning reservation blocks detach; if detach commits before the reservation or claim, its version advance makes the stale reservation or claim fail before any Stripe call, while a claim that owns the reservation makes detach wait for terminal cleanup. Cleanup retries return the committed terminal result, and a stale cleanup cannot clear a different reservation after a competing version advance. The worker then creates or recovers the provider subscription using the same `subscription_provisioning_request_id`. A crash, timeout, or lost response is recovered by retrying that same operation identity and reconciling Stripe before any new subscription create is attempted. Customer reconciliation remains a separate operation using only its customer identity. If Stripe created the subscription but the local provider ID was not recorded, reconciliation locates the resource by the subscription operation's idempotency identity/provider metadata and repairs `provider_subscription_id` without creating a second subscription. -5. Account records the confirmed Stripe `subscription` ID before moving the local subscription into `trialing` or `active`; activation and invoice charging are forbidden while the row is `pending`, `provisioning`, or missing a confirmed provider ID. Stripe webhook and reconciliation processing rechecks the persisted binding before accepting activation or any invoice charge, including renewals. Changed-term renewal protection and any period-end exit/refund are target-only under [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md); they must not be inferred from a payment, decline, or current subscription state. +5. Account records the confirmed Stripe `subscription` ID before activating hosting or accepting an invoice charge. A `pending` row cannot activate or be charged. A `provisioning` row may only be charged through [owner-authorized first-invoice confirmation](#first-invoice-confirmation-and-completion), and hosting authority starts only after the exact first-invoice fulfillment commits. Stripe webhook and reconciliation processing rechecks the persisted binding before accepting activation or any invoice charge, including renewals. Changed-term renewal protection and any period-end exit/refund are target-only under [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md); they must not be inferred from a payment, decline, or current subscription state. 6. Stripe webhooks caused by initial provisioning or an explicit existing-subscription update resolve through the exact typed `subscription_provisioning` or `subscription_update` operation identity carried in provider metadata. Provider-lifecycle events such as subscription status or invoice events that do not originate from a current command use a separate `subscription_lifecycle` correlation: Account verifies the signature, deduplicates by Stripe `event.id` in `stripe_event_inbox`, resolves the provider subscription ID from the event payload to the unique canonical subscription and its immutable internal `subscriptionId`, and does not fabricate or reuse a command operation identity. If the provider ID is not yet linked or the local row cannot be resolved, the inbox correlation remains durably `pending` with retry state; reconciliation looks up current provider state, repairs the provider-ID/local-row linkage, and then applies a guarded transition. Replayed events are no-ops after durable deduplication, while out-of-order or ambiguous lifecycle events remain pending for reconciliation rather than regressing local state. Both command and lifecycle paths keep the internal `subscription` table in sync. 7. Changes to `subscription.status` are propagated to tenant-management and quota-enforcement components so that tenant availability and resource limits reflect the current billing state. For hard cutoff transitions such as `suspended` or `canceled`, Account transactionally advances the durable tenant authority generation with the committed billing state and emits `SubscriptionStatusChanged` plus `TenantBillingStateChanged`. Downstream services consume those events to invalidate projections and terminate affected gameplay sessions; they never advance Account authority themselves. See [Subscription Management](./subscription-management.md#tenant-availability-and-quota-enforcement) and [Session Behavior](../../system-architecture-session-behavior.md#session-and-identity-management). diff --git a/design/architecture/microservices/account-service/subscription-management.md b/design/architecture/microservices/account-service/subscription-management.md index b98c53c999..7edd910da2 100644 --- a/design/architecture/microservices/account-service/subscription-management.md +++ b/design/architecture/microservices/account-service/subscription-management.md @@ -85,9 +85,11 @@ The subscription lifecycle is modeled as a finite state machine: Before the billing lifecycle states below, creation uses two durable provisioning states: - `pending` – Account has committed the subscription operation, pending subscription row, billing-owner/instrument binding, captured and locally revalidated owner authority version/generation, observed instrument version reservation, customer-operation reference, stable creation-operation provider idempotency identity, separate cleanup/cancellation-operation identity, and outbox work item before any customer reconciliation or provider call; provider creation has not been claimed. -- `provisioning` – A worker has confirmed the customer operation, then atomically revalidated instrument ownership, the exact reserved version, matching customer, and attachability before claiming the outbox item and creating or reconciling the provider subscription. Creation retries reuse the creation-operation identity; terminal cleanup uses the separate cleanup/cancellation identity while retaining the creation identity for provider-object lookup. This state grants no hosting entitlement and cannot be billed. +- `provisioning` – A worker has confirmed the customer operation, then atomically revalidated instrument ownership, the exact reserved version, matching customer, and attachability before claiming the outbox item and creating or reconciling the provider subscription. Creation retries reuse the creation-operation identity; terminal cleanup uses the separate cleanup/cancellation identity while retaining the creation identity for provider-object lookup. This state grants no hosting entitlement. The [owner-authorized first-invoice flow](./stripe-integration.md#first-invoice-confirmation-and-completion) is the only permitted charge in this state. -Only a confirmed provider subscription ID may transition the row from `pending`/`provisioning` into `trialing` or `active`. A timeout or lost provider response is reconciled with the creation-operation identity before another create is attempted; if the provider resource exists but the local ID is missing, the creation lookup repairs the reference without creating a duplicate. +Provider linkage is necessary but not first-payment authority. An incomplete provider subscription remains non-authorizing while Account owns the exact awaiting-payment invoice and intent. Any initial authorizing receipt (`trialing`, `active`, `past_due` or `grace`) additionally requires the signed exact first-invoice completion and atomic Account fulfillment described in [Stripe Integration](./stripe-integration.md#first-invoice-confirmation-and-completion); creation, polling and browser/SCA results alone cannot supply it. + +A positive unpaid first invoice cannot gain authority through `trialing`; zero/free-trial onboarding remains unsupported by this paid-checkout component. Only a confirmed provider subscription ID may transition the row from `pending`/`provisioning` into `trialing` or `active`. A timeout or lost provider response is reconciled with the creation-operation identity before another create is attempted; if the provider resource exists but the local ID is missing, the creation lookup repairs the reference without creating a duplicate. The immutable internal `subscriptionId` is the sole stable subscription identity. `subscription_provisioning_request_id` is only the immutable provider-idempotency identity for the initial subscription-create operation; the cleanup/cancellation operation has a distinct immutable provider identity and retains the creation identity for provider-object lookup. Neither identity may be reused as the identity of a later plan, instrument, cancellation, or other existing-subscription update. Each existing-subscription update creates its own immutable operation-specific request ID and captures the subscription row version expected by that operation. Account commits the update only when that row version still matches; retries reuse the same update request ID and row-version/CAS guard, so a stale caller cannot overwrite a newer update and a provider mutation cannot be issued twice for one logical operation. 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 faf801be0c..85e435073e 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -56,9 +56,13 @@ The unregistered retained-denial read composes the Game Session client, the auth The Account owner can retry a rolled-back PostgreSQL serialization failure up to three times in fresh transactions, with short randomized delays and one retry-admission deadline. The player evaluation transaction rolls back and reports source unavailability when exact retention readback fails. An exact reservation replay in RELEASED or QUARANTINED state cannot authorize original NEW execution. -The Account-owned family comprises immutable evaluation, attempt-history, and recovery evidence plus guarded reservations and usage, with replay, restore, and hold dependencies. `PLAYER_ADMISSION` registration remains held. Its category classification and approved finite retention/erasure schedule, reference-safe owner cleanup preserving replay/restore dependencies and holds, and bounded size/health proof remain missing. See the canonical [Account runtime/data capacity retention limitation](../../architecture/microservices/account-service/runtime-and-data.md), [ADR 0050](../../architecture/decisions/adr-0050-versioned-export-retention-and-erasure-policy.md), and [ADR 0163](../../architecture/decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md). +The additive [V1044 conservation correction](../../../services/account-service/src/main/resources/db/migration/V1044__account_tenant_capacity_incremental_conservation.sql) follows unchanged V1041–V1043, audits retained complete sums under a writer lock, seeds a protected tenant/owner aggregate and maintains exact reservation-transition deltas. Deferred checks use indexed/point reads rather than lifetime-history sums. The conservation route from #3407 was already fixed on published `70ddd8b4a2ee8fc197bfaf94dcd5d425430c25ec`; current-source proof at #3408 `eacc8d5bc56f359d81c857058b4bb070b05d2dc8` is [Validation run 43018214593](https://github.com/benhook1013/FireMUD/actions/runs/43018214593), attempt 1, [Account partition 4 job 130514704488](https://github.com/benhook1013/FireMUD/actions/runs/43018214593/job/130514704488), artifact `13855961789`. All six PostgreSQL 18.6 cases pass with zero failures, errors or skips, covering empty/populated V1043 upgrade, preserved rows/history and prior migration artifacts, fresh SQL-trigger composition, inconsistent inventory and forged-write refusal, atomic rollback, two-worker serialization and bounded reservation reads with 4,096 finalized rows. The read-count case proves at most eight reservation rows read for each selected hold, finalization and metadata operation, not a latency or production-load benchmark. Candidate and tested synthetic merge `bfde19362676759f34f4a618ff96f9f9ae7bd9b1` share tree `521124b63ee37fd73a80831387eab62fb0e93bc9`; V1044 and test blobs match. These fixtures drive real SQL transactions/triggers rather than the Java owner API, and their populated preservation cohort has no attempt-history or recovery-evidence rows. This already-recorded conservation fix is separate from unresolved family-wide retention, cleanup, restore/replay, teardown and activation qualification. -The current positive owner boundary is public SHARED/PRESEEDED new player binding with exact shape `(activeSessions=0, instances=0, storage=0)` to `(1,0,0)` and explicit delta `1`, against exact retained evidence and current Account membership/issuance/scope sources. World lifecycle activation, authoritative prior-shape/zero-delta recovery, and existing-tenant usage import remain held without genuine complete owner sources. The schema and controlled persistence fixtures do not make those paths available. Paid evidence is not converted into DEMO; the separate NEW gameplay lease's currently supported explicit DEMO boundary is unchanged. +The Account-owned capacity evidence family remains subject to its [canonical retention and cleanup requirements](../../architecture/microservices/account-service/runtime-and-data.md#capacity-evidence-lifecycle). This slice retains [V1045 supporting indexes](../../../services/account-service/src/main/resources/db/migration/V1045__account_capacity_evaluation_retention.sql). The unregistered evaluation inspection and its proof belong to the existing [#3435 receiving change](https://github.com/benhook1013/FireMUD/pull/3435). The finite environment schedule, authoritative holds, bounded cleanup and family-wide replay and restore qualification remain open. `PLAYER_ADMISSION` registration and activation remain held. + +The local [V1046 freshness correction](../../../services/account-service/src/main/resources/db/migration/V1046__account_capacity_attempt_write_freshness.sql) keeps earlier migrations and retained rows immutable. New creation qualifies current sources after the usage lock and rechecks fresh database time before mutation; a deferred new-attempt guard rejects expiry before commit without releasing historical holds. Added PostgreSQL proof sources cover the actual usage-lock wait across expiry with a frozen application clock, additive upgrade preservation, and original/rearm rollback. The Game Session resource boundary also exposes safely retained release-failure slots through its existing Micrometer path, with once-per-operation counting and test-thread cancellation-order assertions. Focused Account owner and Game Session resource-budget proof passes 21 tests with zero failures, errors or skips. Owning source generation, production/test/integration compilation, Java formatting, parent-pinned Flyway validation and enabled affected Checkstyle/SpotBugs tasks pass. The first attempts exposed a meter-registry fixture compilation issue, reused-exception cleanup suppression and a missed direct fixture caller; those were corrected before the passing results. Physical PostgreSQL proof remains unrun because the VM cannot access its Docker socket; compiled assertions are not execution proof. No activation or family-wide lifecycle qualification is claimed. + +The current positive owner boundary is public SHARED/PRESEEDED new player binding with exact shape `(activeSessions=0, instances=0, storage=0)` to `(1,0,0)` and explicit delta `1`, against exact retained evidence and current Account membership/issuance/scope sources. World lifecycle activation, authoritative prior-shape/zero-delta recovery, and existing-tenant usage import remain held without genuine complete owner sources. The schema and controlled persistence fixtures do not make those paths available. The default NEW gameplay lease constructor keeps its explicit DEMO boundary. The separate paid-hosting composition uses the genuine paid owner path and remains unregistered. Its controlled PostgreSQL proof and outstanding production custody are recorded below. At the earlier preparation checkpoint on base `2e23db82384efa3221a53633dd43b45c62cd6ecc`, focused local validation passed 51 Java cases and two Python vector cases, with zero failures, errors or skips. The Java cases cover the shared digest, strict codec, Account capacity replay/refusal and workload guard, player-evidence retention/rollback, and Game Session loopback mTLS client. Scoped source generation and Java compilation, including Account integration sources, and all named enabled Checkstyle, SpotBugs and Java format tasks pass. Those physical PostgreSQL migration, fresh-bootstrap, retention/rollback, finalization/release and bounded recovery/quarantine definitions were unrun at that checkpoint. The later seven-case Account/Game Session composition below executes fresh bootstrap and authenticated positive finalization; separate closure/race and exhaustion definitions remain unrun. Controlled sources do not qualify genuine World lifecycle, deployed custody or admission. @@ -106,7 +110,11 @@ This receiver owns the [Stripe provisioner](../../../services/account-service/sr Focused source coverage includes `refusedDispatchCommitsLocalDeferralWithoutCallingProvider` and `refusedDispatchCannotHideStaleClaimSettlementFailure` in the composition units, and `displayRefreshAfterClaimRefusesDispatchButRetainedWorkReachesOperatorDeadline`, `displayRefreshAfterDispatchPreparationRefusesReadbackAndStillAllowsLocalDeadlineFailure`, and `displayRefreshBeforeInitialClaimRetainsTerminalFailureWithoutDispatch` in the dispatch physical suite. These changes do not establish new payment support or completed physical qualification; the execution limits above remain, and both components stay manually composed and unregistered, with the authenticated create producer, provider worker and public billing route held. -The paid first-invoice confirmation finding remains open in this receiving boundary. Stripe `default_incomplete` creation and subscription polling do not confirm a required first payment. The dispatch physical suite models an incomplete create, checks that no active receipt commits, and supplies a controlled confirmation before the same lifecycle operation can commit. Live confirmation still belongs to the accepted Account/provider-hosted checkout boundary after confirmed provider linkage, preserving [ADR 0044](../../architecture/decisions/adr-0044-account-owned-payment-instruments-with-explicit-subscription-binding.md) and [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); do not enable automatic charging inside the held provisioning adapter. Runtime registration and activation remain held. +The separate Account first-invoice successor now prepares provider-linked `AWAITING_PAYMENT` without authority, exact versioned commercial invoice/intent/instrument binding, distinct billing-purpose primary reauthentication, durable explicit consent, one existing-intent confirmation and narrowly protected HTTPS Stripe.js handoff. Exact signed payment success and a fresh invoice read precede atomic receipt, audit, billing and tenant-authority completion; delayed read-only reconciliation preserves the historical authorization without renewing a command or disclosing an expired secret. The checkout transport, browser and their proof are carried by the isolated receiving PR #3410. This producer retains the Account payment owner and its SQL proof. The same unregistered owner now prepares explicit fresh primary reauthentication and unchanged-consent renewal, append-only authorization-version fencing, and one durable command claim on the original payment operation. A crash before claim may resume only after a fresh explicit authorization; a claimed/ambiguous command is never resent. Renewal may resume the same intent's SCA handoff without changing any commercial/provider identity or extending invoice expiry. Focused renewal cases cover exact authorization/invoice expiry, replay, wrong operation/proof identity, changed consent, stale subscription/authorization fences, crash before claim, and ambiguous provider or claim outcomes. Canonical contracts remain [Account API](../../architecture/microservices/account-service/api-contracts.md#hosting-first-invoice-checkout) and [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md#first-invoice-confirmation-and-completion). The prior post-renewal local graph executed 54 selected Account unit cases and all main/unit/integration compilation, schema generation, enabled main/unit/integration Checkstyle and SpotBugs, and Java formatting with zero unit failures, errors or skips. That prior unmounted client/component run passed 32 cases, build, lint and formatting. Earlier 55-case Account and 29-case frontend results remain overlapping historical proof, not additional current coverage. Physical PostgreSQL/HTTPS migration and composition definitions compiled but were unexecuted in that historical post-renewal run because Docker was unavailable. The final Markdown gate passed; link checking remains unrun after an existing external URL denial. No skipped case establishes physical qualification. The paid first-invoice finding and accepted route finding remain open. Registration, deletion, retention, backup/source custody and runtime activation remain held, with no live Stripe transaction or automatic provisioning charge. + +Earlier rejected-bearer and uncertain-confirmation presentation proof passed eight controller/MVC cases and 34 browser/API cases. MVC exercises exact no-store 401 for the typed JWT rejection, preserves 400/409 mappings, and leaves typed verifier unavailability to the owning availability handler. The browser's original status-only hold is the baseline for the same-operation recovery proof below. + +Retained positive-subscription qualification remains open. V1041 creates empty completion relations and guards and leaves historical `trialing`, `active`, `past_due` and `grace` subscriptions in place. Current positive lifecycle reads and reconciliation require exact first-payment and completion joins. An old positive receipt without that evidence fails closed. The explicit disposition is now refuse-upgrade through forward V1046.1: lock subscription writes, reject unresolved current positives without changing their evidence, and install deferred completion consistency for later writers. V1041 stays immutable and activation remains held. Genuine predecessor fixture evidence is available from the old c8dab91d owner via `AccountHostingSubscriptionDispatchPostgresIntegrationTest.paymentRequiredSdkCreateCannotCommitUntilProviderConfirmsFirstInvoice`; its prior-source proof does not qualify this migration. The manually composed lifecycle repository now has an explicit read-only completion-gap prerequisite, with a caller-selected one-to-five-second query timeout and fail-closed database errors. It is not registered or an activation grant. Focused definitions cover invalid transaction/budget, unresolved or indeterminate results, database failure, and preserved populated pre-V1041 schema rows across upgrade for all four positive statuses. Current local predecessor definitions are controlled schema-valid data, not a replay of the genuine historical owner. Additional physical definitions cover upgrade refusal, final-transaction completion, existing completion immutability and blocked concurrent insert/update writers; none has been executed here. Bounded Java 25 compilation of all three changed Java files against cached APIs and the three new unit methods pass with no failures or skips. This is not a clean exact-tree Gradle build; physical execution and genuine positive-row remediation remain unqualified for this change. The current billing-owner tuple deliberately rejects unaudited updates. Fixture reconciliation preserves that refusal and unchanged row/xmin, stale owner version/generation capture refusal, and genuine payment-instrument advancement concurrency. Positive queued-create fencing after a real audited owner-transfer commit remains an obligation of the unimplemented transfer owner; constructed stale comparison inputs do not prove that transfer. @@ -114,6 +122,14 @@ The same receiving boundary carries the distinct TENANT_OPERATION evidence, Acco The earlier published #3389 comparison deliberately left public facade and numeric runtime entitlement paths unavailable; its historical source-built340 run passed held-edge denial and LOGIN but failed PLAY with ENTITLEMENT_UNAVAILABLE. Authenticated teardown and independently empty resources passed. This remains incomplete runtime qualification for that historical comparison, not a passing smoke result or a description of the reconstructed #3389 foundation, which preserves the supported parent runtime. The complete public consumer receiving below restores its own supported canonical compositions; canonical runtime cutover and final functional restoration remain separate obligations. Ordinary UUID identity/profile/retention protections retain their focused proof. +#### #3408 Account checkout-recovery producer + +The #3408 receiving source adds the Account-owned original-operation fence and immutable typed billing reauthentication binding for an exact owned `AWAITING_PAYMENT` invoice. Original confirmation and explicit fresh same-operation pre-row renewal compete under the same owner and fence for one first-consent, authorization and dispatch winner. The original operation, invoice and opening evidence remain retained. The additive [V1043 migration](../../../services/account-service/src/main/resources/db/migration/V1043__hosting_first_invoice_operation_fence.sql) follows the verified V1042 frontier and preserves V1041/V1042. + +The additive [V1046.4 migration](../../../services/account-service/src/main/resources/db/migration/V1046.4__retain_first_invoice_expiry_before_post.sql) retains the winning invocation's exact expiry-before-confirm observation against its independently committed claim. [V1046.7](../../../services/account-service/src/main/resources/db/migration/V1046.7__settle_first_invoice_expiry_before_post.sql) binds that evidence to the atomic terminal cancellation receipt and instrument release under the [canonical Stripe recovery contract](../../architecture/microservices/account-service/stripe-integration.md#first-invoice-confirmation-and-completion). + +Focused validation passes 29 Account units, 37 physical PostgreSQL and HTTPS cases, and 34 browser tests. The owner cases cover both first-winner outcomes, an already-arrived delayed original confirmation, competing and exact retries, rollback, stale/expired refusal, loss of the provider response, and one retained command claim. The V1042 witness preserves the legacy unbound billing row and its `xmin` through V1043 and refuses a substitute typed binding. The browser sends typed opening and follow-up proof, and offers explicit version-zero renewal only for the same invoice and original operation retained from a successful opening proof. An observational null confirmation ID alone provides no recovery identity. The HTTPS, browser and registered receiving proof are owned by #3410. The prior results above remain attributed to their original combined source. Payment activation, registration, retention/deletion/backup, source custody and the separate retained-entitlement activation obligation remain held. The provider and deployment are controlled fixtures in this proof. + ### Canonical public Account facade receiving The receiving source now restores the complete canonical V2 public facade, actual Account JOIN intent/member/pair/role/event/audit owners, V1037 diagnostics and V1038 existing-membership terminal guard, plus the distinct PLAYER_ADMISSION codec/Account receiver/Game Session client and persisted Account→Entity CHARS purpose. It retains actual same-row actor UUID/name/level, successful empty discovery only for supported targets, truthful admission flags, default-unavailable composition and all original positive cases. Contracts belong to [Account API](../../architecture/microservices/account-service/api-contracts.md#public-bootstrap-worlds-discovery) and [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#account-bootstrap-persisted-actor-discovery). diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index a561467fa3..317e0c6613 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -63,6 +63,8 @@ dependencies { implementation(libs.spring.boot.starter.mail) implementation(libs.argon2) implementation(libs.stripe.java) + implementation(libs.postgresql) + compileOnly("com.google.code.gson:gson") testFixturesImplementation(platform(libs.spring.boot.dependencies)) testFixturesImplementation(project(":common-platform-core")) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeFirstInvoiceHttpClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeFirstInvoiceHttpClient.java new file mode 100644 index 0000000000..19543331e4 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeFirstInvoiceHttpClient.java @@ -0,0 +1,72 @@ +package net.firedevops.firemud.accountservice.client; + +import com.stripe.exception.ApiConnectionException; +import com.stripe.net.HttpHeaders; +import com.stripe.net.StripeRequest; +import com.stripe.net.StripeResponse; +import java.net.URISyntaxException; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +/** The held first-invoice composition uses one bounded transport for its small JSON replies. */ +public final class StripeFirstInvoiceHttpClient extends com.stripe.net.HttpClient { + private static final long MAX_RESPONSE_BYTES = 1_048_576; + + private final HttpClient transport; + private final Duration responseTimeout; + + public StripeFirstInvoiceHttpClient(Duration connectTimeout, Duration responseTimeout) { + if (responseTimeout == null || responseTimeout.isNegative() || responseTimeout.isZero()) { + throw new IllegalArgumentException("A positive provider response timeout is required"); + } + this.responseTimeout = responseTimeout; + transport = HttpClient.newBuilder().connectTimeout(connectTimeout).build(); + } + + @Override + public StripeResponse request(StripeRequest request) throws ApiConnectionException { + HttpRequest.Builder outbound; + try { + outbound = HttpRequest.newBuilder(request.url().toURI()).timeout(responseTimeout); + } catch (URISyntaxException invalid) { + throw new ApiConnectionException("Invalid first-invoice provider endpoint", invalid); + } + request + .headers() + .map() + .forEach((name, values) -> values.forEach(value -> outbound.header(name, value))); + if (request.content() != null) { + outbound.setHeader("Content-Type", request.content().contentType()); + } + var body = + request.content() == null + ? HttpRequest.BodyPublishers.noBody() + : HttpRequest.BodyPublishers.ofByteArray(request.content().byteArrayContent()); + var exchange = + transport.sendAsync( + outbound.method(request.method().name(), body).build(), + HttpResponse.BodyHandlers.limiting( + HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8), MAX_RESPONSE_BYTES)); + try { + var received = exchange.get(responseTimeout.toNanos(), TimeUnit.NANOSECONDS); + return new StripeResponse( + received.statusCode(), HttpHeaders.of(received.headers().map()), received.body()); + } catch (TimeoutException timeout) { + exchange.cancel(true); + throw new ApiConnectionException("First-invoice provider response deadline expired", timeout); + } catch (InterruptedException interrupted) { + exchange.cancel(true); + Thread.currentThread().interrupt(); + throw new ApiConnectionException("First-invoice provider request interrupted", interrupted); + } catch (ExecutionException failed) { + throw new ApiConnectionException( + "First-invoice provider transport failed", failed.getCause()); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingFirstInvoicePaymentClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingFirstInvoicePaymentClient.java new file mode 100644 index 0000000000..c4470a3106 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingFirstInvoicePaymentClient.java @@ -0,0 +1,660 @@ +package net.firedevops.firemud.accountservice.client; + +import com.stripe.StripeClient; +import com.stripe.exception.StripeException; +import com.stripe.model.Invoice; +import com.stripe.model.PaymentIntent; +import com.stripe.model.Subscription; +import com.stripe.net.RequestOptions; +import com.stripe.param.InvoiceRetrieveParams; +import com.stripe.param.PaymentIntentConfirmParams; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountHostingFirstInvoicePayment; +import net.firedevops.firemud.accountservice.repository.AccountHostingFirstInvoicePaymentRepository.CommandClaim; +import net.firedevops.firemud.accountservice.repository.AccountHostingFirstInvoicePaymentRepository.ConfirmationDispatch; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProviderDispatch; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Existing invoice/intent only. Never creates a PaymentIntent, Checkout Session or replacement. */ +public final class StripeHostingFirstInvoicePaymentClient { + private final StripeClient stripe; + private final Clock clock; + private final RequestOptions options; + private final Duration exchangeBudget; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Private injected SDK transport remains owner-composed; copying it would discard the configured provider transport.") + public StripeHostingFirstInvoicePaymentClient( + StripeClient stripe, Clock clock, Duration connect, Duration read) { + this.stripe = Objects.requireNonNull(stripe); + this.clock = Objects.requireNonNull(clock); + this.exchangeBudget = read; + options = + RequestOptions.builder() + .setConnectTimeout(timeout(connect)) + .setReadTimeout(timeout(read)) + .setMaxNetworkRetries(0) + .build(); + } + + public Observation capture(ProviderDispatch dispatch, String providerId) throws StripeException { + outsideSql(); + if (!dispatch.readyForProviderIo()) + throw new IllegalStateException("Independent provider-dispatch receipt required"); + Instant started = clock.instant(); + Subscription subscription = stripe.subscriptions().retrieve(providerId, options); + if (subscription == null) throw refused(); + var binding = dispatch.expectedBinding(providerId); + require( + "subscription".equals(subscription.getObject()) + && providerId.equals(subscription.getId()) + && binding.providerCustomerId().equals(subscription.getCustomer()) + && binding.providerPaymentMethodId().equals(subscription.getDefaultPaymentMethod()) + && Boolean.valueOf(binding.livemode()).equals(subscription.getLivemode()) + && "incomplete".equals(subscription.getStatus()) + && subscription.getCreated() != null + && subscription.getMetadata() != null + && binding + .operationId() + .toString() + .equals(subscription.getMetadata().get("firemud_operation_id")) + && binding + .subscriptionId() + .toString() + .equals(subscription.getMetadata().get("firemud_subscription_id"))); + String invoiceId = subscription.getLatestInvoice(); + require(invoiceId != null && invoiceId.matches("in_[A-Za-z0-9]+")); + var result = + readInvoice( + invoiceId, + providerId, + binding.providerCustomerId(), + binding.providerPaymentMethodId(), + binding.livemode(), + binding.providerPriceId(), + binding.expectedQuantity(), + started, + Instant.ofEpochSecond(subscription.getCreated()).plus(Duration.ofHours(23)), + true) + .observation(); + require(!"succeeded".equals(result.status())); + return result; + } + + public Observation observe(AccountHostingFirstInvoicePayment expected) throws StripeException { + outsideSql(); + return observeOriginal(expected, false).observation(); + } + + private InvoiceRead observeOriginal( + AccountHostingFirstInvoicePayment expected, boolean allowUnassigned) throws StripeException { + var read = + readInvoice( + expected.invoiceId(), + expected.providerSubscriptionId(), + expected.providerCustomerId(), + expected.providerPaymentMethodId(), + expected.livemode(), + expected.providerPriceId(), + expected.providerQuantity(), + clock.instant(), + expected.expiresAt(), + allowUnassigned); + var result = read.observation(); + require( + expected.paymentIntentId().equals(result.paymentIntentId()) + && expected.amount() == result.amount() + && expected.currency().equals(result.currency())); + return read; + } + + /** + * Independently observes that the retained original invoice and its existing intent are + * terminally unpaid. This is read-only evidence; it does not establish payment or entitlement. + */ + public TerminalUnpaidObservation observeTerminalUnpaid( + AccountHostingFirstInvoicePayment expected, boolean allowUnassignedIntent) + throws StripeException { + outsideSql(); + Objects.requireNonNull(expected); + Instant started = clock.instant(); + Invoice invoice = + stripe + .invoices() + .retrieve( + expected.invoiceId(), + InvoiceRetrieveParams.builder() + .addExpand("payments.data.payment.payment_intent") + .build(), + options); + if (invoice == null) throw refused(); + require( + "invoice".equals(invoice.getObject()) + && expected.invoiceId().equals(invoice.getId()) + && expected.providerCustomerId().equals(invoice.getCustomer()) + && Boolean.valueOf(expected.livemode()).equals(invoice.getLivemode()) + && "subscription_create".equals(invoice.getBillingReason()) + && invoice.getParent() != null + && invoice.getParent().getSubscriptionDetails() != null + && expected + .providerSubscriptionId() + .equals(invoice.getParent().getSubscriptionDetails().getSubscription()) + && "void".equals(invoice.getStatus()) + && Long.valueOf(0).equals(invoice.getAmountPaid()) + && Long.valueOf(0).equals(invoice.getAmountRemaining()) + && Long.valueOf(0).equals(invoice.getStartingBalance()) + && Long.valueOf(expected.amount()).equals(invoice.getAmountDue()) + && Long.valueOf(expected.amount()).equals(invoice.getTotal()) + && expected.currency().equals(invoice.getCurrency()) + && invoice.getPayments() != null + && Boolean.FALSE.equals(invoice.getPayments().getHasMore()) + && invoice.getPayments().getData() != null + && invoice.getPayments().getData().size() == 1 + && invoice.getLines() != null + && Boolean.FALSE.equals(invoice.getLines().getHasMore()) + && invoice.getLines().getData() != null + && invoice.getLines().getData().size() == 1); + var line = invoice.getLines().getData().getFirst(); + require( + line != null + && "line_item".equals(line.getObject()) + && Long.valueOf(expected.providerQuantity()).equals(line.getQuantity()) + && (line.getQuantityDecimal() == null + || java.math.BigDecimal.valueOf(expected.providerQuantity()) + .compareTo(line.getQuantityDecimal()) + == 0) + && Long.valueOf(expected.amount()).equals(line.getAmount()) + && expected.currency().equals(line.getCurrency()) + && line.getPricing() != null + && "price_details".equals(line.getPricing().getType()) + && line.getPricing().getPriceDetails() != null + && expected.providerPriceId().equals(line.getPricing().getPriceDetails().getPrice())); + var payment = invoice.getPayments().getData().getFirst(); + if (payment == null) throw refused(); + require( + payment.getPayment() != null + && "payment_intent".equals(payment.getPayment().getType()) + && expected.paymentIntentId().equals(payment.getPayment().getPaymentIntent())); + PaymentIntent expandedIntent = payment.getPayment().getPaymentIntentObject(); + requireTerminalIntent(expandedIntent, expected, allowUnassignedIntent); + + PaymentIntent intent = stripe.paymentIntents().retrieve(expected.paymentIntentId(), options); + requireTerminalIntent(intent, expected, allowUnassignedIntent); + require(Objects.equals(expandedIntent.getPaymentMethod(), intent.getPaymentMethod())); + + Instant observed = clock.instant(); + require( + !observed.isBefore(started) + && Duration.between(started, observed).compareTo(Duration.ofSeconds(20)) < 0); + return new TerminalUnpaidObservation( + expected.invoiceId(), + expected.paymentIntentId(), + expected.digest(), + intent.getPaymentMethod() == null, + started, + observed); + } + + private static void requireTerminalIntent( + PaymentIntent intent, + AccountHostingFirstInvoicePayment expected, + boolean allowUnassignedIntent) { + require( + intent != null + && "payment_intent".equals(intent.getObject()) + && expected.paymentIntentId().equals(intent.getId()) + && expected.providerCustomerId().equals(intent.getCustomer()) + && (expected.providerPaymentMethodId().equals(intent.getPaymentMethod()) + || (allowUnassignedIntent + && intent.getPaymentMethod() == null + && intent.getLatestCharge() == null)) + && Boolean.valueOf(expected.livemode()).equals(intent.getLivemode()) + && "automatic".equals(intent.getConfirmationMethod()) + && "canceled".equals(intent.getStatus()) + && Long.valueOf(expected.amount()).equals(intent.getAmount()) + && Long.valueOf(0).equals(intent.getAmountReceived()) + && expected.currency().equals(intent.getCurrency())); + } + + /** + * Only the original durable authorization may issue one confirm; recovery observes the same + * intent. + */ + public Handoff confirm( + ConfirmationDispatch dispatch, java.util.function.Supplier claimCommand) + throws StripeException { + outsideSql(); + if (!dispatch.independentlyRead() || !clock.instant().isBefore(dispatch.validUntil())) { + throw new IllegalStateException("Committed current billing-owner consent required"); + } + boolean allowUnassigned = dispatch.initialCommandAvailable(); + var read = observeOriginal(dispatch.invoice(), allowUnassigned); + PaymentIntent intent = + stripe.paymentIntents().retrieve(read.observation().paymentIntentId(), options); + validateIntent( + intent, + dispatch.invoice().providerCustomerId(), + dispatch.invoice().providerPaymentMethodId(), + dispatch.invoice().livemode(), + allowUnassigned); + require(read.unassigned() == (intent.getPaymentMethod() == null)); + require( + dispatch.invoice().paymentIntentId().equals(intent.getId()) + && Long.valueOf(dispatch.invoice().amount()).equals(intent.getAmount()) + && dispatch.invoice().currency().equals(intent.getCurrency())); + if (preConfirmation(intent.getStatus())) { + require(preConfirmation(read.observation().status())); + if (!dispatch.takeInitialCommandPermission()) + return new Handoff("AUTHORIZED_NOT_CONFIRMED", null); + require(clock.instant().plus(exchangeBudget).isBefore(dispatch.validUntil())); + CommandClaim claim = claimCommand.get(); + outsideSql(); + if (claim == null || !claim.takePermission(dispatch)) + return new Handoff("AUTHORIZED_NOT_CONFIRMED", null); + Instant beforePost = clock.instant(); + if (!beforePost.isBefore(dispatch.validUntil())) { + throw new ExpiredBeforePost(dispatch.requestId(), beforePost); + } + intent = + stripe + .paymentIntents() + .confirm( + intent.getId(), + PaymentIntentConfirmParams.builder() + .setPaymentMethod(dispatch.invoice().providerPaymentMethodId()) + .setUseStripeSdk(true) + .build(), + options + .toBuilderFullCopy() + .setIdempotencyKey(dispatch.providerIdempotencyId().toString()) + .build()); + } + validateIntent( + intent, + dispatch.invoice().providerCustomerId(), + dispatch.invoice().providerPaymentMethodId(), + dispatch.invoice().livemode(), + false); + require( + dispatch.invoice().paymentIntentId().equals(intent.getId()) + && Long.valueOf(dispatch.invoice().amount()).equals(intent.getAmount()) + && dispatch.invoice().currency().equals(intent.getCurrency())); + require(clock.instant().isBefore(dispatch.validUntil())); + String secret = "requires_action".equals(intent.getStatus()) ? intent.getClientSecret() : null; + require( + !"requires_action".equals(intent.getStatus()) + || (secret != null && secret.startsWith(intent.getId() + "_secret_"))); + return new Handoff(intent.getStatus(), secret); + } + + private InvoiceRead readInvoice( + String invoiceId, + String subscriptionId, + String customerId, + String methodId, + boolean livemode, + String priceId, + long quantity, + Instant started, + Instant expiry, + boolean allowUnassigned) + throws StripeException { + Invoice invoice = + stripe + .invoices() + .retrieve( + invoiceId, + InvoiceRetrieveParams.builder() + .addExpand("payments.data.payment.payment_intent") + .build(), + options); + if (invoice == null) throw refused(); + require( + "invoice".equals(invoice.getObject()) + && invoiceId.equals(invoice.getId()) + && customerId.equals(invoice.getCustomer()) + && Boolean.valueOf(livemode).equals(invoice.getLivemode()) + && "subscription_create".equals(invoice.getBillingReason()) + && invoice.getParent() != null + && invoice.getParent().getSubscriptionDetails() != null + && subscriptionId.equals(invoice.getParent().getSubscriptionDetails().getSubscription()) + && invoice.getPayments() != null + && Boolean.FALSE.equals(invoice.getPayments().getHasMore()) + && invoice.getPayments().getData() != null + && invoice.getPayments().getData().size() == 1); + require( + invoice.getLines() != null + && Boolean.FALSE.equals(invoice.getLines().getHasMore()) + && invoice.getLines().getData() != null + && invoice.getLines().getData().size() == 1); + var line = invoice.getLines().getData().getFirst(); + require( + line != null + && "line_item".equals(line.getObject()) + && Long.valueOf(quantity).equals(line.getQuantity()) + && (line.getQuantityDecimal() == null + || java.math.BigDecimal.valueOf(quantity).compareTo(line.getQuantityDecimal()) == 0) + && line.getPricing() != null + && "price_details".equals(line.getPricing().getType()) + && line.getPricing().getPriceDetails() != null + && priceId.equals(line.getPricing().getPriceDetails().getPrice()) + && invoice.getAmountDue() != null + && invoice.getAmountDue().equals(line.getAmount()) + && invoice.getCurrency() != null + && invoice.getCurrency().equals(line.getCurrency())); + var payment = invoice.getPayments().getData().getFirst(); + if (payment == null) throw refused(); + require( + payment.getPayment() != null && "payment_intent".equals(payment.getPayment().getType())); + PaymentIntent intent = payment.getPayment().getPaymentIntentObject(); + if (intent == null) throw refused(); + require(payment.getPayment().getPaymentIntent().equals(intent.getId())); + validateIntent(intent, customerId, methodId, livemode, allowUnassigned); + require( + invoice.getAmountDue() != null + && invoice.getAmountDue() > 0 + && invoice.getAmountDue().equals(invoice.getTotal()) + && Long.valueOf(0).equals(invoice.getStartingBalance()) + && invoice.getAmountDue().equals(intent.getAmount()) + && invoice.getCurrency().equals(intent.getCurrency())); + if ("succeeded".equals(intent.getStatus())) { + require( + "paid".equals(invoice.getStatus()) + && invoice.getAmountDue().equals(invoice.getAmountPaid()) + && Long.valueOf(0).equals(invoice.getAmountRemaining()) + && invoice.getAmountDue().equals(intent.getAmountReceived())); + } else { + require( + "open".equals(invoice.getStatus()) + && Long.valueOf(0).equals(invoice.getAmountPaid()) + && invoice.getAmountDue().equals(invoice.getAmountRemaining())); + } + Instant observed = clock.instant(); + require( + !observed.isBefore(started) + && Duration.between(started, observed).compareTo(Duration.ofSeconds(20)) < 0); + return new InvoiceRead( + new Observation( + subscriptionId, + customerId, + methodId, + livemode, + priceId, + quantity, + invoiceId, + intent.getId(), + intent.getAmount(), + intent.getCurrency(), + intent.getStatus(), + started, + observed, + expiry), + intent.getPaymentMethod() == null); + } + + private static boolean preConfirmation(String status) { + return "requires_confirmation".equals(status) || "requires_payment_method".equals(status); + } + + private record InvoiceRead(Observation observation, boolean unassigned) {} + + private static void validateIntent( + PaymentIntent intent, String customer, String method, boolean live, boolean allowUnassigned) { + require( + intent != null + && "payment_intent".equals(intent.getObject()) + && intent.getId() != null + && customer.equals(intent.getCustomer()) + && (method.equals(intent.getPaymentMethod()) + || (allowUnassigned + && intent.getPaymentMethod() == null + && "requires_payment_method".equals(intent.getStatus()) + && Long.valueOf(0).equals(intent.getAmountReceived()) + && intent.getLatestCharge() == null)) + && Boolean.valueOf(live).equals(intent.getLivemode()) + && "automatic".equals(intent.getConfirmationMethod()) + && intent.getStatus() != null + && java.util.Set.of( + "requires_confirmation", + "requires_payment_method", + "requires_action", + "processing", + "succeeded") + .contains(intent.getStatus())); + } + + private static int timeout(Duration value) { + if (value == null + || value.isNegative() + || value.isZero() + || value.toMillis() > 10000 + || value.getNano() % 1000000 != 0) { + throw new IllegalArgumentException("Bounded whole-millisecond provider timeout required"); + } + return Math.toIntExact(value.toMillis()); + } + + private static void outsideSql() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("First-invoice provider IO refuses ambient SQL transaction"); + } + } + + private static void require(boolean valid) { + if (!valid) throw refused(); + } + + private static ProviderEvidenceRefused refused() { + return new ProviderEvidenceRefused(); + } + + /** The provider returned a supported response shape that cannot establish the retained tuple. */ + public static final class ProviderEvidenceRefused extends IllegalStateException { + private static final long serialVersionUID = 1L; + + public ProviderEvidenceRefused() { + super("Exact existing first-invoice provider binding refused"); + } + } + + /** The winning committed claim was consumed locally, before entry to the Stripe confirm call. */ + public static final class ExpiredBeforePost extends IllegalStateException { + private static final long serialVersionUID = 1L; + private final UUID requestId; + private final Instant observedAt; + + private ExpiredBeforePost(UUID requestId, Instant observedAt) { + super("Exact existing first-invoice provider binding refused"); + this.requestId = requestId; + this.observedAt = observedAt; + } + + public UUID requestId() { + return requestId; + } + + public Instant observedAt() { + return observedAt; + } + } + + /** Contains no client secret, and is not payment or entitlement authority. */ + public static final class Observation { + private final String invoiceId, paymentIntentId, currency, status; + private final String providerSubscriptionId, + providerCustomerId, + providerPaymentMethodId, + providerPriceId; + private final long providerQuantity; + private final boolean livemode; + private final long amount; + private final Instant readStartedAt, observedAt, expiresAt; + + private Observation( + String providerSubscriptionId, + String providerCustomerId, + String providerPaymentMethodId, + boolean livemode, + String providerPriceId, + long providerQuantity, + String invoiceId, + String paymentIntentId, + long amount, + String currency, + String status, + Instant readStartedAt, + Instant observedAt, + Instant expiresAt) { + this.providerSubscriptionId = providerSubscriptionId; + this.providerCustomerId = providerCustomerId; + this.providerPaymentMethodId = providerPaymentMethodId; + this.livemode = livemode; + this.providerPriceId = providerPriceId; + this.providerQuantity = providerQuantity; + this.invoiceId = invoiceId; + this.paymentIntentId = paymentIntentId; + this.amount = amount; + this.currency = currency; + this.status = status; + this.readStartedAt = readStartedAt; + this.observedAt = observedAt; + this.expiresAt = expiresAt; + } + + public String providerSubscriptionId() { + return providerSubscriptionId; + } + + public String providerCustomerId() { + return providerCustomerId; + } + + public String providerPaymentMethodId() { + return providerPaymentMethodId; + } + + public String providerPriceId() { + return providerPriceId; + } + + public long providerQuantity() { + return providerQuantity; + } + + public boolean livemode() { + return livemode; + } + + public String invoiceId() { + return invoiceId; + } + + public String paymentIntentId() { + return paymentIntentId; + } + + public long amount() { + return amount; + } + + public String currency() { + return currency; + } + + public String status() { + return status; + } + + public Instant readStartedAt() { + return readStartedAt; + } + + public Instant observedAt() { + return observedAt; + } + + public Instant expiresAt() { + return expiresAt; + } + } + + /** Closed, read-only evidence for the exact unpaid original invoice/intent tuple. */ + public static final class TerminalUnpaidObservation { + private final String invoiceId; + private final String paymentIntentId; + private final String tupleDigest; + private final boolean intentMethodUnassigned; + private final Instant readStartedAt; + private final Instant observedAt; + + private TerminalUnpaidObservation( + String invoiceId, + String paymentIntentId, + String tupleDigest, + boolean intentMethodUnassigned, + Instant readStartedAt, + Instant observedAt) { + this.invoiceId = invoiceId; + this.paymentIntentId = paymentIntentId; + this.tupleDigest = tupleDigest; + this.intentMethodUnassigned = intentMethodUnassigned; + this.readStartedAt = readStartedAt; + this.observedAt = observedAt; + } + + public String invoiceId() { + return invoiceId; + } + + public String paymentIntentId() { + return paymentIntentId; + } + + public String tupleDigest() { + return tupleDigest; + } + + public boolean intentMethodUnassigned() { + return intentMethodUnassigned; + } + + public Instant readStartedAt() { + return readStartedAt; + } + + public Instant observedAt() { + return observedAt; + } + } + + /** The secret is released only to the authenticated HTTPS owner and never persisted or logged. */ + public static final class Handoff { + private final String status; + private final String clientSecret; + + private Handoff(String status, String secret) { + this.status = status; + this.clientSecret = secret; + } + + public String status() { + return status; + } + + public String clientSecret() { + return clientSecret; + } + + @Override + public String toString() { + return "HostingFirstInvoiceHandoff[redacted]"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountHostingFirstInvoiceConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountHostingFirstInvoiceConfiguration.java new file mode 100644 index 0000000000..f6cc2d3ad8 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountHostingFirstInvoiceConfiguration.java @@ -0,0 +1,31 @@ +package net.firedevops.firemud.accountservice.config; + +import java.time.Clock; +import java.time.Duration; +import net.firedevops.firemud.accountservice.client.StripeFirstInvoiceHttpClient; +import net.firedevops.firemud.accountservice.client.StripeHostingFirstInvoicePaymentClient; +import net.firedevops.firemud.accountservice.client.StripeHostingWebhookVerifier; + +/** + * Explicit held composition helpers, with no Spring annotation, bean, worker or route activation. + */ +public final class AccountHostingFirstInvoiceConfiguration { + private AccountHostingFirstInvoiceConfiguration() {} + + public static StripeHostingFirstInvoicePaymentClient provider( + PaymentProperties properties, Clock clock) { + Duration connect = Duration.ofSeconds(2); + Duration exchange = Duration.ofSeconds(5); + var client = + com.stripe.StripeClient.builder() + .setApiKey(properties.getStripeApiKey()) + .setMaxNetworkRetries(0) + .setHttpClient(new StripeFirstInvoiceHttpClient(connect, exchange)) + .build(); + return new StripeHostingFirstInvoicePaymentClient(client, clock, connect, exchange); + } + + public static StripeHostingWebhookVerifier verifier(PaymentProperties properties, Clock clock) { + return new StripeHostingWebhookVerifier(properties.getHostingWebhookSecret(), clock); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/PaymentProperties.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/PaymentProperties.java index e5ac1e33b0..427c9ce7d8 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/PaymentProperties.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/PaymentProperties.java @@ -6,6 +6,8 @@ @Data @ConfigurationProperties(prefix = "firemud.payment") public class PaymentProperties { - private String stripeApiKey; + @lombok.ToString.Exclude private String stripeApiKey; + @lombok.ToString.Exclude private String hostingWebhookSecret; + private String stripePublishableKey; private double platformFeePercent = 0.0; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java index 02b676fbdd..45f13f9fe0 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java @@ -218,6 +218,12 @@ public void insertCanonical( } } + /** Uses the same database clock as the consumer of an issued scope. */ + public Instant canonicalIssuanceTime() { + requireWritableOwnerTransaction(); + return AccountTenantCapacityRepository.databaseNow(dsl); + } + /** Resolves v2 only from a bearer whose exact immutable owner evidence is persisted. */ @Transactional(propagation = Propagation.MANDATORY) public Optional findCanonical(String connectScopeId) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountEmailLoginChallengeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountEmailLoginChallengeRepository.java index 2097f39e2a..8464626264 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountEmailLoginChallengeRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountEmailLoginChallengeRepository.java @@ -32,6 +32,12 @@ public void lockAccountChallenge(long accountId) { dsl.fetch("select pg_advisory_xact_lock(?)", accountId); } + /** Billing already holds shared producer locks and must release them on OTP contention. */ + public boolean tryLockAccountChallenge(long accountId) { + return Boolean.TRUE.equals( + dsl.fetchSingle("select pg_try_advisory_xact_lock(?)", accountId).get(0, Boolean.class)); + } + public AccountEmailLoginChallenge save(AccountEmailLoginChallenge entity) { if (entity.getId() == null) { Long id = 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 59baf1c0f2..021b5574be 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 @@ -1,6 +1,7 @@ package net.firedevops.firemud.accountservice.repository; import java.sql.Connection; +import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -46,7 +47,7 @@ * 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 { +public final class AccountGameplayAdmissionCurrentSources { private static final String ACCOUNT_ISSUER = GameSessionAccountDelegationProfile.ISSUER; private static final UUID NIL_UUID = new UUID(0L, 0L); private static final Set LEASE_SOURCE_FIELDS = @@ -183,6 +184,40 @@ Current readCurrentPublicProductionNew( return new Current(snapshot, typedTenantEvent, currentCommittedCandidate); } + /** + * Locks the exact caller and current tenant billing-owner Account rows in deterministic order. + * + *

Call inside the caller's writable SERIALIZABLE transaction, before hosting-wallet or tenant + * source locks. This shared lock step keeps paid admission readers on the same Account-first + * order even when the caller is not the billing owner. + */ + public static void lockRequiredAccountsBeforeTenantSources( + DSLContext exactDsl, UUID tenantId, UUID callerAccountId) { + Objects.requireNonNull(exactDsl, "The caller-enlisted DSLContext is required"); + requireNonNilUuid(tenantId, "Canonical tenant UUID"); + requireNonNilUuid(callerAccountId, "Verified caller Account UUID"); + requireWritableSerializableAccountTransaction(exactDsl); + + Record owner = + exactDsl.fetchOne( + "SELECT owner_account_uuid FROM account_tenant_billing_owners WHERE tenant_uuid = ?", + tenantId); + UUID billingOwnerAccountId = owner == null ? null : owner.get("owner_account_uuid", UUID.class); + if (billingOwnerAccountId != null) { + requireNonNilUuid(billingOwnerAccountId, "Tenant billing-owner Account UUID"); + } + + List requiredAccounts = new ArrayList<>(2); + requiredAccounts.add(callerAccountId); + if (billingOwnerAccountId != null && !billingOwnerAccountId.equals(callerAccountId)) { + requiredAccounts.add(billingOwnerAccountId); + } + requiredAccounts.sort(UUID::compareTo); + for (UUID accountId : requiredAccounts) { + lockExactAccountFirst(exactDsl, accountId); + } + } + /** * Revalidates only the current authenticated Account caller for non-admitting exact recovery. * @@ -417,6 +452,10 @@ private static boolean sameAccountSecurityCutoff( } private void requireWritableSerializableAccountTransaction() { + requireWritableSerializableAccountTransaction(dsl); + } + + private static void requireWritableSerializableAccountTransaction(DSLContext dsl) { if (!TransactionSynchronizationManager.isActualTransactionActive() || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { throw unavailable(); @@ -436,6 +475,10 @@ private void requireWritableSerializableAccountTransaction() { } private void lockExactAccountFirst(UUID accountId) { + lockExactAccountFirst(dsl, accountId); + } + + private static void lockExactAccountFirst(DSLContext dsl, UUID accountId) { Record locked = dsl.fetchOne( "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", accountId); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingBillingPolicyRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingBillingPolicyRepository.java new file mode 100644 index 0000000000..2795e50e82 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingBillingPolicyRepository.java @@ -0,0 +1,94 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.util.Map; +import java.util.Objects; +import org.jooq.DSLContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit versioned commercial policy. No client amount, Stripe balance or tax fallback. */ +public final class AccountHostingBillingPolicyRepository { + private final DSLContext dsl; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Private injected transactional DSLContext is retained for the Account transaction boundary and never exposed.") + public AccountHostingBillingPolicyRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + public Policy requireCurrent(AccountHostingPlanQuote quote) { + requireTransaction(); + var row = + dsl.fetchOne( + "SELECT v.* FROM account_hosting_billing_policy_current c " + + "JOIN account_hosting_billing_policy_values v USING (provider_price_id, policy_version) " + + "WHERE c.provider_price_id = ? FOR SHARE OF c", + quote.providerPriceId()); + if (row == null) + throw new IllegalStateException("Explicit current hosting billing policy unavailable"); + var result = + new Policy( + row.get("provider_price_id", String.class), + row.get("policy_version", Long.class), + row.get("quantity", Long.class), + row.get("amount", Long.class), + row.get("currency", String.class)); + if (result.quantity() != quote.providerQuantity()) + throw new IllegalStateException("Hosting policy quantity mismatch"); + return result; + } + + public void requireUnchanged( + AccountHostingFirstInvoicePayment invoice, AccountHostingPlanQuote quote) { + Policy current = requireCurrent(quote); + if (!current.providerPriceId().equals(invoice.providerPriceId()) + || current.quantity() != invoice.providerQuantity() + || current.version() != invoice.billingPolicyVersion() + || !current.digest().equals(invoice.billingPolicyDigest()) + || current.amount() != invoice.amount() + || !current.currency().equals(invoice.currency()) + || !quote.digest().equals(invoice.quoteDigest())) { + throw new IllegalStateException( + "Hosting billing policy changed; first-invoice checkout refused"); + } + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) + throw new IllegalStateException("Account owner transaction required"); + } + + public record Policy( + String providerPriceId, long version, long quantity, long amount, String currency) { + public Policy { + if (providerPriceId == null + || !providerPriceId.matches("price_[A-Za-z0-9]+") + || version < 1 + || quantity < 1 + || amount < 1 + || currency == null + || !currency.matches("[a-z]{3}")) { + throw new IllegalArgumentException("Explicit positive hosting commercial policy required"); + } + } + + public String digest() { + return AccountHostingSubscriptionLifecycleEvidence.digest( + AccountHostingSubscriptionLifecycleEvidence.encode( + Map.of( + "schemaVersion", + "account-hosting-billing-policy/v1", + "providerPriceId", + providerPriceId, + "version", + Long.toString(version), + "quantity", + Long.toString(quantity), + "amount", + Long.toString(amount), + "currency", + currency))); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingFirstInvoicePayment.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingFirstInvoicePayment.java new file mode 100644 index 0000000000..6057b332a4 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingFirstInvoicePayment.java @@ -0,0 +1,96 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; + +/** Exact retained first invoice. This value and provider linkage confer no hosting authority. */ +public record AccountHostingFirstInvoicePayment( + UUID subscriptionId, + UUID creationRequestId, + UUID tenantId, + UUID ownerAccountId, + UUID paymentInstrumentId, + long instrumentVersion, + String providerSubscriptionId, + String providerCustomerId, + String providerPaymentMethodId, + String invoiceId, + String paymentIntentId, + long amount, + String currency, + String quoteDigest, + String providerPriceId, + long providerQuantity, + long billingPolicyVersion, + String billingPolicyDigest, + boolean livemode, + Instant capturedAt, + Instant expiresAt) { + public AccountHostingFirstInvoicePayment { + capturedAt = Objects.requireNonNull(capturedAt).truncatedTo(ChronoUnit.MICROS); + expiresAt = Objects.requireNonNull(expiresAt).truncatedTo(ChronoUnit.MICROS); + for (UUID id : + new UUID[] { + subscriptionId, creationRequestId, tenantId, ownerAccountId, paymentInstrumentId + }) { + AccountBillingCustomerRecord.requireUuid(id); + } + requireId(providerSubscriptionId, "sub_"); + requireId(providerCustomerId, "cus_"); + requireId(providerPaymentMethodId, "pm_"); + requireId(invoiceId, "in_"); + requireId(paymentIntentId, "pi_"); + requireId(providerPriceId, "price_"); + if (providerQuantity < 1 + || instrumentVersion < 1 + || billingPolicyVersion < 1 + || amount <= 0 + || currency == null + || !currency.matches("[a-z]{3}") + || quoteDigest == null + || !quoteDigest.matches("sha256:[0-9a-f]{64}") + || billingPolicyDigest == null + || !billingPolicyDigest.matches("sha256:[0-9a-f]{64}") + || !expiresAt.isAfter(capturedAt)) { + throw new IllegalArgumentException( + "Exact first-invoice commercial and expiry binding required"); + } + } + + public String digest() { + Map fields = new java.util.LinkedHashMap<>(); + fields.put("schemaVersion", "account-hosting-first-invoice/v1"); + fields.put("subscriptionId", subscriptionId.toString()); + fields.put("creationRequestId", creationRequestId.toString()); + fields.put("tenantId", tenantId.toString()); + fields.put("ownerAccountId", ownerAccountId.toString()); + fields.put("paymentInstrumentId", paymentInstrumentId.toString()); + fields.put("instrumentVersion", Long.toString(instrumentVersion)); + fields.put("providerSubscriptionId", providerSubscriptionId); + fields.put("providerCustomerId", providerCustomerId); + fields.put("providerPaymentMethodId", providerPaymentMethodId); + fields.put("invoiceId", invoiceId); + fields.put("paymentIntentId", paymentIntentId); + fields.put("amount", Long.toString(amount)); + fields.put("currency", currency); + fields.put("quoteDigest", quoteDigest); + fields.put("providerPriceId", providerPriceId); + fields.put("providerQuantity", Long.toString(providerQuantity)); + fields.put("billingPolicyVersion", Long.toString(billingPolicyVersion)); + fields.put("billingPolicyDigest", billingPolicyDigest); + fields.put("livemode", livemode); + fields.put("capturedAt", capturedAt.toString()); + fields.put("expiresAt", expiresAt.toString()); + return AccountHostingSubscriptionLifecycleEvidence.digest( + AccountHostingSubscriptionLifecycleEvidence.encode(fields)); + } + + private static void requireId(String value, String prefix) { + if (value == null || !value.matches(prefix + "[A-Za-z0-9]{1,251}")) { + throw new IllegalArgumentException("Exact provider identity required"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingFirstInvoicePaymentConflictRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingFirstInvoicePaymentConflictRepository.java new file mode 100644 index 0000000000..ad653a7b29 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingFirstInvoicePaymentConflictRepository.java @@ -0,0 +1,381 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.client.StripeHostingFirstInvoicePaymentClient.Observation; +import net.firedevops.firemud.accountservice.client.StripeHostingWebhookVerifier.VerifiedEvent; +import net.firedevops.firemud.accountservice.repository.AccountHostingFirstInvoicePaymentRepository.ConfirmationDispatch; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.JacksonException; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** Account-owned immutable record of a verified payment succeeding after retained cancellation. */ +final class AccountHostingFirstInvoicePaymentConflictRepository { + private static final String TABLE = "subscription_first_invoice_late_paid_conflicts"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final DSLContext dsl; + + AccountHostingFirstInvoicePaymentConflictRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + } + + /** + * Returns the original first-invoice confirmation request for an exact verified-event replay. The + * cancellation record remains addressable after its subscription row is superseded. + */ + UUID retainedConflictRequestId(VerifiedEvent verified) { + requireTransaction(); + Objects.requireNonNull(verified, "verified Stripe event is required"); + Record row = + dsl.fetchOne( + "SELECT conflict.request_id, COALESCE(replay.event_payload_digest," + + " conflict.event_payload_digest) AS event_payload_digest, inbox.raw_payload," + + " inbox.payload_sha256, inbox.event_type," + + " inbox.provider_created_at_epoch_seconds, inbox.provider_api_version," + + " inbox.livemode, replay.provider_event_id IS NOT NULL AS linked_replay," + + " confirmation.consented_at FROM stripe_event_inbox inbox LEFT JOIN" + + " subscription_first_invoice_late_paid_event_replays replay USING" + + " (provider_event_id) JOIN " + + TABLE + + " conflict ON conflict.provider_event_id = inbox.provider_event_id " + + "OR conflict.subscription_id = replay.subscription_id " + + "JOIN subscription_first_invoice_confirmations confirmation " + + "ON confirmation.request_id = conflict.request_id " + + "AND confirmation.subscription_id = conflict.subscription_id " + + "WHERE inbox.provider_event_id = ?", + verified.providerEventId()); + if (row == null) return null; + requireExactEvent(verified, row); + if (Boolean.TRUE.equals(row.get("linked_replay", Boolean.class)) + && verified.eventCreatedAtEpochSeconds() + < Objects.requireNonNull(row.get("consented_at", OffsetDateTime.class)) + .toInstant() + .getEpochSecond()) { + // A historical link is not consent. Let the signed classifier retain this as read-only + // reconciliation without provider I/O or fulfillment. + return null; + } + return row.get("request_id", UUID.class); + } + + /** + * Retains a paid conflict only when the same Account subscription is already canceled by its + * exact committed unpaid-first-invoice receipt. The payment owner has already verified the signed + * tuple and provider readback. False leaves its existing fulfillment path in charge. + */ + boolean retainIfCanceled( + VerifiedEvent verified, ConfirmationDispatch candidate, Observation observed) { + requireWritableTransaction(); + Objects.requireNonNull(verified, "verified Stripe event is required"); + + UUID replayRequestId = retainedConflictRequestId(verified); + if (replayRequestId != null) { + if (!candidate.requestId().equals(replayRequestId)) throw refused(); + return true; + } + AccountHostingFirstInvoicePayment invoice = candidate.invoice(); + Record current = + dsl.fetchOne( + "SELECT status, provider_subscription_id, current_receipt_request_id, " + + "lifecycle_inflight_request_id " + + "FROM subscription WHERE subscription_id = ? FOR UPDATE", + invoice.subscriptionId()); + if (current == null) throw refused(); + if (!"canceled".equals(current.get("status", String.class))) return false; + if (current.get("current_receipt_request_id", UUID.class) == null + || current.get("lifecycle_inflight_request_id", UUID.class) != null + || !invoice + .providerSubscriptionId() + .equals(current.get("provider_subscription_id", String.class))) throw refused(); + + Record cancellation = exactCommittedCancellation(invoice); + if (cancellation == null) return false; + + // The signed event has already been retained by webhook intake in the usual path. Retaining + // here as well keeps this owner safe when called directly, while an altered duplicate payload + // cannot be rebound to the first immutable inbox receipt. + StripeEventInboxRecord intake = new StripeEventInboxRepository(dsl).retainOrReplay(verified); + if (!intake.payloadSha256().equals(StripeEventInboxRecord.sha256(intake.rawPayload())) + || !sameSignedSuccessTuple(intake.rawPayload(), verified.rawPayload())) throw refused(); + + int inserted = + dsl.execute( + "INSERT INTO " + + TABLE + + " (subscription_id, request_id, lifecycle_request_id, creation_request_id, tuple_digest, " + + "invoice_id, payment_intent_id, provider_event_id, event_payload_digest, provider_subscription_id, " + + "provider_customer_id, provider_payment_method_id, provider_price_id, provider_quantity, amount, " + + "currency, livemode, observed_status, observation_read_started_at, observation_observed_at, " + + "observation_expires_at, cancellation_request_id, cancellation_receipt_digest, " + + "cancellation_row_version, cancellation_committed_transaction_id) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?::timestamptz, " + + "?::timestamptz, ?::timestamptz, ?, ?, ?, ?) ON CONFLICT DO NOTHING", + invoice.subscriptionId(), + candidate.requestId(), + candidate.lifecycleRequestId(), + invoice.creationRequestId(), + invoice.digest(), + invoice.invoiceId(), + invoice.paymentIntentId(), + intake.providerEventId(), + intake.payloadSha256(), + observed.providerSubscriptionId(), + observed.providerCustomerId(), + observed.providerPaymentMethodId(), + observed.providerPriceId(), + observed.providerQuantity(), + observed.amount(), + observed.currency(), + observed.livemode(), + observed.status(), + utcMicros(observed.readStartedAt()), + utcMicros(observed.observedAt()), + utcMicros(observed.readStartedAt().plusSeconds(20)), + cancellation.get("cancellation_request_id", UUID.class), + cancellation.get("cancellation_receipt_digest", String.class), + cancellation.get("cancellation_row_version", Long.class), + cancellation.get("cancellation_committed_transaction_id", Long.class)); + if (inserted == 0) { + requireMatchingSubscriptionConflict(invoice, candidate, cancellation, verified); + dsl.execute( + "INSERT INTO subscription_first_invoice_late_paid_event_replays " + + "(provider_event_id, subscription_id, event_payload_digest) VALUES (?, ?, ?) " + + "ON CONFLICT (provider_event_id) DO NOTHING", + intake.providerEventId(), + invoice.subscriptionId(), + intake.payloadSha256()); + } else if (inserted != 1) { + throw refused(); + } + if (!candidate.requestId().equals(retainedConflictRequestId(verified))) throw refused(); + return true; + } + + private void requireMatchingSubscriptionConflict( + AccountHostingFirstInvoicePayment invoice, + ConfirmationDispatch candidate, + Record cancellation, + VerifiedEvent verified) { + Record winner = + dsl.fetchOne( + "SELECT conflict.request_id, conflict.lifecycle_request_id, conflict.creation_request_id, " + + "conflict.tuple_digest, conflict.cancellation_request_id, " + + "conflict.cancellation_receipt_digest, conflict.cancellation_row_version, " + + "conflict.cancellation_committed_transaction_id, conflict.event_payload_digest, " + + "inbox.raw_payload, inbox.payload_sha256 FROM " + + TABLE + + " conflict JOIN stripe_event_inbox inbox USING (provider_event_id) " + + "WHERE conflict.subscription_id = ?", + invoice.subscriptionId()); + if (winner == null + || !candidate.requestId().equals(winner.get("request_id", UUID.class)) + || !candidate.lifecycleRequestId().equals(winner.get("lifecycle_request_id", UUID.class)) + || !invoice.creationRequestId().equals(winner.get("creation_request_id", UUID.class)) + || !invoice.digest().equals(winner.get("tuple_digest", String.class)) + || !Objects.equals( + cancellation.get("cancellation_request_id", UUID.class), + winner.get("cancellation_request_id", UUID.class)) + || !Objects.equals( + cancellation.get("cancellation_receipt_digest", String.class), + winner.get("cancellation_receipt_digest", String.class)) + || !Objects.equals( + cancellation.get("cancellation_row_version", Long.class), + winner.get("cancellation_row_version", Long.class)) + || !Objects.equals( + cancellation.get("cancellation_committed_transaction_id", Long.class), + winner.get("cancellation_committed_transaction_id", Long.class))) throw refused(); + byte[] retainedPayload = winner.get("raw_payload", byte[].class); + String digest = winner.get("payload_sha256", String.class); + if (retainedPayload == null + || !sha256(retainedPayload).equals(digest) + || !digest.equals(winner.get("event_payload_digest", String.class)) + || !signedSuccessTuple(decodeUtf8(retainedPayload)) + .payment() + .equals(signedSuccessTuple(verified.rawPayload()).payment())) throw refused(); + } + + private Record exactCommittedCancellation(AccountHostingFirstInvoicePayment invoice) { + return dsl.fetchOne( + "SELECT operation.request_id AS cancellation_request_id, receipt.receipt_digest AS cancellation_receipt_digest, " + + "receipt.subscription_row_version AS cancellation_row_version, " + + "receipt.committed_transaction_id AS cancellation_committed_transaction_id " + + "FROM subscription s " + + "JOIN subscription_provisioning_work work ON work.request_id = ? AND work.subscription_id = s.subscription_id " + + "JOIN subscription_first_invoices first_invoice ON first_invoice.subscription_id = s.subscription_id " + + "JOIN subscription_lifecycle_operations operation ON operation.request_id = s.current_receipt_request_id " + + "AND operation.subscription_id = s.subscription_id " + + "JOIN subscription_lifecycle_receipts receipt ON receipt.request_id = operation.request_id " + + "AND receipt.subscription_id = operation.subscription_id " + + "WHERE s.subscription_id = ? AND s.status = 'canceled' " + + "AND s.current_receipt_request_id = operation.request_id " + + "AND operation.state = 'COMMITTED' AND operation.provisioning_attempt_id IS NULL " + + "AND operation.creation_request_id = first_invoice.creation_request_id " + + "AND operation.provider_subscription_id = first_invoice.provider_subscription_id " + + "AND receipt.status = 'canceled' AND receipt.provider_subscription_id = first_invoice.provider_subscription_id " + + "AND work.phase = 'CANCELED' AND work.last_attempt_id IS NOT NULL " + + "AND convert_from(operation.request_payload, 'UTF8')::jsonb->>'schemaVersion' = ? " + + "AND receipt.committed_transaction_id <> txid_current()", + invoice.creationRequestId(), + invoice.subscriptionId(), + "account-hosting-unpaid-first-invoice-cancellation/v1"); + } + + private static void requireExactEvent(VerifiedEvent verified, Record row) { + byte[] retainedPayload = row.get("raw_payload", byte[].class); + if (!"payment_intent.succeeded".equals(verified.eventType()) + || !row.get("payload_sha256", String.class) + .equals(row.get("event_payload_digest", String.class)) + || !sha256(retainedPayload).equals(row.get("payload_sha256", String.class)) + || !verified.eventType().equals(row.get("event_type", String.class)) + || verified.eventCreatedAtEpochSeconds() + != row.get("provider_created_at_epoch_seconds", Long.class) + || !Objects.equals( + verified.providerApiVersion(), row.get("provider_api_version", String.class)) + || verified.livemode() != row.get("livemode", Boolean.class) + || !sameSignedSuccessTuple(decodeUtf8(retainedPayload), verified.rawPayload())) + throw refused(); + } + + private static boolean sameSignedSuccessTuple(String retainedPayload, String incomingPayload) { + return signedSuccessTuple(retainedPayload).equals(signedSuccessTuple(incomingPayload)); + } + + private static SignedSuccessTuple signedSuccessTuple(String payload) { + try { + JsonNode event = JSON.readTree(payload); + if (event == null || !event.isObject() || !event.path("data").isObject()) throw refused(); + JsonNode object = event.path("data").path("object"); + if (!object.isObject()) throw refused(); + JsonNode eventId = event.path("id"); + JsonNode eventType = event.path("type"); + JsonNode created = event.path("created"); + JsonNode apiVersion = event.path("api_version"); + JsonNode eventLivemode = event.path("livemode"); + JsonNode objectType = object.path("object"); + JsonNode status = object.path("status"); + JsonNode id = object.path("id"); + JsonNode customer = object.path("customer"); + JsonNode paymentMethod = object.path("payment_method"); + JsonNode amount = object.path("amount"); + JsonNode amountReceived = object.path("amount_received"); + JsonNode currency = object.path("currency"); + JsonNode livemode = object.path("livemode"); + if (!text(eventId) + || !"payment_intent.succeeded".equals(eventType.asText()) + || !created.isIntegralNumber() + || !created.canConvertToLong() + || !(apiVersion.isMissingNode() || apiVersion.isNull() || apiVersion.isTextual()) + || !eventLivemode.isBoolean() + || !"payment_intent".equals(objectType.asText()) + || !"succeeded".equals(status.asText()) + || !text(id) + || !text(customer) + || !text(paymentMethod) + || !amount.isIntegralNumber() + || !amount.canConvertToLong() + || !amountReceived.isIntegralNumber() + || !amountReceived.canConvertToLong() + || !currency.isTextual() + || currency.asText().isBlank() + || !livemode.isBoolean()) throw refused(); + return new SignedSuccessTuple( + eventId.asText(), + created.asLong(), + apiVersion.isTextual() ? apiVersion.asText() : null, + new SignedPaymentTuple( + eventLivemode.asBoolean(), + id.asText(), + customer.asText(), + paymentMethod.asText(), + amount.asLong(), + amountReceived.asLong(), + currency.asText(), + livemode.asBoolean())); + } catch (JacksonException malformed) { + throw refused(); + } + } + + private static boolean text(JsonNode value) { + return value.isTextual() && !value.asText().isBlank(); + } + + private static String decodeUtf8(byte[] payload) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + .decode(java.nio.ByteBuffer.wrap(payload)) + .toString(); + } catch (java.nio.charset.CharacterCodingException malformed) { + throw refused(); + } + } + + private static String sha256(byte[] payload) { + try { + return "sha256:" + + java.util.HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(payload)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private record SignedSuccessTuple( + String eventId, + long eventCreatedAtEpochSeconds, + String providerApiVersion, + SignedPaymentTuple payment) {} + + private record SignedPaymentTuple( + boolean eventLivemode, + String paymentIntentId, + String customerId, + String paymentMethodId, + long amount, + long amountReceived, + String currency, + boolean livemode) {} + + private static OffsetDateTime utcMicros(java.time.Instant instant) { + return OffsetDateTime.ofInstant( + Objects.requireNonNull(instant).truncatedTo(java.time.temporal.ChronoUnit.MICROS), + ZoneOffset.UTC); + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Late first-invoice conflict lookup requires an Account transaction"); + } + } + + private static void requireWritableTransaction() { + requireTransaction(); + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Late first-invoice conflict retention requires a writable Account transaction"); + } + } + + private static IllegalStateException refused() { + return new IllegalStateException("Exact late first-invoice payment conflict refused"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingFirstInvoicePaymentRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingFirstInvoicePaymentRepository.java new file mode 100644 index 0000000000..d4a04f221c --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingFirstInvoicePaymentRepository.java @@ -0,0 +1,1198 @@ +package net.firedevops.firemud.accountservice.repository; + +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.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.client.StripeHostingFirstInvoicePaymentClient.ExpiredBeforePost; +import net.firedevops.firemud.accountservice.client.StripeHostingFirstInvoicePaymentClient.Observation; +import net.firedevops.firemud.accountservice.client.StripeHostingWebhookVerifier.VerifiedEvent; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProviderDispatch; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProvisioningClaim; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.FenceRejectedException; +import net.firedevops.firemud.accountservice.service.session.AccountRecentReauthenticationEvidence; +import net.firedevops.firemud.accountservice.service.session.AccountRecentReauthenticationEvidence.BillingAuthorizationPurpose; +import net.firedevops.firemud.accountservice.service.session.AccountRecentReauthenticationPolicy; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** Held Account checkout journal, separate from immutable webhook intake and hosting authority. */ +public final class AccountHostingFirstInvoicePaymentRepository { + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + static final String AWAITING_PAYMENT_SQL = + "SELECT s.status, s.row_version, s.provider_subscription_id, w.phase " + + "FROM subscription s JOIN subscription_provisioning_work w ON w.subscription_id = s.subscription_id " + + "WHERE s.subscription_id = ? AND w.request_id = ? AND s.superseded_at IS NULL"; + private final DSLContext dsl; + private final AccountSubscriptionIntentRepository intents; + private final AccountHostingBillingPolicyRepository policies; + private final Clock clock; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Private injected transaction collaborators must preserve the Account owner transaction boundary and are never exposed.") + public AccountHostingFirstInvoicePaymentRepository( + DSLContext dsl, AccountSubscriptionIntentRepository intents, Clock clock) { + this.dsl = Objects.requireNonNull(dsl); + this.intents = Objects.requireNonNull(intents); + this.clock = Objects.requireNonNull(clock); + policies = new AccountHostingBillingPolicyRepository(dsl); + } + + /** Retains linkage while status stays non-authorizing provisioning. No confirmation is sent. */ + public AccountHostingFirstInvoicePayment retainAwaitingPayment( + ProviderDispatch dispatch, String providerId, Observation observation) { + transaction(); + if (!dispatch.readyForProviderIo()) throw refused(); + var claim = dispatch.claim(); + var creation = claim.creation(); + AccountHostingFirstInvoicePayment retained = findAwaitingPayment(claim); + if (retained != null) { + if (!retained.providerSubscriptionId().equals(providerId) + || !retained.invoiceId().equals(observation.invoiceId()) + || !retained.paymentIntentId().equals(observation.paymentIntentId())) throw refused(); + return retained; + } + var current = intents.lockForLifecycle(creation.requestId(), claim.subscriptionRowVersion()); + var policy = policies.requireCurrent(creation.planQuote()); + Instant now = now(); + if (!"provisioning".equals(current.status()) + || current.providerSubscriptionId() != null + || !now.isBefore(dispatch.claim().expiresAt()) + || !now.isBefore(observation.expiresAt()) + || now.isBefore(observation.observedAt()) + || observation.readStartedAt().isBefore(dispatch.claim().claimedAt()) + || Duration.between(observation.readStartedAt(), now).compareTo(Duration.ofSeconds(20)) >= 0 + || !providerId.equals(observation.providerSubscriptionId()) + || !creation.providerCustomerId().equals(observation.providerCustomerId()) + || !dispatch.providerPaymentMethodId().equals(observation.providerPaymentMethodId()) + || dispatch.expectedBinding(providerId).livemode() != observation.livemode() + || !creation.planQuote().providerPriceId().equals(observation.providerPriceId()) + || creation.planQuote().providerQuantity() != observation.providerQuantity() + || policy.amount() != observation.amount() + || !policy.currency().equals(observation.currency())) throw refused(); + var invoice = + new AccountHostingFirstInvoicePayment( + creation.subscriptionId(), + creation.requestId(), + creation.tenantId(), + creation.owner().accountUuid(), + creation.paymentInstrumentId(), + creation.reservedInstrumentVersion(), + providerId, + creation.providerCustomerId(), + dispatch.providerPaymentMethodId(), + observation.invoiceId(), + observation.paymentIntentId(), + observation.amount(), + observation.currency(), + creation.planQuote().digest(), + observation.providerPriceId(), + observation.providerQuantity(), + policy.version(), + policy.digest(), + dispatch.expectedBinding(providerId).livemode(), + now, + observation.expiresAt()); + dsl.execute( + "INSERT INTO subscription_provider_history (provider_subscription_id, subscription_id, operation_kind, request_id, " + + "provider_operation_id, role, effective_at, evidence_digest) VALUES (?, ?, 'SUBSCRIPTION_PROVISIONING', ?, ?, 'canonical', ?::timestamptz, ?)", + providerId, + creation.subscriptionId(), + creation.requestId(), + creation.subscriptionProvisioningRequestId(), + utc(now), + invoice.digest()); + dsl.execute( + "INSERT INTO subscription_first_invoices (subscription_id, creation_request_id, tenant_id, account_uuid, payment_instrument_id, " + + "instrument_version, provider_subscription_id, provider_customer_id, provider_payment_method_id, invoice_id, payment_intent_id, amount, currency, " + + "quote_digest, provider_price_id, provider_quantity, billing_policy_version, billing_policy_digest, livemode, captured_at, expires_at, tuple_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?::timestamptz, ?::timestamptz, ?)", + invoice.subscriptionId(), + invoice.creationRequestId(), + invoice.tenantId(), + invoice.ownerAccountId(), + invoice.paymentInstrumentId(), + invoice.instrumentVersion(), + invoice.providerSubscriptionId(), + invoice.providerCustomerId(), + invoice.providerPaymentMethodId(), + invoice.invoiceId(), + invoice.paymentIntentId(), + invoice.amount(), + invoice.currency(), + invoice.quoteDigest(), + invoice.providerPriceId(), + invoice.providerQuantity(), + invoice.billingPolicyVersion(), + invoice.billingPolicyDigest(), + invoice.livemode(), + utc(invoice.capturedAt()), + utc(invoice.expiresAt()), + invoice.digest()); + if (dsl.execute( + "UPDATE subscription SET provider_subscription_id = ?, row_version = row_version + 1 WHERE subscription_id = ? " + + "AND row_version = ? AND provider_subscription_id IS NULL AND status = 'provisioning' AND superseded_at IS NULL", + providerId, + creation.subscriptionId(), + current.rowVersion()) + != 1) throw refused(); + if (dsl.execute( + "UPDATE subscription_provisioning_work SET phase = 'AWAITING_PAYMENT', row_version = row_version + 1 " + + "WHERE request_id = ? AND phase = 'CLAIMED' AND last_attempt_id = ?", + creation.requestId(), + dispatch.claim().attemptId()) + != 1) throw refused(); + return Objects.requireNonNull(find(invoice.subscriptionId())); + } + + /** + * Read-only recovery of the exact invoice retained by this original provisioning claim. A + * committed AWAITING_PAYMENT work row cannot be claimed or dispatched again; recovery only + * returns its immutable invoice after rechecking the original claim, dispatch, owner and + * reservation fences. + */ + public AccountHostingFirstInvoicePayment findAwaitingPayment(ProvisioningClaim claim) { + transaction(); + Objects.requireNonNull(claim, "Original retained provisioning claim is required"); + var creation = claim.creation(); + var invoice = find(creation.subscriptionId()); + if (invoice == null) return null; + if (!creation.equals(intents.findCreation(creation.requestId()).orElse(null))) + throw awaitingPaymentRefused(); + + Record attempt = + dsl.fetchOne( + "SELECT * FROM subscription_provisioning_attempts WHERE attempt_id = ?", + claim.attemptId()); + if (attempt == null + || !creation.requestId().equals(attempt.get("request_id", UUID.class)) + || !creation.subscriptionId().equals(attempt.get("subscription_id", UUID.class)) + || claim.attemptNumber() != attempt.get("attempt_number", Integer.class) + || claim.subscriptionRowVersion() != attempt.get("claimed_row_version", Long.class) + || claim.subscriptionRowVersion() - 1L != attempt.get("expected_row_version", Long.class) + || !claim.claimedAt().equals(instant(attempt, "claimed_at")) + || !claim.expiresAt().equals(instant(attempt, "expires_at"))) + throw awaitingPaymentRefused(); + + var current = + intents.lockForLifecycle( + creation.requestId(), Math.addExact(claim.subscriptionRowVersion(), 1L)); + if (!"provisioning".equals(current.status()) + || current.supersededAt() != null + || !creation.subscriptionId().equals(current.subscriptionId()) + || !creation.requestId().equals(current.creationRequestId()) + || !invoice.providerSubscriptionId().equals(current.providerSubscriptionId()) + || !invoice.subscriptionId().equals(creation.subscriptionId()) + || !invoice.creationRequestId().equals(creation.requestId()) + || !invoice.tenantId().equals(creation.tenantId()) + || !invoice.ownerAccountId().equals(creation.owner().accountUuid()) + || !invoice.paymentInstrumentId().equals(creation.paymentInstrumentId()) + || invoice.instrumentVersion() != creation.reservedInstrumentVersion() + || !invoice.providerCustomerId().equals(creation.providerCustomerId()) + || !invoice.quoteDigest().equals(creation.planQuote().digest()) + || !invoice.providerPriceId().equals(creation.planQuote().providerPriceId()) + || invoice.providerQuantity() != creation.planQuote().providerQuantity()) + throw awaitingPaymentRefused(); + + Record work = + dsl.fetchOne( + "SELECT * FROM subscription_provisioning_work WHERE request_id = ?", + creation.requestId()); + if (work == null + || !creation.subscriptionId().equals(work.get("subscription_id", UUID.class)) + || !"AWAITING_PAYMENT".equals(work.get("phase", String.class)) + || !claim.attemptId().equals(work.get("last_attempt_id", UUID.class)) + || claim.subscriptionRowVersion() != work.get("subscription_row_version", Long.class)) + throw awaitingPaymentRefused(); + + Record dispatch = + dsl.fetchOne( + "SELECT * FROM subscription_provider_dispatch_claim WHERE creation_request_id = ?", + creation.requestId()); + if (dispatch == null + || !creation.subscriptionId().equals(dispatch.get("subscription_id", UUID.class)) + || !creation + .subscriptionProvisioningRequestId() + .equals(dispatch.get("provider_operation_id", UUID.class))) + throw awaitingPaymentRefused(); + + Record history = + dsl.fetchOne( + "SELECT * FROM subscription_provider_history WHERE provider_subscription_id = ?", + invoice.providerSubscriptionId()); + if (history == null + || !creation.subscriptionId().equals(history.get("subscription_id", UUID.class)) + || !"SUBSCRIPTION_PROVISIONING".equals(history.get("operation_kind", String.class)) + || !creation.requestId().equals(history.get("request_id", UUID.class)) + || !creation + .subscriptionProvisioningRequestId() + .equals(history.get("provider_operation_id", UUID.class)) + || !"canonical".equals(history.get("role", String.class)) + || !invoice.digest().equals(history.get("evidence_digest", String.class))) + throw awaitingPaymentRefused(); + return invoice; + } + + public AccountHostingFirstInvoicePayment requireOwner(UUID subscriptionId, UUID actor) { + transaction(); + var invoice = find(subscriptionId); + if (invoice == null) throw refused(); + var row = + dsl.fetchOne( + "SELECT row_version FROM subscription WHERE subscription_id = ? AND account_uuid = ? AND superseded_at IS NULL", + subscriptionId, + actor); + if (!invoice.ownerAccountId().equals(actor) || row == null) throw refused(); + intents.lockForLifecycle(invoice.creationRequestId(), row.get("row_version", Long.class)); + return invoice; + } + + public long ownerRowVersion(UUID subscriptionId, UUID actor) { + requireOwner(subscriptionId, actor); + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT row_version FROM subscription WHERE subscription_id = ? AND superseded_at IS NULL", + subscriptionId)) + .get("row_version", Long.class); + } + + public boolean hasCanceledCheckout(AccountHostingFirstInvoicePayment invoice) { + transaction(); + return dsl.fetchOne( + "SELECT 1 FROM subscription WHERE subscription_id = ?" + + " AND account_uuid = ? AND status = 'canceled' AND superseded_at IS NULL", + invoice.subscriptionId(), + invoice.ownerAccountId()) + != null; + } + + public UUID confirmationRequestId(UUID subscriptionId) { + transaction(); + Record row = + dsl.fetchOne( + "SELECT request_id FROM subscription_first_invoice_confirmations WHERE subscription_id = ?", + subscriptionId); + return row == null ? null : row.get("request_id", UUID.class); + } + + public UUID openingRequestId(AccountHostingFirstInvoicePayment invoice, long rowVersion) { + transaction(); + Record fence = operationFence(invoice.subscriptionId(), false); + if (fence == null) return null; + if (!invoice.ownerAccountId().equals(fence.get("account_uuid", UUID.class)) + || !invoice.digest().equals(fence.get("tuple_digest", String.class)) + || rowVersion != fence.get("expected_row_version", Long.class) + || !invoice.expiresAt().equals(instant(fence, "invoice_expires_at"))) throw refused(); + return fence.get("request_id", UUID.class); + } + + public long authorizationVersion(UUID subscriptionId) { + transaction(); + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT COALESCE(MAX(authorization_version), 0) AS version FROM subscription_first_invoice_authorizations WHERE subscription_id = ?", + subscriptionId)) + .get("version", Long.class); + } + + /** + * Stores the original reauthentication as a durable, exact operation fence, or validates a + * separately bound renewal attempt against that fence or an already retained confirmation. The + * caller holds the current authenticated Account and exact reauthentication evidence locks. + */ + public void bindReauthenticationContext( + UUID actor, + UUID subscriptionId, + AccountRecentReauthenticationEvidence.BillingContext context, + AccountRecentReauthenticationEvidence evidence) { + transaction(); + Objects.requireNonNull(context); + Objects.requireNonNull(evidence); + var invoice = requireOwner(subscriptionId, actor); + requireCheckoutCurrent(invoice); + requireAwaitingPayment(invoice, context.expectedRowVersion()); + requireContext(invoice, actor, context, evidence); + long currentAuthorizationVersion = authorizationVersion(subscriptionId); + Record original = + dsl.fetchOne( + "SELECT * FROM subscription_first_invoice_confirmations WHERE subscription_id = ? FOR UPDATE", + subscriptionId); + Record fence = operationFence(subscriptionId, true); + if (context.authorizationPurpose() == BillingAuthorizationPurpose.INITIAL_CONFIRMATION) { + if (context.expectedAuthorizationVersion() != 0L) throw refused(); + if (fence == null) { + if (original != null || currentAuthorizationVersion != 0L) throw refused(); + dsl.execute( + "INSERT INTO subscription_first_invoice_operation_fences (subscription_id, request_id, account_uuid, tuple_digest, " + + "expected_row_version, invoice_expires_at, reauthentication_evidence_id, binding_digest) " + + "VALUES (?, ?, ?, ?, ?, ?::timestamptz, ?, ?)", + subscriptionId, + context.originalRequestId(), + actor, + invoice.digest(), + context.expectedRowVersion(), + utc(context.invoiceExpiresAt()), + evidence.evidenceId(), + context.digest()); + fence = operationFence(subscriptionId, true); + } + requireFenceMatches(fence, invoice, actor, context, evidence.evidenceId()); + return; + } + + if (context.authorizationPurpose() == BillingAuthorizationPurpose.PRE_ROW_RENEWAL) { + requireFenceMatches(fence, invoice, actor, context, null); + if (context.expectedAuthorizationVersion() != 0L) throw refused(); + if (original == null) { + if (currentAuthorizationVersion != 0L + || dsl.fetchOne( + "SELECT 1 FROM subscription_first_invoice_dispatches WHERE subscription_id = ? LIMIT 1", + subscriptionId) + != null + || dsl.fetchOne( + "SELECT 1 FROM subscription_first_invoice_command_claims WHERE subscription_id = ? LIMIT 1", + subscriptionId) + != null) throw refused(); + } else { + Record winner = authorization(context.authorizationRequestId()); + if (!context.originalRequestId().equals(original.get("request_id", UUID.class)) + || winner == null + || winner.get("authorization_version", Long.class) != 1L + || !evidence + .evidenceId() + .equals(winner.get("reauthentication_evidence_id", UUID.class))) throw refused(); + } + return; + } + if (original == null + || !context.originalRequestId().equals(original.get("request_id", UUID.class)) + || !context.tupleDigest().equals(original.get("tuple_digest", String.class)) + || context.expectedRowVersion() != original.get("expected_row_version", Long.class) + || !actor.equals(original.get("account_uuid", UUID.class))) throw refused(); + if (fence != null) requireFenceMatches(fence, invoice, actor, context, null); + Record priorAttempt = authorization(context.authorizationRequestId()); + if (priorAttempt != null) { + if (priorAttempt.get("authorization_version", Long.class) + != context.expectedAuthorizationVersion() + 1L + || !evidence + .evidenceId() + .equals(priorAttempt.get("reauthentication_evidence_id", UUID.class))) + throw refused(); + } else if (currentAuthorizationVersion != context.expectedAuthorizationVersion()) { + throw refused(); + } + } + + public boolean hasCompleted(UUID subscriptionId) { + transaction(); + Record row = + dsl.fetchOne( + "SELECT lifecycle_request_id FROM subscription_first_invoice_completions WHERE subscription_id = ?", + subscriptionId); + return row != null && completed(subscriptionId, row.get("lifecycle_request_id", UUID.class)); + } + + /** + * First dispatch permission is durable consent plus real purpose-bound consumed reauthentication. + */ + public ConfirmationDispatch prepareConfirmation( + UUID actor, + UUID requestId, + UUID subscriptionId, + long expectedVersion, + String acceptedTupleDigest, + AccountRecentReauthenticationEvidence reauthentication) { + transaction(); + AccountBillingCustomerRecord.requireUuid(requestId); + var invoice = requireOwner(subscriptionId, actor); + requireCheckoutCurrent(invoice); + requireAwaitingPayment(invoice, expectedVersion); + if (!invoice.digest().equals(acceptedTupleDigest) + || !AccountRecentReauthenticationPolicy.BILLING_PURPOSE.equals(reauthentication.purpose()) + || !requestId.equals(reauthentication.creationOperationId()) + || !actor.equals(reauthentication.accountId())) throw refused(); + Record fence = operationFence(subscriptionId, true); + Record existing = + dsl.fetchOne( + "SELECT * FROM subscription_first_invoice_confirmations WHERE subscription_id = ? FOR UPDATE", + subscriptionId); + if (existing != null) { + if (!requestId.equals(existing.get("request_id", UUID.class)) + || !acceptedTupleDigest.equals(existing.get("tuple_digest", String.class)) + || !reauthentication + .evidenceId() + .equals(existing.get("reauthentication_evidence_id", UUID.class)) + || expectedVersion != existing.get("expected_row_version", Long.class)) throw refused(); + return authorizedDispatch(existing, authorization(requestId), invoice, false, false); + } + var context = reauthentication.billingContext(); + if (context == null + || context.authorizationPurpose() != BillingAuthorizationPurpose.INITIAL_CONFIRMATION + || !requestId.equals(context.originalRequestId()) + || context.expectedAuthorizationVersion() != 0L + || context.expectedRowVersion() != expectedVersion + || !context.tupleDigest().equals(acceptedTupleDigest)) throw refused(); + requireContext(invoice, actor, context, reauthentication); + requireFenceMatches(fence, invoice, actor, context, reauthentication.evidenceId()); + if (authorizationVersion(subscriptionId) != 0L) throw refused(); + intents.lockForLifecycle(invoice.creationRequestId(), expectedVersion); + Instant validUntil = + earlier( + invoice.expiresAt(), + reauthentication + .issuedAt() + .plusSeconds( + reauthentication.recentAgeSeconds() - reauthentication.maxClockSkewSeconds())); + if (!now().isBefore(validUntil)) throw refused(); + dsl.execute( + "INSERT INTO subscription_first_invoice_confirmations (request_id, subscription_id, account_uuid, tuple_digest, expected_row_version, " + + "reauthentication_evidence_id, provider_idempotency_id, lifecycle_request_id, audit_event_id, consented_at, valid_until) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?::timestamptz, ?::timestamptz)", + requestId, + subscriptionId, + actor, + invoice.digest(), + expectedVersion, + reauthentication.evidenceId(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + utc(now()), + utc(validUntil)); + dsl.execute( + "INSERT INTO subscription_first_invoice_dispatches (request_id, subscription_id, authorized_at) VALUES (?, ?, ?::timestamptz)", + requestId, + subscriptionId, + utc(now())); + Record original = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM subscription_first_invoice_confirmations WHERE request_id = ?", + requestId)); + retainAuthorization(original, invoice, requestId, 1, reauthentication, validUntil); + return authorizedDispatch(original, authorization(requestId), invoice, false, true); + } + + /** Fresh consent renews only authorization. It never replaces the immutable payment operation. */ + public ConfirmationDispatch renewAuthorization( + UUID actor, + UUID requestId, + UUID authorizationRequestId, + UUID subscriptionId, + long expectedVersion, + long expectedAuthorizationVersion, + String acceptedTupleDigest, + AccountRecentReauthenticationEvidence reauthentication) { + transaction(); + AccountBillingCustomerRecord.requireUuid(requestId); + AccountBillingCustomerRecord.requireUuid(authorizationRequestId); + var invoice = requireOwner(subscriptionId, actor); + requireCheckoutCurrent(invoice); + requireAwaitingPayment(invoice, expectedVersion); + Record fence = operationFence(subscriptionId, true); + Record original = + dsl.fetchOne( + "SELECT * FROM subscription_first_invoice_confirmations WHERE subscription_id = ? FOR UPDATE", + subscriptionId); + if (requestId.equals(authorizationRequestId) + || !invoice.digest().equals(acceptedTupleDigest) + || !actor.equals(reauthentication.accountId()) + || !AccountRecentReauthenticationPolicy.BILLING_PURPOSE.equals(reauthentication.purpose()) + || !authorizationRequestId.equals(reauthentication.creationOperationId())) throw refused(); + Record existing = authorization(authorizationRequestId); + if (existing != null) { + if (!requestId.equals(existing.get("request_id", UUID.class)) + || !subscriptionId.equals(existing.get("subscription_id", UUID.class)) + || !reauthentication + .evidenceId() + .equals(existing.get("reauthentication_evidence_id", UUID.class)) + || existing.get("authorization_version", Long.class) != expectedAuthorizationVersion + 1) + throw refused(); + if (original == null + || !requestId.equals(original.get("request_id", UUID.class)) + || !acceptedTupleDigest.equals(original.get("tuple_digest", String.class)) + || expectedVersion != original.get("expected_row_version", Long.class)) throw refused(); + var context = reauthentication.billingContext(); + if (context != null) { + requireContext(invoice, actor, context, reauthentication); + if (!requestId.equals(context.originalRequestId()) + || !authorizationRequestId.equals(context.authorizationRequestId()) + || context.expectedAuthorizationVersion() != expectedAuthorizationVersion + || context.expectedRowVersion() != expectedVersion + || !context.tupleDigest().equals(acceptedTupleDigest) + || (expectedAuthorizationVersion == 0L + && context.authorizationPurpose() != BillingAuthorizationPurpose.PRE_ROW_RENEWAL) + || (expectedAuthorizationVersion > 0L + && context.authorizationPurpose() != BillingAuthorizationPurpose.FOLLOWUP_RENEWAL)) + throw refused(); + if (context.authorizationPurpose() == BillingAuthorizationPurpose.PRE_ROW_RENEWAL + || fence != null) { + requireFenceMatches(fence, invoice, actor, context, null); + } + } else if (existing.get("authorization_version", Long.class) <= 1L) { + throw refused(); + } + return authorizedDispatch(original, existing, invoice, false, false); + } + if (expectedAuthorizationVersion < 0L + || authorizationVersion(subscriptionId) != expectedAuthorizationVersion) throw refused(); + var context = reauthentication.billingContext(); + if (context == null) throw refused(); + requireContext(invoice, actor, context, reauthentication); + if (!requestId.equals(context.originalRequestId()) + || !authorizationRequestId.equals(context.authorizationRequestId()) + || context.expectedAuthorizationVersion() != expectedAuthorizationVersion + || context.expectedRowVersion() != expectedVersion + || !context.tupleDigest().equals(acceptedTupleDigest)) throw refused(); + Instant validUntil = + earlier( + invoice.expiresAt(), + reauthentication + .issuedAt() + .plusSeconds( + reauthentication.recentAgeSeconds() - reauthentication.maxClockSkewSeconds())); + if (!now().isBefore(validUntil)) throw refused(); + + if (original == null) { + if (expectedAuthorizationVersion != 0L + || context.authorizationPurpose() != BillingAuthorizationPurpose.PRE_ROW_RENEWAL) { + throw refused(); + } + requireFenceMatches(fence, invoice, actor, context, null); + dsl.execute( + "INSERT INTO subscription_first_invoice_confirmations (request_id, subscription_id, account_uuid, tuple_digest, expected_row_version, " + + "reauthentication_evidence_id, provider_idempotency_id, lifecycle_request_id, audit_event_id, consented_at, valid_until) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?::timestamptz, ?::timestamptz)", + requestId, + subscriptionId, + actor, + invoice.digest(), + expectedVersion, + reauthentication.evidenceId(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + utc(now()), + utc(validUntil)); + dsl.execute( + "INSERT INTO subscription_first_invoice_dispatches (request_id, subscription_id, authorized_at) VALUES (?, ?, ?::timestamptz)", + requestId, + subscriptionId, + utc(now())); + original = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM subscription_first_invoice_confirmations WHERE request_id = ?", + requestId)); + } else { + if (!requestId.equals(original.get("request_id", UUID.class)) + || !acceptedTupleDigest.equals(original.get("tuple_digest", String.class)) + || expectedVersion != original.get("expected_row_version", Long.class) + || !actor.equals(original.get("account_uuid", UUID.class)) + || expectedAuthorizationVersion < 1L + || context.authorizationPurpose() != BillingAuthorizationPurpose.FOLLOWUP_RENEWAL) + throw refused(); + if (fence != null) requireFenceMatches(fence, invoice, actor, context, null); + } + retainAuthorization( + original, + invoice, + authorizationRequestId, + Math.addExact(expectedAuthorizationVersion, 1), + reauthentication, + validUntil); + return authorizedDispatch( + original, authorization(authorizationRequestId), invoice, false, true); + } + + private Record authorization(UUID authorizationRequestId) { + return dsl.fetchOne( + "SELECT * FROM subscription_first_invoice_authorizations WHERE authorization_request_id = ?", + authorizationRequestId); + } + + private Record operationFence(UUID subscriptionId, boolean lock) { + return dsl.fetchOne( + "SELECT * FROM subscription_first_invoice_operation_fences WHERE subscription_id = ?" + + (lock ? " FOR UPDATE" : ""), + subscriptionId); + } + + private static void requireContext( + AccountHostingFirstInvoicePayment invoice, + UUID actor, + AccountRecentReauthenticationEvidence.BillingContext context, + AccountRecentReauthenticationEvidence evidence) { + if (!actor.equals(context.accountId()) + || !invoice.subscriptionId().equals(context.subscriptionId()) + || !invoice.digest().equals(context.tupleDigest()) + || !invoice.expiresAt().equals(context.invoiceExpiresAt()) + || !AccountRecentReauthenticationPolicy.BILLING_PURPOSE.equals(evidence.purpose()) + || !context.authorizationRequestId().equals(evidence.creationOperationId()) + || !context.equals(evidence.billingContext())) throw refused(); + } + + private static void requireFenceMatches( + Record fence, + AccountHostingFirstInvoicePayment invoice, + UUID actor, + AccountRecentReauthenticationEvidence.BillingContext context, + UUID expectedEvidenceId) { + if (fence == null + || !invoice.subscriptionId().equals(fence.get("subscription_id", UUID.class)) + || !context.originalRequestId().equals(fence.get("request_id", UUID.class)) + || !actor.equals(fence.get("account_uuid", UUID.class)) + || !invoice.digest().equals(fence.get("tuple_digest", String.class)) + || context.expectedRowVersion() != fence.get("expected_row_version", Long.class) + || !context.invoiceExpiresAt().equals(instant(fence, "invoice_expires_at")) + || (expectedEvidenceId != null + && !context.digest().equals(fence.get("binding_digest", String.class))) + || (expectedEvidenceId != null + && !expectedEvidenceId.equals(fence.get("reauthentication_evidence_id", UUID.class)))) + throw refused(); + } + + private void retainAuthorization( + Record original, + AccountHostingFirstInvoicePayment invoice, + UUID authorizationRequestId, + long version, + AccountRecentReauthenticationEvidence evidence, + Instant validUntil) { + dsl.execute( + "INSERT INTO subscription_first_invoice_authorizations (authorization_request_id, request_id, subscription_id, authorization_version, reauthentication_evidence_id, consented_at, valid_until) VALUES (?, ?, ?, ?, ?, ?::timestamptz, ?::timestamptz)", + authorizationRequestId, + original.get("request_id"), + invoice.subscriptionId(), + version, + evidence.evidenceId(), + utc(now()), + utc(validUntil)); + } + + /** A separate transaction and current owner/policy readback precede any provider confirmation. */ + public ConfirmationDispatch readDispatch(ConfirmationDispatch prepared, UUID actor) { + var current = requireCurrentDispatch(prepared, actor); + return authorizedDispatch( + current.confirmation(), + current.authorization(), + current.invoice(), + true, + prepared.takeInitialCommandPermission()); + } + + /** + * Rechecks a secret-bearing provider handoff under the current Account and owner locks. This path + * is read-only: it neither consumes the one-shot command permission nor opens a claim. + */ + public void validateHandoffAuthorization( + ConfirmationDispatch dispatch, UUID actor, AccountRecentReauthenticationEvidence evidence) { + Objects.requireNonNull(evidence); + var current = requireCurrentDispatch(dispatch, actor); + var context = evidence.billingContext(); + if (context == null) throw refused(); + requireContext(current.invoice(), actor, context, evidence); + long expectedAuthorizationVersion = dispatch.authorizationVersion() - 1; + BillingAuthorizationPurpose expectedPurpose = + dispatch.authorizationVersion() == 1L + ? dispatch.requestId().equals(dispatch.authorizationRequestId()) + ? BillingAuthorizationPurpose.INITIAL_CONFIRMATION + : BillingAuthorizationPurpose.PRE_ROW_RENEWAL + : BillingAuthorizationPurpose.FOLLOWUP_RENEWAL; + if (!dispatch.independentlyRead() + || !dispatch.invoice().equals(current.invoice()) + || dispatch.expectedRowVersion() + != current.confirmation().get("expected_row_version", Long.class) + || dispatch.authorizationVersion() + != current.authorization().get("authorization_version", Long.class) + || !dispatch + .reauthenticationEvidenceId() + .equals(current.authorization().get("reauthentication_evidence_id", UUID.class)) + || !dispatch.validUntil().equals(instant(current.authorization(), "valid_until")) + || !evidence.evidenceId().equals(dispatch.reauthenticationEvidenceId()) + || !dispatch.requestId().equals(context.originalRequestId()) + || dispatch.expectedRowVersion() != context.expectedRowVersion() + || !dispatch.authorizationRequestId().equals(context.authorizationRequestId()) + || expectedAuthorizationVersion != context.expectedAuthorizationVersion() + || context.authorizationPurpose() != expectedPurpose) { + throw refused(); + } + } + + private CurrentDispatch requireCurrentDispatch(ConfirmationDispatch prepared, UUID actor) { + transaction(); + UUID requestId = prepared.requestId(); + Record row = + dsl.fetchOne( + "SELECT * FROM subscription_first_invoice_confirmations WHERE request_id = ?", + requestId); + if (row == null) throw refused(); + var invoice = requireOwner(row.get("subscription_id", UUID.class), actor); + requireCheckoutCurrent(invoice); + requireAwaitingPayment(invoice, row.get("expected_row_version", Long.class)); + Record authorization = authorization(prepared.authorizationRequestId()); + if (authorization == null) throw refused(); + Instant validUntil = instant(authorization, "valid_until"); + if (!actor.equals(row.get("account_uuid", UUID.class)) + || !requestId.equals(authorization.get("request_id", UUID.class)) + || authorization.get("authorization_version", Long.class) + != authorizationVersion(invoice.subscriptionId()) + || authorization.get("created_transaction_id", Long.class) == transactionId() + || !invoice.digest().equals(row.get("tuple_digest", String.class)) + || !now().isBefore(validUntil)) throw refused(); + return new CurrentDispatch(row, authorization, invoice); + } + + /** + * Commits before provider POST. Any lost response, including a crash after this claim, fences all + * later POSTs permanently; provider observation/signed completion must resolve that outcome. + */ + public CommandClaim claimCommand(ConfirmationDispatch dispatch, UUID actor) { + transaction(); + var invoice = requireOwner(dispatch.invoice().subscriptionId(), actor); + requireCheckoutCurrent(invoice); + requireAwaitingPayment(invoice, dispatch.expectedRowVersion()); + intents.lockForFirstInvoiceCommand(invoice.creationRequestId(), dispatch.expectedRowVersion()); + Record auth = Objects.requireNonNull(authorization(dispatch.authorizationRequestId())); + if (!dispatch.independentlyRead() + || !dispatch.requestId().equals(auth.get("request_id", UUID.class)) + || !dispatch + .reauthenticationEvidenceId() + .equals(auth.get("reauthentication_evidence_id", UUID.class)) + || dispatch.authorizationVersion() != auth.get("authorization_version", Long.class) + || dispatch.authorizationVersion() != authorizationVersion(invoice.subscriptionId()) + || !now().isBefore(instant(auth, "valid_until"))) throw refused(); + int inserted = + dsl.execute( + "INSERT INTO subscription_first_invoice_command_claims (request_id, subscription_id, authorization_request_id, claimed_at) VALUES (?, ?, ?, ?::timestamptz) ON CONFLICT (request_id) DO NOTHING", + dispatch.requestId(), + invoice.subscriptionId(), + dispatch.authorizationRequestId(), + utc(now())); + return inserted == 1 ? new CommandClaim(dispatch) : null; + } + + /** Retains the exact no-send observation without altering the original command claim. */ + public void retainExpiredBeforePost(ExpiredBeforePost observation) { + transaction(); + Instant observedAt = observation.observedAt().truncatedTo(ChronoUnit.MICROS); + dsl.execute( + "INSERT INTO subscription_first_invoice_expired_before_post (request_id, observed_at) " + + "VALUES (?, ?::timestamptz) ON CONFLICT (request_id) DO NOTHING", + observation.requestId(), + utc(observedAt)); + Record retained = + dsl.fetchOne( + "SELECT observed_at FROM subscription_first_invoice_expired_before_post WHERE request_id = ?", + observation.requestId()); + if (retained == null || !observedAt.equals(instant(retained, "observed_at"))) throw refused(); + } + + void requireAwaitingPayment(AccountHostingFirstInvoicePayment invoice, long expectedVersion) { + transaction(); + Record row = + dsl.fetchOne(AWAITING_PAYMENT_SQL, invoice.subscriptionId(), invoice.creationRequestId()); + if (row == null + || !"provisioning".equals(row.get("status", String.class)) + || !"AWAITING_PAYMENT".equals(row.get("phase", String.class)) + || !Long.valueOf(expectedVersion).equals(row.get("row_version", Long.class)) + || !invoice + .providerSubscriptionId() + .equals(row.get("provider_subscription_id", String.class))) throw refused(); + } + + private void requireCheckoutCurrent(AccountHostingFirstInvoicePayment invoice) { + policies.requireUnchanged( + invoice, intents.findCreation(invoice.creationRequestId()).orElseThrow().planQuote()); + if (!now().isBefore(invoice.expiresAt())) throw refused(); + } + + /** Reads the immutable captured invoice and its original consent in one SQL statement. */ + public SignedClassification classifySignedEvent(VerifiedEvent verified) { + transaction(); + if (!"payment_intent.succeeded".equals(verified.eventType())) + return new SignedClassification(null, false); + String intent = + JSON.readTree(verified.rawPayload()).path("data").path("object").path("id").asText(); + Record row = + dsl.fetchOne( + "SELECT c.*, i.subscription_id AS original_subscription_id, " + + "(s.status = 'canceled' OR " + + "(s.status = 'provisioning' AND EXISTS (SELECT 1 FROM subscription_provisioning_work w " + + "WHERE w.subscription_id = i.subscription_id AND w.request_id = i.creation_request_id " + + "AND w.phase = 'AWAITING_PAYMENT'))) AS original_checkout_held " + + "FROM subscription_first_invoices i JOIN subscription s USING (subscription_id) " + + "LEFT JOIN subscription_first_invoice_confirmations c USING (subscription_id) " + + "WHERE i.payment_intent_id = ?", + intent); + if (row == null) return new SignedClassification(null, false); + var invoice = Objects.requireNonNull(find(row.get("original_subscription_id", UUID.class))); + var consent = row.get("consented_at", java.time.OffsetDateTime.class); + if (consent != null + && verified.eventCreatedAtEpochSeconds() >= consent.toInstant().getEpochSecond()) { + requireSignedTuple(verified, invoice); + return new SignedClassification(dispatch(row, invoice, false, false), false); + } + if (!Boolean.TRUE.equals(row.get("original_checkout_held", Boolean.class))) + return new SignedClassification(null, false); + // Local capture time does not change the identity of an already-existing provider intent. + requireSignedTuple(verified, invoice); + return new SignedClassification(null, true); + } + + public record SignedClassification(ConfirmationDispatch candidate, boolean reconciliationOnly) {} + + public UUID retainedSignedConflictRequestId(VerifiedEvent verified) { + transaction(); + return new AccountHostingFirstInvoicePaymentConflictRepository(dsl) + .retainedConflictRequestId(verified); + } + + public boolean completed(UUID subscriptionId, UUID lifecycleRequestId) { + transaction(); + Record row = + dsl.fetchOne( + "SELECT c.receipt_digest AS completed_digest, r.receipt_digest AS actual_digest, r.receipt_payload, " + + "c.tuple_digest, a.payload AS audit_payload, a.payload_digest AS audit_digest " + + "FROM subscription_first_invoice_completions c JOIN subscription_lifecycle_receipts r " + + "ON r.request_id = c.lifecycle_request_id JOIN account_audit_outbox a ON a.audit_event_id = c.audit_event_id " + + "WHERE c.subscription_id = ? AND c.lifecycle_request_id = ?", + subscriptionId, + lifecycleRequestId); + if (row == null) return false; + if (!row.get("completed_digest", String.class).equals(row.get("actual_digest", String.class)) + || !AccountHostingSubscriptionLifecycleEvidence.digest( + row.get("receipt_payload", byte[].class)) + .equals(row.get("actual_digest", String.class))) throw refused(); + String auditPayload = row.get("audit_payload", String.class); + JsonNode audit = JSON.readTree(auditPayload); + if (!net.firedevops.firemud.accountservice.dto.AccountAuditDigest.ofPayload(auditPayload) + .equals(row.get("audit_digest", String.class)) + || !row.get("tuple_digest", String.class).equals(audit.path("tupleDigest").asText()) + || !row.get("actual_digest", String.class).equals(audit.path("receiptDigest").asText())) + throw refused(); + return true; + } + + /** The verified payload, not a browser result or invoice.paid, establishes success evidence. */ + public ConfirmationDispatch retainSignedSuccess(VerifiedEvent verified, Observation observed) { + var retained = retainSignedOutcome(verified, observed); + if (retained.latePaidConflict()) throw refused(); + return retained.dispatch(); + } + + /** Separately retains a verified paid conflict without changing a committed cancellation. */ + public SignedOutcome retainSignedOutcome(VerifiedEvent verified, Observation observed) { + transaction(); + if (!"payment_intent.succeeded".equals(verified.eventType())) throw refused(); + JsonNode object = JSON.readTree(verified.rawPayload()).path("data").path("object"); + Record subscription = + dsl.fetchOne( + "SELECT s.subscription_id FROM subscription s JOIN subscription_first_invoices i USING (subscription_id) " + + "WHERE i.payment_intent_id = ? FOR UPDATE OF s", + object.path("id").asText()); + if (subscription == null) throw refused(); + UUID subscriptionId = subscription.get("subscription_id", UUID.class); + Record row = + dsl.fetchOne( + "SELECT * FROM subscription_first_invoice_confirmations WHERE subscription_id = ? FOR UPDATE", + subscriptionId); + if (row == null) throw refused(); + var invoice = Objects.requireNonNull(find(subscriptionId)); + requireSignedTuple(verified, invoice); + if (verified.eventCreatedAtEpochSeconds() < instant(row, "consented_at").getEpochSecond()) + throw refused(); + if (!"succeeded".equals(observed.status()) + || !invoice.invoiceId().equals(observed.invoiceId()) + || !invoice.paymentIntentId().equals(observed.paymentIntentId()) + || !invoice.providerSubscriptionId().equals(observed.providerSubscriptionId()) + || !invoice.providerCustomerId().equals(observed.providerCustomerId()) + || !invoice.providerPaymentMethodId().equals(observed.providerPaymentMethodId()) + || invoice.livemode() != observed.livemode() + || !invoice.providerPriceId().equals(observed.providerPriceId()) + || invoice.providerQuantity() != observed.providerQuantity() + || invoice.amount() != observed.amount() + || !invoice.currency().equals(observed.currency()) + || observed.readStartedAt().isBefore(verified.receivedAt()) + || now().isBefore(observed.observedAt()) + || Duration.between(observed.readStartedAt(), now()).compareTo(Duration.ofSeconds(20)) >= 0) + throw refused(); + var dispatch = dispatch(row, invoice, true, false); + if (new AccountHostingFirstInvoicePaymentConflictRepository(dsl) + .retainIfCanceled(verified, dispatch, observed)) { + return new SignedOutcome(dispatch, true); + } + var intake = new StripeEventInboxRepository(dsl).retainOrReplay(verified); + dsl.execute( + "INSERT INTO subscription_first_invoice_success_evidence (request_id, subscription_id, provider_event_id, event_payload_digest, tuple_digest, observed_at) " + + "VALUES (?, ?, ?, ?, ?, ?::timestamptz) ON CONFLICT (request_id) DO NOTHING", + row.get("request_id"), + invoice.subscriptionId(), + intake.providerEventId(), + intake.payloadSha256(), + invoice.digest(), + utc(observed.observedAt())); + return new SignedOutcome(dispatch, false); + } + + private record CurrentDispatch( + Record confirmation, Record authorization, AccountHostingFirstInvoicePayment invoice) {} + + public record SignedOutcome(ConfirmationDispatch dispatch, boolean latePaidConflict) {} + + private static void requireSignedTuple( + VerifiedEvent verified, AccountHostingFirstInvoicePayment invoice) { + JsonNode object = JSON.readTree(verified.rawPayload()).path("data").path("object"); + if (!"payment_intent.succeeded".equals(verified.eventType()) + || !"payment_intent".equals(object.path("object").asText()) + || !"succeeded".equals(object.path("status").asText()) + || !invoice.paymentIntentId().equals(object.path("id").asText()) + || !invoice.providerCustomerId().equals(object.path("customer").asText()) + || !invoice.providerPaymentMethodId().equals(object.path("payment_method").asText()) + || !object.path("amount").isIntegralNumber() + || !object.path("amount_received").isIntegralNumber() + || !object.path("amount").canConvertToLong() + || !object.path("amount_received").canConvertToLong() + || invoice.amount() != object.path("amount").asLong() + || invoice.amount() != object.path("amount_received").asLong() + || !invoice.currency().equals(object.path("currency").asText()) + || !object.path("livemode").isBoolean() + || invoice.livemode() != object.path("livemode").asBoolean() + || invoice.livemode() != verified.livemode()) throw refused(); + } + + public AccountHostingFirstInvoicePayment find(UUID subscriptionId) { + transaction(); + Record row = + dsl.fetchOne( + "SELECT * FROM subscription_first_invoices WHERE subscription_id = ?", subscriptionId); + if (row == null) return null; + var invoice = + new AccountHostingFirstInvoicePayment( + row.get("subscription_id", UUID.class), + row.get("creation_request_id", UUID.class), + row.get("tenant_id", UUID.class), + row.get("account_uuid", UUID.class), + row.get("payment_instrument_id", UUID.class), + row.get("instrument_version", Long.class), + row.get("provider_subscription_id", String.class), + row.get("provider_customer_id", String.class), + row.get("provider_payment_method_id", String.class), + row.get("invoice_id", String.class), + row.get("payment_intent_id", String.class), + row.get("amount", Long.class), + row.get("currency", String.class), + row.get("quote_digest", String.class), + row.get("provider_price_id", String.class), + row.get("provider_quantity", Long.class), + row.get("billing_policy_version", Long.class), + row.get("billing_policy_digest", String.class), + row.get("livemode", Boolean.class), + instant(row, "captured_at"), + instant(row, "expires_at")); + if (!invoice.digest().equals(row.get("tuple_digest", String.class))) throw refused(); + return invoice; + } + + private static ConfirmationDispatch dispatch( + Record row, AccountHostingFirstInvoicePayment invoice, boolean read, boolean commandAllowed) { + return new ConfirmationDispatch( + invoice, + row.get("request_id", UUID.class), + row.get("provider_idempotency_id", UUID.class), + row.get("lifecycle_request_id", UUID.class), + row.get("reauthentication_evidence_id", UUID.class), + row.get("request_id", UUID.class), + 1, + row.get("expected_row_version", Long.class), + instant(row, "valid_until"), + read, + commandAllowed); + } + + private static ConfirmationDispatch authorizedDispatch( + Record original, + Record authorization, + AccountHostingFirstInvoicePayment invoice, + boolean read, + boolean commandAllowed) { + return new ConfirmationDispatch( + invoice, + original.get("request_id", UUID.class), + original.get("provider_idempotency_id", UUID.class), + original.get("lifecycle_request_id", UUID.class), + authorization.get("reauthentication_evidence_id", UUID.class), + authorization.get("authorization_request_id", UUID.class), + authorization.get("authorization_version", Long.class), + original.get("expected_row_version", Long.class), + instant(authorization, "valid_until"), + read, + commandAllowed); + } + + private long transactionId() { + return Objects.requireNonNull(dsl.fetchOne("SELECT txid_current() AS id")) + .get("id", Long.class); + } + + private Instant now() { + return clock.instant().truncatedTo(java.time.temporal.ChronoUnit.MICROS); + } + + private static Instant instant(Record row, String field) { + return row.get(field, OffsetDateTime.class).toInstant(); + } + + private static OffsetDateTime utc(Instant value) { + return OffsetDateTime.ofInstant(value, ZoneOffset.UTC); + } + + private static Instant earlier(Instant left, Instant right) { + return left.isBefore(right) ? left : right; + } + + private static FenceRejectedException awaitingPaymentRefused() { + return new FenceRejectedException("Exact retained awaiting-payment claim refused"); + } + + private static IllegalStateException refused() { + return new IllegalStateException("Exact current first-invoice owner/payment evidence refused"); + } + + private static void transaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable Account owner transaction required"); + } + } + + /** Closed durable dispatch evidence, not constructible from request booleans or provider IDs. */ + public static final class CommandClaim { + private final ConfirmationDispatch dispatch; + private final java.util.concurrent.atomic.AtomicBoolean available = + new java.util.concurrent.atomic.AtomicBoolean(true); + + private CommandClaim(ConfirmationDispatch dispatch) { + this.dispatch = dispatch; + } + + public boolean takePermission(ConfirmationDispatch expected) { + return dispatch == expected && available.compareAndSet(true, false); + } + + @Override + public String toString() { + return "HostingFirstInvoiceCommandClaim[redacted]"; + } + } + + /** Closed durable dispatch evidence, not constructible from request booleans or provider IDs. */ + public static final class ConfirmationDispatch { + private final AccountHostingFirstInvoicePayment invoice; + private final UUID requestId, + providerIdempotencyId, + lifecycleRequestId, + reauthenticationEvidenceId, + authorizationRequestId; + private final long expectedRowVersion, authorizationVersion; + private final Instant validUntil; + private final boolean independentlyRead; + private final java.util.concurrent.atomic.AtomicBoolean initialCommandAllowed; + + private ConfirmationDispatch( + AccountHostingFirstInvoicePayment invoice, + UUID requestId, + UUID providerIdempotencyId, + UUID lifecycleRequestId, + UUID reauthenticationEvidenceId, + UUID authorizationRequestId, + long authorizationVersion, + long expectedRowVersion, + Instant validUntil, + boolean independentlyRead, + boolean initialCommandAllowed) { + this.invoice = invoice; + this.requestId = requestId; + this.providerIdempotencyId = providerIdempotencyId; + this.lifecycleRequestId = lifecycleRequestId; + this.reauthenticationEvidenceId = reauthenticationEvidenceId; + this.authorizationRequestId = authorizationRequestId; + this.authorizationVersion = authorizationVersion; + this.expectedRowVersion = expectedRowVersion; + this.validUntil = validUntil; + this.independentlyRead = independentlyRead; + this.initialCommandAllowed = + new java.util.concurrent.atomic.AtomicBoolean(initialCommandAllowed); + } + + public AccountHostingFirstInvoicePayment invoice() { + return invoice; + } + + public UUID requestId() { + return requestId; + } + + public UUID providerIdempotencyId() { + return providerIdempotencyId; + } + + public UUID lifecycleRequestId() { + return lifecycleRequestId; + } + + public UUID reauthenticationEvidenceId() { + return reauthenticationEvidenceId; + } + + public long expectedRowVersion() { + return expectedRowVersion; + } + + public UUID authorizationRequestId() { + return authorizationRequestId; + } + + public long authorizationVersion() { + return authorizationVersion; + } + + public Instant validUntil() { + return validUntil; + } + + public boolean independentlyRead() { + return independentlyRead; + } + + /** + * Read-only hint for pre-confirmation evidence; only the claim can authorize a provider call. + */ + public boolean initialCommandAvailable() { + return initialCommandAllowed.get(); + } + + public boolean takeInitialCommandPermission() { + return initialCommandAllowed.getAndSet(false); + } + + @Override + public String toString() { + return "HostingFirstInvoiceDispatch[redacted]"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java index 02d2fb3bcf..7b3b231bd7 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java @@ -13,6 +13,7 @@ import java.util.Map; import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.accountservice.client.StripeHostingFirstInvoicePaymentClient.TerminalUnpaidObservation; import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver.ExpectedBinding; import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver.ObservedSubscription; @@ -25,12 +26,13 @@ import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; import org.jooq.DSLContext; import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronization; 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. + * Manually composed hosting lifecycle owner. Mutation 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; @@ -77,6 +79,37 @@ public AccountHostingSubscriptionLifecycleRepository( dsl, new AccountAuthorityOutboxRepository(dsl), billing, tenantIdentity, generations); } + /** + * Read-only activation prerequisite, not an activation grant or a retained-row repair. + * + *

The caller owns a read-only transaction and must keep registration held on any failure. A + * clear snapshot does not fence concurrent writers or qualify the remaining activation gates. No + * subscription identities or retained evidence leave this check. + */ + public void requireNoRetainedPositiveCompletionGaps(int queryTimeoutSeconds) { + if (queryTimeoutSeconds < 1 || queryTimeoutSeconds > 5) { + throw new IllegalArgumentException( + "Retained-positive inspection requires a 1..5 second budget"); + } + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Retained-positive inspection requires read-only Account SQL"); + } + var query = + dsl.resultQuery( + "SELECT EXISTS (SELECT 1 FROM subscription s WHERE s.superseded_at IS NULL " + + "AND s.status IN ('trialing', 'active', 'past_due', 'grace') " + + "AND NOT EXISTS (SELECT 1 FROM subscription_first_invoice_completions c " + + "WHERE c.subscription_id = s.subscription_id)) AS unresolved"); + query.queryTimeout(queryTimeoutSeconds); + Record result = Objects.requireNonNull(query.fetchOne(), "Retained-positive inspection absent"); + if (!Boolean.FALSE.equals(result.get("unresolved", Boolean.class))) { + throw new FenceRejectedException( + "HOSTING_ACTIVATION_UNAVAILABLE: retained positive completion evidence unresolved"); + } + } + /** Locked read capture only. No journal, intent, audit or fence changes precede final auth. */ public ResolutionPreparation prepareTerminalResolution(Request request) { requireTransaction(); @@ -363,7 +396,134 @@ public Preparation prepare( long expectedVersion, String providerId, UUID provisioningAttemptId) { + return prepare(requestId, creationId, expectedVersion, providerId, provisioningAttemptId, null); + } + + /** Captures the exact unpaid checkout for a fresh terminal provider read without reserving it. */ + public UnpaidCancellationCapture captureUnpaidFirstInvoiceCancellation( + UUID requestId, UUID creationId, long expectedVersion, String providerId) { + requireTransaction(); + byte[] input = + reconciliationInput(requestId, creationId, expectedVersion, providerId, null, true); + var original = intents.findCreation(creationId).orElseThrow(); + lockReconciliationWallet(original); + Record operation = matchingOperation(requestId, input); + if (operation != null) { + if (!"COMMITTED".equals(operation.get("state", String.class))) { + throw new FenceRejectedException("Unpaid cancellation has no committed outcome to replay"); + } + return new UnpaidCancellationCapture( + requestId, + creationId, + expectedVersion, + null, + null, + null, + null, + preparationOutcome(operation).result()); + } + var current = intents.lockForLifecycle(creationId, expectedVersion); + ExpectedBinding binding = expected(original, providerId); + var invoice = requireUnpaidFirstInvoice(current, binding); + UUID confirmationId = cancellationClaim(current.subscriptionId()); + if (links(current.subscriptionId()).get("lifecycle_inflight_request_id") != null) { + throw new FenceRejectedException("Another lifecycle request owns the current fence"); + } + return new UnpaidCancellationCapture( + requestId, creationId, expectedVersion, binding, now(), invoice, confirmationId, null); + } + + /** A nonterminal or ambiguous observation never takes the durable lifecycle fence. */ + public TransitionResult applyUnpaidFirstInvoiceCancellation( + UnpaidCancellationCapture captured, + StripeHostingSubscriptionObserver.Result result, + TerminalUnpaidObservation unpaid) { requireTransaction(); + Record isolation = dsl.fetchOne("SHOW transaction_isolation"); + if (isolation == null || !"read committed".equals(isolation.get(0, String.class))) { + throw new IllegalStateException( + "Unpaid first-invoice cancellation requires READ COMMITTED isolation"); + } + Objects.requireNonNull(captured); + if (captured.replayResult() != null) return captured.replayResult(); + Instant evaluated = now(); + if (!(result instanceof ObservedSubscription observed) + || !observed.providerStatusIsCanceled() + || observed.readStartedAt().isBefore(captured.capturedAt) + || !evaluated.isBefore(captured.capturedAt.plus(limits.lease())) + || policy.evaluate(observed, evaluated, null).status() != Status.CANCELED + || unpaid == null + || !captured.invoice.digest().equals(unpaid.tupleDigest()) + || !captured.invoice.invoiceId().equals(unpaid.invoiceId()) + || !captured.invoice.paymentIntentId().equals(unpaid.paymentIntentId()) + || (unpaid.intentMethodUnassigned() && !captured.allowsUnassignedIntent()) + || unpaid.readStartedAt().isBefore(observed.observedAt()) + || evaluated.isBefore(unpaid.observedAt().truncatedTo(ChronoUnit.MICROS)) + || !evaluated.isBefore(terminalUnpaidCutoff(unpaid))) { + return new TransitionResult( + captured.requestId, Outcome.RECONCILING, 0, "UNPAID_CANCELLATION_UNCONFIRMED"); + } + requireObservedBinding(captured.binding(), observed); + var prepared = + prepare( + captured.requestId, + captured.creationId, + captured.expectedVersion, + captured.binding().providerSubscriptionId(), + null, + captured); + if (prepared.outcome() == Outcome.COMMITTED) return prepared.result(); + if (prepared.outcome() == Outcome.RECONCILING) return prepared.result(); + if (prepared.outcome() != Outcome.READY) { + throw new FenceRejectedException( + "Unpaid first-invoice cancellation did not reserve its receipt"); + } + if (captured.confirmationId != null) { + dsl.execute( + "INSERT INTO subscription_first_invoice_no_send_cancellations " + + "(cancellation_request_id, confirmation_request_id, invoice_id, payment_intent_id, " + + "read_started_at, observed_at) VALUES (?, ?, ?, ?, ?::timestamptz, ?::timestamptz)", + captured.requestId, + captured.confirmationId, + unpaid.invoiceId(), + unpaid.paymentIntentId(), + utc(unpaid.readStartedAt().truncatedTo(ChronoUnit.MICROS)), + utc(unpaid.observedAt().truncatedTo(ChronoUnit.MICROS))); + } + TransitionResult applied = apply(prepared, observed, true); + if (applied.outcome() == Outcome.COMMITTED) { + requireTerminalUnpaidFreshnessAtCommit(terminalUnpaidCutoff(unpaid)); + } + return applied; + } + + private Instant terminalUnpaidCutoff(TerminalUnpaidObservation unpaid) { + return unpaid + .readStartedAt() + .truncatedTo(ChronoUnit.MICROS) + .plus(policy.maximumObservationAge()); + } + + private void requireTerminalUnpaidFreshnessAtCommit(Instant cutoff) { + TransactionSynchronizationManager.registerSynchronization( + new TransactionSynchronization() { + @Override + public void beforeCommit(boolean readOnly) { + if (!databaseNow().isBefore(cutoff)) { + throw new FenceRejectedException( + "Terminal unpaid first-invoice observation expired before owner commit"); + } + } + }); + } + + private static byte[] reconciliationInput( + UUID requestId, + UUID creationId, + long expectedVersion, + String providerId, + UUID provisioningAttemptId, + boolean unpaidCancellation) { AccountBillingCustomerRecord.requireUuid(requestId); AccountBillingCustomerRecord.requireUuid(creationId); if (expectedVersion < 1 @@ -373,27 +533,25 @@ public Preparation prepare( 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")); + return AccountHostingSubscriptionLifecycleEvidence.encode( + Map.of( + "schemaVersion", + unpaidCancellation + ? "account-hosting-unpaid-first-invoice-cancellation/v1" + : "account-hosting-reconciliation-request/v1", + "requestId", + requestId.toString(), + "creationRequestId", + creationId.toString(), + "expectedRowVersion", + Long.toString(expectedVersion), + "providerSubscriptionId", + providerId, + "provisioningAttemptId", + provisioningAttemptId == null ? "" : provisioningAttemptId.toString())); + } + + private Record matchingOperation(UUID requestId, byte[] input) { Record operation = dsl.fetchOne( "SELECT * FROM subscription_lifecycle_operations WHERE request_id = ?", requestId); @@ -401,6 +559,36 @@ public Preparation prepare( && !Arrays.equals(input, operation.get("request_payload", byte[].class))) { throw new FenceRejectedException("IDEMPOTENCY_CONFLICT: lifecycle request changed"); } + return operation; + } + + private Preparation prepare( + UUID requestId, + UUID creationId, + long expectedVersion, + String providerId, + UUID provisioningAttemptId, + UnpaidCancellationCapture cancellation) { + requireTransaction(); + boolean unpaidCancellation = cancellation != null; + byte[] input = + reconciliationInput( + requestId, + creationId, + expectedVersion, + providerId, + provisioningAttemptId, + unpaidCancellation); + 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. + lockReconciliationWallet(original); + Record operation = matchingOperation(requestId, input); + if (unpaidCancellation + && operation != null + && !"COMMITTED".equals(operation.get("state", String.class))) { + throw new FenceRejectedException("Unpaid cancellation has no committed outcome to replay"); + } if (operation != null && !"PENDING".equals(operation.get("state", String.class))) { return preparationOutcome(operation); } @@ -410,6 +598,9 @@ public Preparation prepare( operation == null ? expectedVersion : operation.get("reserved_row_version", Long.class)); + if (!unpaidCancellation && "canceled".equals(current.status())) { + requireOrdinaryRenewalNotReplacingUnpaidCancellation(current.subscriptionId()); + } Instant now = now(); if (now.isBefore(original.createdAt())) { throw new FenceRejectedException("Lifecycle clock predates its durable creation operation"); @@ -420,31 +611,58 @@ public Preparation prepare( throw new FenceRejectedException("Another lifecycle request owns the current fence"); } Record priorReceipt = receiptForCurrent(currentLinks); + if (unpaidCancellation) { + var invoice = requireUnpaidFirstInvoice(current, expected(original, providerId)); + if (!invoice.digest().equals(cancellation.invoice.digest()) + || !Objects.equals( + cancellationClaim(current.subscriptionId()), cancellation.confirmationId)) { + throw new FenceRejectedException("First-invoice cancellation evidence changed"); + } + if (Boolean.TRUE.equals( + dsl.fetchSingle( + "SELECT account_first_invoice_signed_success_retained(?, ?)", + invoice.paymentIntentId(), + invoice.livemode()) + .get(0, Boolean.class))) { + return new Preparation( + requestId, null, null, Outcome.RECONCILING, "UNPAID_CANCELLATION_UNCONFIRMED", 0); + } + } 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); - Instant provisioningNow = databaseNow(); - if (provisioningAttemptId == null - || !"provisioning".equals(current.status()) - || claimedAttempt == null - || provisioningNow.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) - || !provisioningNow.isBefore(instant(work, "lease_expires_at")) - || !provisioningNow.isBefore(instant(work, "deadline_at"))) { - throw new FenceRejectedException( - "Initial confirmation lacks its exact durable provisioning claim"); + if (current.providerSubscriptionId() != null) { + if (!unpaidCancellation + && (firstPaymentProof(current.subscriptionId(), requestId) == null + || provisioningAttemptId != null + || !"provisioning".equals(current.status()))) { + throw new FenceRejectedException( + "Initial paid lifecycle requires exact signed first-invoice completion evidence"); + } + } else { + Record work = workForUpdate(creationId); + Record claimedAttempt = + provisioningAttemptId == null + ? null + : dsl.fetchOne( + "SELECT claimed_at FROM subscription_provisioning_attempts WHERE attempt_id = ?", + provisioningAttemptId); + Instant provisioningNow = databaseNow(); + if (provisioningAttemptId == null + || !"provisioning".equals(current.status()) + || claimedAttempt == null + || provisioningNow.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) + || !provisioningNow.isBefore(instant(work, "lease_expires_at")) + || !provisioningNow.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( @@ -509,9 +727,10 @@ public Preparation prepare( return new Preparation(requestId, null, null, Outcome.RECONCILING, "BACKOFF_OR_INFLIGHT", 0); } UUID attemptId = UUID.randomUUID(); + Instant attemptStarted = unpaidCancellation ? cancellation.capturedAt : now; Instant expires = earlier( - now.plusMillis(operation.get("lease_millis", Long.class)), + attemptStarted.plusMillis(operation.get("lease_millis", Long.class)), instant(operation, "deadline_at")); int number = operation.get("attempt_count", Integer.class) + 1; dsl.execute( @@ -519,7 +738,7 @@ public Preparation prepare( attemptId, requestId, number, - utc(now), + utc(attemptStarted), utc(expires)); dsl.execute( "UPDATE subscription_lifecycle_operations SET attempt_count = ?, last_attempt_id = ?, retry_at = ?::timestamptz, " @@ -543,6 +762,13 @@ public Preparation prepare( */ public TransitionResult apply( Preparation prepared, StripeHostingSubscriptionObserver.Result result) { + return apply(prepared, result, false); + } + + private TransitionResult apply( + Preparation prepared, + StripeHostingSubscriptionObserver.Result result, + boolean unpaidCancellation) { requireTransaction(); Objects.requireNonNull(prepared); Objects.requireNonNull(result); @@ -576,10 +802,19 @@ public TransitionResult apply( requireObservedBinding(binding, observed); } Record oldReceipt = receiptForCurrent(links(current.subscriptionId())); + if (!unpaidCancellation && "canceled".equals(current.status())) { + requireOrdinaryRenewalNotReplacingUnpaidCancellation(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); + if (unpaidCancellation + && (!(result instanceof ObservedSubscription observed) + || !observed.providerStatusIsCanceled() + || decision.status() != Status.CANCELED)) { + throw new FenceRejectedException("Fresh exact canceled SDK evidence is required"); + } byte[] observation = AccountHostingSubscriptionLifecycleEvidence.observation(result); String observationDigest = AccountHostingSubscriptionLifecycleEvidence.digest(observation); String factsDigest = @@ -629,6 +864,27 @@ public TransitionResult apply( prepared.requestId(), Outcome.RECONCILING, 0, decision.reason().name()); } Objects.requireNonNull(observed); + if (!unpaidCancellation + && oldReceipt == null + && current.status().equals("provisioning") + && decision.status() == Status.CANCELED + && firstPaymentProof(current.subscriptionId(), prepared.requestId()) != null) { + String reason = "PAID_FIRST_INVOICE_PROVIDER_CANCELED"; + terminalLifecycle(operation, reason, now); + return new TransitionResult(prepared.requestId(), Outcome.TERMINAL_FAILURE, 0, reason); + } + Record firstPayment = null; + if (java.util.Set.of(Status.TRIALING, Status.ACTIVE, Status.PAST_DUE, Status.GRACE) + .contains(decision.status()) + && dsl.fetchOne( + "SELECT subscription_id FROM subscription_first_invoice_completions WHERE subscription_id = ?", + current.subscriptionId()) + == null) { + firstPayment = firstPaymentProof(current.subscriptionId(), prepared.requestId()); + if (firstPayment == null) + throw new FenceRejectedException( + "Authorizing hosting requires exact signed first-invoice payment completion"); + } if (current.status().equals("canceled") && decision.status() != Status.CANCELED) { throw new FenceRejectedException("A canceled subscription cannot be reactivated"); } @@ -747,6 +1003,35 @@ public TransitionResult apply( authorityEvent.eventId().toString(), authorityEvent.eventDigest(), utc(now)); + if (firstPayment != null) { + var auditFields = new LinkedHashMap(); + auditFields.put("schemaVersion", "account-hosting-first-invoice-completed/v1"); + auditFields.put("checkoutRequestId", firstPayment.get("request_id", UUID.class).toString()); + auditFields.put("subscriptionId", current.subscriptionId().toString()); + auditFields.put("invoiceId", firstPayment.get("invoice_id", String.class)); + auditFields.put("paymentIntentId", firstPayment.get("payment_intent_id", String.class)); + auditFields.put("tupleDigest", firstPayment.get("tuple_digest", String.class)); + auditFields.put( + "receiptDigest", AccountHostingSubscriptionLifecycleEvidence.digest(receiptPayload)); + new AccountAuditOutboxRepository(dsl) + .appendCanonicalTenant( + firstPayment.get("audit_event_id", UUID.class), + current.tenantId().toString(), + "HOSTING_FIRST_INVOICE_COMPLETED", + new String( + AccountHostingSubscriptionLifecycleEvidence.encode(auditFields), + StandardCharsets.UTF_8)); + dsl.execute( + "INSERT INTO subscription_first_invoice_completions (subscription_id, request_id, lifecycle_request_id, tuple_digest, receipt_digest, audit_event_id, committed_at) " + + "VALUES (?, ?, ?, ?, ?, ?, ?::timestamptz)", + current.subscriptionId(), + firstPayment.get("request_id"), + prepared.requestId(), + firstPayment.get("tuple_digest"), + AccountHostingSubscriptionLifecycleEvidence.digest(receiptPayload), + firstPayment.get("audit_event_id", UUID.class), + utc(now)); + } UUID terminalResolution = current.terminalResolutionId(); if (observed.providerStatusIsCanceled() && terminalResolution == null) { terminalResolution = UUID.randomUUID(); @@ -785,9 +1070,17 @@ public TransitionResult apply( + "row_version = row_version + 1 WHERE request_id = ?", factsDigest, prepared.requestId()); - if (operation.get("provisioning_attempt_id") != null) { + if (unpaidCancellation) { + if (dsl.execute( + "UPDATE subscription_provisioning_work SET phase = 'CANCELED', row_version = row_version + 1 WHERE request_id = ? AND phase = 'AWAITING_PAYMENT'", + original.requestId()) + != 1) { + throw new FenceRejectedException( + "Unpaid first-invoice cancellation lost its provisioning work"); + } + } else if (operation.get("provisioning_attempt_id") != null || firstPayment != null) { dsl.execute( - "UPDATE subscription_provisioning_work SET phase = 'CONFIRMED', row_version = row_version + 1 WHERE request_id = ? AND phase = 'CLAIMED'", + "UPDATE subscription_provisioning_work SET phase = 'CONFIRMED', row_version = row_version + 1 WHERE request_id = ? AND phase IN ('CLAIMED','AWAITING_PAYMENT')", original.requestId()); } tenantEvents.readHostingCheckpoint(current.tenantId(), prepared.requestId()); @@ -795,6 +1088,73 @@ public TransitionResult apply( prepared.requestId(), Outcome.COMMITTED, current.rowVersion() + 1, null); } + private AccountHostingFirstInvoicePayment requireUnpaidFirstInvoice( + AccountSubscriptionCurrentRecord current, ExpectedBinding binding) { + var payments = new AccountHostingFirstInvoicePaymentRepository(dsl, intents, clock); + var invoice = payments.find(current.subscriptionId()); + if (invoice == null + || current.terminalResolutionId() != null + || links(current.subscriptionId()).get("current_receipt_request_id") != null + || !current.creationRequestId().equals(invoice.creationRequestId()) + || !current.tenantId().equals(invoice.tenantId()) + || !current.owner().accountUuid().equals(invoice.ownerAccountId()) + || !current.paymentInstrumentId().equals(invoice.paymentInstrumentId()) + || current.reservedInstrumentVersion() != invoice.instrumentVersion() + || !current.planQuote().digest().equals(invoice.quoteDigest()) + || !binding.providerSubscriptionId().equals(invoice.providerSubscriptionId()) + || !binding.providerCustomerId().equals(invoice.providerCustomerId()) + || !binding.providerPaymentMethodId().equals(invoice.providerPaymentMethodId()) + || !binding.providerPriceId().equals(invoice.providerPriceId()) + || binding.expectedQuantity() != invoice.providerQuantity() + || binding.livemode() != invoice.livemode() + || dsl.fetchOne( + "SELECT 1 FROM subscription_first_invoice_success_evidence WHERE subscription_id = ?", + current.subscriptionId()) + != null) { + throw new FenceRejectedException("Exact unpaid first invoice is required for cancellation"); + } + payments.requireAwaitingPayment(invoice, current.rowVersion()); + return invoice; + } + + private UUID cancellationClaim(UUID subscriptionId) { + Record claim = + dsl.fetchOne( + "SELECT request_id FROM subscription_first_invoice_command_claims WHERE subscription_id = ?", + subscriptionId); + if (claim == null) return null; + UUID requestId = claim.get("request_id", UUID.class); + if (dsl.fetchOne( + "SELECT request_id FROM subscription_first_invoice_expired_before_post " + + "WHERE request_id = ? AND original_creation_proven " + + "AND created_transaction_id <> txid_current()", + requestId) + == null) { + throw new FenceRejectedException( + "Exact unclaimed unpaid first invoice or committed no-send evidence is required for cancellation"); + } + return requestId; + } + + private void lockReconciliationWallet(AccountSubscriptionCreationRecord original) { + new AccountPaymentInstrumentRepository(dsl) + .findByOwnerForUpdate(original.owner().accountUuid(), original.paymentInstrumentId()) + .orElseThrow(() -> new FenceRejectedException("Original provisioning wallet is absent")); + } + + private Record firstPaymentProof(UUID subscriptionId, UUID lifecycleRequestId) { + // Historical authorization was atomically consumed before the single provider dispatch. + // Reading it after expiry cannot renew payment permission or disclose a client secret. + return dsl.fetchOne( + "SELECT c.*, i.invoice_id, i.payment_intent_id, e.tuple_digest AS evidence_tuple FROM subscription_first_invoice_confirmations c " + + "JOIN subscription_first_invoice_success_evidence e USING (request_id, subscription_id) " + + "JOIN subscription_first_invoice_dispatches d USING (request_id, subscription_id) " + + "JOIN subscription_first_invoices i ON i.subscription_id = c.subscription_id AND i.tuple_digest = c.tuple_digest " + + "WHERE c.subscription_id = ? AND c.lifecycle_request_id = ? AND c.tuple_digest = e.tuple_digest FOR SHARE OF c", + subscriptionId, + lifecycleRequestId); + } + private Map receiptFields( Record operation, AccountSubscriptionCreationRecord original, @@ -874,6 +1234,32 @@ private Record links(UUID subscriptionId) { subscriptionId)); } + // Caller holds the current subscription row lock. In particular, refuse before reserving a + // lifecycle version: the original terminal receipt must still match the current row version. + private void requireOrdinaryRenewalNotReplacingUnpaidCancellation(UUID subscriptionId) { + boolean retainedUnpaidCancellation = + Boolean.TRUE.equals( + dsl.fetchSingle( + "SELECT EXISTS (SELECT 1 FROM subscription s" + + " JOIN subscription_lifecycle_receipts r ON r.request_id = s.current_receipt_request_id" + + " AND r.subscription_id = s.subscription_id AND r.tenant_id = s.tenant_id" + + " JOIN subscription_lifecycle_operations o ON o.request_id = r.request_id" + + " AND o.subscription_id = s.subscription_id AND o.tenant_id = s.tenant_id" + + " AND o.creation_request_id = s.creation_request_id" + + " WHERE s.subscription_id = ? AND s.status = 'canceled'" + + " AND r.status = 'canceled' AND o.state = 'COMMITTED'" + + " AND o.request_digest = r.request_digest" + + " AND o.request_digest = 'sha256:' || encode(sha256(o.request_payload), 'hex')" + + " AND convert_from(o.request_payload, 'UTF8')::jsonb->>'schemaVersion'" + + " = 'account-hosting-unpaid-first-invoice-cancellation/v1')", + subscriptionId) + .get(0, Boolean.class)); + if (retainedUnpaidCancellation) { + throw new FenceRejectedException( + "Ordinary lifecycle cannot replace the retained unpaid first-invoice cancellation"); + } + } + private Record receiptForCurrent(Record links) { UUID id = links.get("current_receipt_request_id", UUID.class); return id == null @@ -948,6 +1334,14 @@ public ReadFence prepareCurrentRead(UUID tenantId) { var candidate = intents.findCurrentByTenant(tenantId).orElseThrow(); var current = intents.lockForLifecycle(candidate.creationRequestId(), candidate.rowVersion()); Record currentLinks = links(current.subscriptionId()); + if (java.util.Set.of("trialing", "active", "past_due", "grace").contains(current.status()) + && dsl.fetchOne( + "SELECT subscription_id FROM subscription_first_invoice_completions WHERE subscription_id = ?", + current.subscriptionId()) + == null) { + throw new FenceRejectedException( + "ENTITLEMENT_UNAVAILABLE: signed first-invoice fulfillment is absent"); + } if (currentLinks.get("lifecycle_inflight_request_id") != null || current.providerSubscriptionId() == null) { throw new FenceRejectedException( @@ -1197,6 +1591,52 @@ public TransitionResult result() { } } + public static final class UnpaidCancellationCapture { + private final UUID requestId; + private final UUID creationId; + private final long expectedVersion; + private final ExpectedBinding binding; + private final Instant capturedAt; + private final AccountHostingFirstInvoicePayment invoice; + private final UUID confirmationId; + private final TransitionResult replay; + + private UnpaidCancellationCapture( + UUID requestId, + UUID creationId, + long expectedVersion, + ExpectedBinding binding, + Instant capturedAt, + AccountHostingFirstInvoicePayment invoice, + UUID confirmationId, + TransitionResult replay) { + this.requestId = requestId; + this.creationId = creationId; + this.expectedVersion = expectedVersion; + this.binding = binding; + this.capturedAt = capturedAt; + this.invoice = invoice; + this.confirmationId = confirmationId; + this.replay = replay; + } + + public ExpectedBinding binding() { + return binding; + } + + public TransitionResult replayResult() { + return replay; + } + + public AccountHostingFirstInvoicePayment invoiceRequiringTerminalRead() { + return invoice; + } + + public boolean allowsUnassignedIntent() { + return confirmationId != null; + } + } + /** * 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; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java index f92bedbf5f..3217e6d298 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java @@ -212,7 +212,16 @@ public AccountSubscriptionCurrentRecord lockForProvisioningRecovery( */ public AccountSubscriptionCurrentRecord lockForLifecycle( UUID requestId, long expectedRowVersion) { - return lockBinding(requestId, expectedRowVersion, true, true, true); + return lockBinding(requestId, expectedRowVersion, true, true, InstrumentRequirement.RETAINED); + } + + /** + * First-invoice dispatch requires the current observation of the retained method to be usable. + */ + AccountSubscriptionCurrentRecord lockForFirstInvoiceCommand( + UUID requestId, long expectedRowVersion) { + return lockBinding( + requestId, expectedRowVersion, true, false, InstrumentRequirement.ATTACHABLE); } /** @@ -221,12 +230,19 @@ public AccountSubscriptionCurrentRecord lockForLifecycle( */ AccountSubscriptionCurrentRecord lockForProvisioningSettlement( UUID requestId, long expectedRowVersion) { - return lockBinding(requestId, expectedRowVersion, true, false, true); + return lockBinding(requestId, expectedRowVersion, true, false, InstrumentRequirement.RETAINED); } private AccountSubscriptionCurrentRecord lockProvisioningBinding( UUID requestId, long expectedRowVersion, boolean allowProvisioning) { - return lockBinding(requestId, expectedRowVersion, allowProvisioning, false, false); + return lockBinding( + requestId, expectedRowVersion, allowProvisioning, false, InstrumentRequirement.ORIGINAL); + } + + private enum InstrumentRequirement { + ORIGINAL, + ATTACHABLE, + RETAINED } private AccountSubscriptionCurrentRecord lockBinding( @@ -234,7 +250,7 @@ private AccountSubscriptionCurrentRecord lockBinding( long expectedRowVersion, boolean allowProvisioning, boolean lifecycle, - boolean allowInstrumentObservation) { + InstrumentRequirement instrumentRequirement) { requireWritableTransaction(); AccountBillingCustomerRecord.requireUuid(requestId); if (expectedRowVersion < 1) { @@ -252,12 +268,12 @@ private AccountSubscriptionCurrentRecord lockBinding( currentForUpdate(original.tenantId()) .orElseThrow(() -> new FenceRejectedException("Current subscription is absent")); boolean instrumentVersionAndStateMatch = - allowInstrumentObservation - ? instrument.rowVersion() >= original.reservedInstrumentVersion() - && (instrument.state() == AccountPaymentInstrumentRecord.State.ATTACHABLE - || instrument.state() == AccountPaymentInstrumentRecord.State.UNAVAILABLE) - : instrument.rowVersion() == original.reservedInstrumentVersion() - && instrument.state() == AccountPaymentInstrumentRecord.State.ATTACHABLE; + instrument.rowVersion() >= original.reservedInstrumentVersion() + && (instrumentRequirement != InstrumentRequirement.ORIGINAL + || instrument.rowVersion() == original.reservedInstrumentVersion()) + && (instrument.state() == AccountPaymentInstrumentRecord.State.ATTACHABLE + || (instrumentRequirement == InstrumentRequirement.RETAINED + && instrument.state() == AccountPaymentInstrumentRecord.State.UNAVAILABLE)); if (!current.subscriptionId().equals(original.subscriptionId()) || !current.tenantId().equals(original.tenantId()) || !current.owner().equals(original.owner()) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java index 8d414a885f..f1c192d7c1 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java @@ -1,7 +1,6 @@ package net.firedevops.firemud.accountservice.repository; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import java.time.Clock; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneOffset; @@ -39,17 +38,17 @@ public AccountTenantCapacityRepository(DSLContext dsl) { } /** Called by the actual Account player evaluator before its final source transaction commits. */ - public void retainPlayerEvaluation(RuntimePlayerAdmissionEntitlementEvidence source) { - retain(Evidence.player(source)); - } - - private void retain(Evidence evidence) { + public void retainPlayerEvaluation( + RuntimePlayerAdmissionEntitlementEvidence source, Instant originalPaidCutoff) { transaction(); + Evidence evidence = Evidence.player(source); + OffsetDateTime cutoff = originalPaidCutoff == null ? null : at(originalPaidCutoff); + requirePaidCutoff(evidence, cutoff); int inserted = dsl.execute( "INSERT INTO account_tenant_capacity_evaluations " - + "(evaluation_identity, snapshot_identity, tenant_uuid, caller_workload, owner_service, canonical_evidence, evaluated_at, expires_at) " - + "VALUES (?, ?, ?, ?, ?, ?, ?::timestamptz, ?::timestamptz) ON CONFLICT (evaluation_identity) DO NOTHING", + + "(evaluation_identity, snapshot_identity, tenant_uuid, caller_workload, owner_service, canonical_evidence, evaluated_at, expires_at, original_paid_cutoff) " + + "VALUES (?, ?, ?, ?, ?, ?, ?::timestamptz, ?::timestamptz, ?::timestamptz) ON CONFLICT (evaluation_identity) DO NOTHING", evidence.evaluationIdentity(), evidence.snapshotIdentity(), evidence.tenantId(), @@ -57,12 +56,36 @@ private void retain(Evidence evidence) { evidence.owner().service(), evidence.canonicalBytes(), at(evidence.evaluatedAt()), - at(evidence.expiresAt())); + at(evidence.expiresAt()), + cutoff); if (inserted != 0 && inserted != 1) throw unavailable(); - requireRetained(evidence); + OffsetDateTime retained = + retainedEvaluation(evidence).get("original_paid_cutoff", OffsetDateTime.class); + if (!Objects.equals(toInstant(cutoff), toInstant(retained))) throw unavailable(); } public Instant requireRetained(Evidence evidence) { + return time(retainedEvaluation(evidence), "expires_at"); + } + + /** Returns the original application-clock cutoff for an exact fresh paid evaluation. */ + public Instant requireRetainedOriginalPaidCutoff(Evidence evidence) { + OffsetDateTime cutoff = + retainedEvaluation(evidence).get("original_paid_cutoff", OffsetDateTime.class); + requirePaidCutoff(evidence, cutoff); + return toInstant(cutoff); + } + + private static void requirePaidCutoff(Evidence evidence, OffsetDateTime cutoff) { + if ("PAID_HOSTING".equals(evidence.fields().get("sourceKind")) != (cutoff != null) + || (cutoff != null && cutoff.isBefore(at(evidence.expiresAt())))) throw unavailable(); + } + + private static Instant toInstant(OffsetDateTime value) { + return value == null ? null : value.toInstant(); + } + + private Record retainedEvaluation(Evidence evidence) { transaction(); Record row = dsl.fetchOne( @@ -82,7 +105,7 @@ public Instant requireRetained(Evidence evidence) { .expiresAt() .truncatedTo(java.time.temporal.ChronoUnit.MICROS) .equals(time(row, "expires_at"))) throw unavailable(); - return time(row, "expires_at"); + return row; } /** Compare the exact retained deadline to the database clock after locking its evaluation. */ @@ -176,15 +199,29 @@ public void requirePriorHistory(Request prior, Request next) { || history.get("owner_readback", byte[].class) == null) throw conflict(); } + /** Fresh database time, not the transaction-start timestamp or an injected application clock. */ + public void requireFresh(Evidence evidence) { + transaction(); + requireCurrentLifetime(evidence, databaseNow(dsl)); + } + + /** + * Reads PostgreSQL wall time for evidence creation/freshness checks across application clocks. + */ + public static Instant databaseNow(DSLContext exactDsl) { + return time( + Objects.requireNonNull(exactDsl).fetchSingle("SELECT clock_timestamp() AS observed_at"), + "observed_at"); + } + /** Retains acceptance only after the locked quota check, in the same reservation transaction. */ - public Optional createIfQuotaAvailable(Request request, Instant expiresAt, Clock clock) { - Record usage = usage(request); - requireCurrentLifetime(request.evidence(), clock.instant()); + public Optional createIfQuotaAvailable(Request request, Record usage, Instant expiresAt) { + requireFresh(request.evidence()); long delta = Objects.requireNonNull(request.capacityDelta()); long occupied = Math.addExact(number(usage, "held_units"), number(usage, "used_units")); if (delta > request.evidence().quota() - occupied) return Optional.empty(); new AccountCapacityOriginDecisionRepository(dsl).accept(request); - requireCurrentLifetime(request.evidence(), clock.instant()); + requireFresh(request.evidence()); long held = Math.addExact(number(usage, "held_units"), delta); updateUsage(request, usage, held, number(usage, "used_units")); int created = 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 index 06219ae3f5..806e81f794 100644 --- 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 @@ -275,7 +275,10 @@ private List listRealmScopes( throw entitlementUnavailable(null); } requireFresh(entitlement); - Instant evaluatedAt = now(); + Instant applicationTime = now(); + Instant databaseTime = scopes.canonicalIssuanceTime(); + Instant evaluatedAt = + databaseTime.isBefore(applicationTime) ? databaseTime : applicationTime; Instant expiresAt = evaluatedAt.plusMillis(scopeLifetimeMillis); if (original.expiresAt().isBefore(expiresAt)) expiresAt = original.expiresAt(); // JWT NumericDate has second precision. The persisted preimage uses that exact @@ -305,8 +308,10 @@ private List listRealmScopes( }); // No value escapes a failed commit or a caller/source observation that expired during commit. requireSameCaller(original, authenticate.get()); + Instant databaseTime = inTransaction(scopes::canonicalIssuanceTime); requireFresh(entitlement); - if (!now().isBefore(Instant.parse(retained.scope().connectScopeExpiresAt()))) { + Instant expiresAt = Instant.parse(retained.scope().connectScopeExpiresAt()); + if (!databaseTime.isBefore(expiresAt) || !now().isBefore(expiresAt)) { throw authUnavailable("Canonical scope expired before publication", null); } return List.of(retained); 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 index c0105015d6..e2380ec838 100644 --- 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 @@ -1,9 +1,13 @@ package net.firedevops.firemud.accountservice.service; +import com.stripe.exception.StripeException; import java.util.Objects; import java.util.UUID; import java.util.function.Function; +import net.firedevops.firemud.accountservice.client.StripeHostingFirstInvoicePaymentClient; +import net.firedevops.firemud.accountservice.client.StripeHostingFirstInvoicePaymentClient.TerminalUnpaidObservation; import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver.ObservedSubscription; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionCurrentReceipt; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ClaimResult; @@ -23,16 +27,31 @@ public final class AccountHostingSubscriptionLifecycleService { private final AccountHostingSubscriptionLifecycleRepository repository; private final StripeHostingSubscriptionObserver observer; + private final StripeHostingFirstInvoicePaymentClient firstInvoice; private final TransactionTemplate transaction; + private final TransactionTemplate unpaidCancellationTransaction; public AccountHostingSubscriptionLifecycleService( AccountHostingSubscriptionLifecycleRepository repository, StripeHostingSubscriptionObserver observer, PlatformTransactionManager transactions) { + this(repository, observer, transactions, null); + } + + public AccountHostingSubscriptionLifecycleService( + AccountHostingSubscriptionLifecycleRepository repository, + StripeHostingSubscriptionObserver observer, + PlatformTransactionManager transactions, + StripeHostingFirstInvoicePaymentClient firstInvoice) { this.repository = Objects.requireNonNull(repository); this.observer = Objects.requireNonNull(observer); + this.firstInvoice = firstInvoice; transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + unpaidCancellationTransaction = new TransactionTemplate(transactions); + unpaidCancellationTransaction.setPropagationBehavior( + TransactionDefinition.PROPAGATION_REQUIRES_NEW); + unpaidCancellationTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); } public ClaimResult claimProvisioning( @@ -72,6 +91,40 @@ public TransitionResult reconcile( transaction.execute(s -> repository.apply(prepared, actualSdkResult))); } + /** Read-only Stripe reconciliation of an externally canceled first invoice. */ + public TransitionResult reconcileUnpaidFirstInvoiceCancellation( + UUID requestId, + UUID creationRequestId, + long expectedRowVersion, + String providerSubscriptionId) { + requireNoAmbientTransaction(); + var captured = + Objects.requireNonNull( + transaction.execute(s -> + repository.captureUnpaidFirstInvoiceCancellation( + requestId, creationRequestId, expectedRowVersion, providerSubscriptionId))); + if (captured.replayResult() != null) return captured.replayResult(); + var observed = observer.observe(captured.binding()); + var invoice = captured.invoiceRequiringTerminalRead(); + TerminalUnpaidObservation unpaid = null; + if (invoice != null + && firstInvoice != null + && observed instanceof ObservedSubscription subscription + && subscription.providerStatusIsCanceled()) { + try { + unpaid = firstInvoice.observeTerminalUnpaid(invoice, captured.allowsUnassignedIntent()); + } catch (StripeException | IllegalStateException unproven) { + return new TransitionResult( + requestId, Outcome.RECONCILING, 0, "UNPAID_CANCELLATION_UNCONFIRMED"); + } + } + TerminalUnpaidObservation retainedObservation = unpaid; + return Objects.requireNonNull( + unpaidCancellationTransaction.execute(s -> + repository.applyUnpaidFirstInvoiceCancellation( + captured, observed, retainedObservation))); + } + /** * Fresh SDK facts cannot override the same locked committed receipt; discrepancies require * reconciliation. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java index 3460cbe732..9b567e2680 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java @@ -2,14 +2,14 @@ import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.accountservice.client.StripeHostingFirstInvoicePaymentClient; import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionProvisioner; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionCurrentReceipt; +import net.firedevops.firemud.accountservice.repository.AccountHostingFirstInvoicePayment; +import net.firedevops.firemud.accountservice.repository.AccountHostingFirstInvoicePaymentRepository; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Disposition; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Outcome; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProviderDispatch; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProvisioningClaim; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.TransitionResult; import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.FenceRejectedException; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; @@ -26,26 +26,32 @@ public final class AccountHostingSubscriptionProvisioningService { private final AccountHostingSubscriptionLifecycleRepository repository; private final StripeHostingSubscriptionProvisioner provider; - private final AccountHostingSubscriptionLifecycleService lifecycle; + private final StripeHostingFirstInvoicePaymentClient firstInvoiceProvider; + private final AccountHostingFirstInvoicePaymentRepository firstInvoices; private final TransactionTemplate transaction; public AccountHostingSubscriptionProvisioningService( AccountHostingSubscriptionLifecycleRepository repository, StripeHostingSubscriptionProvisioner provider, - AccountHostingSubscriptionLifecycleService lifecycle, + StripeHostingFirstInvoicePaymentClient firstInvoiceProvider, + AccountHostingFirstInvoicePaymentRepository firstInvoices, PlatformTransactionManager transactions) { this.repository = Objects.requireNonNull(repository); this.provider = Objects.requireNonNull(provider); - this.lifecycle = Objects.requireNonNull(lifecycle); + this.firstInvoiceProvider = Objects.requireNonNull(firstInvoiceProvider); + this.firstInvoices = Objects.requireNonNull(firstInvoices); transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); } - public Result provision(ProvisioningClaim claim, UUID dispatchId, UUID lifecycleRequestId) { + public Result provision(ProvisioningClaim claim, UUID dispatchId) { Objects.requireNonNull(claim, "Existing genuine owner provisioning claim is required"); requireUuid(dispatchId); - requireUuid(lifecycleRequestId); requireNoAmbientTransaction(); + // retainAwaitingPayment may commit before its independent invoice readback or caller response + // is lost. Recover that exact retained outcome before attempting to claim or contact Stripe. + var replay = transaction.execute(status -> firstInvoices.findAwaitingPayment(claim)); + if (replay != null) return new AwaitingPayment(replay); ProviderDispatch dispatch; try { var prepared = @@ -55,49 +61,77 @@ public Result provision(ProvisioningClaim claim, UUID dispatchId, UUID lifecycle Objects.requireNonNull( transaction.execute(status -> repository.readProviderDispatch(prepared))); } catch (FenceRejectedException refused) { + // Retention may have committed after the first read but before dispatch was fenced. + replay = transaction.execute(status -> firstInvoices.findAwaitingPayment(claim)); + if (replay != null) return new AwaitingPayment(replay); // Dispatch remains strictly fenced. A new local transaction may only settle the same retained // work; stale/current-owner/reservation mismatches still reject there before any write. - Disposition disposition = - Objects.requireNonNull(transaction.execute(status -> repository.deferUnresolved(claim))); - return new Pending( - disposition, - new StripeHostingSubscriptionProvisioner.Pending("DISPATCH_FENCE_REJECTED", null)); + return deferUnresolved( + claim, new StripeHostingSubscriptionProvisioner.Pending("DISPATCH_FENCE_REJECTED", null)); } requireNoAmbientTransaction(); var located = provider.provision(dispatch); if (!(located instanceof StripeHostingSubscriptionProvisioner.Located actual)) { - Disposition disposition = - Objects.requireNonNull( - transaction.execute(status -> repository.deferUnresolved(dispatch.claim()))); - return new Pending(disposition, located); + return deferUnresolved(dispatch.claim(), located); } - // Locator and actual observation select the existing owner operation, never an ad-hoc write. - TransitionResult transition = - lifecycle.reconcile( - lifecycleRequestId, - claim.creation().requestId(), - claim.subscriptionRowVersion(), - actual.providerSubscriptionId(), - claim.attemptId()); - if (transition.outcome() != Outcome.COMMITTED) { - return new Reconciling(transition); + // DEFAULT_INCOMPLETE only locates an existing invoice. Provisioning never confirms or grants. + StripeHostingFirstInvoicePaymentClient.Observation observed; + try { + observed = firstInvoiceProvider.capture(dispatch, actual.providerSubscriptionId()); + } catch (StripeHostingFirstInvoicePaymentClient.ProviderEvidenceRefused unresolved) { + return deferFirstInvoice(dispatch, null); + } catch (com.stripe.exception.StripeException unresolved) { + return deferFirstInvoice(dispatch, unresolved); } - AccountHostingSubscriptionCurrentReceipt current; + try { - current = lifecycle.readCurrent(claim.creation().tenantId()); - } catch ( - AccountHostingSubscriptionLifecycleService.EntitlementUnavailableException unavailable) { - return new ReadbackUnavailable(transition); + var retained = + Objects.requireNonNull( + transaction.execute(status -> + firstInvoices.retainAwaitingPayment( + dispatch, actual.providerSubscriptionId(), observed))); + var readback = + transaction.execute(status -> firstInvoices.findAwaitingPayment(dispatch.claim())); + if (!retained.equals(readback)) + throw new IllegalStateException("Independent awaiting-payment readback mismatch"); + return new AwaitingPayment(readback); + } catch (FenceRejectedException refused) { + return recoverRetainedInvoice(dispatch.claim(), refused); + } + } + + private Result deferFirstInvoice( + ProviderDispatch dispatch, com.stripe.exception.StripeException providerFailure) { + return deferUnresolved( + dispatch.claim(), + new StripeHostingSubscriptionProvisioner.Pending( + "FIRST_INVOICE_UNRESOLVED", providerFailure)); + } + + private Result deferUnresolved( + ProvisioningClaim claim, StripeHostingSubscriptionProvisioner.Result providerResult) { + try { + var disposition = + Objects.requireNonNull(transaction.execute(status -> repository.deferUnresolved(claim))); + return new Pending(disposition, providerResult); + } catch (FenceRejectedException refused) { + return recoverRetainedInvoice(claim, refused); } - if (!current.receiptRequestId().equals(lifecycleRequestId) - || current.current().rowVersion() != transition.committedRowVersion() - || !current.current().subscriptionId().equals(claim.creation().subscriptionId()) - || !current.current().creationRequestId().equals(claim.creation().requestId()) - || !actual.providerSubscriptionId().equals(current.current().providerSubscriptionId()) - || !current.current().planQuote().equals(claim.creation().planQuote())) { - throw new IllegalStateException("Independent committed hosting receipt readback mismatch"); + } + + private AwaitingPayment recoverRetainedInvoice( + ProvisioningClaim claim, FenceRejectedException refused) { + // A sibling may have retained the invoice after our previous read. Read the exact claim in a + // fresh transaction after the rejected transaction has ended. + AccountHostingFirstInvoicePayment winner; + try { + winner = transaction.execute(status -> firstInvoices.findAwaitingPayment(claim)); + } catch (FenceRejectedException mismatch) { + if (refused != mismatch) refused.addSuppressed(mismatch); + throw refused; } - return new Committed(transition, current); + if (winner == null) throw refused; + return new AwaitingPayment(winner); } private static void requireUuid(UUID value) { @@ -113,34 +147,12 @@ private static void requireNoAmbientTransaction() { } } - public sealed interface Result permits Pending, Reconciling, ReadbackUnavailable, Committed {} + public sealed interface Result permits Pending, AwaitingPayment {} public record Pending( Disposition disposition, StripeHostingSubscriptionProvisioner.Result providerResult) implements Result {} - public record Reconciling(TransitionResult transition) implements Result {} - - /** The transition committed, but a fresh current receipt could not be obtained. */ - public record ReadbackUnavailable(TransitionResult transition) implements Result {} - - /** Privately constructed after actual lifecycle commit and independent current readback. */ - public static final class Committed implements Result { - private final TransitionResult transition; - private final AccountHostingSubscriptionCurrentReceipt current; - - private Committed( - TransitionResult transition, AccountHostingSubscriptionCurrentReceipt current) { - this.transition = transition; - this.current = current; - } - - public TransitionResult transition() { - return transition; - } - - public AccountHostingSubscriptionCurrentReceipt current() { - return current; - } - } + /** Provider linkage is non-authorizing and still reserves the exact selected instrument. */ + public record AwaitingPayment(AccountHostingFirstInvoicePayment invoice) implements Result {} } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java index 3f8921fc89..fd10e30618 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java @@ -4,6 +4,7 @@ import io.grpc.StatusRuntimeException; import java.sql.Connection; import java.time.Clock; +import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.LinkedHashMap; @@ -19,6 +20,7 @@ import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository.CanonicalConnectScopeEvidence; import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionCurrentSources; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionCurrentReceipt; @@ -133,22 +135,33 @@ public RuntimePlayerAdmissionEntitlementEvidence evaluate( return new Prepared(player, sources.readCurrentSourceSelection(request.tenantId())); }); requireCurrentTimes(prepared.player(), now()); - RuntimePlayerAdmissionEntitlementEvidence evidence = + Captured captured = switch (prepared.selection().kind()) { case PAID_HOSTING -> capturePaidSources(request, caller, prepared); - case NON_PAID_DEMO -> captureDemoSources(request, caller, prepared); + case NON_PAID_DEMO -> new Captured(captureDemoSources(request, caller, prepared), null); }; + RuntimePlayerAdmissionEntitlementEvidence evidence = captured.evidence(); + // Preserve the live caller-scope deadline after the final source transaction commits. This + // check uses Account's application clock; the evidence timestamp comparison below uses the + // same PostgreSQL clock that stamped the retained bundle. + requireCurrentTimes(prepared.player(), now()); try { - evidence.requireCurrentAt(now()); + evidence.requireCurrentAt( + inSourceTransaction(() -> AccountTenantCapacityRepository.databaseNow(dsl))); } catch (IllegalArgumentException expired) { // This final post-commit check only rejects an expired or future source observation. throw unavailable(); } + Instant completedAt = now(); + requireCurrentTimes(prepared.player(), completedAt); + if (captured.originalPaidDeadline() != null + && !completedAt.isBefore(captured.originalPaidDeadline())) { + throw unavailable(); + } return evidence; } - private RuntimePlayerAdmissionEntitlementEvidence capturePaidSources( - Request request, VerifiedCaller caller, Prepared prepared) { + private Captured capturePaidSources(Request request, VerifiedCaller caller, Prepared prepared) { var fence = inSourceTransaction(() -> { try { @@ -161,15 +174,17 @@ private RuntimePlayerAdmissionEntitlementEvidence capturePaidSources( var observation = observer.observe(fence.binding()); PublishedRealmEvidence target = readProtectedTarget(request, prepared.player().scope()); return inSourceTransaction(() -> { - CurrentPlayer player = readCurrentPlayer(request, caller); - if (!prepared.player().scope().equals(player.scope())) throw unavailable(); - requireSameHead(request, prepared.selection()); + AccountGameplayAdmissionCurrentSources.lockRequiredAccountsBeforeTenantSources( + dsl, request.tenantId(), caller.identity().accountId()); final AccountHostingSubscriptionCurrentReceipt receipt; try { receipt = hosting.readCurrent(fence, observation); } catch (FenceRejectedException rejected) { throw unavailable(); } + CurrentPlayer player = readCurrentPlayer(request, caller); + if (!prepared.player().scope().equals(player.scope())) throw unavailable(); + requireSameHead(request, prepared.selection()); Instant evaluatedAt = now(); requireFreshReceipt(request, receipt, evaluatedAt); var event = receipt.tenantAuthorityEvent(); @@ -190,33 +205,34 @@ private RuntimePlayerAdmissionEntitlementEvidence capturePaidSources( } requireCurrentTimes(player, evaluatedAt); var quote = receipt.current().planQuote(); - return capture( - request, - player, - target, - facts( - "PAID_HOSTING", - receipt.subscriptionStatus().storageValue(), - receipt.gameplayAvailable(), - receipt.allowPublicJoin(), - receipt.allowNewGameplayBindings(), - receipt.allowNewInstanceStarts(), - quote.maxActiveSessions(), - quote.maxConcurrentGameInstances(), - quote.maxStorageBytes(), - receipt.entitlementVersion(), - receipt.tenantBillingSequence(), - event.tenantAuthorityGeneration()), - RuntimePlayerAdmissionEntitlementEvidence.digest( - Map.of( - "receiptRequestId", receipt.receiptRequestId().toString(), - "subscriptionId", receipt.current().subscriptionId().toString(), - "subscriptionRowVersion", Long.toString(receipt.current().rowVersion()), - "billingEventId", receipt.billingEventId().toString(), - "billingEventDigest", receipt.billingEventDigest(), - "tenantAuthorityEventDigest", event.eventDigest())), - evaluatedAt, - receipt.validUntil()); + var evidence = + capture( + request, + player, + target, + facts( + "PAID_HOSTING", + receipt.subscriptionStatus().storageValue(), + receipt.gameplayAvailable(), + receipt.allowPublicJoin(), + receipt.allowNewGameplayBindings(), + receipt.allowNewInstanceStarts(), + quote.maxActiveSessions(), + quote.maxConcurrentGameInstances(), + quote.maxStorageBytes(), + receipt.entitlementVersion(), + receipt.tenantBillingSequence(), + event.tenantAuthorityGeneration()), + RuntimePlayerAdmissionEntitlementEvidence.digest( + Map.of( + "receiptRequestId", receipt.receiptRequestId().toString(), + "subscriptionId", receipt.current().subscriptionId().toString(), + "subscriptionRowVersion", Long.toString(receipt.current().rowVersion()), + "billingEventId", receipt.billingEventId().toString(), + "billingEventDigest", receipt.billingEventDigest(), + "tenantAuthorityEventDigest", event.eventDigest())), + receipt.validUntil()); + return new Captured(evidence, receipt.validUntil()); }); } @@ -270,7 +286,6 @@ private RuntimePlayerAdmissionEntitlementEvidence captureDemoSources( demo.tenantBillingSequence(), demo.tenantAuthorityGeneration()), demo.snapshotIdentity(), - capturedAt, null); }); } @@ -571,7 +586,6 @@ private RuntimePlayerAdmissionEntitlementEvidence capture( PublishedRealmEvidence target, Map facts, String entitlementSourceDigest, - Instant time, Instant paidReceiptValidUntil) { var scope = player.scope(); var current = target.currentTarget(); @@ -601,9 +615,6 @@ private RuntimePlayerAdmissionEntitlementEvidence capture( sources.put( "callerTokenExpiresAt", Instant.ofEpochSecond(caller.identity().expiresAtEpochSecond()).toString()); - sources.put( - "paidReceiptValidUntil", - paidReceiptValidUntil == null ? null : paidReceiptValidUntil.toString()); sources.put("callerTokenSha256", caller.tokenSha256()); sources.put("callerRegistryRecordSha256", caller.canonicalRegistryRecordSha256()); sources.put("callerCommitProofSha256", caller.commitProofSha256()); @@ -624,6 +635,15 @@ private RuntimePlayerAdmissionEntitlementEvidence capture( RuntimePlayerAdmissionEntitlementEvidence.digestBytes(world.canonicalBytes())); sources.put("worldCaptureId", world.captureId().toString()); sources.put("worldRowVersion", Long.toString(world.rowVersion())); + Instant capacityEvaluatedAt = AccountTenantCapacityRepository.databaseNow(dsl); + requireCurrentTimes(player, capacityEvaluatedAt); + Instant retainedPaidDeadline = + paidReceiptValidUntil == null + ? null + : conservativePaidReceiptDeadline(paidReceiptValidUntil, capacityEvaluatedAt, now()); + sources.put( + "paidReceiptValidUntil", + retainedPaidDeadline == null ? null : retainedPaidDeadline.toString()); var evidence = RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( request.requestId(), @@ -633,11 +653,12 @@ private RuntimePlayerAdmissionEntitlementEvidence capture( binding, facts, sources, - time); + capacityEvaluatedAt); // Retain only inside this actual evaluator's final source transaction. A supplied bundle // cannot register itself as capacity authority, and commit failure returns no evidence. try { - new AccountTenantCapacityRepository(dsl).retainPlayerEvaluation(evidence); + new AccountTenantCapacityRepository(dsl) + .retainPlayerEvaluation(evidence, paidReceiptValidUntil); } catch (CapacityException retentionFailure) { if (retentionFailure.code() == Failure.ENTITLEMENT_UNAVAILABLE) throw unavailable(); throw retentionFailure; @@ -645,6 +666,20 @@ private RuntimePlayerAdmissionEntitlementEvidence capture( return evidence; } + /** + * Bounds a provider receipt in the database clock domain without extending its original cutoff. + * The database stamp must be sampled before the application clock. + */ + static Instant conservativePaidReceiptDeadline( + Instant originalPaidDeadline, Instant databaseStamp, Instant applicationStamp) { + if (!applicationStamp.isBefore(originalPaidDeadline) + || !databaseStamp.isBefore(originalPaidDeadline)) { + throw unavailable(); + } + if (!databaseStamp.isBefore(applicationStamp)) return originalPaidDeadline; + return databaseStamp.plus(Duration.between(applicationStamp, originalPaidDeadline)); + } + private static Map facts( String kind, String status, @@ -683,6 +718,9 @@ private static Map facts( private record Prepared(CurrentPlayer player, SourceSelection selection) {} + private record Captured( + RuntimePlayerAdmissionEntitlementEvidence evidence, Instant originalPaidDeadline) {} + private record CurrentPlayer( Snapshot snapshot, CanonicalConnectScopeEvidence scope, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java index 7302bc19a4..72d1554a1a 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java @@ -3,7 +3,6 @@ import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.at; import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.conflict; import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.number; -import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.requireCurrentLifetime; import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.unavailable; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; @@ -38,9 +37,11 @@ import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import org.jooq.DSLContext; import org.jooq.Record; +import org.postgresql.util.PSQLException; import org.springframework.dao.CannotSerializeTransactionException; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; @@ -56,6 +57,8 @@ justification = "Private Account owner collaborators.") public final class AccountTenantCapacityOwner { private static final int TRANSACTION_TIMEOUT_SECONDS = 5; + private static final String CAPACITY_ATTEMPT_FRESHNESS_CONSTRAINT = + "account_tenant_capacity_attempt_freshness"; private static final int MAX_SERIALIZATION_ATTEMPTS = 4; private static final long INITIAL_RETRY_DELAY_MILLIS = 5; @@ -192,39 +195,40 @@ public Result commit(Request request, String authenticatedCaller) { lockPlayerAccount(request); var evidence = request.evidence(); Instant retainedExpiry = capacity.requireRetained(evidence); - Instant now = clock.instant(); - if (now.isBefore(evidence.evaluatedAt())) + boolean expired = capacity.retainedEvaluationExpired(retainedExpiry); + if (expired && !evidence.permitsCreation()) { throw new CapacityException(Failure.CAPACITY_ADMISSION_STALE); - if (!evidence.permitsCreation()) requireCurrentLifetime(evidence, now); + } var parsed = currentMembership(request); requireSupportedShape(request); - boolean expired = capacity.retainedEvaluationExpired(retainedExpiry); - if (!expired && now.isBefore(retainedExpiry)) { - currentDelegationAndScope(request, parsed, now); - now = clock.instant(); - expired = capacity.retainedEvaluationExpired(retainedExpiry); + if (expired) { + return expiredOriginal(request, retainedExpiry); } - if (expired && !now.isBefore(retainedExpiry) && evidence.permitsCreation()) { - return new CommitDecision( - null, originDecisions.refuse(request, Failure.CAPACITY_EVALUATION_EXPIRED)); + + capacity.requireFresh(evidence); + var authority = currentDelegationAndScope(request, parsed); + if (capacity.retainedEvaluationExpired(retainedExpiry)) { + return expiredOriginal(request, retainedExpiry); } - requireCurrentLifetime(evidence, now); - if (expired) throw new CapacityException(Failure.CAPACITY_ADMISSION_STALE); - if (!evidence.permitsCreation()) + if (!evidence.permitsCreation()) { + authority.requireCurrent(clock.instant()); throw new CapacityException(Failure.TENANT_BILLING_BLOCKED); - var reservation = - capacity.createIfQuotaAvailable(request, request.evidence().expiresAt(), clock); - // The quota lock and write path can outlive the last qualification read. A late - // database observation rolls back any provisional acceptance, reservation and usage. - if (capacity.retainedEvaluationExpired(retainedExpiry)) - throw new CapacityException(Failure.CAPACITY_ADMISSION_STALE); + } + + // A wait on usage can consume the remaining lifetime. Recheck under the lock. + Record usage = capacity.usage(request); + authority.requireCurrent(clock.instant()); + var reservation = capacity.createIfQuotaAvailable(request, usage, evidence.expiresAt()); if (reservation.isPresent()) { + authority.requireCurrent(clock.instant()); + requireFreshAtCommit(request, authority); return new CommitDecision(reservation.orElseThrow(), null); } + authority.requireCurrent(clock.instant()); Refusal denial = originDecisions.refuse(request, Failure.CAPACITY_QUOTA_EXCEEDED); - requireCurrentLifetime(evidence, clock.instant()); - if (capacity.retainedEvaluationExpired(retainedExpiry)) - throw new CapacityException(Failure.CAPACITY_ADMISSION_STALE); + capacity.requireFresh(evidence); + authority.requireCurrent(clock.instant()); + requireFreshAtCommit(request, authority); return new CommitDecision(null, denial); }); // Throw only after the transaction has committed the exact denial. @@ -233,6 +237,14 @@ public Result commit(Request request, String authenticatedCaller) { return decision.reservation(); } + private CommitDecision expiredOriginal(Request request, Instant retainedExpiry) { + if (!request.evidence().permitsCreation() || clock.instant().isBefore(retainedExpiry)) { + throw new CapacityException(Failure.CAPACITY_ADMISSION_STALE); + } + return new CommitDecision( + null, originDecisions.refuse(request, Failure.CAPACITY_EVALUATION_EXPIRED)); + } + private record CommitDecision(Result reservation, Refusal denial) {} /** Only the Account-owned recovery worker calls this after storing terminal no-commit proof. */ @@ -263,14 +275,16 @@ Result rearm(Request prior, Request next, UUID recoveryOwner, long claimFence) { if (!"RESERVED".equals(row.get("state", String.class)) || !"NOT_EXECUTED_AFTER_AUTHORIZATION".equals(row.get("execution_status", String.class)) || row.get("owner_readback", byte[].class) == null) throw conflict(); - capacity.requireRetained(next.evidence()); - current(next, clock.instant()); requireSupportedShape(next); // Match the fresh reservation/refusal path before arbitrating the attempt UUID. capacity.usage(next); + var authority = current(next); + capacity.requireFresh(next.evidence()); + authority.requireCurrent(clock.instant()); originDecisions.accept(next); requireClaim(row, recoveryOwner, claimFence, clock.instant()); - requireCurrentLifetime(next.evidence(), clock.instant()); + capacity.requireFresh(next.evidence()); + authority.requireCurrent(clock.instant()); int history = dsl.execute( "INSERT INTO account_tenant_capacity_attempt_history " @@ -306,16 +320,31 @@ Result rearm(Request prior, Request next, UUID recoveryOwner, long claimFence) { claimFence); if (changed != 1) throw conflict(); // Reservation identity and both usage columns are deliberately untouched. - return capacity.exact(next, Objects.requireNonNull(capacity.find(next.identity()))); + var result = capacity.exact(next, Objects.requireNonNull(capacity.find(next.identity()))); + authority.requireCurrent(clock.instant()); + requireFreshAtCommit(next, authority); + return result; }); } - private void current(Request request, Instant now) { - var evidence = request.evidence(); - requireCurrentLifetime(evidence, now); - var parsed = currentMembership(request); - currentDelegationAndScope(request, parsed, now); - requireCurrentLifetime(evidence, clock.instant()); + private void requireFreshAtCommit(Request request, AppAuthorityWindow authority) { + if (!TransactionSynchronizationManager.isSynchronizationActive()) throw unavailable(); + TransactionSynchronizationManager.registerSynchronization( + new TransactionSynchronization() { + @Override + public void beforeCommit(boolean readOnly) { + capacity.requireFresh(request.evidence()); + authority.requireCurrent(clock.instant()); + } + }); + } + + private AppAuthorityWindow current(Request request) { + capacity.requireFresh(request.evidence()); + var authority = currentDelegationAndScope(request, currentMembership(request)); + capacity.requireFresh(request.evidence()); + authority.requireCurrent(clock.instant()); + return authority; } private RuntimePlayerAdmissionEntitlementEvidence currentMembership(Request request) { @@ -345,8 +374,10 @@ private RuntimePlayerAdmissionEntitlementEvidence currentMembership(Request requ return parsed; } - private void currentDelegationAndScope( - Request request, RuntimePlayerAdmissionEntitlementEvidence parsed, Instant now) { + private AppAuthorityWindow currentDelegationAndScope( + Request request, RuntimePlayerAdmissionEntitlementEvidence parsed) { + Instant paidCutoff = capacity.requireRetainedOriginalPaidCutoff(request.evidence()); + Instant now = clock.instant(); if (!(request.context() instanceof PlayerContext player)) throw unavailable(); var fields = request.evidence().fields(); if (!(fields.get("sourceReferences") instanceof Map source)) throw unavailable(); @@ -378,6 +409,23 @@ private void currentDelegationAndScope( || !scope.realmId().equals(player.realmId()) || !scope.playableStateScope().equals(player.playableStateScope()) || !now.isBefore(Instant.parse(scope.connectScopeExpiresAt()))) throw unavailable(); + // PostgreSQL owns evaluation freshness. The caller, scope and paid receipt + // retain their independent application-clock cutoffs. + return new AppAuthorityWindow( + issuance.identity().notBeforeEpochSecond(), + issuance.identity().expiresAtEpochSecond(), + Instant.parse(scope.connectScopeExpiresAt()), + paidCutoff); + } + + private record AppAuthorityWindow( + long notBeforeEpochSecond, long expiresEpochSecond, Instant scopeExpiry, Instant paidCutoff) { + private void requireCurrent(Instant now) { + if (now.getEpochSecond() < notBeforeEpochSecond + || now.getEpochSecond() >= expiresEpochSecond + || !now.isBefore(scopeExpiry) + || (paidCutoff != null && !now.isBefore(paidCutoff))) throw unavailable(); + } } private static T qualifiedSource(Supplier read) { @@ -457,6 +505,20 @@ private static boolean waitForFreshSnapshot(Context caller, Deadline deadline, i return !caller.isCancelled() && !deadline.isExpired(); } + private static boolean capacityAttemptFreshnessFailure(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof PSQLException postgresFailure + && "23514".equals(postgresFailure.getSQLState())) { + var serverError = postgresFailure.getServerErrorMessage(); + if (serverError != null + && CAPACITY_ATTEMPT_FRESHNESS_CONSTRAINT.equals(serverError.getConstraint())) { + return true; + } + } + } + return false; + } + private static boolean serializationFailure(RuntimeException failure) { for (Throwable cause = failure; cause != null; cause = cause.getCause()) { if (cause instanceof CannotSerializeTransactionException @@ -470,16 +532,22 @@ private static boolean serializationFailure(RuntimeException failure) { T inTransaction(Supplier action) { if (TransactionSynchronizationManager.isActualTransactionActive() || TransactionSynchronizationManager.isSynchronizationActive()) throw unavailable(); - return Objects.requireNonNull( - transaction.execute(status -> { - AccountTenantCapacityRepository.transaction(); - dsl.connection(connection -> { - if (connection.getAutoCommit() - || connection.isReadOnly() - || connection.getTransactionIsolation() != Connection.TRANSACTION_SERIALIZABLE) - throw unavailable(); - }); - return action.get(); - })); + try { + return Objects.requireNonNull( + transaction.execute(status -> { + AccountTenantCapacityRepository.transaction(); + dsl.connection(connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_SERIALIZABLE) + throw unavailable(); + }); + return action.get(); + })); + } catch (RuntimeException failure) { + if (capacityAttemptFreshnessFailure(failure)) + throw new CapacityException(Failure.CAPACITY_ADMISSION_STALE); + throw failure; + } } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 4c4387eebd..6c9400ad38 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -1400,6 +1400,107 @@ public ControlUiPrimaryIdentity authenticateControlUiPrimaryIdentity( return new ControlUiPrimaryIdentity(accountUuid); } + /** Evaluates the credential against a read-only snapshot before billing takes producer locks. */ + public BillingPrimaryVerification preverifyBillingPrimaryCredential( + UUID accountId, String email, String secret) { + Account account = + accountRepository.findByAccountUuid(accountId).orElseThrow(this::invalidCredentials); + requireAuthenticationPersistedIdentity(account); + if (!email.equals(EmailCanonicalization.normalize(account.getEmail()))) { + throw invalidCredentials(); + } + var challenge = + allowsEmailLoginOtp(account) + ? accountEmailLoginChallengeRepository.findByAccountId(account.getId()).orElse(null) + : null; + boolean active = billingOtpActive(challenge, LocalDateTime.now()); + boolean otpAccepted = active && matchesEmailLoginOtp(challenge, secret); + boolean accepted = + otpAccepted + || (allowsPassword(account) && verifyPassword(secret, account.getPasswordHash())); + return new BillingPrimaryVerification(account, challenge, active, otpAccepted, accepted); + } + + /** Applies an exact, still-current verification in the billing evidence owner's transaction. */ + @Transactional( + propagation = org.springframework.transaction.annotation.Propagation.MANDATORY, + noRollbackFor = AuthenticationException.class) + public ControlUiPrimaryIdentity applyBillingPrimaryVerification( + Account lockedAccount, BillingPrimaryVerification verification) { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable Account billing transaction required"); + } + requireAuthenticationPersistedIdentity(lockedAccount); + requireAuthenticationEligible(lockedAccount); + if (verification == null || !verification.matches(lockedAccount)) { + throw new IllegalStateException("Account billing credential changed before retention"); + } + AccountEmailLoginChallenge challenge = null; + if (allowsEmailLoginOtp(lockedAccount)) { + if (!accountEmailLoginChallengeRepository.tryLockAccountChallenge(lockedAccount.getId())) { + throw new org.springframework.dao.CannotAcquireLockException( + "Account billing email challenge is busy"); + } + challenge = + accountEmailLoginChallengeRepository.findByAccountId(lockedAccount.getId()).orElse(null); + } + LocalDateTime now = LocalDateTime.now(); + boolean challengeUnchanged = + Objects.equals(verification.challenge, challenge) + && verification.activeChallenge == billingOtpActive(challenge, now); + boolean passwordAccepted = verification.accepted && !verification.otpAccepted; + if (!challengeUnchanged && !passwordAccepted) { + throw new IllegalStateException("Account billing email challenge changed before retention"); + } + if (verification.otpAccepted) { + accountEmailLoginChallengeRepository.delete(challenge); + } else if (challengeUnchanged + && challenge != null + && (!verification.activeChallenge || !verification.accepted)) { + recordFailedEmailLoginAttempt(challenge, now); + } + if (!verification.accepted) throw invalidCredentials(); + return new ControlUiPrimaryIdentity(lockedAccount.getAccountUuid()); + } + + private static boolean billingOtpActive(AccountEmailLoginChallenge challenge, LocalDateTime now) { + return challenge != null + && !challenge.getExpiresAt().isBefore(now) + && challenge.getInvalidAttemptCount() < EMAIL_LOGIN_OTP_MAX_ATTEMPTS; + } + + /** Private credential state tied to one observation. It grants no authority on its own. */ + public static final class BillingPrimaryVerification { + private final Account account; + private final AccountEmailLoginChallenge challenge; + private final boolean activeChallenge; + private final boolean otpAccepted; + private final boolean accepted; + + private BillingPrimaryVerification( + Account account, + AccountEmailLoginChallenge challenge, + boolean activeChallenge, + boolean otpAccepted, + boolean accepted) { + this.account = account; + this.challenge = challenge; + this.activeChallenge = activeChallenge; + this.otpAccepted = otpAccepted; + this.accepted = accepted; + } + + private boolean matches(Account current) { + return account.getId().equals(current.getId()) + && account.getAccountUuid().equals(current.getAccountUuid()) + && account.getAccountUuidProvenance() == current.getAccountUuidProvenance() + && Objects.equals(account.getEmail(), current.getEmail()) + && Objects.equals(account.getLoginAuthModes(), current.getLoginAuthModes()) + && Objects.equals(account.getPasswordHash(), current.getPasswordHash()); + } + } + private Account lockSelectedAccountForPrimaryAuthentication(String selector) { String normalizedSelector = EmailCanonicalization.normalize(selector); Account selectedAccount = diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java index f4ee504d3a..a052a5ed30 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java @@ -3,6 +3,7 @@ import java.nio.charset.StandardCharsets; import java.time.Clock; import java.time.Duration; +import java.time.Instant; import java.util.Arrays; import java.util.List; import java.util.Map; @@ -97,9 +98,7 @@ public AccountAuthenticatedActor authenticateAccount(String compactJwt) { AccountControlUiAuthority.ScopeKind.ACCOUNT, null, null, - current -> - new AccountAuthenticatedActor( - current.stored.accountId, current.stored.operationId, current.stored.tokenHash)); + current -> new AccountAuthenticatedActor(current.stored)); } /** Consumes current Account evidence and producer fences in the mutation's owner transaction. */ @@ -107,13 +106,7 @@ public T withCurrentAccount( String compactJwt, Function action) { Objects.requireNonNull(action, "current Account action is required"); return withCurrentAccountSources( - compactJwt, - current -> - action.apply( - new AccountAuthenticatedActor( - current.stored.accountId, - current.stored.operationId, - current.stored.tokenHash))); + compactJwt, current -> action.apply(new AccountAuthenticatedActor(current.stored))); } /** @@ -417,11 +410,20 @@ static void requireAcceptedSignerKey( record AcceptedSignerKey(String keyId, String fingerprint) {} private void requireCurrentOriginalToken(AccountControlUiIssuanceRepository.Stored original) { + requireCurrentOriginalToken(original.issuedAt, original.expiresAt); + } + + /** Checks the original bearer after billing evidence has been bound under Account SQL locks. */ + void requireCurrentOriginalToken(AccountAuthenticatedActor original) { + requireCurrentOriginalToken(original.issuedAt, original.expiresAt); + } + + private void requireCurrentOriginalToken(Instant issuedAt, Instant expiresAt) { var now = clock.instant(); - if (original.issuedAt == null - || original.expiresAt == null - || now.isBefore(original.issuedAt) - || !now.isBefore(original.expiresAt)) { + if (issuedAt == null + || expiresAt == null + || now.isBefore(issuedAt) + || !now.isBefore(expiresAt)) { throw denied(); } } @@ -577,11 +579,15 @@ public static final class AccountAuthenticatedActor { private final UUID accountId; private final UUID issuanceOperationId; private final String tokenHash; - - private AccountAuthenticatedActor(UUID accountId, UUID issuanceOperationId, String tokenHash) { - this.accountId = accountId; - this.issuanceOperationId = issuanceOperationId; - this.tokenHash = tokenHash; + private final Instant issuedAt; + private final Instant expiresAt; + + private AccountAuthenticatedActor(AccountControlUiIssuanceRepository.Stored original) { + this.accountId = original.accountId; + this.issuanceOperationId = original.operationId; + this.tokenHash = original.tokenHash; + this.issuedAt = original.issuedAt; + this.expiresAt = original.expiresAt; } public UUID accountId() { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoicePaymentService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoicePaymentService.java new file mode 100644 index 0000000000..38c27e0239 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoicePaymentService.java @@ -0,0 +1,352 @@ +package net.firedevops.firemud.accountservice.service.session; + +import com.stripe.exception.SignatureVerificationException; +import com.stripe.exception.StripeException; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.client.StripeHostingFirstInvoicePaymentClient; +import net.firedevops.firemud.accountservice.client.StripeHostingFirstInvoicePaymentClient.ExpiredBeforePost; +import net.firedevops.firemud.accountservice.client.StripeHostingFirstInvoicePaymentClient.Handoff; +import net.firedevops.firemud.accountservice.client.StripeHostingWebhookVerifier; +import net.firedevops.firemud.accountservice.repository.AccountHostingFirstInvoicePayment; +import net.firedevops.firemud.accountservice.repository.AccountHostingFirstInvoicePaymentRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Outcome; +import net.firedevops.firemud.accountservice.repository.StripeEventInboxRepository; +import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionLifecycleService; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Held owner composition. Provider IO follows durable consent and independent current readback. */ +public final class AccountHostingFirstInvoicePaymentService { + private final AccountControlUiActorService actors; + private final AccountRecentReauthenticationService reauthentication; + private final AccountHostingFirstInvoicePaymentRepository payments; + private final StripeEventInboxRepository inbox; + private final StripeHostingFirstInvoicePaymentClient provider; + private final StripeHostingWebhookVerifier verifier; + private final AccountHostingSubscriptionLifecycleService lifecycle; + private final TransactionTemplate transaction; + + public AccountHostingFirstInvoicePaymentService( + AccountControlUiActorService actors, + AccountRecentReauthenticationService reauthentication, + AccountHostingFirstInvoicePaymentRepository payments, + StripeEventInboxRepository inbox, + StripeHostingFirstInvoicePaymentClient provider, + StripeHostingWebhookVerifier verifier, + AccountHostingSubscriptionLifecycleService lifecycle, + PlatformTransactionManager transactions) { + this.actors = Objects.requireNonNull(actors); + this.reauthentication = Objects.requireNonNull(reauthentication); + this.payments = Objects.requireNonNull(payments); + this.inbox = Objects.requireNonNull(inbox); + this.provider = Objects.requireNonNull(provider); + this.verifier = Objects.requireNonNull(verifier); + this.lifecycle = Objects.requireNonNull(lifecycle); + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + } + + public OwnerView describeOwner(String bearer, UUID subscriptionId) { + outsideSql(); + return actors.withCurrentAccount( + bearer, + actor -> { + var invoice = payments.requireOwner(subscriptionId, actor.accountId()); + long rowVersion = payments.ownerRowVersion(subscriptionId, actor.accountId()); + UUID confirmationRequestId = payments.confirmationRequestId(subscriptionId); + boolean completed = payments.hasCompleted(subscriptionId); + boolean canceled = !completed && payments.hasCanceledCheckout(invoice); + return new OwnerView( + invoice.subscriptionId(), + invoice.invoiceId(), + invoice.paymentIntentId(), + invoice.paymentInstrumentId(), + Long.toString(invoice.amount()), + invoice.currency(), + invoice.digest(), + rowVersion, + completed ? "COMMITTED" : canceled ? "CANCELED" : "AWAITING_PAYMENT", + invoice.expiresAt(), + confirmationRequestId, + confirmationRequestId == null && !canceled + ? payments.openingRequestId(invoice, rowVersion) + : null, + payments.authorizationVersion(subscriptionId)); + }); + } + + /** Genuine reauthentication bound to one exact invoice and its intended authorization attempt. */ + public UUID reauthenticate( + String bearer, + UUID subscriptionId, + UUID reauthenticationRequestId, + UUID authorizationRequestId, + UUID originalRequestId, + long expectedRowVersion, + long expectedAuthorizationVersion, + String acceptedTupleDigest, + java.time.Instant invoiceExpiresAt, + AccountRecentReauthenticationEvidence.BillingAuthorizationPurpose authorizationPurpose, + String email, + String secret) { + outsideSql(); + var snapshot = + actors.withCurrentAccount( + bearer, + actor -> { + var invoice = payments.requireOwner(subscriptionId, actor.accountId()); + return new OwnerReauthenticationSnapshot( + actor.accountId(), + invoice, + payments.ownerRowVersion(subscriptionId, actor.accountId())); + }); + if (expectedRowVersion != snapshot.rowVersion() + || !Objects.equals(acceptedTupleDigest, snapshot.invoice().digest()) + || !Objects.equals(invoiceExpiresAt, snapshot.invoice().expiresAt())) { + throw new IllegalStateException( + "Exact current first-invoice reauthentication binding refused"); + } + var context = + new AccountRecentReauthenticationEvidence.BillingContext( + snapshot.accountId(), + subscriptionId, + originalRequestId, + acceptedTupleDigest, + expectedRowVersion, + invoiceExpiresAt, + authorizationRequestId, + expectedAuthorizationVersion, + authorizationPurpose); + var evidence = + reauthentication.reauthenticateAndBindBilling( + new AccountRecentReauthenticationService.Request( + reauthenticationRequestId, + snapshot.accountId(), + AccountRecentReauthenticationPolicy.BILLING_PURPOSE, + authorizationRequestId, + context, + email, + secret), + actors, + bearer, + current -> + payments.bindReauthenticationContext( + snapshot.accountId(), subscriptionId, context, current)); + return evidence.evidenceId(); + } + + /** + * Explicit consent names the immutable tuple shown to the owner; browser success grants nothing. + */ + public Handoff confirm( + String bearer, + UUID subscriptionId, + UUID requestId, + long expectedRowVersion, + UUID reauthenticationEvidenceId, + String acceptedTupleDigest) + throws StripeException { + outsideSql(); + var prepared = + actors.withCurrentAccount( + bearer, + actor -> { + var evidence = + reauthentication.requireCurrentBillingEvidenceLocked( + reauthenticationEvidenceId, actor.accountId(), requestId); + reauthentication.validateAndConsumeLocked( + evidence, + actor.accountId(), + AccountRecentReauthenticationPolicy.BILLING_PURPOSE, + requestId); + return payments.prepareConfirmation( + actor.accountId(), + requestId, + subscriptionId, + expectedRowVersion, + acceptedTupleDigest, + evidence); + }); + return dispatch(bearer, prepared); + } + + /** Explicit new primary proof and consent, fenced against any concurrent authorization. */ + public Handoff renew( + String bearer, + UUID subscriptionId, + UUID requestId, + UUID authorizationRequestId, + long expectedRowVersion, + long expectedAuthorizationVersion, + UUID reauthenticationEvidenceId, + String acceptedTupleDigest) + throws StripeException { + outsideSql(); + var prepared = + actors.withCurrentAccount( + bearer, + actor -> { + var evidence = + reauthentication.requireCurrentBillingEvidenceLocked( + reauthenticationEvidenceId, actor.accountId(), authorizationRequestId); + reauthentication.validateAndConsumeLocked( + evidence, + actor.accountId(), + AccountRecentReauthenticationPolicy.BILLING_PURPOSE, + authorizationRequestId); + return payments.renewAuthorization( + actor.accountId(), + requestId, + authorizationRequestId, + subscriptionId, + expectedRowVersion, + expectedAuthorizationVersion, + acceptedTupleDigest, + evidence); + }); + return dispatch(bearer, prepared); + } + + private Handoff dispatch( + String bearer, AccountHostingFirstInvoicePaymentRepository.ConfirmationDispatch prepared) + throws StripeException { + var dispatch = + actors.withCurrentAccount( + bearer, + actor -> { + reauthentication.requireCurrentBillingEvidenceLocked( + prepared.reauthenticationEvidenceId(), + actor.accountId(), + prepared.authorizationRequestId()); + return payments.readDispatch(prepared, actor.accountId()); + }); + outsideSql(); + try { + Handoff handoff = + provider.confirm( + dispatch, + () -> + actors.withCurrentAccount( + bearer, + actor -> { + var evidence = + reauthentication.requireCurrentBillingEvidenceLocked( + dispatch.reauthenticationEvidenceId(), + actor.accountId(), + dispatch.authorizationRequestId()); + if (evidence.billingContext() == null) { + throw new IllegalStateException( + "Exact first-invoice billing binding required"); + } + return payments.claimCommand(dispatch, actor.accountId()); + })); + if (handoff.clientSecret() != null) { + actors.withCurrentAccount( + bearer, + actor -> { + var evidence = + reauthentication.requireCurrentBillingEvidenceLocked( + dispatch.reauthenticationEvidenceId(), + actor.accountId(), + dispatch.authorizationRequestId()); + payments.validateHandoffAuthorization(dispatch, actor.accountId(), evidence); + return null; + }); + } + return handoff; + } catch (ExpiredBeforePost observation) { + transaction.executeWithoutResult(status -> payments.retainExpiredBeforePost(observation)); + throw observation; + } + } + + /** Immutable intake commits separately. A failed fulfillment resumes this exact completion. */ + public Completion completeSigned(String payload, String signature) + throws SignatureVerificationException, StripeException { + outsideSql(); + var event = verifier.verify(payload, signature); + transaction.executeWithoutResult(status -> inbox.retainOrReplay(event)); + UUID retainedConflict = + transaction.execute(status -> payments.retainedSignedConflictRequestId(event)); + if (retainedConflict != null) { + return new Completion("OPERATOR_RECONCILIATION_REQUIRED", retainedConflict); + } + var classification = + Objects.requireNonNull(transaction.execute(status -> payments.classifySignedEvent(event))); + var candidate = classification.candidate(); + if (candidate == null) { + return new Completion(classification.reconciliationOnly() ? "RECONCILING" : "IGNORED", null); + } + boolean alreadyCompleted = + Boolean.TRUE.equals( + transaction.execute(status -> + payments.completed( + candidate.invoice().subscriptionId(), candidate.lifecycleRequestId()))); + if (!alreadyCompleted) { + var observed = provider.observe(candidate.invoice()); + var signed = + Objects.requireNonNull( + transaction.execute(status -> payments.retainSignedOutcome(event, observed))); + if (signed.latePaidConflict()) { + return new Completion("OPERATOR_RECONCILIATION_REQUIRED", candidate.requestId()); + } + var transition = + lifecycle.reconcile( + candidate.lifecycleRequestId(), + candidate.invoice().creationRequestId(), + candidate.expectedRowVersion(), + candidate.invoice().providerSubscriptionId(), + null); + if (transition.outcome() == Outcome.TERMINAL_FAILURE) + return new Completion("OPERATOR_RECONCILIATION_REQUIRED", candidate.requestId()); + if (transition.outcome() != Outcome.COMMITTED) + return new Completion("RECONCILING", candidate.requestId()); + } + // A later cancellation/authority checkpoint cannot erase the immutable paid outcome. + // Newly committed fulfillment additionally proves the independent current authority read. + if (!alreadyCompleted) { + var current = lifecycle.readCurrent(candidate.invoice().tenantId()); + if (!candidate.invoice().subscriptionId().equals(current.current().subscriptionId()) + || !candidate.lifecycleRequestId().equals(current.receiptRequestId())) { + throw new IllegalStateException("Independent first-invoice authority readback refused"); + } + } + if (!Boolean.TRUE.equals( + transaction.execute(status -> + payments.completed( + candidate.invoice().subscriptionId(), candidate.lifecycleRequestId())))) { + throw new IllegalStateException("Independent first-invoice fulfillment readback refused"); + } + return new Completion("COMMITTED", candidate.requestId()); + } + + private static void outsideSql() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("First-invoice checkout refuses ambient SQL"); + } + } + + public record OwnerView( + UUID subscriptionId, + String invoiceId, + String paymentIntentId, + UUID paymentInstrumentId, + String amount, + String currency, + String tupleDigest, + long expectedRowVersion, + String state, + java.time.Instant expiresAt, + UUID confirmationRequestId, + UUID openingRequestId, + long authorizationVersion) {} + + public record Completion(String state, UUID requestId) {} + + private record OwnerReauthenticationSnapshot( + UUID accountId, AccountHostingFirstInvoicePayment invoice, long rowVersion) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationEvidence.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationEvidence.java index c8c33ac3cf..59cf83b65e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationEvidence.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationEvidence.java @@ -1,6 +1,10 @@ package net.firedevops.firemud.accountservice.service.session; +import java.nio.charset.StandardCharsets; import java.time.Instant; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeFormatterBuilder; +import java.util.Locale; import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; @@ -27,6 +31,7 @@ public final class AccountRecentReauthenticationEvidence { private final long recentAgeSeconds; private final long maxClockSkewSeconds; private final Instant issuedAt; + private final BillingContext billingContext; AccountRecentReauthenticationEvidence( UUID evidenceId, @@ -48,6 +53,50 @@ public final class AccountRecentReauthenticationEvidence { long recentAgeSeconds, long maxClockSkewSeconds, Instant issuedAt) { + this( + evidenceId, + requestId, + accountId, + purpose, + creationOperationId, + requestDigest, + identityProvenance, + identitySourceNumericId, + lifecycleState, + accountAuthorityGeneration, + accountAuthoritySourceVersion, + issuanceFence, + issuanceFenceSourceVersion, + platformPolicyVersion, + deploymentPolicyVersion, + effectivePolicyVersion, + recentAgeSeconds, + maxClockSkewSeconds, + issuedAt, + null); + } + + AccountRecentReauthenticationEvidence( + UUID evidenceId, + UUID requestId, + UUID accountId, + String purpose, + UUID creationOperationId, + String requestDigest, + AccountIdentityProvenance identityProvenance, + long identitySourceNumericId, + AccountLifecycleState lifecycleState, + long accountAuthorityGeneration, + long accountAuthoritySourceVersion, + long issuanceFence, + long issuanceFenceSourceVersion, + long platformPolicyVersion, + long deploymentPolicyVersion, + String effectivePolicyVersion, + long recentAgeSeconds, + long maxClockSkewSeconds, + Instant issuedAt, + BillingContext billingContext) { this.evidenceId = Objects.requireNonNull(evidenceId); this.requestId = Objects.requireNonNull(requestId); this.accountId = Objects.requireNonNull(accountId); @@ -67,7 +116,8 @@ public final class AccountRecentReauthenticationEvidence { this.recentAgeSeconds = recentAgeSeconds; this.maxClockSkewSeconds = maxClockSkewSeconds; this.issuedAt = Objects.requireNonNull(issuedAt); - if (AccountRecentReauthenticationPolicy.PURPOSE.equals(purpose) == false + this.billingContext = billingContext; + if (!AccountRecentReauthenticationPolicy.supportedPurpose(purpose) || identitySourceNumericId <= 0L || lifecycleState != AccountLifecycleState.ACTIVE || accountAuthorityGeneration <= 0L @@ -81,6 +131,16 @@ public final class AccountRecentReauthenticationEvidence { || maxClockSkewSeconds >= recentAgeSeconds) { throw new IllegalArgumentException("Immutable recent-reauthentication evidence is invalid"); } + if (billingContext != null + && (!AccountRecentReauthenticationPolicy.BILLING_PURPOSE.equals(purpose) + || !accountId.equals(billingContext.accountId()) + || !creationOperationId.equals(billingContext.authorizationRequestId()) + || !requestDigest.equals( + AccountRecentReauthenticationRepository.digest( + AccountRecentReauthenticationRepository.requestPayload( + requestId, accountId, purpose, creationOperationId, billingContext))))) { + throw new IllegalArgumentException("Immutable billing reauthentication binding is invalid"); + } } public UUID evidenceId() { @@ -159,8 +219,113 @@ public Instant issuedAt() { return issuedAt; } + /** Null only for historical/unbound billing rows and non-billing reauthentication purposes. */ + public BillingContext billingContext() { + return billingContext; + } + @Override public String toString() { return "AccountRecentReauthenticationEvidence[redacted]"; } + + /** Exact immutable checkout context; credentials never enter this value. */ + public record BillingContext( + UUID accountId, + UUID subscriptionId, + UUID originalRequestId, + String tupleDigest, + long expectedRowVersion, + Instant invoiceExpiresAt, + UUID authorizationRequestId, + long expectedAuthorizationVersion, + BillingAuthorizationPurpose authorizationPurpose) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final DateTimeFormatter CANONICAL_MICROSECOND_INSTANT = + new DateTimeFormatterBuilder().appendInstant(6).toFormatter(Locale.ROOT); + + private static void requireUuid(UUID value) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException("Non-nil billing UUID is required"); + } + } + + public BillingContext { + requireUuid(accountId); + requireUuid(subscriptionId); + requireUuid(originalRequestId); + requireUuid(authorizationRequestId); + Objects.requireNonNull(invoiceExpiresAt); + Objects.requireNonNull(authorizationPurpose); + if (tupleDigest == null + || !tupleDigest.matches("sha256:[0-9a-f]{64}") + || expectedRowVersion <= 0L + || expectedAuthorizationVersion < 0L + || invoiceExpiresAt.getNano() % 1_000 != 0) { + throw new IllegalArgumentException("Exact billing reauthentication context required"); + } + switch (authorizationPurpose) { + case INITIAL_CONFIRMATION -> { + if (!originalRequestId.equals(authorizationRequestId) + || expectedAuthorizationVersion != 0L) { + throw new IllegalArgumentException("Initial billing proof must name version zero"); + } + } + case PRE_ROW_RENEWAL -> { + if (originalRequestId.equals(authorizationRequestId) + || expectedAuthorizationVersion != 0L) { + throw new IllegalArgumentException( + "Pre-row renewal must name a distinct version-zero attempt"); + } + } + case FOLLOWUP_RENEWAL -> { + if (originalRequestId.equals(authorizationRequestId) + || expectedAuthorizationVersion < 1L) { + throw new IllegalArgumentException( + "Follow-up renewal must name a distinct retained attempt"); + } + } + } + } + + public byte[] canonicalPayload() { + String payload = + "account-hosting-billing-reauth-context/v1\n" + + "accountId=" + + accountId + + "\nsubscriptionId=" + + subscriptionId + + "\noriginalRequestId=" + + originalRequestId + + "\ntupleDigest=" + + tupleDigest + + "\nexpectedRowVersion=" + + expectedRowVersion + + "\ninvoiceExpiresAt=" + + CANONICAL_MICROSECOND_INSTANT.format(invoiceExpiresAt) + + "\nauthorizationRequestId=" + + authorizationRequestId + + "\nexpectedAuthorizationVersion=" + + expectedAuthorizationVersion + + "\nauthorizationPurpose=" + + authorizationPurpose.name() + + "\n"; + return payload.getBytes(StandardCharsets.UTF_8); + } + + public String digest() { + return AccountRecentReauthenticationRepository.digest(canonicalPayload()); + } + + @Override + public String toString() { + return "AccountRecentReauthenticationEvidence.BillingContext[redacted]"; + } + } + + public enum BillingAuthorizationPurpose { + INITIAL_CONFIRMATION, + PRE_ROW_RENEWAL, + FOLLOWUP_RENEWAL + } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPolicy.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPolicy.java index db6e60fbd1..a52e12927b 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPolicy.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPolicy.java @@ -15,12 +15,25 @@ /** Account-owned versioned platform/deployment policy for tenantless game creation reauth. */ public final class AccountRecentReauthenticationPolicy { public static final String PURPOSE = "SELF_SERVICE_GAME_CREATION"; + public static final String BILLING_PURPOSE = "HOSTING_FIRST_INVOICE_PAYMENT"; + + public static boolean supportedPurpose(String purpose) { + return PURPOSE.equals(purpose) || BILLING_PURPOSE.equals(purpose); + } + public static final long PLATFORM_RECENT_AGE_MAX_SECONDS = 300L; public static final long PLATFORM_CLOCK_SKEW_MAX_SECONDS = 30L; private AccountRecentReauthenticationPolicy() {} public static Effective resolve(PlatformValue platform, DeploymentValue deployment) { + return resolve(PURPOSE, platform, deployment); + } + + public static Effective resolve( + String purpose, PlatformValue platform, DeploymentValue deployment) { + if (!supportedPurpose(purpose)) + throw new IllegalArgumentException("Unsupported reauthentication purpose"); Objects.requireNonNull(platform, "Current platform policy is required"); Objects.requireNonNull(deployment, "Current deployment policy is required"); requireBounded(platform.version(), platform.recentAgeSeconds(), platform.maxClockSkewSeconds()); @@ -40,7 +53,7 @@ public static Effective resolve(PlatformValue platform, DeploymentValue deployme + HexFormat.of() .formatHex( sha256( - canonicalPolicy(platform, deployment, effectiveAge, effectiveSkew) + canonicalPolicy(purpose, platform, deployment, effectiveAge, effectiveSkew) .getBytes(StandardCharsets.UTF_8))); return new Effective( platform.version(), deployment.version(), effectiveAge, effectiveSkew, version); @@ -104,13 +117,14 @@ private static void requireBounded(long version, long ageSeconds, long skewSecon } private static String canonicalPolicy( + String purpose, PlatformValue platform, DeploymentValue deployment, long effectiveAgeSeconds, long effectiveSkewSeconds) { return "account-recent-reauthentication-policy/v1\n" + "purpose=" - + PURPOSE + + purpose + "\nplatformVersion=" + platform.version() + "\nplatformRecentAgeSeconds=" diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPolicyRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPolicyRepository.java index 5c8bcb200e..8b1ac575ec 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPolicyRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPolicyRepository.java @@ -67,6 +67,40 @@ public CurrentSourcesForGameCreation resolveCurrentSourcesForGameCreation() { } } + /** + * Billing has distinct retained policy rows; game-creation evidence cannot authorize a charge. + */ + public AccountRecentReauthenticationPolicy.Effective resolveCurrentForPurpose(String purpose) { + if (AccountRecentReauthenticationPolicy.PURPOSE.equals(purpose)) { + return resolveCurrentForGameCreation(); + } + if (!AccountRecentReauthenticationPolicy.BILLING_PURPOSE.equals(purpose)) { + throw unavailable(); + } + requireTransaction(); + Record row = + dsl.fetchOne( + "SELECT p.policy_version AS platform_version, p.recent_age_seconds AS platform_age, " + + "p.max_clock_skew_seconds AS platform_skew, d.policy_version AS deployment_version, " + + "d.recent_age_seconds AS deployment_age, d.max_clock_skew_seconds AS deployment_skew " + + "FROM account_billing_reauthentication_policy_current pc " + + "JOIN account_billing_reauthentication_policy_values p USING (policy_scope, policy_version) " + + "CROSS JOIN account_billing_reauthentication_policy_current dc " + + "JOIN account_billing_reauthentication_policy_values d ON d.policy_scope = dc.policy_scope AND d.policy_version = dc.policy_version " + + "WHERE pc.policy_scope = 'PLATFORM' AND dc.policy_scope = 'DEPLOYMENT' FOR SHARE OF pc, dc"); + if (row == null) throw unavailable(); + return AccountRecentReauthenticationPolicy.resolve( + purpose, + new AccountRecentReauthenticationPolicy.PlatformValue( + requiredPositive(row, "platform_version"), + requiredPositive(row, "platform_age"), + requiredNonnegative(row, "platform_skew")), + new AccountRecentReauthenticationPolicy.DeploymentValue( + requiredPositive(row, "deployment_version"), + requiredPositive(row, "deployment_age"), + requiredNonnegative(row, "deployment_skew"))); + } + public record CurrentSourcesForGameCreation( AccountRecentReauthenticationPolicy.Effective effectivePolicy, List sources) { public CurrentSourcesForGameCreation { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationRepository.java index 692b69e004..56f6641273 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationRepository.java @@ -36,6 +36,12 @@ void lockCreationOperation(UUID creationOperationId) { lockIdentity("recent-reauth-creation", creationOperationId); } + Optional findByEvidenceId(UUID evidenceId) { + requireTransaction(); + return Optional.ofNullable( + map(dsl.fetchOne("SELECT * FROM " + EVIDENCE + " WHERE evidence_id = ?", evidenceId))); + } + Optional findByRequest(UUID requestId) { requireTransaction(); return Optional.ofNullable( @@ -68,8 +74,14 @@ void insert( + "account_uuid_source_numeric_id, account_lifecycle_state, " + "account_authority_generation, account_authority_source_version, issuance_fence, " + "issuance_fence_source_version, platform_policy_version, deployment_policy_version, " - + "effective_policy_version, recent_age_seconds, max_clock_skew_seconds, issued_at) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?::timestamptz)", + + "effective_policy_version, recent_age_seconds, max_clock_skew_seconds, issued_at, " + + "billing_context_subscription_id, billing_context_original_request_id, " + + "billing_context_tuple_digest, billing_context_expected_row_version, " + + "billing_context_invoice_expires_at, billing_context_authorization_request_id, " + + "billing_context_expected_authorization_version, billing_context_authorization_purpose, " + + "billing_context_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?::timestamptz, " + + "?, ?, ?, ?, ?::timestamptz, ?, ?, ?, ?)", evidence.evidenceId(), evidence.requestId(), evidence.accountId(), @@ -89,7 +101,16 @@ void insert( evidence.effectivePolicyVersion(), evidence.recentAgeSeconds(), evidence.maxClockSkewSeconds(), - OffsetDateTime.ofInstant(evidence.issuedAt(), ZoneOffset.UTC)); + OffsetDateTime.ofInstant(evidence.issuedAt(), ZoneOffset.UTC), + contextValue(evidence, BillingField.SUBSCRIPTION_ID), + contextValue(evidence, BillingField.ORIGINAL_REQUEST_ID), + contextValue(evidence, BillingField.TUPLE_DIGEST), + contextValue(evidence, BillingField.EXPECTED_ROW_VERSION), + contextValue(evidence, BillingField.INVOICE_EXPIRES_AT), + contextValue(evidence, BillingField.AUTHORIZATION_REQUEST_ID), + contextValue(evidence, BillingField.EXPECTED_AUTHORIZATION_VERSION), + contextValue(evidence, BillingField.AUTHORIZATION_PURPOSE), + evidence.billingContext() == null ? null : evidence.billingContext().digest()); if (inserted != 1) { throw unavailable(); } @@ -273,8 +294,20 @@ Consumption insertConsumption( } static byte[] requestPayload(UUID requestId, UUID accountId, String purpose, UUID operationId) { + return requestPayload(requestId, accountId, purpose, operationId, null); + } + + static byte[] requestPayload( + UUID requestId, + UUID accountId, + String purpose, + UUID operationId, + AccountRecentReauthenticationEvidence.BillingContext billingContext) { + String version = billingContext == null ? "v1" : "v2"; String payload = - "account-recent-reauthentication-request/v1\n" + "account-recent-reauthentication-request/" + + version + + "\n" + "requestId=" + requestId + "\naccountId=" @@ -284,6 +317,7 @@ static byte[] requestPayload(UUID requestId, UUID accountId, String purpose, UUI + "\ncreationOperationId=" + operationId + "\n"; + if (billingContext != null) payload += "billingContextDigest=" + billingContext.digest() + "\n"; return payload.getBytes(StandardCharsets.UTF_8); } @@ -315,9 +349,10 @@ private static AccountRecentReauthenticationEvidence map(Record row) { UUID operationId = required(row, "creation_operation_id", UUID.class); byte[] payload = required(row, "request_payload", byte[].class); String requestDigest = required(row, "request_digest", String.class); + AccountRecentReauthenticationEvidence.BillingContext context = billingContext(row, accountId); if (!requestDigest.equals(digest(payload)) || !java.util.Arrays.equals( - payload, requestPayload(requestId, accountId, purpose, operationId))) { + payload, requestPayload(requestId, accountId, purpose, operationId, context))) { throw unavailable(); } OffsetDateTime issuedAt = required(row, "issued_at", OffsetDateTime.class); @@ -341,7 +376,8 @@ payload, requestPayload(requestId, accountId, purpose, operationId))) { required(row, "effective_policy_version", String.class), requiredPositive(row, "recent_age_seconds"), requiredNonnegative(row, "max_clock_skew_seconds"), - issuedAt.toInstant()); + issuedAt.toInstant(), + context); } catch (IllegalArgumentException | IllegalStateException malformed) { throw unavailable(); } @@ -367,7 +403,82 @@ private static boolean sameEvidence( && first.effectivePolicyVersion().equals(second.effectivePolicyVersion()) && first.recentAgeSeconds() == second.recentAgeSeconds() && first.maxClockSkewSeconds() == second.maxClockSkewSeconds() - && first.issuedAt().equals(second.issuedAt()); + && first.issuedAt().equals(second.issuedAt()) + && Objects.equals(first.billingContext(), second.billingContext()); + } + + private static AccountRecentReauthenticationEvidence.BillingContext billingContext( + Record row, UUID accountId) { + UUID subscriptionId = row.get("billing_context_subscription_id", UUID.class); + UUID originalRequestId = row.get("billing_context_original_request_id", UUID.class); + String tupleDigest = row.get("billing_context_tuple_digest", String.class); + Long expectedRowVersion = row.get("billing_context_expected_row_version", Long.class); + OffsetDateTime expiresAt = row.get("billing_context_invoice_expires_at", OffsetDateTime.class); + UUID authorizationRequestId = row.get("billing_context_authorization_request_id", UUID.class); + Long expectedAuthorizationVersion = + row.get("billing_context_expected_authorization_version", Long.class); + String authorizationPurpose = row.get("billing_context_authorization_purpose", String.class); + String digest = row.get("billing_context_digest", String.class); + Object[] fields = { + subscriptionId, + originalRequestId, + tupleDigest, + expectedRowVersion, + expiresAt, + authorizationRequestId, + expectedAuthorizationVersion, + authorizationPurpose, + digest + }; + boolean any = java.util.Arrays.stream(fields).anyMatch(Objects::nonNull); + if (!any) return null; + if (java.util.Arrays.stream(fields).anyMatch(Objects::isNull)) throw unavailable(); + try { + var context = + new AccountRecentReauthenticationEvidence.BillingContext( + accountId, + subscriptionId, + originalRequestId, + tupleDigest, + expectedRowVersion, + expiresAt.toInstant(), + authorizationRequestId, + expectedAuthorizationVersion, + AccountRecentReauthenticationEvidence.BillingAuthorizationPurpose.valueOf( + authorizationPurpose)); + if (!context.digest().equals(digest)) throw unavailable(); + return context; + } catch (IllegalArgumentException malformed) { + throw unavailable(); + } + } + + private static Object contextValue( + AccountRecentReauthenticationEvidence evidence, BillingField field) { + var context = evidence.billingContext(); + if (context == null) return null; + return switch (field) { + case SUBSCRIPTION_ID -> context.subscriptionId(); + case ORIGINAL_REQUEST_ID -> context.originalRequestId(); + case TUPLE_DIGEST -> context.tupleDigest(); + case EXPECTED_ROW_VERSION -> context.expectedRowVersion(); + case INVOICE_EXPIRES_AT -> + OffsetDateTime.ofInstant(context.invoiceExpiresAt(), ZoneOffset.UTC); + case AUTHORIZATION_REQUEST_ID -> context.authorizationRequestId(); + case EXPECTED_AUTHORIZATION_VERSION -> context.expectedAuthorizationVersion(); + case AUTHORIZATION_PURPOSE -> context.authorizationPurpose().name(); + }; + } + + private enum BillingField { + SUBSCRIPTION_ID, + ORIGINAL_REQUEST_ID, + TUPLE_DIGEST, + EXPECTED_ROW_VERSION, + INVOICE_EXPIRES_AT, + AUTHORIZATION_REQUEST_ID, + EXPECTED_AUTHORIZATION_VERSION, + AUTHORIZATION_PURPOSE } private static long requiredPositive(Record row, String field) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationService.java index 038424413b..a4e278d077 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationService.java @@ -13,6 +13,9 @@ import java.util.Objects; import java.util.Optional; import java.util.UUID; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; @@ -23,6 +26,7 @@ import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl.BillingPrimaryVerification; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl.ControlUiPrimaryIdentity; import net.firedevops.firemud.common.EmailCanonicalization; import org.springframework.transaction.PlatformTransactionManager; @@ -35,7 +39,6 @@ * Account's existing real primary-authentication producer and creates no token, route or session. */ public final class AccountRecentReauthenticationService { - private static final String PURPOSE = AccountRecentReauthenticationPolicy.PURPOSE; private final AccountServiceImpl primaryAuthentication; private final AccountRepository accounts; private final AccountAuthorityGenerationRepository generations; @@ -75,6 +78,58 @@ public AccountRecentReauthenticationService( * exact Account/action/creation-operation evidence in the same writable owner transaction. */ public AccountRecentReauthenticationEvidence reauthenticate(Request request) { + requireRequest(request); + if (!AccountRecentReauthenticationPolicy.PURPOSE.equals(request.purpose)) throw conflict(); + return reauthenticate( + request, + action -> transaction.execute(ignored -> action.get()), + account -> + primaryAuthentication.authenticateControlUiPrimaryIdentity( + EmailCanonicalization.normalize(request.email), request.secret)); + } + + AccountRecentReauthenticationEvidence reauthenticateAndBindBilling( + Request request, + AccountControlUiActorService actors, + String bearer, + Consumer bind) { + requireRequest(request); + if (!AccountRecentReauthenticationPolicy.BILLING_PURPOSE.equals(request.purpose) + || request.billingContext == null) throw conflict(); + // Exact retained retries authenticate against the existing request MAC. Fresh requests + // perform the expensive verifier before taking the shared producer locks. + boolean retained = + Boolean.TRUE.equals( + transaction.execute( + ignored -> evidenceRepository.findByRequest(request.requestId).isPresent())); + BillingPrimaryVerification verification = + retained + ? null + : primaryAuthentication.preverifyBillingPrimaryCredential( + request.accountId, EmailCanonicalization.normalize(request.email), request.secret); + return reauthenticate( + request, + action -> + actors.withCurrentAccount( + bearer, + actor -> { + if (!request.accountId.equals(actor.accountId())) throw conflict(); + Attempt attempt = action.get(); + if (attempt.denial == null) { + var evidence = + requireCurrentBillingEvidenceLocked( + attempt.evidence.evidenceId(), + actor.accountId(), + request.creationOperationId); + bind.accept(evidence); + actors.requireCurrentOriginalToken(actor); + } + return attempt; + }), + account -> primaryAuthentication.applyBillingPrimaryVerification(account, verification)); + } + + private static void requireRequest(Request request) { Objects.requireNonNull(request, "Account reauthentication request is required"); if (TransactionSynchronizationManager.isActualTransactionActive()) { throw new IllegalStateException("Recent reauthentication must own its Account transaction"); @@ -94,12 +149,21 @@ public AccountRecentReauthenticationEvidence reauthenticate(Request request) { || request.secret.length() > 1024) { throw new IllegalArgumentException("Bounded Account reauthentication request is required"); } + } + private AccountRecentReauthenticationEvidence reauthenticate( + Request request, + Function, Attempt> retainInOwnerTransaction, + Function authenticate) { byte[] credentialRequest = credentialRequest(request); Attempt attempt; try { attempt = - transaction.execute(ignored -> { + retainInOwnerTransaction.apply(() -> { + // Match billing's Account-before-request lock order. Validate the locked row only + // for new evidence so exact historical game-creation replay keeps its semantics. + Optional lockedAccount = + accounts.findByAccountUuidForUpdate(request.accountId); evidenceRepository.lockRequest(request.requestId); Optional existingRequest = evidenceRepository.findByRequest(request.requestId); @@ -108,7 +172,11 @@ public AccountRecentReauthenticationEvidence reauthenticate(Request request) { requireExactRequest(existing, request); return replayAttempt(existing, credentialRequest); } - if (!PURPOSE.equals(request.purpose)) { + if (!AccountRecentReauthenticationPolicy.supportedPurpose(request.purpose)) { + throw conflict(); + } + if (AccountRecentReauthenticationPolicy.BILLING_PURPOSE.equals(request.purpose) + && request.billingContext == null) { throw conflict(); } @@ -122,8 +190,10 @@ public AccountRecentReauthenticationEvidence reauthenticate(Request request) { // Resolve and lock the current policy before primary authentication. Missing policy // therefore cannot consume an OTP or commit a new authentication grant. AccountRecentReauthenticationPolicy.Effective policy = - policyRepository.resolveCurrentForGameCreation(); - Account account = requireCurrentAccount(request.accountId); + AccountRecentReauthenticationPolicy.PURPOSE.equals(request.purpose) + ? policyRepository.resolveCurrentForGameCreation() + : policyRepository.resolveCurrentForPurpose(request.purpose); + Account account = requireCurrentAccount(request.accountId, lockedAccount); String email = EmailCanonicalization.normalize(request.email); if (!email.equals(EmailCanonicalization.normalize(account.getEmail()))) { throw conflict(); @@ -131,8 +201,7 @@ public AccountRecentReauthenticationEvidence reauthenticate(Request request) { ControlUiPrimaryIdentity authenticated; try { - authenticated = - primaryAuthentication.authenticateControlUiPrimaryIdentity(email, request.secret); + authenticated = authenticate.apply(account); } catch (AuthenticationException denied) { // Return the denial from the transaction callback so normal failed-attempt // accounting commits. A successful OTP remains rollback-capable with retention. @@ -152,7 +221,8 @@ public AccountRecentReauthenticationEvidence reauthenticate(Request request) { request.requestId, request.accountId, request.purpose, - request.creationOperationId); + request.creationOperationId, + request.billingContext); var evidence = new AccountRecentReauthenticationEvidence( UUID.randomUUID(), @@ -173,7 +243,8 @@ public AccountRecentReauthenticationEvidence reauthenticate(Request request) { policy.effectivePolicyVersion(), policy.recentAgeSeconds(), policy.maxClockSkewSeconds(), - issuedAt); + issuedAt, + request.billingContext); String keyId = cryptography.currentKeyId(); var replayProof = new AccountRecentReauthenticationRepository.ReplayProof( @@ -189,24 +260,24 @@ public AccountRecentReauthenticationEvidence reauthenticate(Request request) { throw new AuthenticationException(attempt.denial.code, attempt.denial.message); } var expected = Objects.requireNonNull(attempt.evidence); - Attempt readback = + var readback = transaction.execute(ignored -> { evidenceRepository.lockRequest(expected.requestId()); var retained = evidenceRepository.readExactOriginal(expected); - return replayAttempt(retained, credentialRequest); + if (!replayCredentialsMatch(retained, credentialRequest)) { + throw unavailable(); + } + return retained; }); if (readback == null) throw unavailable(); - if (readback.denial != null) { - throw new AuthenticationException(readback.denial.code, readback.denial.message); - } - return Objects.requireNonNull(readback.evidence); + return readback; } finally { Arrays.fill(credentialRequest, (byte) 0); } } - // Both callers hold the original request lock. Denials leave the callback as values so the - // independent failure history commits before any exception reaches the caller. + // Public replay holds the original request lock. Credential denials leave the callback as + // values so the failed-attempt history commits before any exception reaches the caller. private Attempt replayAttempt(AccountRecentReauthenticationEvidence evidence, byte[] request) { if (evidenceRepository.countReplayFailures(evidence) >= 5) { return Attempt.denied("INVALID_CREDENTIALS", "Invalid credentials"); @@ -240,7 +311,11 @@ private boolean replayCredentialsMatch( private static byte[] credentialRequest(Request request) { byte[] identity = AccountRecentReauthenticationRepository.requestPayload( - request.requestId, request.accountId, request.purpose, request.creationOperationId); + request.requestId, + request.accountId, + request.purpose, + request.creationOperationId, + request.billingContext); byte[] email = new byte[0]; byte[] secret = new byte[0]; try { @@ -332,7 +407,7 @@ private AccountRecentReauthenticationEvidence lockExactBinding( Objects.requireNonNull(presented, "Typed Account reauthentication evidence is required"); requireNonNilUuid(expectedAccountId, "expected Account identity"); requireNonNilUuid(expectedCreationOperationId, "expected creation operation ID"); - if (!PURPOSE.equals(expectedPurpose)) { + if (!AccountRecentReauthenticationPolicy.supportedPurpose(expectedPurpose)) { throw conflict(); } @@ -345,6 +420,22 @@ private AccountRecentReauthenticationEvidence lockExactBinding( return evidence; } + /** + * Current billing proof, including a previous exact one-time consumption, never game creation. + */ + public AccountRecentReauthenticationEvidence requireCurrentBillingEvidenceLocked( + UUID evidenceId, UUID accountId, UUID operationId) { + var retained = + evidenceRepository + .findByEvidenceId(evidenceId) + .orElseThrow(AccountRecentReauthenticationService::unavailable); + var exact = + lockExactBinding( + retained, accountId, AccountRecentReauthenticationPolicy.BILLING_PURPOSE, operationId); + requireCurrentEvidence(exact); + return exact; + } + private void requireCurrentEvidence(AccountRecentReauthenticationEvidence evidence) { Account account = requireCurrentAccount(evidence.accountId()); if (account.getAccountUuidProvenance() != evidence.identityProvenance() @@ -365,7 +456,9 @@ private void requireCurrentEvidence(AccountRecentReauthenticationEvidence eviden } AccountRecentReauthenticationPolicy.Effective policy = - policyRepository.resolveCurrentForGameCreation(); + AccountRecentReauthenticationPolicy.PURPOSE.equals(evidence.purpose()) + ? policyRepository.resolveCurrentForGameCreation() + : policyRepository.resolveCurrentForPurpose(evidence.purpose()); if (policy.platformVersion() != evidence.platformPolicyVersion() || policy.deploymentVersion() != evidence.deploymentPolicyVersion() || !policy.effectivePolicyVersion().equals(evidence.effectivePolicyVersion()) @@ -377,10 +470,11 @@ private void requireCurrentEvidence(AccountRecentReauthenticationEvidence eviden } private Account requireCurrentAccount(UUID accountId) { - Account account = - accounts - .findByAccountUuidForUpdate(accountId) - .orElseThrow(AccountRecentReauthenticationService::unavailable); + return requireCurrentAccount(accountId, accounts.findByAccountUuidForUpdate(accountId)); + } + + private static Account requireCurrentAccount(UUID accountId, Optional lockedAccount) { + Account account = lockedAccount.orElseThrow(AccountRecentReauthenticationService::unavailable); if (account.getId() == null || account.getId() <= 0L || !accountId.equals(account.getAccountUuid()) @@ -410,7 +504,11 @@ private static void requireExactRequest( AccountRecentReauthenticationEvidence evidence, Request request) { byte[] payload = AccountRecentReauthenticationRepository.requestPayload( - request.requestId, request.accountId, request.purpose, request.creationOperationId); + request.requestId, + request.accountId, + request.purpose, + request.creationOperationId, + request.billingContext); if (!evidence.requestId().equals(request.requestId) || !evidence.accountId().equals(request.accountId) || !evidence.purpose().equals(request.purpose) @@ -420,6 +518,7 @@ private static void requireExactRequest( .equals(AccountRecentReauthenticationRepository.digest(payload))) { throw conflict(); } + if (!Objects.equals(evidence.billingContext(), request.billingContext)) throw conflict(); } private static void requireNonNilUuid(UUID value, String field) { @@ -450,6 +549,7 @@ public static final class Request { private final UUID accountId; private final String purpose; private final UUID creationOperationId; + private final AccountRecentReauthenticationEvidence.BillingContext billingContext; private final String email; private final String secret; @@ -460,12 +560,30 @@ public Request( UUID creationOperationId, String email, String secret) { + this(requestId, accountId, purpose, creationOperationId, null, email, secret); + } + + public Request( + UUID requestId, + UUID accountId, + String purpose, + UUID creationOperationId, + AccountRecentReauthenticationEvidence.BillingContext billingContext, + String email, + String secret) { this.requestId = requestId; this.accountId = accountId; this.purpose = purpose; this.creationOperationId = creationOperationId; + this.billingContext = billingContext; this.email = email; this.secret = secret; + if (billingContext != null + && (!AccountRecentReauthenticationPolicy.BILLING_PURPOSE.equals(purpose) + || !Objects.equals(accountId, billingContext.accountId()) + || !Objects.equals(creationOperationId, billingContext.authorizationRequestId()))) { + throw new IllegalArgumentException("Typed billing context differs from Account request"); + } } @Override diff --git a/services/account-service/src/main/resources/application-prod.yml b/services/account-service/src/main/resources/application-prod.yml index 398e261710..1d9d619c58 100644 --- a/services/account-service/src/main/resources/application-prod.yml +++ b/services/account-service/src/main/resources/application-prod.yml @@ -126,3 +126,6 @@ server: enabled: true mime-types: application/json,application/xml,text/html,text/xml,text/plain min-response-size: 1024 + +# First-invoice checkout remains deliberately unregistered. Its explicit composition requires +# protected webhook custody and versioned billing policies; no payment or route is enabled here. diff --git a/services/account-service/src/main/resources/application.yml b/services/account-service/src/main/resources/application.yml index f7437be265..61e4302487 100644 --- a/services/account-service/src/main/resources/application.yml +++ b/services/account-service/src/main/resources/application.yml @@ -150,3 +150,6 @@ server: enabled: true mime-types: application/json,application/xml,text/html,text/xml,text/plain min-response-size: 1024 + +# First-invoice checkout remains deliberately unregistered. Its explicit composition requires +# protected webhook custody and versioned billing policies; no payment or route is enabled here. diff --git a/services/account-service/src/main/resources/db/migration/V1041__hosting_first_invoice_completion.sql b/services/account-service/src/main/resources/db/migration/V1041__hosting_first_invoice_completion.sql new file mode 100644 index 0000000000..b579626f52 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1041__hosting_first_invoice_completion.sql @@ -0,0 +1,545 @@ +-- Held Account-owned existing first-invoice checkout. No registration, payment or entitlement is +-- authorized by this migration. Provider/reauth policy rows are deliberately not seeded. +CREATE TABLE account_billing_reauthentication_policy_values ( + policy_scope VARCHAR(16) NOT NULL CHECK (policy_scope IN ('PLATFORM', 'DEPLOYMENT')), + policy_version BIGINT NOT NULL CHECK (policy_version > 0), + recent_age_seconds BIGINT NOT NULL CHECK (recent_age_seconds BETWEEN 1 AND 300), + max_clock_skew_seconds BIGINT NOT NULL CHECK (max_clock_skew_seconds BETWEEN 0 AND 30), + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + CHECK (max_clock_skew_seconds < recent_age_seconds), + PRIMARY KEY (policy_scope, policy_version) +); + +CREATE TABLE account_billing_reauthentication_policy_current ( + policy_scope VARCHAR(16) PRIMARY KEY CHECK (policy_scope IN ('PLATFORM', 'DEPLOYMENT')), + policy_version BIGINT NOT NULL CHECK (policy_version > 0), + FOREIGN KEY (policy_scope, policy_version) + REFERENCES account_billing_reauthentication_policy_values(policy_scope, policy_version) + ON DELETE RESTRICT +); + +CREATE TABLE account_hosting_billing_policy_values ( + provider_price_id VARCHAR(255) NOT NULL CHECK (provider_price_id ~ '^price_[A-Za-z0-9]+$'), + policy_version BIGINT NOT NULL CHECK (policy_version > 0), + quantity BIGINT NOT NULL CHECK (quantity > 0), + amount BIGINT NOT NULL CHECK (amount > 0), + currency VARCHAR(3) NOT NULL CHECK (currency ~ '^[a-z]{3}$'), + PRIMARY KEY (provider_price_id, policy_version) +); +CREATE TABLE account_hosting_billing_policy_current ( + provider_price_id VARCHAR(255) PRIMARY KEY, + policy_version BIGINT NOT NULL, + FOREIGN KEY (provider_price_id, policy_version) REFERENCES account_hosting_billing_policy_values ON DELETE RESTRICT +); +CREATE TABLE subscription_first_invoices ( + subscription_id UUID PRIMARY KEY REFERENCES subscription(subscription_id) ON DELETE RESTRICT, + creation_request_id UUID NOT NULL UNIQUE REFERENCES subscription_create_operations(request_id) ON DELETE RESTRICT, + tenant_id UUID NOT NULL, + account_uuid UUID NOT NULL REFERENCES accounts(account_uuid) ON DELETE RESTRICT, + payment_instrument_id UUID NOT NULL REFERENCES payment_instrument(instrument_uuid) ON DELETE RESTRICT, + instrument_version BIGINT NOT NULL CHECK (instrument_version > 0), + provider_subscription_id VARCHAR(255) NOT NULL UNIQUE, + provider_customer_id VARCHAR(255) NOT NULL, + provider_payment_method_id VARCHAR(255) NOT NULL, + invoice_id VARCHAR(255) NOT NULL UNIQUE CHECK (invoice_id ~ '^in_[A-Za-z0-9]+$'), + payment_intent_id VARCHAR(255) NOT NULL UNIQUE CHECK (payment_intent_id ~ '^pi_[A-Za-z0-9]+$'), + amount BIGINT NOT NULL CHECK (amount > 0), + currency VARCHAR(3) NOT NULL CHECK (currency ~ '^[a-z]{3}$'), + quote_digest VARCHAR(71) NOT NULL, + provider_price_id VARCHAR(255) NOT NULL CHECK (provider_price_id ~ '^price_[A-Za-z0-9]+$'), + provider_quantity BIGINT NOT NULL CHECK (provider_quantity > 0), + billing_policy_version BIGINT NOT NULL CHECK (billing_policy_version > 0), + billing_policy_digest VARCHAR(71) NOT NULL, + livemode BOOLEAN NOT NULL, + captured_at TIMESTAMPTZ NOT NULL, + expires_at TIMESTAMPTZ NOT NULL CHECK (expires_at > captured_at), + tuple_digest VARCHAR(71) NOT NULL CHECK (tuple_digest ~ '^sha256:[0-9a-f]{64}$'), + UNIQUE (subscription_id, tuple_digest), + FOREIGN KEY (provider_price_id, billing_policy_version) REFERENCES account_hosting_billing_policy_values(provider_price_id, policy_version) ON DELETE RESTRICT, + FOREIGN KEY (provider_subscription_id, subscription_id) REFERENCES subscription_provider_history(provider_subscription_id, subscription_id) ON DELETE RESTRICT +); +CREATE TABLE subscription_first_invoice_confirmations ( + request_id UUID PRIMARY KEY CHECK (request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + subscription_id UUID NOT NULL UNIQUE, + account_uuid UUID NOT NULL REFERENCES accounts(account_uuid) ON DELETE RESTRICT, + tuple_digest VARCHAR(71) NOT NULL, + expected_row_version BIGINT NOT NULL CHECK (expected_row_version > 0), + reauthentication_evidence_id UUID NOT NULL UNIQUE REFERENCES account_recent_reauthentication_consumptions(evidence_id) ON DELETE RESTRICT, + provider_idempotency_id UUID NOT NULL UNIQUE, + lifecycle_request_id UUID NOT NULL UNIQUE, + audit_event_id UUID NOT NULL UNIQUE, + consented_at TIMESTAMPTZ NOT NULL, + valid_until TIMESTAMPTZ NOT NULL CHECK (valid_until > consented_at), + created_transaction_id BIGINT NOT NULL DEFAULT txid_current(), + CHECK (request_id <> provider_idempotency_id AND request_id <> lifecycle_request_id AND provider_idempotency_id <> lifecycle_request_id), + FOREIGN KEY (subscription_id, tuple_digest) REFERENCES subscription_first_invoices(subscription_id, tuple_digest) ON DELETE RESTRICT, + UNIQUE (request_id, subscription_id, tuple_digest), + UNIQUE (request_id, subscription_id) +); +CREATE TABLE subscription_first_invoice_dispatches ( + request_id UUID PRIMARY KEY, + subscription_id UUID NOT NULL UNIQUE, + authorized_at TIMESTAMPTZ NOT NULL, + created_transaction_id BIGINT NOT NULL DEFAULT txid_current(), + FOREIGN KEY (request_id, subscription_id) REFERENCES subscription_first_invoice_confirmations(request_id, subscription_id) ON DELETE RESTRICT, + UNIQUE (request_id, subscription_id) +); +-- Authorization attempts are append-only; the original payment/consent/idempotency tuple never +-- changes. Only a newly created current attempt can win the sole durable command claim. +CREATE TABLE subscription_first_invoice_authorizations ( + authorization_request_id UUID PRIMARY KEY CHECK (authorization_request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + request_id UUID NOT NULL, + subscription_id UUID NOT NULL, + authorization_version BIGINT NOT NULL CHECK (authorization_version > 0), + reauthentication_evidence_id UUID NOT NULL UNIQUE REFERENCES account_recent_reauthentication_consumptions(evidence_id) ON DELETE RESTRICT, + consented_at TIMESTAMPTZ NOT NULL, + valid_until TIMESTAMPTZ NOT NULL CHECK (valid_until > consented_at), + created_transaction_id BIGINT NOT NULL DEFAULT txid_current(), + FOREIGN KEY (request_id, subscription_id) REFERENCES subscription_first_invoice_dispatches(request_id, subscription_id) ON DELETE RESTRICT, + UNIQUE (subscription_id, authorization_version), + UNIQUE (authorization_request_id, request_id, subscription_id) +); +CREATE TABLE subscription_first_invoice_command_claims ( + request_id UUID PRIMARY KEY, + subscription_id UUID NOT NULL UNIQUE, + authorization_request_id UUID NOT NULL UNIQUE, + claimed_at TIMESTAMPTZ NOT NULL, + created_transaction_id BIGINT NOT NULL DEFAULT txid_current(), + FOREIGN KEY (authorization_request_id, request_id, subscription_id) REFERENCES subscription_first_invoice_authorizations(authorization_request_id, request_id, subscription_id) ON DELETE RESTRICT +); +CREATE TABLE subscription_first_invoice_success_evidence ( + request_id UUID PRIMARY KEY, + subscription_id UUID NOT NULL UNIQUE, + provider_event_id VARCHAR(255) NOT NULL REFERENCES stripe_event_inbox(provider_event_id) ON DELETE RESTRICT, + event_payload_digest VARCHAR(71) NOT NULL, + tuple_digest VARCHAR(71) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + FOREIGN KEY (request_id, subscription_id) REFERENCES subscription_first_invoice_dispatches(request_id, subscription_id) ON DELETE RESTRICT, + FOREIGN KEY (request_id, subscription_id, tuple_digest) REFERENCES subscription_first_invoice_confirmations(request_id, subscription_id, tuple_digest) ON DELETE RESTRICT, + UNIQUE (request_id, subscription_id) +); +CREATE TABLE subscription_first_invoice_completions ( + subscription_id UUID PRIMARY KEY, + request_id UUID NOT NULL UNIQUE, + lifecycle_request_id UUID NOT NULL UNIQUE REFERENCES subscription_lifecycle_receipts(request_id) DEFERRABLE INITIALLY DEFERRED, + tuple_digest VARCHAR(71) NOT NULL, + receipt_digest VARCHAR(71) NOT NULL, + audit_event_id UUID NOT NULL UNIQUE REFERENCES account_audit_outbox(audit_event_id) ON DELETE RESTRICT, + committed_at TIMESTAMPTZ NOT NULL, + committed_transaction_id BIGINT NOT NULL DEFAULT txid_current(), + FOREIGN KEY (request_id, subscription_id) REFERENCES subscription_first_invoice_success_evidence(request_id, subscription_id) ON DELETE RESTRICT +); +-- [jooq ignore start] +CREATE FUNCTION account_first_invoice_authorization_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE consent subscription_first_invoice_confirmations%ROWTYPE; auth account_recent_reauthentication_evidence%ROWTYPE; invoice subscription_first_invoices%ROWTYPE; current_row RECORD; latest BIGINT; +BEGIN + SELECT s.status, s.row_version, s.provider_subscription_id, w.phase INTO STRICT current_row + FROM subscription s JOIN subscription_provisioning_work w ON w.subscription_id = s.subscription_id + WHERE s.subscription_id = NEW.subscription_id AND s.superseded_at IS NULL FOR UPDATE OF s; + SELECT * INTO STRICT consent FROM subscription_first_invoice_confirmations WHERE request_id = NEW.request_id; + SELECT * INTO STRICT invoice FROM subscription_first_invoices WHERE subscription_id = NEW.subscription_id; + SELECT * INTO STRICT auth FROM account_recent_reauthentication_evidence WHERE evidence_id = NEW.reauthentication_evidence_id; + SELECT COALESCE(MAX(authorization_version), 0) INTO latest FROM subscription_first_invoice_authorizations WHERE subscription_id = NEW.subscription_id; + IF consent.subscription_id <> NEW.subscription_id OR current_row.status <> 'provisioning' OR current_row.phase <> 'AWAITING_PAYMENT' + OR current_row.row_version <> consent.expected_row_version OR current_row.provider_subscription_id <> invoice.provider_subscription_id + OR NEW.authorization_version <> latest + 1 + OR (NEW.authorization_version = 1 AND (NEW.authorization_request_id <> NEW.request_id OR NEW.reauthentication_evidence_id <> consent.reauthentication_evidence_id OR consent.created_transaction_id <> txid_current())) + OR (NEW.authorization_version > 1 AND NEW.authorization_request_id = NEW.request_id) + OR auth.account_uuid <> consent.account_uuid OR auth.purpose <> 'HOSTING_FIRST_INVOICE_PAYMENT' + OR auth.creation_operation_id <> NEW.authorization_request_id + OR NEW.consented_at < auth.issued_at OR NEW.consented_at >= NEW.valid_until + OR NEW.valid_until > invoice.expires_at + OR NEW.valid_until > auth.issued_at + (auth.recent_age_seconds - auth.max_clock_skew_seconds) * INTERVAL '1 second' + OR NOT EXISTS (SELECT 1 FROM account_recent_reauthentication_consumptions c WHERE c.evidence_id = auth.evidence_id AND c.creation_operation_id = NEW.authorization_request_id AND c.account_uuid = consent.account_uuid AND c.purpose = auth.purpose) THEN + RAISE EXCEPTION 'First-invoice authorization requires fresh exact consumed consent and current version' USING ERRCODE = '23514'; + END IF; + NEW.created_transaction_id := txid_current(); + RETURN NEW; +END; +$$; +CREATE TRIGGER first_invoice_authorization BEFORE INSERT ON subscription_first_invoice_authorizations + FOR EACH ROW EXECUTE FUNCTION account_first_invoice_authorization_guard(); +CREATE FUNCTION account_first_invoice_command_claim_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE auth subscription_first_invoice_authorizations%ROWTYPE; consent subscription_first_invoice_confirmations%ROWTYPE; current_row RECORD; latest BIGINT; +BEGIN + SELECT * INTO STRICT auth FROM subscription_first_invoice_authorizations WHERE authorization_request_id = NEW.authorization_request_id; + SELECT * INTO STRICT consent FROM subscription_first_invoice_confirmations WHERE request_id = NEW.request_id; + SELECT s.status, s.row_version, w.phase INTO STRICT current_row FROM subscription s + JOIN subscription_provisioning_work w ON w.subscription_id = s.subscription_id + WHERE s.subscription_id = NEW.subscription_id AND s.superseded_at IS NULL FOR UPDATE OF s; + SELECT MAX(authorization_version) INTO latest FROM subscription_first_invoice_authorizations WHERE subscription_id = NEW.subscription_id; + IF auth.authorization_version <> latest OR auth.created_transaction_id = txid_current() + OR current_row.status <> 'provisioning' OR current_row.phase <> 'AWAITING_PAYMENT' OR current_row.row_version <> consent.expected_row_version + OR NEW.claimed_at < auth.consented_at OR NEW.claimed_at >= auth.valid_until THEN + RAISE EXCEPTION 'First-invoice command requires independently read latest unexpired authorization' USING ERRCODE = '23514'; + END IF; + NEW.created_transaction_id := txid_current(); + RETURN NEW; +END; +$$; +CREATE TRIGGER first_invoice_command_claim BEFORE INSERT ON subscription_first_invoice_command_claims + FOR EACH ROW EXECUTE FUNCTION account_first_invoice_command_claim_guard(); +CREATE TRIGGER first_invoice_authorizations_immutable BEFORE UPDATE OR DELETE ON subscription_first_invoice_authorizations + FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER first_invoice_authorizations_no_truncate BEFORE TRUNCATE ON subscription_first_invoice_authorizations + FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER first_invoice_command_claims_immutable BEFORE UPDATE OR DELETE ON subscription_first_invoice_command_claims + FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER first_invoice_command_claims_no_truncate BEFORE TRUNCATE ON subscription_first_invoice_command_claims + FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +ALTER TABLE subscription_first_invoices ADD CONSTRAINT first_invoice_expiry_bound CHECK (expires_at <= captured_at + INTERVAL '23 hours'); +ALTER TABLE account_recent_reauthentication_evidence DROP CONSTRAINT account_recent_reauthentication_evidence_purpose_check; +ALTER TABLE account_recent_reauthentication_evidence ADD CONSTRAINT account_recent_reauthentication_evidence_purpose_check CHECK (purpose IN ('SELF_SERVICE_GAME_CREATION','HOSTING_FIRST_INVOICE_PAYMENT')); +ALTER TABLE account_recent_reauthentication_consumptions DROP CONSTRAINT account_recent_reauthentication_consumptions_purpose_check; +ALTER TABLE account_recent_reauthentication_consumptions ADD CONSTRAINT account_recent_reauthentication_consumptions_purpose_check CHECK (purpose IN ('SELF_SERVICE_GAME_CREATION','HOSTING_FIRST_INVOICE_PAYMENT')); +-- PostgreSQL truncates generated relation/column constraint names differently from SQL identifiers. +-- Resolve the one existing purpose-column check rather than assuming its truncated name. +DO $$ +DECLARE existing_check TEXT; +BEGIN + SELECT constraint_row.conname INTO STRICT existing_check FROM pg_constraint constraint_row + WHERE constraint_row.conrelid = 'account_recent_reauthentication_replay_credentials'::REGCLASS + AND constraint_row.contype = 'c' + AND constraint_row.conkey = ARRAY[(SELECT attnum FROM pg_attribute + WHERE attrelid = constraint_row.conrelid AND attname = 'purpose')]::SMALLINT[]; + EXECUTE format('ALTER TABLE account_recent_reauthentication_replay_credentials DROP CONSTRAINT %I', existing_check); +END; +$$; +ALTER TABLE account_recent_reauthentication_replay_credentials ADD CONSTRAINT billing_reauth_replay_credentials_purpose_check CHECK (purpose IN ('SELF_SERVICE_GAME_CREATION','HOSTING_FIRST_INVOICE_PAYMENT')); +ALTER TABLE account_recent_reauthentication_replay_failures DROP CONSTRAINT account_recent_reauthentication_replay_failures_purpose_check; +ALTER TABLE account_recent_reauthentication_replay_failures ADD CONSTRAINT account_recent_reauthentication_replay_failures_purpose_check CHECK (purpose IN ('SELF_SERVICE_GAME_CREATION','HOSTING_FIRST_INVOICE_PAYMENT')); +CREATE OR REPLACE FUNCTION account_recent_reauthentication_evidence_source_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + account_row RECORD; + generation_row RECORD; + fence_row RECORD; + platform_row RECORD; + deployment_row RECORD; + effective_age BIGINT; + effective_skew BIGINT; + policy_preimage TEXT; + expected_policy_version TEXT; +BEGIN + SELECT id, account_uuid, account_uuid_provenance, account_uuid_source_numeric_id, lifecycle_state + INTO account_row FROM accounts WHERE account_uuid = NEW.account_uuid FOR SHARE; + IF NOT FOUND OR account_row.account_uuid IS DISTINCT FROM NEW.account_uuid + OR account_row.id IS DISTINCT FROM NEW.account_uuid_source_numeric_id + OR account_row.account_uuid_provenance IS DISTINCT FROM NEW.identity_provenance + OR account_row.lifecycle_state IS DISTINCT FROM 'active' THEN + RAISE EXCEPTION 'Recent reauthentication requires the exact current active Account identity' + USING ERRCODE = '23514'; + END IF; + + SELECT generation, source_version INTO generation_row + FROM account_authority_generations + WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid FOR SHARE; + SELECT issuance_fence, source_version INTO fence_row + FROM account_authority_issuance_fences + WHERE account_uuid = NEW.account_uuid FOR SHARE; + IF NOT FOUND OR generation_row.generation IS DISTINCT FROM NEW.account_authority_generation + OR generation_row.source_version IS DISTINCT FROM NEW.account_authority_source_version + OR fence_row.issuance_fence IS DISTINCT FROM NEW.issuance_fence + OR fence_row.source_version IS DISTINCT FROM NEW.issuance_fence_source_version THEN + RAISE EXCEPTION 'Recent reauthentication Account authority source is stale' + USING ERRCODE = '23514'; + END IF; + + IF NEW.purpose = 'HOSTING_FIRST_INVOICE_PAYMENT' THEN + SELECT value.policy_version, value.recent_age_seconds, value.max_clock_skew_seconds + INTO platform_row + FROM account_billing_reauthentication_policy_current current + JOIN account_billing_reauthentication_policy_values value + ON value.policy_scope = current.policy_scope AND value.policy_version = current.policy_version + WHERE current.policy_scope = 'PLATFORM'; + SELECT value.policy_version, value.recent_age_seconds, value.max_clock_skew_seconds + INTO deployment_row + FROM account_billing_reauthentication_policy_current current + JOIN account_billing_reauthentication_policy_values value + ON value.policy_scope = current.policy_scope AND value.policy_version = current.policy_version + WHERE current.policy_scope = 'DEPLOYMENT'; + ELSE + SELECT value.policy_version, value.recent_age_seconds, value.max_clock_skew_seconds + INTO platform_row + FROM account_recent_reauthentication_policy_current current + JOIN account_recent_reauthentication_policy_values value + ON value.policy_scope = current.policy_scope AND value.policy_version = current.policy_version + WHERE current.policy_scope = 'PLATFORM'; + SELECT value.policy_version, value.recent_age_seconds, value.max_clock_skew_seconds + INTO deployment_row + FROM account_recent_reauthentication_policy_current current + JOIN account_recent_reauthentication_policy_values value + ON value.policy_scope = current.policy_scope AND value.policy_version = current.policy_version + WHERE current.policy_scope = 'DEPLOYMENT'; + END IF; + IF NOT FOUND OR platform_row.policy_version IS DISTINCT FROM NEW.platform_policy_version + OR deployment_row.policy_version IS DISTINCT FROM NEW.deployment_policy_version + OR deployment_row.recent_age_seconds > platform_row.recent_age_seconds + OR deployment_row.max_clock_skew_seconds > platform_row.max_clock_skew_seconds THEN + RAISE EXCEPTION 'Recent reauthentication policy source is missing, stale, or non-tightening' + USING ERRCODE = '23514'; + END IF; + effective_age := LEAST(platform_row.recent_age_seconds, deployment_row.recent_age_seconds); + effective_skew := LEAST(platform_row.max_clock_skew_seconds, deployment_row.max_clock_skew_seconds); + IF effective_skew >= effective_age + OR NEW.recent_age_seconds IS DISTINCT FROM effective_age + OR NEW.max_clock_skew_seconds IS DISTINCT FROM effective_skew THEN + RAISE EXCEPTION 'Recent reauthentication effective policy values are invalid' + USING ERRCODE = '23514'; + END IF; + + policy_preimage := 'account-recent-reauthentication-policy/v1' || E'\n' + || 'purpose=' || NEW.purpose || E'\n' + || 'platformVersion=' || platform_row.policy_version::TEXT || E'\n' + || 'platformRecentAgeSeconds=' || platform_row.recent_age_seconds::TEXT || E'\n' + || 'platformMaxClockSkewSeconds=' || platform_row.max_clock_skew_seconds::TEXT || E'\n' + || 'deploymentVersion=' || deployment_row.policy_version::TEXT || E'\n' + || 'deploymentRecentAgeSeconds=' || deployment_row.recent_age_seconds::TEXT || E'\n' + || 'deploymentMaxClockSkewSeconds=' || deployment_row.max_clock_skew_seconds::TEXT || E'\n' + || 'effectiveRecentAgeSeconds=' || effective_age::TEXT || E'\n' + || 'effectiveMaxClockSkewSeconds=' || effective_skew::TEXT || E'\n'; + expected_policy_version := 'sha256:' || encode(sha256(convert_to(policy_preimage, 'UTF8')), 'hex'); + IF NEW.effective_policy_version IS DISTINCT FROM expected_policy_version THEN + RAISE EXCEPTION 'Recent reauthentication effective policy version is invalid' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_billing_reauthentication_policy_values_immutable BEFORE UPDATE OR DELETE ON account_billing_reauthentication_policy_values FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER account_billing_reauthentication_policy_values_no_truncate BEFORE TRUNCATE ON account_billing_reauthentication_policy_values FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER account_billing_reauthentication_policy_current_no_delete BEFORE DELETE ON account_billing_reauthentication_policy_current FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER account_billing_reauthentication_policy_current_no_truncate BEFORE TRUNCATE ON account_billing_reauthentication_policy_current FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER account_hosting_billing_policy_values_immutable BEFORE UPDATE OR DELETE ON account_hosting_billing_policy_values FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER account_hosting_billing_policy_values_no_truncate BEFORE TRUNCATE ON account_hosting_billing_policy_values FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER account_hosting_billing_policy_current_no_delete BEFORE DELETE ON account_hosting_billing_policy_current FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER account_hosting_billing_policy_current_no_truncate BEFORE TRUNCATE ON account_hosting_billing_policy_current FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_first_invoices_immutable BEFORE UPDATE OR DELETE ON subscription_first_invoices FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_first_invoices_no_truncate BEFORE TRUNCATE ON subscription_first_invoices FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_first_invoice_confirmations_immutable BEFORE UPDATE OR DELETE ON subscription_first_invoice_confirmations FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_first_invoice_confirmations_no_truncate BEFORE TRUNCATE ON subscription_first_invoice_confirmations FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_first_invoice_success_evidence_immutable BEFORE UPDATE OR DELETE ON subscription_first_invoice_success_evidence FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_first_invoice_success_evidence_no_truncate BEFORE TRUNCATE ON subscription_first_invoice_success_evidence FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_first_invoice_completions_immutable BEFORE UPDATE OR DELETE ON subscription_first_invoice_completions FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_first_invoice_completions_no_truncate BEFORE TRUNCATE ON subscription_first_invoice_completions FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER account_billing_reauth_current_monotonic BEFORE UPDATE ON account_billing_reauthentication_policy_current + FOR EACH ROW EXECUTE FUNCTION account_recent_reauthentication_policy_current_guard(); +CREATE FUNCTION account_hosting_billing_policy_current_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.provider_price_id IS DISTINCT FROM OLD.provider_price_id OR NEW.policy_version <= OLD.policy_version THEN + RAISE EXCEPTION 'Hosting billing policy must advance monotonically' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER hosting_billing_current_monotonic BEFORE UPDATE ON account_hosting_billing_policy_current + FOR EACH ROW EXECUTE FUNCTION account_hosting_billing_policy_current_guard(); +CREATE FUNCTION account_first_invoice_source_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE current_row subscription%ROWTYPE; creation subscription_create_operations%ROWTYPE; wallet payment_instrument%ROWTYPE; commercial account_hosting_billing_policy_values%ROWTYPE; +BEGIN + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = NEW.subscription_id FOR UPDATE; + SELECT * INTO STRICT creation FROM subscription_create_operations WHERE request_id = current_row.creation_request_id; + SELECT * INTO STRICT wallet FROM payment_instrument WHERE instrument_uuid = current_row.payment_instrument_id; + SELECT * INTO STRICT commercial FROM account_hosting_billing_policy_values WHERE provider_price_id = NEW.provider_price_id AND policy_version = NEW.billing_policy_version; + IF current_row.status <> 'provisioning' OR current_row.superseded_at IS NOT NULL OR current_row.current_receipt_request_id IS NOT NULL + OR (NEW.provider_price_id, NEW.provider_quantity) IS DISTINCT FROM (creation.provider_price_id, creation.provider_quantity) + OR (NEW.provider_quantity, NEW.amount, NEW.currency) IS DISTINCT FROM (commercial.quantity, commercial.amount, commercial.currency) + OR (NEW.creation_request_id, NEW.tenant_id, NEW.account_uuid, NEW.payment_instrument_id, NEW.instrument_version, + NEW.provider_customer_id, NEW.provider_payment_method_id, NEW.quote_digest) + IS DISTINCT FROM (creation.request_id, creation.tenant_id, creation.account_uuid, creation.payment_instrument_id, + creation.reserved_instrument_version, creation.provider_customer_id, wallet.provider_payment_method_id, creation.plan_quote_digest) THEN + RAISE EXCEPTION 'First invoice differs from exact reserved creation tuple' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER first_invoice_source BEFORE INSERT ON subscription_first_invoices FOR EACH ROW EXECUTE FUNCTION account_first_invoice_source_guard(); +CREATE FUNCTION account_first_invoice_consent_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE auth account_recent_reauthentication_evidence%ROWTYPE; invoice subscription_first_invoices%ROWTYPE; current_row RECORD; +BEGIN + SELECT * INTO STRICT auth FROM account_recent_reauthentication_evidence WHERE evidence_id = NEW.reauthentication_evidence_id; + SELECT * INTO STRICT invoice FROM subscription_first_invoices WHERE subscription_id = NEW.subscription_id; + SELECT s.status, s.row_version, s.provider_subscription_id, w.phase INTO STRICT current_row + FROM subscription s JOIN subscription_provisioning_work w ON w.subscription_id = s.subscription_id + WHERE s.subscription_id = NEW.subscription_id AND w.request_id = invoice.creation_request_id + AND s.superseded_at IS NULL FOR SHARE OF s, w; + IF current_row.status <> 'provisioning' OR current_row.phase <> 'AWAITING_PAYMENT' + OR current_row.row_version <> NEW.expected_row_version + OR current_row.provider_subscription_id IS DISTINCT FROM invoice.provider_subscription_id THEN + RAISE EXCEPTION 'First-invoice consent requires exact current awaiting-payment source' USING ERRCODE = '23514'; + END IF; + IF auth.purpose <> 'HOSTING_FIRST_INVOICE_PAYMENT' OR auth.creation_operation_id <> NEW.request_id + OR auth.account_uuid <> NEW.account_uuid OR invoice.account_uuid <> NEW.account_uuid OR invoice.tuple_digest <> NEW.tuple_digest + OR NEW.consented_at < auth.issued_at OR NEW.valid_until > auth.issued_at + (auth.recent_age_seconds - auth.max_clock_skew_seconds) * INTERVAL '1 second' + OR NEW.valid_until > invoice.expires_at THEN + RAISE EXCEPTION 'First-invoice consent requires current exact billing-purpose reauthentication' USING ERRCODE = '23514'; + END IF; + NEW.created_transaction_id := txid_current(); + RETURN NEW; +END; +$$; +CREATE TRIGGER first_invoice_consent BEFORE INSERT ON subscription_first_invoice_confirmations FOR EACH ROW EXECUTE FUNCTION account_first_invoice_consent_guard(); +CREATE FUNCTION account_first_invoice_completion_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE consent subscription_first_invoice_confirmations%ROWTYPE; receipt subscription_lifecycle_receipts%ROWTYPE; audit_row RECORD; +BEGIN + SELECT * INTO STRICT consent FROM subscription_first_invoice_confirmations WHERE request_id = NEW.request_id; + SELECT * INTO STRICT receipt FROM subscription_lifecycle_receipts WHERE request_id = NEW.lifecycle_request_id; + SELECT *, xmin::text::BIGINT AS source_transaction_id INTO STRICT audit_row FROM account_audit_outbox WHERE audit_event_id = NEW.audit_event_id; + IF (consent.subscription_id, consent.lifecycle_request_id, consent.tuple_digest, consent.audit_event_id) + IS DISTINCT FROM (NEW.subscription_id, NEW.lifecycle_request_id, NEW.tuple_digest, NEW.audit_event_id) + OR receipt.subscription_id <> NEW.subscription_id OR receipt.receipt_digest <> NEW.receipt_digest + OR receipt.status NOT IN ('trialing','active','past_due','grace') OR receipt.committed_transaction_id <> txid_current() + OR audit_row.event_type <> 'HOSTING_FIRST_INVOICE_COMPLETED' OR audit_row.tenant_uuid IS DISTINCT FROM receipt.tenant_id + OR audit_row.source_transaction_id <> mod(txid_current(), 4294967296) + OR audit_row.payload::JSONB->>'tupleDigest' IS DISTINCT FROM NEW.tuple_digest + OR audit_row.payload::JSONB->>'receiptDigest' IS DISTINCT FROM NEW.receipt_digest THEN + RAISE EXCEPTION 'First-invoice completion requires exact atomic hosting receipt and authority outboxes' USING ERRCODE = '23514'; + END IF; + NEW.committed_transaction_id := txid_current(); + RETURN NEW; +END; +$$; +CREATE TRIGGER first_invoice_completion BEFORE INSERT ON subscription_first_invoice_completions FOR EACH ROW EXECUTE FUNCTION account_first_invoice_completion_guard(); +-- The original provisioning claim and a later signed first-invoice fulfillment are distinct +-- operations. Neither a provider read nor a NULL provisioning attempt is completion evidence. +CREATE OR REPLACE FUNCTION account_subscription_provisioning_confirmed_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE work subscription_provisioning_work%ROWTYPE; +BEGIN + SELECT * INTO STRICT work FROM subscription_provisioning_work WHERE request_id = NEW.request_id; + IF work.phase = 'CONFIRMED' AND NOT EXISTS ( + SELECT 1 FROM subscription_lifecycle_operations operation + JOIN subscription_lifecycle_receipts receipt USING (request_id, subscription_id) + WHERE operation.creation_request_id = work.request_id AND operation.subscription_id = work.subscription_id + AND operation.provisioning_attempt_id = work.last_attempt_id AND operation.state = 'COMMITTED') + AND NOT EXISTS ( + SELECT 1 FROM subscription_first_invoices invoice + JOIN subscription_first_invoice_confirmations consent + ON consent.subscription_id = invoice.subscription_id AND consent.tuple_digest = invoice.tuple_digest + JOIN subscription_first_invoice_success_evidence success + ON (success.request_id, success.subscription_id, success.tuple_digest) + = (consent.request_id, consent.subscription_id, consent.tuple_digest) + JOIN subscription_first_invoice_completions completion + ON (completion.request_id, completion.subscription_id, completion.lifecycle_request_id, + completion.tuple_digest, completion.audit_event_id) + = (consent.request_id, consent.subscription_id, consent.lifecycle_request_id, + consent.tuple_digest, consent.audit_event_id) + JOIN subscription_lifecycle_operations operation + ON operation.request_id = completion.lifecycle_request_id + AND operation.subscription_id = completion.subscription_id + JOIN subscription_lifecycle_receipts receipt + ON receipt.request_id = operation.request_id AND receipt.subscription_id = operation.subscription_id + WHERE invoice.creation_request_id = work.request_id AND invoice.subscription_id = work.subscription_id + AND operation.creation_request_id = work.request_id AND operation.state = 'COMMITTED' + AND operation.provisioning_attempt_id IS NULL + AND operation.provider_subscription_id = invoice.provider_subscription_id + AND receipt.provider_subscription_id = invoice.provider_subscription_id + AND receipt.status IN ('trialing','active','past_due','grace') + AND receipt.receipt_digest = completion.receipt_digest + AND completion.committed_transaction_id = receipt.committed_transaction_id + AND completion.committed_transaction_id = txid_current()) THEN + RAISE EXCEPTION 'Provisioning confirmation lacks its exact lifecycle receipt' USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; +ALTER TABLE subscription_provisioning_work DROP CONSTRAINT subscription_provisioning_work_phase_check; +ALTER TABLE subscription_provisioning_work ADD CONSTRAINT subscription_provisioning_work_phase_check + CHECK (phase IN ('RECONCILING','CLAIMED','AWAITING_PAYMENT','CONFIRMED','BILLING_RECONCILIATION_TERMINAL_FAILURE')); +CREATE OR REPLACE FUNCTION account_subscription_provisioning_work_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Provisioning work is retained' USING ERRCODE = '23514'; + ELSIF TG_OP = 'INSERT' THEN + IF NEW.phase <> 'RECONCILING' OR NEW.attempt_count <> 0 OR NEW.row_version <> 1 + OR NEW.failure_reason IS NOT NULL OR NEW.terminal_at IS NOT NULL THEN + RAISE EXCEPTION 'Provisioning work must start unclaimed' USING ERRCODE = '23514'; + END IF; + ELSE + IF OLD.phase IN ('CONFIRMED','BILLING_RECONCILIATION_TERMINAL_FAILURE') OR (OLD.phase = 'AWAITING_PAYMENT' AND NEW.phase NOT IN ('CONFIRMED','BILLING_RECONCILIATION_TERMINAL_FAILURE')) + OR (NEW.request_id, NEW.subscription_id, NEW.max_attempts, NEW.max_stalled_attempts, + NEW.lease_millis, NEW.backoff_millis, NEW.deadline_at) + IS DISTINCT FROM (OLD.request_id, OLD.subscription_id, OLD.max_attempts, OLD.max_stalled_attempts, + OLD.lease_millis, OLD.backoff_millis, OLD.deadline_at) + OR NEW.row_version <> OLD.row_version + 1 THEN + RAISE EXCEPTION 'Provisioning identity, limits or terminal fence rejected' USING ERRCODE = '23514'; + END IF; + IF NEW.phase = 'CLAIMED' THEN + IF NEW.attempt_count <> OLD.attempt_count + 1 OR NEW.last_attempt_id IS NOT DISTINCT FROM OLD.last_attempt_id + OR NEW.attempt_count > NEW.max_attempts OR NEW.attempt_count > NEW.max_stalled_attempts THEN + RAISE EXCEPTION 'Provisioning claim count or attempt fence rejected' USING ERRCODE = '23514'; + END IF; + ELSIF (NEW.attempt_count, NEW.last_attempt_id, NEW.subscription_row_version, NEW.lease_expires_at) + IS DISTINCT FROM (OLD.attempt_count, OLD.last_attempt_id, OLD.subscription_row_version, OLD.lease_expires_at) THEN + RAISE EXCEPTION 'Provisioning settlement cannot replace its attempt' USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_first_invoice_link_consistency() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE current_row subscription%ROWTYPE; invoice subscription_first_invoices%ROWTYPE; +BEGIN + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = NEW.subscription_id; + SELECT * INTO STRICT invoice FROM subscription_first_invoices WHERE subscription_id = NEW.subscription_id; + IF current_row.provider_subscription_id IS DISTINCT FROM invoice.provider_subscription_id THEN + RAISE EXCEPTION 'First-invoice linkage requires exact current canonical provider' USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; +CREATE CONSTRAINT TRIGGER first_invoice_link AFTER INSERT ON subscription_first_invoices + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_first_invoice_link_consistency(); +CREATE FUNCTION account_first_invoice_dispatch_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE consent subscription_first_invoice_confirmations%ROWTYPE; +BEGIN + SELECT * INTO STRICT consent FROM subscription_first_invoice_confirmations WHERE request_id = NEW.request_id; + IF consent.subscription_id <> NEW.subscription_id OR consent.created_transaction_id <> txid_current() + OR NEW.authorized_at < consent.consented_at OR NEW.authorized_at >= consent.valid_until THEN + RAISE EXCEPTION 'Initial payment dispatch must commit atomically with original current exact consent' USING ERRCODE = '23514'; + END IF; + NEW.created_transaction_id := txid_current(); + RETURN NEW; +END; +$$; +CREATE TRIGGER first_invoice_dispatch BEFORE INSERT ON subscription_first_invoice_dispatches + FOR EACH ROW EXECUTE FUNCTION account_first_invoice_dispatch_guard(); +CREATE TRIGGER subscription_first_invoice_dispatches_immutable BEFORE UPDATE OR DELETE ON subscription_first_invoice_dispatches + FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER subscription_first_invoice_dispatches_no_truncate BEFORE TRUNCATE ON subscription_first_invoice_dispatches + FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE FUNCTION account_first_invoice_success_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE intake stripe_event_inbox%ROWTYPE; invoice subscription_first_invoices%ROWTYPE; payload JSONB; +BEGIN + SELECT * INTO STRICT intake FROM stripe_event_inbox WHERE provider_event_id = NEW.provider_event_id; + SELECT * INTO STRICT invoice FROM subscription_first_invoices WHERE subscription_id = NEW.subscription_id; + payload := convert_from(intake.raw_payload, 'UTF8')::JSONB #> '{data,object}'; + IF intake.event_type <> 'payment_intent.succeeded' OR intake.payload_sha256 <> NEW.event_payload_digest + OR intake.livemode <> invoice.livemode OR NEW.tuple_digest <> invoice.tuple_digest + OR payload->>'object' IS DISTINCT FROM 'payment_intent' OR payload->>'status' IS DISTINCT FROM 'succeeded' + OR payload->>'id' IS DISTINCT FROM invoice.payment_intent_id OR payload->>'customer' IS DISTINCT FROM invoice.provider_customer_id + OR payload->>'payment_method' IS DISTINCT FROM invoice.provider_payment_method_id OR payload->>'currency' IS DISTINCT FROM invoice.currency + OR payload->'amount' IS DISTINCT FROM to_jsonb(invoice.amount) OR payload->'amount_received' IS DISTINCT FROM to_jsonb(invoice.amount) + OR payload->'livemode' IS DISTINCT FROM to_jsonb(invoice.livemode) THEN + RAISE EXCEPTION 'First invoice requires exact signed successful payment tuple, not invoice.paid' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER first_invoice_success BEFORE INSERT ON subscription_first_invoice_success_evidence + FOR EACH ROW EXECUTE FUNCTION account_first_invoice_success_guard(); +CREATE FUNCTION account_first_invoice_active_receipt_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.status IN ('trialing','active','past_due','grace') AND NOT EXISTS (SELECT 1 FROM subscription_first_invoice_completions WHERE subscription_id = NEW.subscription_id) + AND NOT EXISTS (SELECT 1 FROM subscription_first_invoice_success_evidence e + JOIN subscription_first_invoice_confirmations c USING (request_id, subscription_id) + WHERE c.subscription_id = NEW.subscription_id AND c.lifecycle_request_id = NEW.request_id) THEN + RAISE EXCEPTION 'First authorizing hosting receipt requires exact signed checkout completion evidence' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER first_invoice_active_receipt BEFORE INSERT ON subscription_lifecycle_receipts + FOR EACH ROW EXECUTE FUNCTION account_first_invoice_active_receipt_guard(); +-- [jooq ignore stop] +COMMENT ON TABLE subscription_first_invoices IS 'Immutable provider-linked awaiting-payment evidence only; does not authorize hosting. Retention/deletion/backup registration gates remain held.'; diff --git a/services/account-service/src/main/resources/db/migration/V1042__account_tenant_capacity_state_change_checks.sql b/services/account-service/src/main/resources/db/migration/V1042__account_tenant_capacity_state_change_checks.sql new file mode 100644 index 0000000000..0322c4a976 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1042__account_tenant_capacity_state_change_checks.sql @@ -0,0 +1,19 @@ +-- Recheck complete reservation inventory only when the reservation state changes. +-- Metadata-only claims, recovery observations, and unchanged-state rearm bookkeeping do not +-- alter held or used capacity and must not scan the lifetime reservation inventory. +-- [jooq ignore start] +DROP TRIGGER account_tenant_capacity_reservation_complete + ON account_tenant_capacity_reservations; + +CREATE CONSTRAINT TRIGGER account_tenant_capacity_reservation_complete_insert + AFTER INSERT ON account_tenant_capacity_reservations + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_exact_usage(); + +CREATE CONSTRAINT TRIGGER account_tenant_capacity_reservation_complete_update + AFTER UPDATE ON account_tenant_capacity_reservations + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW + WHEN (OLD.state IS DISTINCT FROM NEW.state) + EXECUTE FUNCTION account_tenant_capacity_exact_usage(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1043__hosting_first_invoice_operation_fence.sql b/services/account-service/src/main/resources/db/migration/V1043__hosting_first_invoice_operation_fence.sql new file mode 100644 index 0000000000..ca475e4f71 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1043__hosting_first_invoice_operation_fence.sql @@ -0,0 +1,368 @@ +-- Account retains a durable original checkout operation before returning its first usable proof. +-- New first consent and explicit pre-row recovery compete for this exact fence; neither the +-- nullable status projection nor unbound historical reauthentication evidence grants authority. +ALTER TABLE account_recent_reauthentication_evidence + ADD COLUMN billing_context_subscription_id UUID, + ADD COLUMN billing_context_original_request_id UUID, + ADD COLUMN billing_context_tuple_digest VARCHAR(71), + ADD COLUMN billing_context_expected_row_version BIGINT, + ADD COLUMN billing_context_invoice_expires_at TIMESTAMPTZ, + ADD COLUMN billing_context_authorization_request_id UUID, + ADD COLUMN billing_context_expected_authorization_version BIGINT, + ADD COLUMN billing_context_authorization_purpose VARCHAR(32), + ADD COLUMN billing_context_digest VARCHAR(71), + ADD CONSTRAINT account_recent_reauthentication_billing_context_all_or_none CHECK ( + (billing_context_subscription_id IS NULL + AND billing_context_original_request_id IS NULL + AND billing_context_tuple_digest IS NULL + AND billing_context_expected_row_version IS NULL + AND billing_context_invoice_expires_at IS NULL + AND billing_context_authorization_request_id IS NULL + AND billing_context_expected_authorization_version IS NULL + AND billing_context_authorization_purpose IS NULL + AND billing_context_digest IS NULL) + OR + (billing_context_subscription_id IS NOT NULL + AND billing_context_original_request_id IS NOT NULL + AND billing_context_tuple_digest IS NOT NULL + AND billing_context_expected_row_version IS NOT NULL + AND billing_context_invoice_expires_at IS NOT NULL + AND billing_context_authorization_request_id IS NOT NULL + AND billing_context_expected_authorization_version IS NOT NULL + AND billing_context_authorization_purpose IS NOT NULL + AND billing_context_digest IS NOT NULL) + ), + ADD CONSTRAINT account_recent_reauthentication_billing_context_purpose_check CHECK ( + billing_context_digest IS NULL + OR (purpose = 'HOSTING_FIRST_INVOICE_PAYMENT' + AND billing_context_tuple_digest ~ '^sha256:[0-9a-f]{64}$' + AND billing_context_expected_row_version > 0 + AND billing_context_expected_authorization_version >= 0 + AND billing_context_digest ~ '^sha256:[0-9a-f]{64}$' + AND billing_context_authorization_purpose IN + ('INITIAL_CONFIRMATION', 'PRE_ROW_RENEWAL', 'FOLLOWUP_RENEWAL')) + ); + +CREATE TABLE subscription_first_invoice_operation_fences ( + subscription_id UUID PRIMARY KEY REFERENCES subscription_first_invoices(subscription_id) ON DELETE RESTRICT, + request_id UUID NOT NULL UNIQUE CHECK (request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + account_uuid UUID NOT NULL REFERENCES accounts(account_uuid) ON DELETE RESTRICT, + tuple_digest VARCHAR(71) NOT NULL CHECK (tuple_digest ~ '^sha256:[0-9a-f]{64}$'), + expected_row_version BIGINT NOT NULL CHECK (expected_row_version > 0), + invoice_expires_at TIMESTAMPTZ NOT NULL, + reauthentication_evidence_id UUID NOT NULL UNIQUE + REFERENCES account_recent_reauthentication_evidence(evidence_id) ON DELETE RESTRICT, + binding_digest VARCHAR(71) NOT NULL CHECK (binding_digest ~ '^sha256:[0-9a-f]{64}$'), + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + FOREIGN KEY (subscription_id, tuple_digest) + REFERENCES subscription_first_invoices(subscription_id, tuple_digest) ON DELETE RESTRICT, + UNIQUE (request_id, subscription_id) +); + +-- [jooq ignore start] +CREATE FUNCTION account_recent_reauthentication_billing_context_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + expected_context_digest TEXT; + expected_request_payload TEXT; + expiry_text TEXT; +BEGIN + IF NEW.billing_context_digest IS NULL THEN + IF NEW.purpose = 'HOSTING_FIRST_INVOICE_PAYMENT' THEN + RAISE EXCEPTION 'New billing reauthentication evidence requires an exact typed context' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF NEW.purpose <> 'HOSTING_FIRST_INVOICE_PAYMENT' + OR NEW.creation_operation_id IS DISTINCT FROM NEW.billing_context_authorization_request_id + OR (NEW.billing_context_authorization_purpose = 'INITIAL_CONFIRMATION' + AND (NEW.billing_context_original_request_id IS DISTINCT FROM NEW.creation_operation_id + OR NEW.billing_context_expected_authorization_version <> 0)) + OR (NEW.billing_context_authorization_purpose = 'PRE_ROW_RENEWAL' + AND (NEW.billing_context_original_request_id = NEW.creation_operation_id + OR NEW.billing_context_expected_authorization_version <> 0)) + OR (NEW.billing_context_authorization_purpose = 'FOLLOWUP_RENEWAL' + AND (NEW.billing_context_original_request_id = NEW.creation_operation_id + OR NEW.billing_context_expected_authorization_version < 1)) THEN + RAISE EXCEPTION 'Typed billing reauthentication context has an invalid operation binding' + USING ERRCODE = '23514'; + END IF; + + -- Java's canonical Instant representation uses six fractional digits for this + -- database-bound context. PostgreSQL timestamptz precision is microseconds. + expiry_text := to_char(NEW.billing_context_invoice_expires_at AT TIME ZONE 'UTC', + 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"'); + expected_context_digest := 'sha256:' || encode(sha256(convert_to( + 'account-hosting-billing-reauth-context/v1' || E'\n' + || 'accountId=' || NEW.account_uuid::TEXT || E'\n' + || 'subscriptionId=' || NEW.billing_context_subscription_id::TEXT || E'\n' + || 'originalRequestId=' || NEW.billing_context_original_request_id::TEXT || E'\n' + || 'tupleDigest=' || NEW.billing_context_tuple_digest || E'\n' + || 'expectedRowVersion=' || NEW.billing_context_expected_row_version::TEXT || E'\n' + || 'invoiceExpiresAt=' || expiry_text || E'\n' + || 'authorizationRequestId=' || NEW.billing_context_authorization_request_id::TEXT || E'\n' + || 'expectedAuthorizationVersion=' || NEW.billing_context_expected_authorization_version::TEXT || E'\n' + || 'authorizationPurpose=' || NEW.billing_context_authorization_purpose || E'\n', 'UTF8')), 'hex'); + IF NEW.billing_context_digest IS DISTINCT FROM expected_context_digest THEN + RAISE EXCEPTION 'Typed billing reauthentication digest does not match its immutable context' + USING ERRCODE = '23514'; + END IF; + + expected_request_payload := 'account-recent-reauthentication-request/v2' || E'\n' + || 'requestId=' || NEW.request_id::TEXT || E'\n' + || 'accountId=' || NEW.account_uuid::TEXT || E'\n' + || 'purpose=' || NEW.purpose || E'\n' + || 'creationOperationId=' || NEW.creation_operation_id::TEXT || E'\n' + || 'billingContextDigest=' || NEW.billing_context_digest || E'\n'; + IF NEW.request_payload IS DISTINCT FROM convert_to(expected_request_payload, 'UTF8') + OR NEW.request_digest IS DISTINCT FROM 'sha256:' || encode( + sha256(convert_to(expected_request_payload, 'UTF8')), 'hex') THEN + RAISE EXCEPTION 'Typed billing reauthentication request digest is not canonical' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_recent_reauthentication_billing_context_guard + BEFORE INSERT ON account_recent_reauthentication_evidence + FOR EACH ROW EXECUTE FUNCTION account_recent_reauthentication_billing_context_guard(); + +CREATE FUNCTION account_first_invoice_operation_fence_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + invoice subscription_first_invoices%ROWTYPE; + evidence account_recent_reauthentication_evidence%ROWTYPE; + current_row RECORD; +BEGIN + SELECT * INTO STRICT invoice FROM subscription_first_invoices + WHERE subscription_id = NEW.subscription_id FOR SHARE; + SELECT s.status, s.row_version, s.provider_subscription_id, w.phase INTO STRICT current_row + FROM subscription s JOIN subscription_provisioning_work w ON w.subscription_id = s.subscription_id + WHERE s.subscription_id = NEW.subscription_id AND w.request_id = invoice.creation_request_id + AND s.superseded_at IS NULL FOR UPDATE OF s; + SELECT * INTO STRICT evidence FROM account_recent_reauthentication_evidence + WHERE evidence_id = NEW.reauthentication_evidence_id FOR UPDATE; + IF current_row.status <> 'provisioning' OR current_row.phase <> 'AWAITING_PAYMENT' + OR current_row.row_version IS DISTINCT FROM NEW.expected_row_version + OR current_row.provider_subscription_id IS DISTINCT FROM invoice.provider_subscription_id + OR invoice.account_uuid IS DISTINCT FROM NEW.account_uuid + OR invoice.tuple_digest IS DISTINCT FROM NEW.tuple_digest + OR invoice.expires_at IS DISTINCT FROM NEW.invoice_expires_at + OR NEW.request_id IS DISTINCT FROM evidence.creation_operation_id + OR NEW.account_uuid IS DISTINCT FROM evidence.account_uuid + OR evidence.purpose <> 'HOSTING_FIRST_INVOICE_PAYMENT' + OR evidence.billing_context_authorization_purpose <> 'INITIAL_CONFIRMATION' + OR evidence.billing_context_subscription_id IS DISTINCT FROM NEW.subscription_id + OR evidence.billing_context_original_request_id IS DISTINCT FROM NEW.request_id + OR evidence.billing_context_tuple_digest IS DISTINCT FROM NEW.tuple_digest + OR evidence.billing_context_expected_row_version IS DISTINCT FROM NEW.expected_row_version + OR evidence.billing_context_invoice_expires_at IS DISTINCT FROM NEW.invoice_expires_at + OR evidence.billing_context_authorization_request_id IS DISTINCT FROM NEW.request_id + OR evidence.billing_context_expected_authorization_version <> 0 + OR evidence.billing_context_digest IS DISTINCT FROM NEW.binding_digest + OR EXISTS (SELECT 1 FROM account_recent_reauthentication_consumptions c + WHERE c.evidence_id = evidence.evidence_id) + OR EXISTS (SELECT 1 FROM subscription_first_invoice_confirmations c + WHERE c.subscription_id = NEW.subscription_id) + OR EXISTS (SELECT 1 FROM subscription_first_invoice_authorizations a + WHERE a.subscription_id = NEW.subscription_id) THEN + RAISE EXCEPTION 'First-invoice operation fence requires exact unconsumed opening proof and current invoice' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER first_invoice_operation_fence + BEFORE INSERT ON subscription_first_invoice_operation_fences + FOR EACH ROW EXECUTE FUNCTION account_first_invoice_operation_fence_guard(); +CREATE TRIGGER first_invoice_operation_fences_immutable BEFORE UPDATE OR DELETE + ON subscription_first_invoice_operation_fences + FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER first_invoice_operation_fences_no_truncate BEFORE TRUNCATE + ON subscription_first_invoice_operation_fences + FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); + +CREATE OR REPLACE FUNCTION account_first_invoice_consent_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + auth account_recent_reauthentication_evidence%ROWTYPE; + invoice subscription_first_invoices%ROWTYPE; + current_row RECORD; + fence subscription_first_invoice_operation_fences%ROWTYPE; +BEGIN + SELECT * INTO STRICT auth FROM account_recent_reauthentication_evidence + WHERE evidence_id = NEW.reauthentication_evidence_id; + SELECT * INTO STRICT invoice FROM subscription_first_invoices + WHERE subscription_id = NEW.subscription_id; + SELECT s.status, s.row_version, s.provider_subscription_id, w.phase INTO STRICT current_row + FROM subscription s JOIN subscription_provisioning_work w ON w.subscription_id = s.subscription_id + WHERE s.subscription_id = NEW.subscription_id AND w.request_id = invoice.creation_request_id + AND s.superseded_at IS NULL FOR SHARE OF s, w; + IF current_row.status <> 'provisioning' OR current_row.phase <> 'AWAITING_PAYMENT' + OR current_row.row_version <> NEW.expected_row_version + OR current_row.provider_subscription_id IS DISTINCT FROM invoice.provider_subscription_id + OR auth.purpose <> 'HOSTING_FIRST_INVOICE_PAYMENT' + OR auth.account_uuid <> NEW.account_uuid OR invoice.account_uuid <> NEW.account_uuid + OR invoice.tuple_digest <> NEW.tuple_digest + OR NEW.consented_at < auth.issued_at + OR NEW.consented_at >= NEW.valid_until + OR NEW.valid_until > auth.issued_at + (auth.recent_age_seconds - auth.max_clock_skew_seconds) * INTERVAL '1 second' + OR NEW.valid_until > invoice.expires_at + OR NOT EXISTS (SELECT 1 FROM account_recent_reauthentication_consumptions c + WHERE c.evidence_id = auth.evidence_id AND c.creation_operation_id = auth.creation_operation_id + AND c.account_uuid = auth.account_uuid AND c.purpose = auth.purpose) THEN + RAISE EXCEPTION 'First-invoice consent requires exact current billing-purpose reauthentication' + USING ERRCODE = '23514'; + END IF; + + IF auth.billing_context_authorization_purpose = 'INITIAL_CONFIRMATION' THEN + SELECT * INTO STRICT fence FROM subscription_first_invoice_operation_fences + WHERE subscription_id = NEW.subscription_id; + IF NEW.request_id IS DISTINCT FROM auth.creation_operation_id + OR NEW.request_id IS DISTINCT FROM auth.billing_context_original_request_id + OR auth.billing_context_authorization_request_id IS DISTINCT FROM NEW.request_id + OR auth.billing_context_expected_authorization_version <> 0 + OR auth.billing_context_subscription_id IS DISTINCT FROM NEW.subscription_id + OR auth.billing_context_tuple_digest IS DISTINCT FROM NEW.tuple_digest + OR auth.billing_context_expected_row_version IS DISTINCT FROM NEW.expected_row_version + OR auth.billing_context_invoice_expires_at IS DISTINCT FROM invoice.expires_at + OR fence.request_id IS DISTINCT FROM NEW.request_id + OR fence.account_uuid IS DISTINCT FROM NEW.account_uuid + OR fence.tuple_digest IS DISTINCT FROM NEW.tuple_digest + OR fence.expected_row_version IS DISTINCT FROM NEW.expected_row_version + OR fence.invoice_expires_at IS DISTINCT FROM invoice.expires_at + OR fence.reauthentication_evidence_id IS DISTINCT FROM auth.evidence_id + OR fence.binding_digest IS DISTINCT FROM auth.billing_context_digest THEN + RAISE EXCEPTION 'Initial first-invoice consent differs from its durable original operation fence' + USING ERRCODE = '23514'; + END IF; + ELSIF auth.billing_context_authorization_purpose = 'PRE_ROW_RENEWAL' THEN + SELECT * INTO STRICT fence FROM subscription_first_invoice_operation_fences + WHERE subscription_id = NEW.subscription_id; + IF auth.creation_operation_id IS DISTINCT FROM auth.billing_context_authorization_request_id + OR auth.billing_context_original_request_id IS DISTINCT FROM NEW.request_id + OR auth.billing_context_expected_authorization_version <> 0 + OR auth.billing_context_subscription_id IS DISTINCT FROM NEW.subscription_id + OR auth.billing_context_tuple_digest IS DISTINCT FROM NEW.tuple_digest + OR auth.billing_context_expected_row_version IS DISTINCT FROM NEW.expected_row_version + OR auth.billing_context_invoice_expires_at IS DISTINCT FROM invoice.expires_at + OR fence.request_id IS DISTINCT FROM NEW.request_id + OR fence.account_uuid IS DISTINCT FROM NEW.account_uuid + OR fence.tuple_digest IS DISTINCT FROM NEW.tuple_digest + OR fence.expected_row_version IS DISTINCT FROM NEW.expected_row_version + OR fence.invoice_expires_at IS DISTINCT FROM invoice.expires_at THEN + RAISE EXCEPTION 'Pre-row first-invoice consent differs from its durable original operation fence' + USING ERRCODE = '23514'; + END IF; + ELSE + RAISE EXCEPTION 'First-invoice consent requires typed opening or pre-row billing proof' + USING ERRCODE = '23514'; + END IF; + NEW.created_transaction_id := txid_current(); + RETURN NEW; +END; +$$; + +CREATE OR REPLACE FUNCTION account_first_invoice_authorization_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + consent subscription_first_invoice_confirmations%ROWTYPE; + auth account_recent_reauthentication_evidence%ROWTYPE; + invoice subscription_first_invoices%ROWTYPE; + current_row RECORD; + fence subscription_first_invoice_operation_fences%ROWTYPE; + latest BIGINT; +BEGIN + SELECT s.status, s.row_version, s.provider_subscription_id, w.phase INTO STRICT current_row + FROM subscription s JOIN subscription_provisioning_work w ON w.subscription_id = s.subscription_id + WHERE s.subscription_id = NEW.subscription_id AND s.superseded_at IS NULL FOR UPDATE OF s; + SELECT * INTO STRICT consent FROM subscription_first_invoice_confirmations + WHERE request_id = NEW.request_id; + SELECT * INTO STRICT invoice FROM subscription_first_invoices + WHERE subscription_id = NEW.subscription_id; + SELECT * INTO STRICT auth FROM account_recent_reauthentication_evidence + WHERE evidence_id = NEW.reauthentication_evidence_id; + SELECT COALESCE(MAX(authorization_version), 0) INTO latest + FROM subscription_first_invoice_authorizations WHERE subscription_id = NEW.subscription_id; + IF consent.subscription_id <> NEW.subscription_id OR current_row.status <> 'provisioning' + OR current_row.phase <> 'AWAITING_PAYMENT' + OR current_row.row_version <> consent.expected_row_version + OR current_row.provider_subscription_id <> invoice.provider_subscription_id + OR NEW.authorization_version <> latest + 1 + OR NEW.request_id <> consent.request_id + OR auth.account_uuid <> consent.account_uuid + OR auth.purpose <> 'HOSTING_FIRST_INVOICE_PAYMENT' + OR auth.creation_operation_id <> NEW.authorization_request_id + OR NEW.consented_at < auth.issued_at OR NEW.consented_at >= NEW.valid_until + OR NEW.valid_until > invoice.expires_at + OR NEW.valid_until > auth.issued_at + (auth.recent_age_seconds - auth.max_clock_skew_seconds) * INTERVAL '1 second' + OR NOT EXISTS (SELECT 1 FROM account_recent_reauthentication_consumptions c + WHERE c.evidence_id = auth.evidence_id + AND c.creation_operation_id = NEW.authorization_request_id + AND c.account_uuid = consent.account_uuid AND c.purpose = auth.purpose) THEN + RAISE EXCEPTION 'First-invoice authorization requires fresh exact consumed consent and current version' + USING ERRCODE = '23514'; + END IF; + + IF NEW.authorization_version = 1 THEN + SELECT * INTO STRICT fence FROM subscription_first_invoice_operation_fences + WHERE subscription_id = NEW.subscription_id; + IF consent.created_transaction_id <> txid_current() + OR NEW.reauthentication_evidence_id <> consent.reauthentication_evidence_id + OR auth.billing_context_subscription_id IS DISTINCT FROM NEW.subscription_id + OR auth.billing_context_original_request_id IS DISTINCT FROM NEW.request_id + OR auth.billing_context_tuple_digest IS DISTINCT FROM consent.tuple_digest + OR auth.billing_context_expected_row_version IS DISTINCT FROM consent.expected_row_version + OR auth.billing_context_invoice_expires_at IS DISTINCT FROM invoice.expires_at + OR auth.billing_context_authorization_request_id IS DISTINCT FROM NEW.authorization_request_id + OR auth.billing_context_expected_authorization_version <> 0 + OR fence.request_id IS DISTINCT FROM NEW.request_id + OR fence.account_uuid IS DISTINCT FROM consent.account_uuid + OR fence.tuple_digest IS DISTINCT FROM consent.tuple_digest + OR fence.expected_row_version IS DISTINCT FROM consent.expected_row_version + OR fence.invoice_expires_at IS DISTINCT FROM invoice.expires_at THEN + RAISE EXCEPTION 'First-invoice winner must bind exact consent to the original operation fence' + USING ERRCODE = '23514'; + END IF; + IF NEW.authorization_request_id = NEW.request_id THEN + IF auth.billing_context_authorization_purpose <> 'INITIAL_CONFIRMATION' + OR fence.reauthentication_evidence_id IS DISTINCT FROM auth.evidence_id + OR fence.binding_digest IS DISTINCT FROM auth.billing_context_digest THEN + RAISE EXCEPTION 'Original confirmation must win only with its retained opening proof' + USING ERRCODE = '23514'; + END IF; + ELSIF auth.billing_context_authorization_purpose <> 'PRE_ROW_RENEWAL' THEN + RAISE EXCEPTION 'Distinct first authorization must be an explicit pre-row renewal' + USING ERRCODE = '23514'; + END IF; + ELSE + IF NEW.authorization_request_id = NEW.request_id + OR auth.billing_context_authorization_purpose <> 'FOLLOWUP_RENEWAL' + OR auth.billing_context_original_request_id IS DISTINCT FROM NEW.request_id + OR auth.billing_context_expected_authorization_version <> NEW.authorization_version - 1 + OR auth.billing_context_subscription_id IS DISTINCT FROM NEW.subscription_id + OR auth.billing_context_tuple_digest IS DISTINCT FROM consent.tuple_digest + OR auth.billing_context_expected_row_version IS DISTINCT FROM consent.expected_row_version + OR auth.billing_context_invoice_expires_at IS DISTINCT FROM invoice.expires_at + OR auth.billing_context_authorization_request_id IS DISTINCT FROM NEW.authorization_request_id THEN + RAISE EXCEPTION 'Follow-up first-invoice authorization requires exact retained operation binding' + USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM subscription_first_invoice_operation_fences f + WHERE f.subscription_id = NEW.subscription_id) + AND NOT EXISTS (SELECT 1 FROM subscription_first_invoice_operation_fences f + WHERE f.subscription_id = NEW.subscription_id AND f.request_id = NEW.request_id + AND f.account_uuid = consent.account_uuid AND f.tuple_digest = consent.tuple_digest + AND f.expected_row_version = consent.expected_row_version + AND f.invoice_expires_at = invoice.expires_at) THEN + RAISE EXCEPTION 'Follow-up authorization differs from its retained operation fence' + USING ERRCODE = '23514'; + END IF; + END IF; + NEW.created_transaction_id := txid_current(); + RETURN NEW; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1044__account_tenant_capacity_incremental_conservation.sql b/services/account-service/src/main/resources/db/migration/V1044__account_tenant_capacity_incremental_conservation.sql new file mode 100644 index 0000000000..c7047ea173 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1044__account_tenant_capacity_incremental_conservation.sql @@ -0,0 +1,166 @@ +-- Audit retained inventory once while excluding all usage/reservation writers. Never repair, +-- initialize or rewrite an existing owner row from an assumed baseline. +-- [jooq ignore start] +LOCK TABLE account_tenant_capacity_usage, account_tenant_capacity_reservations + IN SHARE ROW EXCLUSIVE MODE; + +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM account_tenant_capacity_usage usage + FULL JOIN ( + SELECT tenant_uuid, owner_service, + COALESCE(sum(capacity_delta) FILTER (WHERE state IN + ('RESERVED', 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION')), 0) AS held_units, + COALESCE(sum(capacity_delta) FILTER (WHERE state = 'FINALIZED'), 0) AS used_units + FROM account_tenant_capacity_reservations + GROUP BY tenant_uuid, owner_service + ) inventory USING (tenant_uuid, owner_service) + WHERE usage.tenant_uuid IS NULL + OR usage.held_units IS DISTINCT FROM COALESCE(inventory.held_units, 0) + OR usage.used_units IS DISTINCT FROM COALESCE(inventory.used_units, 0) + ) THEN + RAISE EXCEPTION 'Capacity conservation upgrade refuses inconsistent durable reservation inventory' + USING ERRCODE = '23514'; + END IF; +END; +$$; +-- [jooq ignore stop] + +CREATE TABLE account_tenant_capacity_conservation ( + tenant_uuid UUID NOT NULL, + owner_service VARCHAR(40) NOT NULL, + held_units BIGINT NOT NULL CHECK (held_units >= 0), + used_units BIGINT NOT NULL CHECK (used_units >= 0), + PRIMARY KEY (tenant_uuid, owner_service), + FOREIGN KEY (tenant_uuid, owner_service) + REFERENCES account_tenant_capacity_usage(tenant_uuid, owner_service) ON DELETE RESTRICT, + CHECK (held_units <= 9223372036854775807 - used_units) +); + +-- The lock and audit above make these exact retained values a proven inventory, not an +-- application assertion. Source data and Flyway history, including their xmin, stay untouched. +INSERT INTO account_tenant_capacity_conservation (tenant_uuid, owner_service, held_units, used_units) + SELECT tenant_uuid, owner_service, held_units, used_units FROM account_tenant_capacity_usage; + +-- [jooq ignore start] +CREATE FUNCTION account_tenant_capacity_conservation_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + -- Within the existing DML boundary only the usage-birth and reservation-delta triggers + -- below write this table. Direct DML cannot supply trigger nesting. DDL/disabled triggers + -- are not an alternate owner API. A bootstrap update nests birth at depth three. + IF TG_OP IN ('DELETE', 'TRUNCATE') OR pg_trigger_depth() < 2 THEN + RAISE EXCEPTION 'Capacity conservation is writable only by its nested owner triggers' + USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.held_units <> 0 OR NEW.used_units <> 0 OR NOT EXISTS ( + SELECT 1 FROM account_tenant_capacity_usage usage + JOIN account_tenant_creation_bootstrap_operations bootstrap + ON bootstrap.request_id = usage.bootstrap_request_id + AND bootstrap.tenant_uuid = usage.tenant_uuid + JOIN account_fresh_tenant_identity_associations birth + ON birth.canonical_tenant_id = usage.tenant_uuid + WHERE usage.tenant_uuid = NEW.tenant_uuid AND usage.owner_service = NEW.owner_service + AND usage.held_units = 0 AND usage.used_units = 0 AND usage.usage_revision = 1 + AND bootstrap.status = 'COMMITTED' AND bootstrap.gameplay_admission_allowed IS FALSE + AND bootstrap.baseline_event_sequence = 0 + AND bootstrap.creation_operation_id = birth.operation_id + AND birth.evidence_digest = usage.creation_evidence_digest + AND birth.capacity_birth_transaction = pg_current_xact_id()::TEXT) THEN + RAISE EXCEPTION 'Capacity conservation birth requires exact same-transaction zero usage' + USING ERRCODE = '23514'; + END IF; + ELSIF NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid + OR NEW.owner_service IS DISTINCT FROM OLD.owner_service + OR NEW.used_units < OLD.used_units + OR (NEW.held_units > OLD.held_units AND NEW.used_units <> OLD.used_units) + OR (NEW.used_units > OLD.used_units + AND OLD.held_units::NUMERIC - NEW.held_units <> NEW.used_units::NUMERIC - OLD.used_units) THEN + RAISE EXCEPTION 'Capacity conservation permits only immutable-key reservation deltas' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_tenant_capacity_conservation_owner + BEFORE INSERT OR UPDATE OR DELETE ON account_tenant_capacity_conservation + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_conservation_guard(); +CREATE TRIGGER account_tenant_capacity_conservation_no_truncate + BEFORE TRUNCATE ON account_tenant_capacity_conservation + FOR EACH STATEMENT EXECUTE FUNCTION account_tenant_capacity_conservation_guard(); + +CREATE FUNCTION account_tenant_capacity_conservation_birth() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + -- The existing BEFORE INSERT usage guard supplies the exact fresh-tenant authority. + INSERT INTO account_tenant_capacity_conservation (tenant_uuid, owner_service, held_units, used_units) + VALUES (NEW.tenant_uuid, NEW.owner_service, 0, 0); + RETURN NULL; +END; +$$; +CREATE TRIGGER account_tenant_capacity_usage_conservation_birth + AFTER INSERT ON account_tenant_capacity_usage + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_conservation_birth(); + +CREATE FUNCTION account_tenant_capacity_conservation_delta() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE held_delta BIGINT; used_delta BIGINT; +BEGIN + -- Existing BEFORE reservation guards retain sole transition/identity/fence authority. + held_delta := CASE WHEN NEW.state IN ('RESERVED', 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION') + THEN NEW.capacity_delta ELSE 0 END; + used_delta := CASE WHEN NEW.state = 'FINALIZED' THEN NEW.capacity_delta ELSE 0 END; + IF TG_OP = 'UPDATE' THEN + held_delta := held_delta - CASE WHEN OLD.state IN + ('RESERVED', 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION') THEN OLD.capacity_delta ELSE 0 END; + used_delta := used_delta - CASE WHEN OLD.state = 'FINALIZED' THEN OLD.capacity_delta ELSE 0 END; + END IF; + + -- Serialize with usage writes before touching conservation. The usage identity is immutable, + -- so NO KEY UPDATE suffices and avoids lock-upgrade deadlocks with reservation FK KEY SHARE. + -- No historical reservation is visited. + PERFORM 1 FROM account_tenant_capacity_usage + WHERE tenant_uuid = NEW.tenant_uuid AND owner_service = NEW.owner_service FOR NO KEY UPDATE; + IF held_delta <> 0 OR used_delta <> 0 THEN + UPDATE account_tenant_capacity_conservation + SET held_units = held_units + held_delta, used_units = used_units + used_delta + WHERE tenant_uuid = NEW.tenant_uuid AND owner_service = NEW.owner_service; + IF NOT FOUND THEN + RAISE EXCEPTION 'Capacity reservation requires its protected conservation baseline' + USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NULL; +END; +$$; +CREATE TRIGGER account_tenant_capacity_reservation_conservation_insert + AFTER INSERT ON account_tenant_capacity_reservations + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_conservation_delta(); +CREATE TRIGGER account_tenant_capacity_reservation_conservation_update + AFTER UPDATE ON account_tenant_capacity_reservations + FOR EACH ROW WHEN (OLD.state IS DISTINCT FROM NEW.state) + EXECUTE FUNCTION account_tenant_capacity_conservation_delta(); + +-- Preserve the existing deferred constraint triggers and their state-change-only scheduling. +-- Each invocation now uses two primary-key point lookups, independent of FINALIZED history. +CREATE OR REPLACE FUNCTION account_tenant_capacity_exact_usage() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE actual account_tenant_capacity_usage%ROWTYPE; + conserved account_tenant_capacity_conservation%ROWTYPE; +BEGIN + SELECT * INTO actual FROM account_tenant_capacity_usage + WHERE tenant_uuid = NEW.tenant_uuid AND owner_service = NEW.owner_service FOR NO KEY UPDATE; + SELECT * INTO conserved FROM account_tenant_capacity_conservation + WHERE tenant_uuid = NEW.tenant_uuid AND owner_service = NEW.owner_service; + IF actual.tenant_uuid IS NULL OR conserved.tenant_uuid IS NULL + OR actual.held_units IS DISTINCT FROM conserved.held_units + OR actual.used_units IS DISTINCT FROM conserved.used_units THEN + RAISE EXCEPTION 'Capacity usage differs from its protected reservation conservation' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; +-- [jooq ignore stop] + +COMMENT ON TABLE account_tenant_capacity_conservation IS + 'Audited once, then trigger-maintained exact held/used conservation; no retirement or deletion authority.'; diff --git a/services/account-service/src/main/resources/db/migration/V1045__account_capacity_evaluation_retention.sql b/services/account-service/src/main/resources/db/migration/V1045__account_capacity_evaluation_retention.sql new file mode 100644 index 0000000000..c541f7879f --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1045__account_capacity_evaluation_retention.sql @@ -0,0 +1,9 @@ +-- Read-only retention preparation. No policy is approved and no cleanup is enabled here. +-- Expiry is not retention authority; preserve all existing immutable records and guards. +CREATE INDEX account_capacity_evaluation_oldest_retention_idx + ON account_tenant_capacity_evaluations (evaluated_at, evaluation_identity); + +-- Rearm moves the exact evaluation FK. Conservatively preserve every evaluation in a retained +-- reservation scope, including prior evaluations named only by immutable historical payloads. +CREATE INDEX account_capacity_reservation_retention_scope_idx + ON account_tenant_capacity_reservations (tenant_uuid, owner_service); diff --git a/services/account-service/src/main/resources/db/migration/V1046.1__hosting_retained_positive_completion_gate.sql b/services/account-service/src/main/resources/db/migration/V1046.1__hosting_retained_positive_completion_gate.sql new file mode 100644 index 0000000000..8c0d5a1061 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1046.1__hosting_retained_positive_completion_gate.sql @@ -0,0 +1,51 @@ +-- Refuse upgrade rather than infer payment, rewrite receipts or demote retained positives. +-- Account V1047 belongs to the downstream control-ui replay-failure budget migration. +-- [jooq ignore start] +SET LOCAL lock_timeout = '5s'; +SET LOCAL statement_timeout = '5s'; +DO $$ +BEGIN + IF current_setting('transaction_isolation') <> 'read committed' THEN + RAISE EXCEPTION 'Retained hosting qualification requires READ COMMITTED migration isolation' + USING ERRCODE = '23514'; + END IF; +END; +$$; +-- Serialize the inspection and trigger installation against both INSERT and UPDATE writers. +LOCK TABLE subscription IN SHARE ROW EXCLUSIVE MODE; +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM subscription s + WHERE s.superseded_at IS NULL AND s.status IN ('trialing', 'active', 'past_due', 'grace') + AND NOT EXISTS (SELECT 1 FROM subscription_first_invoice_completions c + WHERE c.subscription_id = s.subscription_id) + ) THEN + RAISE EXCEPTION 'Retained positive hosting subscriptions require evidence-preserving resolution before upgrade' + USING ERRCODE = '23514'; + END IF; +END; +$$; +CREATE FUNCTION account_hosting_positive_completion_consistency() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + -- Inspect the final current row, not an intermediate transition's NEW image. Completion + -- may follow the positive update in the same owner transaction; existing exact-proof + -- and immutable-completion guards remain authoritative and unchanged. + IF EXISTS ( + SELECT 1 FROM subscription s + WHERE s.subscription_id = NEW.subscription_id AND s.superseded_at IS NULL + AND s.status IN ('trialing', 'active', 'past_due', 'grace') + AND NOT EXISTS (SELECT 1 FROM subscription_first_invoice_completions c + WHERE c.subscription_id = s.subscription_id) + ) THEN + RAISE EXCEPTION 'Current positive hosting subscription requires exact first-invoice completion' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE CONSTRAINT TRIGGER account_hosting_positive_completion_consistency + AFTER INSERT OR UPDATE ON subscription + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_hosting_positive_completion_consistency(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1046.2__settle_unclaimed_first_invoice_cancellation.sql b/services/account-service/src/main/resources/db/migration/V1046.2__settle_unclaimed_first_invoice_cancellation.sql new file mode 100644 index 0000000000..4a28877a89 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1046.2__settle_unclaimed_first_invoice_cancellation.sql @@ -0,0 +1,127 @@ +-- [jooq ignore start] +ALTER TABLE subscription_provisioning_work DROP CONSTRAINT subscription_provisioning_work_phase_check; +ALTER TABLE subscription_provisioning_work ADD CONSTRAINT subscription_provisioning_work_phase_check + CHECK (phase IN ('RECONCILING','CLAIMED','AWAITING_PAYMENT','CONFIRMED','CANCELED','BILLING_RECONCILIATION_TERMINAL_FAILURE')); + +CREATE OR REPLACE FUNCTION account_subscription_provisioning_work_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Provisioning work is retained' USING ERRCODE = '23514'; + ELSIF TG_OP = 'INSERT' THEN + IF NEW.phase <> 'RECONCILING' OR NEW.attempt_count <> 0 OR NEW.row_version <> 1 + OR NEW.failure_reason IS NOT NULL OR NEW.terminal_at IS NOT NULL THEN + RAISE EXCEPTION 'Provisioning work must start unclaimed' USING ERRCODE = '23514'; + END IF; + ELSE + IF OLD.phase IN ('CONFIRMED','CANCELED','BILLING_RECONCILIATION_TERMINAL_FAILURE') + OR (OLD.phase = 'AWAITING_PAYMENT' AND NEW.phase NOT IN ('CONFIRMED','CANCELED','BILLING_RECONCILIATION_TERMINAL_FAILURE')) + OR (NEW.phase = 'CANCELED' AND OLD.phase <> 'AWAITING_PAYMENT') + OR (NEW.request_id, NEW.subscription_id, NEW.max_attempts, NEW.max_stalled_attempts, + NEW.lease_millis, NEW.backoff_millis, NEW.deadline_at) + IS DISTINCT FROM (OLD.request_id, OLD.subscription_id, OLD.max_attempts, OLD.max_stalled_attempts, + OLD.lease_millis, OLD.backoff_millis, OLD.deadline_at) + OR NEW.row_version <> OLD.row_version + 1 THEN + RAISE EXCEPTION 'Provisioning identity, limits or terminal fence rejected' USING ERRCODE = '23514'; + END IF; + IF NEW.phase = 'CLAIMED' THEN + IF NEW.attempt_count <> OLD.attempt_count + 1 OR NEW.last_attempt_id IS NOT DISTINCT FROM OLD.last_attempt_id + OR NEW.attempt_count > NEW.max_attempts OR NEW.attempt_count > NEW.max_stalled_attempts THEN + RAISE EXCEPTION 'Provisioning claim count or attempt fence rejected' USING ERRCODE = '23514'; + END IF; + ELSIF (NEW.attempt_count, NEW.last_attempt_id, NEW.subscription_row_version, NEW.lease_expires_at) + IS DISTINCT FROM (OLD.attempt_count, OLD.last_attempt_id, OLD.subscription_row_version, OLD.lease_expires_at) THEN + RAISE EXCEPTION 'Provisioning settlement cannot replace its attempt' USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE OR REPLACE FUNCTION account_subscription_provisioning_consistency() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + work subscription_provisioning_work%ROWTYPE; + attempt subscription_provisioning_attempts%ROWTYPE; + current_row subscription%ROWTYPE; + notice subscription_provisioning_operator_outbox%ROWTYPE; +BEGIN + SELECT * INTO STRICT work FROM subscription_provisioning_work WHERE request_id = NEW.request_id; + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = work.subscription_id; + IF work.last_attempt_id IS NOT NULL THEN + SELECT * INTO STRICT attempt FROM subscription_provisioning_attempts WHERE attempt_id = work.last_attempt_id; + IF (attempt.request_id, attempt.subscription_id, attempt.attempt_number, attempt.claimed_row_version, attempt.expires_at) + IS DISTINCT FROM (work.request_id, work.subscription_id, work.attempt_count, work.subscription_row_version, work.lease_expires_at) + OR attempt.expires_at > work.deadline_at + OR (work.phase NOT IN ('CONFIRMED','CANCELED') + AND (current_row.status <> 'provisioning' OR current_row.row_version < attempt.claimed_row_version + OR current_row.superseded_at IS NOT NULL)) THEN + RAISE EXCEPTION 'Provisioning attempt lacks its exact current CAS' USING ERRCODE = '23514'; + END IF; + END IF; + IF work.phase = 'BILLING_RECONCILIATION_TERMINAL_FAILURE' THEN + SELECT * INTO STRICT notice FROM subscription_provisioning_operator_outbox WHERE request_id = work.request_id; + IF (notice.subscription_id, notice.reason, notice.recorded_at) + IS DISTINCT FROM (work.subscription_id, work.failure_reason, work.terminal_at) THEN + RAISE EXCEPTION 'Provisioning failure lacks its exact operator work item' USING ERRCODE = '23514'; + END IF; + ELSIF EXISTS (SELECT 1 FROM subscription_provisioning_operator_outbox WHERE request_id = work.request_id) THEN + RAISE EXCEPTION 'Operator resolution work requires terminal reconciliation failure' USING ERRCODE = '23514'; + END IF; + IF work.phase = 'CANCELED' AND ( + work.last_attempt_id IS NULL + OR current_row.status <> 'canceled' + OR NOT EXISTS ( + SELECT 1 FROM subscription_first_invoices invoice + JOIN subscription_lifecycle_receipts receipt USING (subscription_id) + JOIN subscription_lifecycle_operations operation USING (request_id, subscription_id) + JOIN subscription_lifecycle_observations observation + ON (observation.request_id, observation.attempt_id, observation.evidence_digest) + = (receipt.request_id, receipt.attempt_id, receipt.observation_digest) + JOIN subscription_provider_terminal_resolutions terminal + ON terminal.subscription_id = invoice.subscription_id + JOIN subscription_instrument_reservations reservation + ON reservation.subscription_id = invoice.subscription_id + WHERE invoice.subscription_id = work.subscription_id + AND invoice.creation_request_id = work.request_id + AND (operation.creation_request_id, operation.provider_subscription_id) + = (invoice.creation_request_id, invoice.provider_subscription_id) + AND operation.request_id = current_row.current_receipt_request_id + AND operation.state = 'COMMITTED' AND operation.provisioning_attempt_id IS NULL + AND convert_from(operation.request_payload, 'UTF8')::jsonb->>'schemaVersion' + = 'account-hosting-unpaid-first-invoice-cancellation/v1' + AND receipt.status = 'canceled' + AND receipt.subscription_row_version = current_row.row_version + AND receipt.provider_subscription_id = current_row.provider_subscription_id + AND receipt.committed_transaction_id = txid_current() + AND observation.raw_status = 'canceled' + AND terminal.resolution_id = current_row.terminal_resolution_id + AND terminal.outcome = 'CANCELED' + AND terminal.evidence_digest = observation.evidence_digest + AND reservation.request_id = work.request_id + AND reservation.terminal_resolution_id = terminal.resolution_id + AND reservation.released_at IS NOT NULL) + OR EXISTS (SELECT 1 FROM subscription_first_invoice_command_claims WHERE subscription_id = work.subscription_id) + OR EXISTS (SELECT 1 FROM subscription_first_invoice_success_evidence WHERE subscription_id = work.subscription_id)) THEN + RAISE EXCEPTION 'Canceled first-invoice provisioning requires exact unclaimed terminal release' USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; + +-- Normal signed fulfillment already has a durable command claim which excludes this cancellation. +-- Serialize an unclaimed signed success on the same subscription row so it cannot race release. +CREATE FUNCTION account_unclaimed_first_invoice_success_cancellation_fence() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE current_status VARCHAR; +BEGIN + IF NOT EXISTS (SELECT 1 FROM subscription_first_invoice_command_claims WHERE subscription_id = NEW.subscription_id) THEN + SELECT status INTO STRICT current_status FROM subscription WHERE subscription_id = NEW.subscription_id FOR UPDATE; + IF current_status = 'canceled' AND EXISTS ( + SELECT 1 FROM subscription_provisioning_work WHERE subscription_id = NEW.subscription_id AND phase = 'CANCELED') THEN + RAISE EXCEPTION 'Unclaimed first-invoice success conflicts with retained terminal cancellation' USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER first_invoice_unclaimed_success_cancellation_fence BEFORE INSERT ON subscription_first_invoice_success_evidence + FOR EACH ROW EXECUTE FUNCTION account_unclaimed_first_invoice_success_cancellation_fence(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1046.3__retain_late_first_invoice_payment_conflicts.sql b/services/account-service/src/main/resources/db/migration/V1046.3__retain_late_first_invoice_payment_conflicts.sql new file mode 100644 index 0000000000..58a86c1c69 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1046.3__retain_late_first_invoice_payment_conflicts.sql @@ -0,0 +1,209 @@ +-- A signed success arriving after the guarded unclaimed cancellation is retained as a conflict. +-- It does not reopen fulfillment, change the canceled subscription, or authorize compensation. +CREATE TABLE subscription_first_invoice_late_paid_conflicts ( + subscription_id UUID PRIMARY KEY REFERENCES subscription(subscription_id) ON DELETE RESTRICT, + request_id UUID NOT NULL UNIQUE, + lifecycle_request_id UUID NOT NULL UNIQUE, + creation_request_id UUID NOT NULL, + tuple_digest VARCHAR(71) NOT NULL CHECK (tuple_digest ~ '^sha256:[0-9a-f]{64}$'), + invoice_id VARCHAR(255) NOT NULL, + payment_intent_id VARCHAR(255) NOT NULL, + provider_event_id VARCHAR(255) NOT NULL UNIQUE + REFERENCES stripe_event_inbox(provider_event_id) ON DELETE RESTRICT, + event_payload_digest VARCHAR(71) NOT NULL + CHECK (event_payload_digest ~ '^sha256:[0-9a-f]{64}$'), + provider_subscription_id VARCHAR(255) NOT NULL, + provider_customer_id VARCHAR(255) NOT NULL, + provider_payment_method_id VARCHAR(255) NOT NULL, + provider_price_id VARCHAR(255) NOT NULL, + provider_quantity BIGINT NOT NULL CHECK (provider_quantity > 0), + amount BIGINT NOT NULL CHECK (amount > 0), + currency VARCHAR(3) NOT NULL CHECK (currency ~ '^[a-z]{3}$'), + livemode BOOLEAN NOT NULL, + observed_status VARCHAR(32) NOT NULL CHECK (observed_status = 'succeeded'), + observation_read_started_at TIMESTAMPTZ NOT NULL, + observation_observed_at TIMESTAMPTZ NOT NULL, + observation_expires_at TIMESTAMPTZ NOT NULL, + cancellation_request_id UUID NOT NULL UNIQUE, + cancellation_receipt_digest VARCHAR(71) NOT NULL + CHECK (cancellation_receipt_digest ~ '^sha256:[0-9a-f]{64}$'), + cancellation_row_version BIGINT NOT NULL CHECK (cancellation_row_version > 0), + cancellation_committed_transaction_id BIGINT NOT NULL CHECK (cancellation_committed_transaction_id > 0), + recorded_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + created_transaction_id BIGINT NOT NULL DEFAULT txid_current(), + CHECK (observation_observed_at >= observation_read_started_at), + CHECK (observation_expires_at > observation_read_started_at), + FOREIGN KEY (request_id, subscription_id, tuple_digest) + REFERENCES subscription_first_invoice_confirmations(request_id, subscription_id, tuple_digest) ON DELETE RESTRICT, + FOREIGN KEY (lifecycle_request_id) + REFERENCES subscription_first_invoice_confirmations(lifecycle_request_id) ON DELETE RESTRICT, + FOREIGN KEY (subscription_id, tuple_digest) + REFERENCES subscription_first_invoices(subscription_id, tuple_digest) ON DELETE RESTRICT, + FOREIGN KEY (invoice_id) REFERENCES subscription_first_invoices(invoice_id) ON DELETE RESTRICT, + FOREIGN KEY (payment_intent_id) REFERENCES subscription_first_invoices(payment_intent_id) ON DELETE RESTRICT, + FOREIGN KEY (cancellation_request_id) REFERENCES subscription_lifecycle_operations(request_id) ON DELETE RESTRICT, + FOREIGN KEY (cancellation_request_id, subscription_id) + REFERENCES subscription_lifecycle_receipts(request_id, subscription_id) ON DELETE RESTRICT +); + +-- [jooq ignore start] +CREATE FUNCTION account_first_invoice_late_paid_conflict_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + current_row subscription%ROWTYPE; + first_invoice subscription_first_invoices%ROWTYPE; + confirmation subscription_first_invoice_confirmations%ROWTYPE; + inbox stripe_event_inbox%ROWTYPE; + cancellation subscription_lifecycle_operations%ROWTYPE; + receipt subscription_lifecycle_receipts%ROWTYPE; + provisioning subscription_provisioning_work%ROWTYPE; + paid_payload JSONB; + cancellation_payload JSONB; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Late first-invoice payment conflicts are retained' USING ERRCODE = '23514'; + ELSIF TG_OP = 'INSERT' THEN + -- Serialize against the exact subscription cancellation/fulfillment boundary. Superseded + -- canceled rows remain addressable by immutable subscription ID and retain their receipt. + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = NEW.subscription_id FOR UPDATE; + SELECT * INTO STRICT first_invoice FROM subscription_first_invoices WHERE subscription_id = NEW.subscription_id; + SELECT * INTO STRICT confirmation FROM subscription_first_invoice_confirmations + WHERE request_id = NEW.request_id AND subscription_id = NEW.subscription_id; + SELECT * INTO STRICT inbox FROM stripe_event_inbox WHERE provider_event_id = NEW.provider_event_id; + + paid_payload := convert_from(inbox.raw_payload, 'UTF8')::jsonb; + IF current_row.status <> 'canceled' + OR current_row.current_receipt_request_id IS NULL + OR current_row.lifecycle_inflight_request_id IS NOT NULL + OR current_row.provider_subscription_id IS DISTINCT FROM first_invoice.provider_subscription_id + OR (current_row.superseded_at IS NULL AND current_row.row_version <> NEW.cancellation_row_version) + OR (first_invoice.creation_request_id, first_invoice.tuple_digest, first_invoice.invoice_id, + first_invoice.payment_intent_id, first_invoice.provider_subscription_id, + first_invoice.provider_customer_id, first_invoice.provider_payment_method_id, + first_invoice.provider_price_id, first_invoice.provider_quantity, + first_invoice.amount, first_invoice.currency, first_invoice.livemode) + IS DISTINCT FROM (NEW.creation_request_id, NEW.tuple_digest, NEW.invoice_id, + NEW.payment_intent_id, NEW.provider_subscription_id, NEW.provider_customer_id, + NEW.provider_payment_method_id, NEW.provider_price_id, NEW.provider_quantity, + NEW.amount, NEW.currency, NEW.livemode) + OR (confirmation.lifecycle_request_id, confirmation.tuple_digest, confirmation.account_uuid) + IS DISTINCT FROM (NEW.lifecycle_request_id, NEW.tuple_digest, first_invoice.account_uuid) + OR inbox.event_type <> 'payment_intent.succeeded' + OR inbox.payload_sha256 <> NEW.event_payload_digest + OR inbox.livemode <> NEW.livemode + OR inbox.provider_event_id IS DISTINCT FROM paid_payload->>'id' + OR inbox.event_type IS DISTINCT FROM paid_payload->>'type' + OR paid_payload->>'livemode' IS DISTINCT FROM NEW.livemode::TEXT + OR paid_payload->'data'->'object'->>'object' IS DISTINCT FROM 'payment_intent' + OR paid_payload->'data'->'object'->>'status' IS DISTINCT FROM 'succeeded' + OR paid_payload->'data'->'object'->>'id' IS DISTINCT FROM NEW.payment_intent_id + OR paid_payload->'data'->'object'->>'customer' IS DISTINCT FROM NEW.provider_customer_id + OR paid_payload->'data'->'object'->>'payment_method' IS DISTINCT FROM NEW.provider_payment_method_id + OR paid_payload->'data'->'object'->>'amount' IS DISTINCT FROM NEW.amount::TEXT + OR paid_payload->'data'->'object'->>'amount_received' IS DISTINCT FROM NEW.amount::TEXT + OR paid_payload->'data'->'object'->>'currency' IS DISTINCT FROM NEW.currency + OR paid_payload->'data'->'object'->>'livemode' IS DISTINCT FROM NEW.livemode::TEXT + OR inbox.provider_created_at_epoch_seconds < floor(EXTRACT(EPOCH FROM confirmation.consented_at)) + OR NEW.observed_status <> 'succeeded' + OR NEW.observation_read_started_at < inbox.received_at + OR NEW.observation_observed_at < NEW.observation_read_started_at + OR NEW.observation_observed_at - NEW.observation_read_started_at >= INTERVAL '20 seconds' + OR NEW.observation_expires_at <> first_invoice.expires_at + OR NOT EXISTS ( + SELECT 1 + FROM subscription_provisioning_work work + JOIN subscription_lifecycle_operations canceled_operation + ON canceled_operation.request_id = current_row.current_receipt_request_id + AND canceled_operation.subscription_id = current_row.subscription_id + JOIN subscription_lifecycle_receipts canceled_receipt + ON canceled_receipt.request_id = canceled_operation.request_id + AND canceled_receipt.subscription_id = canceled_operation.subscription_id + JOIN subscription_lifecycle_observations cancellation_observation + ON (cancellation_observation.request_id, cancellation_observation.attempt_id, + cancellation_observation.evidence_digest) + = (canceled_receipt.request_id, canceled_receipt.attempt_id, + canceled_receipt.observation_digest) + JOIN subscription_provider_terminal_resolutions terminal + ON terminal.resolution_id = current_row.terminal_resolution_id + AND terminal.subscription_id = current_row.subscription_id + JOIN subscription_instrument_reservations reservation + ON reservation.subscription_id = current_row.subscription_id + WHERE work.request_id = first_invoice.creation_request_id + AND work.subscription_id = current_row.subscription_id + AND work.phase = 'CANCELED' + AND work.last_attempt_id IS NOT NULL + AND canceled_operation.state = 'COMMITTED' + AND canceled_operation.creation_request_id = first_invoice.creation_request_id + AND canceled_operation.tenant_id = first_invoice.tenant_id + AND canceled_operation.provider_subscription_id = first_invoice.provider_subscription_id + AND canceled_operation.provisioning_attempt_id IS NULL + AND canceled_operation.request_id = NEW.cancellation_request_id + AND canceled_operation.request_digest = canceled_receipt.request_digest + AND canceled_operation.request_digest = 'sha256:' || encode(sha256(canceled_operation.request_payload), 'hex') + AND canceled_receipt.status = 'canceled' + AND canceled_receipt.receipt_digest = NEW.cancellation_receipt_digest + AND canceled_receipt.subscription_row_version = NEW.cancellation_row_version + AND canceled_receipt.committed_transaction_id = NEW.cancellation_committed_transaction_id + AND canceled_receipt.committed_transaction_id <> txid_current() + AND canceled_receipt.provider_subscription_id = first_invoice.provider_subscription_id + AND canceled_receipt.plan_quote_digest = first_invoice.quote_digest + AND cancellation_observation.raw_status = 'canceled' + AND terminal.request_id = first_invoice.creation_request_id + AND terminal.outcome = 'CANCELED' + AND terminal.provider_subscription_id = first_invoice.provider_subscription_id + AND terminal.evidence_digest = cancellation_observation.evidence_digest + AND reservation.request_id = first_invoice.creation_request_id + AND reservation.terminal_resolution_id = terminal.resolution_id + AND reservation.released_at IS NOT NULL + AND convert_from(canceled_operation.request_payload, 'UTF8')::jsonb->>'schemaVersion' + = 'account-hosting-unpaid-first-invoice-cancellation/v1' + AND convert_from(canceled_operation.request_payload, 'UTF8')::jsonb->>'requestId' + = canceled_operation.request_id::TEXT + AND convert_from(canceled_operation.request_payload, 'UTF8')::jsonb->>'creationRequestId' + = first_invoice.creation_request_id::TEXT + AND convert_from(canceled_operation.request_payload, 'UTF8')::jsonb->>'expectedRowVersion' + = canceled_operation.expected_row_version::TEXT + AND convert_from(canceled_operation.request_payload, 'UTF8')::jsonb->>'providerSubscriptionId' + = first_invoice.provider_subscription_id + AND convert_from(canceled_operation.request_payload, 'UTF8')::jsonb->>'provisioningAttemptId' = '' + AND (current_row.superseded_at IS NOT NULL + OR canceled_receipt.subscription_row_version = current_row.row_version) + ) + OR EXISTS (SELECT 1 FROM subscription_lifecycle_operator_outbox + WHERE request_id = current_row.current_receipt_request_id) + OR EXISTS (SELECT 1 FROM subscription_provisioning_operator_outbox + WHERE request_id = first_invoice.creation_request_id) + OR EXISTS (SELECT 1 FROM subscription_first_invoice_command_claims + WHERE subscription_id = NEW.subscription_id) + OR EXISTS (SELECT 1 FROM subscription_first_invoice_success_evidence + WHERE subscription_id = NEW.subscription_id) + OR EXISTS (SELECT 1 FROM subscription_first_invoice_completions + WHERE subscription_id = NEW.subscription_id) THEN + RAISE EXCEPTION 'Late first-invoice payment requires its exact verified success and committed unpaid cancellation' USING ERRCODE = '23514'; + END IF; + cancellation_payload := convert_from((SELECT request_payload FROM subscription_lifecycle_operations + WHERE request_id = NEW.cancellation_request_id), 'UTF8')::jsonb; + IF NEW.cancellation_request_id IS DISTINCT FROM current_row.current_receipt_request_id + OR NEW.cancellation_committed_transaction_id = txid_current() + OR cancellation_payload->>'schemaVersion' IS DISTINCT FROM 'account-hosting-unpaid-first-invoice-cancellation/v1' THEN + RAISE EXCEPTION 'Late first-invoice payment must retain the current committed unpaid cancellation' USING ERRCODE = '23514'; + END IF; + NEW.created_transaction_id := txid_current(); + RETURN NEW; + ELSE + RAISE EXCEPTION 'Late first-invoice payment conflicts are immutable' USING ERRCODE = '23514'; + END IF; +END; +$$; + +CREATE TRIGGER account_first_invoice_late_paid_conflict_guard + BEFORE INSERT OR UPDATE OR DELETE ON subscription_first_invoice_late_paid_conflicts + FOR EACH ROW EXECUTE FUNCTION account_first_invoice_late_paid_conflict_guard(); +CREATE FUNCTION account_first_invoice_late_paid_conflict_no_truncate() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Late first-invoice payment conflicts are retained' USING ERRCODE = '23514'; +END; +$$; +CREATE TRIGGER account_first_invoice_late_paid_conflict_no_truncate + BEFORE TRUNCATE ON subscription_first_invoice_late_paid_conflicts + FOR EACH STATEMENT EXECUTE FUNCTION account_first_invoice_late_paid_conflict_no_truncate(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1046.4__retain_first_invoice_expiry_before_post.sql b/services/account-service/src/main/resources/db/migration/V1046.4__retain_first_invoice_expiry_before_post.sql new file mode 100644 index 0000000000..0c00c4d1fe --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1046.4__retain_first_invoice_expiry_before_post.sql @@ -0,0 +1,26 @@ +CREATE TABLE subscription_first_invoice_expired_before_post ( + request_id UUID PRIMARY KEY REFERENCES subscription_first_invoice_command_claims(request_id) ON DELETE RESTRICT, + observed_at TIMESTAMPTZ NOT NULL +); + +-- [jooq ignore start] +CREATE FUNCTION account_first_invoice_expired_before_post_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE claim_transaction BIGINT; authorization_expiry TIMESTAMPTZ; +BEGIN + SELECT c.created_transaction_id, a.valid_until INTO STRICT claim_transaction, authorization_expiry + FROM subscription_first_invoice_command_claims c + JOIN subscription_first_invoice_authorizations a USING (authorization_request_id, request_id, subscription_id) + WHERE c.request_id = NEW.request_id; + IF claim_transaction = txid_current() OR NEW.observed_at < authorization_expiry THEN + RAISE EXCEPTION 'First-invoice no-send evidence requires an independently committed claim and expired authorization' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER first_invoice_expired_before_post_insert BEFORE INSERT ON subscription_first_invoice_expired_before_post + FOR EACH ROW EXECUTE FUNCTION account_first_invoice_expired_before_post_guard(); +CREATE TRIGGER first_invoice_expired_before_post_immutable BEFORE UPDATE OR DELETE ON subscription_first_invoice_expired_before_post + FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER first_invoice_expired_before_post_no_truncate BEFORE TRUNCATE ON subscription_first_invoice_expired_before_post + FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1046.5__identify_account_capacity_attempt_freshness_failure.sql b/services/account-service/src/main/resources/db/migration/V1046.5__identify_account_capacity_attempt_freshness_failure.sql new file mode 100644 index 0000000000..4ffe1d8eee --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1046.5__identify_account_capacity_attempt_freshness_failure.sql @@ -0,0 +1,23 @@ +-- Preserve the deferred guard while exposing structured identity for its exact stale-at-commit refusal. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_tenant_capacity_attempt_freshness_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + evaluation account_tenant_capacity_evaluations%ROWTYPE; + observed_at TIMESTAMPTZ; +BEGIN + IF TG_OP = 'UPDATE' AND NEW.admission_attempt_id IS NOT DISTINCT FROM OLD.admission_attempt_id THEN + RETURN NEW; + END IF; + SELECT * INTO evaluation FROM account_tenant_capacity_evaluations + WHERE evaluation_identity = NEW.evaluation_identity FOR SHARE; + -- Capture only after the evaluation lock. CURRENT_TIMESTAMP is frozen before lock waits. + observed_at := clock_timestamp(); + IF NOT FOUND OR evaluation.evaluated_at > observed_at + OR evaluation.expires_at <= observed_at OR NEW.expires_at <= observed_at THEN + RAISE EXCEPTION 'Capacity admission attempt is stale at the reservation write boundary' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_capacity_attempt_freshness'; + END IF; + RETURN NEW; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1046.6__align_first_invoice_billing_clock_skew.sql b/services/account-service/src/main/resources/db/migration/V1046.6__align_first_invoice_billing_clock_skew.sql new file mode 100644 index 0000000000..0d784163a4 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1046.6__align_first_invoice_billing_clock_skew.sql @@ -0,0 +1,184 @@ +-- Preserve exact consent identity and the original upper authorization deadline. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_first_invoice_consent_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + auth account_recent_reauthentication_evidence%ROWTYPE; + invoice subscription_first_invoices%ROWTYPE; + current_row RECORD; + fence subscription_first_invoice_operation_fences%ROWTYPE; +BEGIN + SELECT * INTO STRICT auth FROM account_recent_reauthentication_evidence + WHERE evidence_id = NEW.reauthentication_evidence_id; + SELECT * INTO STRICT invoice FROM subscription_first_invoices + WHERE subscription_id = NEW.subscription_id; + SELECT s.status, s.row_version, s.provider_subscription_id, w.phase INTO STRICT current_row + FROM subscription s JOIN subscription_provisioning_work w ON w.subscription_id = s.subscription_id + WHERE s.subscription_id = NEW.subscription_id AND w.request_id = invoice.creation_request_id + AND s.superseded_at IS NULL FOR SHARE OF s, w; + IF current_row.status <> 'provisioning' OR current_row.phase <> 'AWAITING_PAYMENT' + OR current_row.row_version <> NEW.expected_row_version + OR current_row.provider_subscription_id IS DISTINCT FROM invoice.provider_subscription_id + OR auth.purpose <> 'HOSTING_FIRST_INVOICE_PAYMENT' + OR auth.account_uuid <> NEW.account_uuid OR invoice.account_uuid <> NEW.account_uuid + OR invoice.tuple_digest <> NEW.tuple_digest + OR NEW.consented_at < auth.issued_at - auth.max_clock_skew_seconds * INTERVAL '1 second' + OR NEW.consented_at >= NEW.valid_until + OR NEW.valid_until > auth.issued_at + (auth.recent_age_seconds - auth.max_clock_skew_seconds) * INTERVAL '1 second' + OR NEW.valid_until > invoice.expires_at + OR NOT EXISTS (SELECT 1 FROM account_recent_reauthentication_consumptions c + WHERE c.evidence_id = auth.evidence_id AND c.creation_operation_id = auth.creation_operation_id + AND c.account_uuid = auth.account_uuid AND c.purpose = auth.purpose) THEN + RAISE EXCEPTION 'First-invoice consent requires exact current billing-purpose reauthentication' + USING ERRCODE = '23514'; + END IF; + + IF auth.billing_context_authorization_purpose = 'INITIAL_CONFIRMATION' THEN + SELECT * INTO STRICT fence FROM subscription_first_invoice_operation_fences + WHERE subscription_id = NEW.subscription_id; + IF NEW.request_id IS DISTINCT FROM auth.creation_operation_id + OR NEW.request_id IS DISTINCT FROM auth.billing_context_original_request_id + OR auth.billing_context_authorization_request_id IS DISTINCT FROM NEW.request_id + OR auth.billing_context_expected_authorization_version <> 0 + OR auth.billing_context_subscription_id IS DISTINCT FROM NEW.subscription_id + OR auth.billing_context_tuple_digest IS DISTINCT FROM NEW.tuple_digest + OR auth.billing_context_expected_row_version IS DISTINCT FROM NEW.expected_row_version + OR auth.billing_context_invoice_expires_at IS DISTINCT FROM invoice.expires_at + OR fence.request_id IS DISTINCT FROM NEW.request_id + OR fence.account_uuid IS DISTINCT FROM NEW.account_uuid + OR fence.tuple_digest IS DISTINCT FROM NEW.tuple_digest + OR fence.expected_row_version IS DISTINCT FROM NEW.expected_row_version + OR fence.invoice_expires_at IS DISTINCT FROM invoice.expires_at + OR fence.reauthentication_evidence_id IS DISTINCT FROM auth.evidence_id + OR fence.binding_digest IS DISTINCT FROM auth.billing_context_digest THEN + RAISE EXCEPTION 'Initial first-invoice consent differs from its durable original operation fence' + USING ERRCODE = '23514'; + END IF; + ELSIF auth.billing_context_authorization_purpose = 'PRE_ROW_RENEWAL' THEN + SELECT * INTO STRICT fence FROM subscription_first_invoice_operation_fences + WHERE subscription_id = NEW.subscription_id; + IF auth.creation_operation_id IS DISTINCT FROM auth.billing_context_authorization_request_id + OR auth.billing_context_original_request_id IS DISTINCT FROM NEW.request_id + OR auth.billing_context_expected_authorization_version <> 0 + OR auth.billing_context_subscription_id IS DISTINCT FROM NEW.subscription_id + OR auth.billing_context_tuple_digest IS DISTINCT FROM NEW.tuple_digest + OR auth.billing_context_expected_row_version IS DISTINCT FROM NEW.expected_row_version + OR auth.billing_context_invoice_expires_at IS DISTINCT FROM invoice.expires_at + OR fence.request_id IS DISTINCT FROM NEW.request_id + OR fence.account_uuid IS DISTINCT FROM NEW.account_uuid + OR fence.tuple_digest IS DISTINCT FROM NEW.tuple_digest + OR fence.expected_row_version IS DISTINCT FROM NEW.expected_row_version + OR fence.invoice_expires_at IS DISTINCT FROM invoice.expires_at THEN + RAISE EXCEPTION 'Pre-row first-invoice consent differs from its durable original operation fence' + USING ERRCODE = '23514'; + END IF; + ELSE + RAISE EXCEPTION 'First-invoice consent requires typed opening or pre-row billing proof' + USING ERRCODE = '23514'; + END IF; + NEW.created_transaction_id := txid_current(); + RETURN NEW; +END; +$$; + +CREATE OR REPLACE FUNCTION account_first_invoice_authorization_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + consent subscription_first_invoice_confirmations%ROWTYPE; + auth account_recent_reauthentication_evidence%ROWTYPE; + invoice subscription_first_invoices%ROWTYPE; + current_row RECORD; + fence subscription_first_invoice_operation_fences%ROWTYPE; + latest BIGINT; +BEGIN + SELECT s.status, s.row_version, s.provider_subscription_id, w.phase INTO STRICT current_row + FROM subscription s JOIN subscription_provisioning_work w ON w.subscription_id = s.subscription_id + WHERE s.subscription_id = NEW.subscription_id AND s.superseded_at IS NULL FOR UPDATE OF s; + SELECT * INTO STRICT consent FROM subscription_first_invoice_confirmations + WHERE request_id = NEW.request_id; + SELECT * INTO STRICT invoice FROM subscription_first_invoices + WHERE subscription_id = NEW.subscription_id; + SELECT * INTO STRICT auth FROM account_recent_reauthentication_evidence + WHERE evidence_id = NEW.reauthentication_evidence_id; + SELECT COALESCE(MAX(authorization_version), 0) INTO latest + FROM subscription_first_invoice_authorizations WHERE subscription_id = NEW.subscription_id; + IF consent.subscription_id <> NEW.subscription_id OR current_row.status <> 'provisioning' + OR current_row.phase <> 'AWAITING_PAYMENT' + OR current_row.row_version <> consent.expected_row_version + OR current_row.provider_subscription_id <> invoice.provider_subscription_id + OR NEW.authorization_version <> latest + 1 + OR NEW.request_id <> consent.request_id + OR auth.account_uuid <> consent.account_uuid + OR auth.purpose <> 'HOSTING_FIRST_INVOICE_PAYMENT' + OR auth.creation_operation_id <> NEW.authorization_request_id + OR NEW.consented_at < auth.issued_at - auth.max_clock_skew_seconds * INTERVAL '1 second' OR NEW.consented_at >= NEW.valid_until + OR NEW.valid_until > invoice.expires_at + OR NEW.valid_until > auth.issued_at + (auth.recent_age_seconds - auth.max_clock_skew_seconds) * INTERVAL '1 second' + OR NOT EXISTS (SELECT 1 FROM account_recent_reauthentication_consumptions c + WHERE c.evidence_id = auth.evidence_id + AND c.creation_operation_id = NEW.authorization_request_id + AND c.account_uuid = consent.account_uuid AND c.purpose = auth.purpose) THEN + RAISE EXCEPTION 'First-invoice authorization requires fresh exact consumed consent and current version' + USING ERRCODE = '23514'; + END IF; + + IF NEW.authorization_version = 1 THEN + SELECT * INTO STRICT fence FROM subscription_first_invoice_operation_fences + WHERE subscription_id = NEW.subscription_id; + IF consent.created_transaction_id <> txid_current() + OR NEW.reauthentication_evidence_id <> consent.reauthentication_evidence_id + OR auth.billing_context_subscription_id IS DISTINCT FROM NEW.subscription_id + OR auth.billing_context_original_request_id IS DISTINCT FROM NEW.request_id + OR auth.billing_context_tuple_digest IS DISTINCT FROM consent.tuple_digest + OR auth.billing_context_expected_row_version IS DISTINCT FROM consent.expected_row_version + OR auth.billing_context_invoice_expires_at IS DISTINCT FROM invoice.expires_at + OR auth.billing_context_authorization_request_id IS DISTINCT FROM NEW.authorization_request_id + OR auth.billing_context_expected_authorization_version <> 0 + OR fence.request_id IS DISTINCT FROM NEW.request_id + OR fence.account_uuid IS DISTINCT FROM consent.account_uuid + OR fence.tuple_digest IS DISTINCT FROM consent.tuple_digest + OR fence.expected_row_version IS DISTINCT FROM consent.expected_row_version + OR fence.invoice_expires_at IS DISTINCT FROM invoice.expires_at THEN + RAISE EXCEPTION 'First-invoice winner must bind exact consent to the original operation fence' + USING ERRCODE = '23514'; + END IF; + IF NEW.authorization_request_id = NEW.request_id THEN + IF auth.billing_context_authorization_purpose <> 'INITIAL_CONFIRMATION' + OR fence.reauthentication_evidence_id IS DISTINCT FROM auth.evidence_id + OR fence.binding_digest IS DISTINCT FROM auth.billing_context_digest THEN + RAISE EXCEPTION 'Original confirmation must win only with its retained opening proof' + USING ERRCODE = '23514'; + END IF; + ELSIF auth.billing_context_authorization_purpose <> 'PRE_ROW_RENEWAL' THEN + RAISE EXCEPTION 'Distinct first authorization must be an explicit pre-row renewal' + USING ERRCODE = '23514'; + END IF; + ELSE + IF NEW.authorization_request_id = NEW.request_id + OR auth.billing_context_authorization_purpose <> 'FOLLOWUP_RENEWAL' + OR auth.billing_context_original_request_id IS DISTINCT FROM NEW.request_id + OR auth.billing_context_expected_authorization_version <> NEW.authorization_version - 1 + OR auth.billing_context_subscription_id IS DISTINCT FROM NEW.subscription_id + OR auth.billing_context_tuple_digest IS DISTINCT FROM consent.tuple_digest + OR auth.billing_context_expected_row_version IS DISTINCT FROM consent.expected_row_version + OR auth.billing_context_invoice_expires_at IS DISTINCT FROM invoice.expires_at + OR auth.billing_context_authorization_request_id IS DISTINCT FROM NEW.authorization_request_id THEN + RAISE EXCEPTION 'Follow-up first-invoice authorization requires exact retained operation binding' + USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM subscription_first_invoice_operation_fences f + WHERE f.subscription_id = NEW.subscription_id) + AND NOT EXISTS (SELECT 1 FROM subscription_first_invoice_operation_fences f + WHERE f.subscription_id = NEW.subscription_id AND f.request_id = NEW.request_id + AND f.account_uuid = consent.account_uuid AND f.tuple_digest = consent.tuple_digest + AND f.expected_row_version = consent.expected_row_version + AND f.invoice_expires_at = invoice.expires_at) THEN + RAISE EXCEPTION 'Follow-up authorization differs from its retained operation fence' + USING ERRCODE = '23514'; + END IF; + END IF; + NEW.created_transaction_id := txid_current(); + RETURN NEW; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1046.7__settle_first_invoice_expiry_before_post.sql b/services/account-service/src/main/resources/db/migration/V1046.7__settle_first_invoice_expiry_before_post.sql new file mode 100644 index 0000000000..2f93e9c159 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1046.7__settle_first_invoice_expiry_before_post.sql @@ -0,0 +1,653 @@ +-- A claimed confirmation may be canceled only when its winning invocation retained an +-- independently committed expiry-before-post marker and an exact later terminal Stripe read. +ALTER TABLE subscription_first_invoice_expired_before_post + ADD COLUMN created_transaction_id BIGINT NOT NULL DEFAULT txid_current() + CHECK (created_transaction_id > 0); + +CREATE INDEX idx_stripe_event_inbox_first_invoice_success_mode_created + ON stripe_event_inbox (livemode, provider_created_at_epoch_seconds) + WHERE event_type = 'payment_intent.succeeded'; + +CREATE TABLE subscription_first_invoice_no_send_cancellations ( + cancellation_request_id UUID PRIMARY KEY + REFERENCES subscription_lifecycle_operations(request_id) ON DELETE RESTRICT, + confirmation_request_id UUID NOT NULL UNIQUE + REFERENCES subscription_first_invoice_expired_before_post(request_id) ON DELETE RESTRICT, + invoice_id VARCHAR(255) NOT NULL UNIQUE + REFERENCES subscription_first_invoices(invoice_id) ON DELETE RESTRICT, + payment_intent_id VARCHAR(255) NOT NULL UNIQUE + REFERENCES subscription_first_invoices(payment_intent_id) ON DELETE RESTRICT, + read_started_at TIMESTAMPTZ NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + created_transaction_id BIGINT NOT NULL DEFAULT txid_current() CHECK (created_transaction_id > 0), + CHECK (cancellation_request_id <> confirmation_request_id), + CHECK (observed_at >= read_started_at), + FOREIGN KEY (cancellation_request_id) + REFERENCES subscription_lifecycle_receipts(request_id) DEFERRABLE INITIALLY DEFERRED +); + +-- The only inbox rows which block cancellation are an exact signed success for the retained +-- first intent, mode, customer, method, amount, currency and original consent. +-- [jooq ignore start] +CREATE FUNCTION account_first_invoice_signed_success_retained(intent_id TEXT, provider_livemode BOOLEAN) +RETURNS BOOLEAN LANGUAGE SQL STABLE AS $$ + SELECT EXISTS ( + SELECT 1 + FROM stripe_event_inbox inbox + JOIN subscription_first_invoices invoice + ON invoice.payment_intent_id = intent_id + AND invoice.livemode = provider_livemode + JOIN subscription_first_invoice_command_claims claim + ON claim.subscription_id = invoice.subscription_id + JOIN subscription_first_invoice_expired_before_post marker + ON marker.request_id = claim.request_id + JOIN subscription_first_invoice_confirmations confirmation + ON (confirmation.request_id, confirmation.subscription_id) + = (claim.request_id, claim.subscription_id) + WHERE inbox.event_type = 'payment_intent.succeeded' + AND inbox.livemode = provider_livemode + AND inbox.provider_event_id = convert_from(inbox.raw_payload, 'UTF8')::jsonb->>'id' + AND convert_from(inbox.raw_payload, 'UTF8')::jsonb->>'type' = inbox.event_type + AND convert_from(inbox.raw_payload, 'UTF8')::jsonb->>'livemode' = provider_livemode::TEXT + AND convert_from(inbox.raw_payload, 'UTF8')::jsonb->'data'->'object'->>'object' = 'payment_intent' + AND convert_from(inbox.raw_payload, 'UTF8')::jsonb->'data'->'object'->>'status' = 'succeeded' + AND convert_from(inbox.raw_payload, 'UTF8')::jsonb->'data'->'object'->>'id' = invoice.payment_intent_id + AND convert_from(inbox.raw_payload, 'UTF8')::jsonb->'data'->'object'->>'customer' = invoice.provider_customer_id + AND convert_from(inbox.raw_payload, 'UTF8')::jsonb->'data'->'object'->>'payment_method' = invoice.provider_payment_method_id + AND convert_from(inbox.raw_payload, 'UTF8')::jsonb->'data'->'object'->>'amount' = invoice.amount::TEXT + AND convert_from(inbox.raw_payload, 'UTF8')::jsonb->'data'->'object'->>'amount_received' = invoice.amount::TEXT + AND convert_from(inbox.raw_payload, 'UTF8')::jsonb->'data'->'object'->>'currency' = invoice.currency + AND convert_from(inbox.raw_payload, 'UTF8')::jsonb->'data'->'object'->>'livemode' = provider_livemode::TEXT + AND inbox.provider_created_at_epoch_seconds >= floor(EXTRACT(EPOCH FROM confirmation.consented_at)) + ); +$$; + +-- Intake and terminal release serialize on the immutable subscription row. If intake wins, the +-- cancellation journal observes the retained success and refuses. If cancellation wins, intake +-- remains available for the separate late-payment conflict journal. +CREATE FUNCTION account_first_invoice_success_intake_lock() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE event_payload JSONB; target_subscription UUID; +BEGIN + IF TG_OP <> 'INSERT' OR NEW.event_type <> 'payment_intent.succeeded' THEN + RETURN NEW; + END IF; + event_payload := convert_from(NEW.raw_payload, 'UTF8')::jsonb; + IF event_payload->>'id' IS DISTINCT FROM NEW.provider_event_id + OR event_payload->>'type' IS DISTINCT FROM NEW.event_type + OR event_payload->>'livemode' IS DISTINCT FROM NEW.livemode::TEXT + OR event_payload->'data'->'object'->>'object' IS DISTINCT FROM 'payment_intent' + OR event_payload->'data'->'object'->>'status' IS DISTINCT FROM 'succeeded' THEN + RETURN NEW; + END IF; + SELECT invoice.subscription_id INTO target_subscription + FROM subscription_first_invoices invoice + WHERE invoice.payment_intent_id = event_payload->'data'->'object'->>'id' + AND invoice.livemode = NEW.livemode + AND invoice.provider_customer_id = event_payload->'data'->'object'->>'customer' + AND invoice.provider_payment_method_id = event_payload->'data'->'object'->>'payment_method' + AND invoice.amount::TEXT = event_payload->'data'->'object'->>'amount' + AND invoice.amount::TEXT = event_payload->'data'->'object'->>'amount_received' + AND invoice.currency = event_payload->'data'->'object'->>'currency' + AND event_payload->'data'->'object'->>'livemode' = invoice.livemode::TEXT + LIMIT 1; + IF target_subscription IS NOT NULL THEN + PERFORM 1 FROM subscription WHERE subscription_id = target_subscription FOR UPDATE; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER first_invoice_success_intake_lock + BEFORE INSERT ON stripe_event_inbox + FOR EACH ROW EXECUTE FUNCTION account_first_invoice_success_intake_lock(); + +CREATE FUNCTION account_first_invoice_no_send_cancellation_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + invoice subscription_first_invoices%ROWTYPE; + confirmation subscription_first_invoice_confirmations%ROWTYPE; + claim subscription_first_invoice_command_claims%ROWTYPE; + auth subscription_first_invoice_authorizations%ROWTYPE; + marker subscription_first_invoice_expired_before_post%ROWTYPE; + operation subscription_lifecycle_operations%ROWTYPE; + current_row subscription%ROWTYPE; + creation subscription_create_operations%ROWTYPE; + owner account_tenant_billing_owners%ROWTYPE; + operation_payload JSONB; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'First-invoice no-send cancellations are immutable' USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT invoice FROM subscription_first_invoices + WHERE invoice_id = NEW.invoice_id AND payment_intent_id = NEW.payment_intent_id; + SELECT * INTO STRICT claim FROM subscription_first_invoice_command_claims + WHERE request_id = NEW.confirmation_request_id AND subscription_id = invoice.subscription_id; + SELECT * INTO STRICT marker FROM subscription_first_invoice_expired_before_post + WHERE request_id = NEW.confirmation_request_id; + SELECT * INTO STRICT confirmation FROM subscription_first_invoice_confirmations + WHERE request_id = claim.request_id AND subscription_id = claim.subscription_id; + SELECT * INTO STRICT auth FROM subscription_first_invoice_authorizations + WHERE authorization_request_id = claim.authorization_request_id + AND request_id = claim.request_id AND subscription_id = claim.subscription_id; + SELECT * INTO STRICT operation FROM subscription_lifecycle_operations + WHERE request_id = NEW.cancellation_request_id; + SELECT * INTO STRICT current_row FROM subscription + WHERE subscription_id = invoice.subscription_id FOR UPDATE; + SELECT * INTO STRICT creation FROM subscription_create_operations + WHERE request_id = invoice.creation_request_id; + SELECT * INTO STRICT owner FROM account_tenant_billing_owners + WHERE tenant_uuid = invoice.tenant_id; + operation_payload := convert_from(operation.request_payload, 'UTF8')::jsonb; + + IF NEW.created_transaction_id <> txid_current() + OR claim.created_transaction_id = txid_current() + OR marker.created_transaction_id = txid_current() + OR marker.created_transaction_id = claim.created_transaction_id + OR operation.created_transaction_id <> txid_current() + OR operation.state <> 'PENDING' + OR operation.provisioning_attempt_id IS NOT NULL + OR (operation.creation_request_id, operation.subscription_id, operation.tenant_id, + operation.provider_subscription_id) + IS DISTINCT FROM (invoice.creation_request_id, invoice.subscription_id, invoice.tenant_id, + invoice.provider_subscription_id) + OR (current_row.status, current_row.account_uuid, current_row.tenant_id, + current_row.creation_request_id, current_row.provider_subscription_id, + current_row.provider_customer_id, current_row.payment_instrument_id, + current_row.reserved_instrument_version, current_row.row_version, + current_row.lifecycle_inflight_request_id, current_row.superseded_at) + IS DISTINCT FROM ('provisioning', invoice.account_uuid, invoice.tenant_id, + invoice.creation_request_id, invoice.provider_subscription_id, + invoice.provider_customer_id, invoice.payment_instrument_id, + invoice.instrument_version, operation.reserved_row_version, + operation.request_id, NULL::timestamptz) + OR (creation.account_uuid, creation.tenant_id, creation.owner_version, creation.owner_generation, + creation.provider_customer_id, creation.payment_instrument_id, creation.reserved_instrument_version) + IS DISTINCT FROM (invoice.account_uuid, invoice.tenant_id, current_row.owner_version, + current_row.owner_generation, invoice.provider_customer_id, invoice.payment_instrument_id, + invoice.instrument_version) + OR (owner.owner_account_uuid, owner.owner_version, owner.owner_generation) + IS DISTINCT FROM (invoice.account_uuid, creation.owner_version, creation.owner_generation) + OR (confirmation.tuple_digest, confirmation.account_uuid) + IS DISTINCT FROM (invoice.tuple_digest, invoice.account_uuid) + OR marker.observed_at < auth.valid_until + OR NEW.read_started_at < marker.observed_at + OR NEW.observed_at < NEW.read_started_at + OR NEW.observed_at > operation.created_at + OR operation.created_at >= operation.deadline_at + OR operation.created_at - NEW.read_started_at + >= operation.observation_age_millis * INTERVAL '1 millisecond' + OR operation_payload->>'schemaVersion' IS DISTINCT FROM 'account-hosting-unpaid-first-invoice-cancellation/v1' + OR operation_payload->>'requestId' IS DISTINCT FROM operation.request_id::TEXT + OR operation_payload->>'creationRequestId' IS DISTINCT FROM invoice.creation_request_id::TEXT + OR operation_payload->>'expectedRowVersion' IS DISTINCT FROM operation.expected_row_version::TEXT + OR operation_payload->>'providerSubscriptionId' IS DISTINCT FROM invoice.provider_subscription_id + OR operation_payload->>'provisioningAttemptId' IS DISTINCT FROM '' + OR account_first_invoice_signed_success_retained(invoice.payment_intent_id, invoice.livemode) + OR EXISTS (SELECT 1 FROM subscription_first_invoice_success_evidence + WHERE subscription_id = invoice.subscription_id) + OR EXISTS (SELECT 1 FROM subscription_first_invoice_completions + WHERE subscription_id = invoice.subscription_id) THEN + RAISE EXCEPTION 'Claimed first-invoice cancellation requires an exact expired no-send claim and fresh terminal read' USING ERRCODE = '23514'; + END IF; + NEW.created_transaction_id := txid_current(); + RETURN NEW; +END; +$$; +CREATE TRIGGER first_invoice_no_send_cancellation_guard + BEFORE INSERT OR UPDATE OR DELETE ON subscription_first_invoice_no_send_cancellations + FOR EACH ROW EXECUTE FUNCTION account_first_invoice_no_send_cancellation_guard(); + +CREATE FUNCTION account_first_invoice_no_send_cancellation_consistency() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM subscription_first_invoice_no_send_cancellations release + JOIN subscription_first_invoices invoice + ON invoice.invoice_id = release.invoice_id + AND invoice.payment_intent_id = release.payment_intent_id + JOIN subscription_first_invoice_command_claims claim + ON claim.request_id = release.confirmation_request_id + AND claim.subscription_id = invoice.subscription_id + JOIN subscription_first_invoice_expired_before_post marker + ON marker.request_id = claim.request_id + JOIN subscription_first_invoice_authorizations auth + ON (auth.authorization_request_id, auth.request_id, auth.subscription_id) + = (claim.authorization_request_id, claim.request_id, claim.subscription_id) + JOIN subscription_lifecycle_operations operation + ON operation.request_id = release.cancellation_request_id + AND operation.subscription_id = invoice.subscription_id + JOIN subscription_lifecycle_receipts receipt + ON receipt.request_id = operation.request_id + AND receipt.subscription_id = operation.subscription_id + JOIN subscription_lifecycle_observations observation + ON (observation.request_id, observation.attempt_id, observation.evidence_digest) + = (receipt.request_id, receipt.attempt_id, receipt.observation_digest) + JOIN subscription_lifecycle_attempts attempt + ON (attempt.request_id, attempt.attempt_id) = (receipt.request_id, receipt.attempt_id) + JOIN subscription_provider_terminal_resolutions terminal + ON terminal.subscription_id = invoice.subscription_id + JOIN subscription_instrument_reservations reservation + ON reservation.subscription_id = invoice.subscription_id + JOIN subscription current_row + ON current_row.subscription_id = invoice.subscription_id + JOIN subscription_create_operations creation + ON creation.request_id = invoice.creation_request_id + JOIN account_tenant_billing_owners owner + ON owner.tenant_uuid = invoice.tenant_id + WHERE release.cancellation_request_id = NEW.cancellation_request_id + AND release.confirmation_request_id = NEW.confirmation_request_id + AND release.invoice_id = NEW.invoice_id + AND release.payment_intent_id = NEW.payment_intent_id + AND release.created_transaction_id = txid_current() + AND claim.created_transaction_id <> marker.created_transaction_id + AND marker.created_transaction_id <> release.created_transaction_id + AND marker.observed_at >= auth.valid_until + AND release.read_started_at >= marker.observed_at + AND release.read_started_at >= observation.observed_at + AND release.read_started_at >= attempt.started_at + AND release.observed_at >= release.read_started_at + AND release.observed_at <= operation.created_at + AND release.observed_at < attempt.expires_at + AND operation.created_at < attempt.expires_at + AND operation.created_at - release.read_started_at + < operation.observation_age_millis * INTERVAL '1 millisecond' + AND operation.state = 'COMMITTED' + AND operation.created_transaction_id = release.created_transaction_id + AND operation.creation_request_id = invoice.creation_request_id + AND operation.tenant_id = invoice.tenant_id + AND operation.provider_subscription_id = invoice.provider_subscription_id + AND operation.provisioning_attempt_id IS NULL + AND operation.request_digest = receipt.request_digest + AND receipt.committed_transaction_id = release.created_transaction_id + AND receipt.status = 'canceled' + AND receipt.tenant_id = invoice.tenant_id + AND receipt.provider_subscription_id = invoice.provider_subscription_id + AND receipt.plan_quote_digest = creation.plan_quote_digest + AND observation.raw_status = 'canceled' + AND terminal.request_id = invoice.creation_request_id + AND terminal.outcome = 'CANCELED' + AND terminal.provider_subscription_id = invoice.provider_subscription_id + AND terminal.evidence_digest = observation.evidence_digest + AND reservation.request_id = invoice.creation_request_id + AND reservation.terminal_resolution_id = terminal.resolution_id + AND reservation.released_at IS NOT NULL + AND current_row.status = 'canceled' + AND current_row.current_receipt_request_id = operation.request_id + AND current_row.lifecycle_inflight_request_id IS NULL + AND current_row.row_version = receipt.subscription_row_version + AND current_row.provider_subscription_id = invoice.provider_subscription_id + AND current_row.tenant_id = invoice.tenant_id + AND current_row.account_uuid = invoice.account_uuid + AND current_row.superseded_at IS NULL + AND (owner.owner_account_uuid, owner.owner_version, owner.owner_generation) + = (invoice.account_uuid, creation.owner_version, creation.owner_generation) + AND (current_row.owner_version, current_row.owner_generation) + = (creation.owner_version, creation.owner_generation) + AND NOT EXISTS (SELECT 1 FROM subscription_lifecycle_operator_outbox + WHERE request_id = operation.request_id) + AND NOT EXISTS (SELECT 1 FROM subscription_provisioning_operator_outbox + WHERE request_id = invoice.creation_request_id) + AND NOT EXISTS (SELECT 1 FROM subscription_first_invoice_success_evidence + WHERE subscription_id = invoice.subscription_id) + AND NOT EXISTS (SELECT 1 FROM subscription_first_invoice_completions + WHERE subscription_id = invoice.subscription_id) + AND convert_from(operation.request_payload, 'UTF8')::jsonb->>'schemaVersion' + = 'account-hosting-unpaid-first-invoice-cancellation/v1' + AND convert_from(operation.request_payload, 'UTF8')::jsonb->>'requestId' + = operation.request_id::TEXT + AND convert_from(operation.request_payload, 'UTF8')::jsonb->>'creationRequestId' + = invoice.creation_request_id::TEXT + AND convert_from(operation.request_payload, 'UTF8')::jsonb->>'expectedRowVersion' + = operation.expected_row_version::TEXT + AND convert_from(operation.request_payload, 'UTF8')::jsonb->>'providerSubscriptionId' + = invoice.provider_subscription_id + AND convert_from(operation.request_payload, 'UTF8')::jsonb->>'provisioningAttemptId' = '' + ) THEN + RAISE EXCEPTION 'No-send cancellation lacks its exact committed lifecycle receipt and terminal release' USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; +CREATE CONSTRAINT TRIGGER first_invoice_no_send_cancellation_consistency + AFTER INSERT ON subscription_first_invoice_no_send_cancellations + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_first_invoice_no_send_cancellation_consistency(); +CREATE TRIGGER first_invoice_no_send_cancellation_immutable + BEFORE UPDATE OR DELETE ON subscription_first_invoice_no_send_cancellations + FOR EACH ROW EXECUTE FUNCTION account_subscription_no_mutation(); +CREATE TRIGGER first_invoice_no_send_cancellation_no_truncate + BEFORE TRUNCATE ON subscription_first_invoice_no_send_cancellations + FOR EACH STATEMENT EXECUTE FUNCTION account_subscription_no_mutation(); + +CREATE OR REPLACE FUNCTION account_subscription_provisioning_consistency() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + work subscription_provisioning_work%ROWTYPE; + attempt subscription_provisioning_attempts%ROWTYPE; + current_row subscription%ROWTYPE; + notice subscription_provisioning_operator_outbox%ROWTYPE; +BEGIN + SELECT * INTO STRICT work FROM subscription_provisioning_work WHERE request_id = NEW.request_id; + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = work.subscription_id; + IF work.last_attempt_id IS NOT NULL THEN + SELECT * INTO STRICT attempt FROM subscription_provisioning_attempts WHERE attempt_id = work.last_attempt_id; + IF (attempt.request_id, attempt.subscription_id, attempt.attempt_number, attempt.claimed_row_version, attempt.expires_at) + IS DISTINCT FROM (work.request_id, work.subscription_id, work.attempt_count, work.subscription_row_version, work.lease_expires_at) + OR attempt.expires_at > work.deadline_at + OR (work.phase NOT IN ('CONFIRMED','CANCELED') + AND (current_row.status <> 'provisioning' OR current_row.row_version < attempt.claimed_row_version + OR current_row.superseded_at IS NOT NULL)) THEN + RAISE EXCEPTION 'Provisioning attempt lacks its exact current CAS' USING ERRCODE = '23514'; + END IF; + END IF; + IF work.phase = 'BILLING_RECONCILIATION_TERMINAL_FAILURE' THEN + SELECT * INTO STRICT notice FROM subscription_provisioning_operator_outbox WHERE request_id = work.request_id; + IF (notice.subscription_id, notice.reason, notice.recorded_at) + IS DISTINCT FROM (work.subscription_id, work.failure_reason, work.terminal_at) THEN + RAISE EXCEPTION 'Provisioning failure lacks its exact operator work item' USING ERRCODE = '23514'; + END IF; + ELSIF EXISTS (SELECT 1 FROM subscription_provisioning_operator_outbox WHERE request_id = work.request_id) THEN + RAISE EXCEPTION 'Operator resolution work requires terminal reconciliation failure' USING ERRCODE = '23514'; + END IF; + IF work.phase = 'CANCELED' AND ( + work.last_attempt_id IS NULL + OR current_row.status <> 'canceled' + OR NOT EXISTS ( + SELECT 1 FROM subscription_first_invoices invoice + JOIN subscription_lifecycle_receipts receipt USING (subscription_id) + JOIN subscription_lifecycle_operations operation USING (request_id, subscription_id) + JOIN subscription_lifecycle_observations observation + ON (observation.request_id, observation.attempt_id, observation.evidence_digest) + = (receipt.request_id, receipt.attempt_id, receipt.observation_digest) + JOIN subscription_provider_terminal_resolutions terminal + ON terminal.subscription_id = invoice.subscription_id + JOIN subscription_instrument_reservations reservation + ON reservation.subscription_id = invoice.subscription_id + WHERE invoice.subscription_id = work.subscription_id + AND invoice.creation_request_id = work.request_id + AND (operation.creation_request_id, operation.provider_subscription_id) + = (invoice.creation_request_id, invoice.provider_subscription_id) + AND operation.request_id = current_row.current_receipt_request_id + AND operation.state = 'COMMITTED' AND operation.provisioning_attempt_id IS NULL + AND convert_from(operation.request_payload, 'UTF8')::jsonb->>'schemaVersion' + = 'account-hosting-unpaid-first-invoice-cancellation/v1' + AND receipt.status = 'canceled' + AND receipt.subscription_row_version = current_row.row_version + AND receipt.provider_subscription_id = current_row.provider_subscription_id + AND receipt.committed_transaction_id = txid_current() + AND observation.raw_status = 'canceled' + AND terminal.resolution_id = current_row.terminal_resolution_id + AND terminal.outcome = 'CANCELED' + AND terminal.evidence_digest = observation.evidence_digest + AND reservation.request_id = work.request_id + AND reservation.terminal_resolution_id = terminal.resolution_id + AND reservation.released_at IS NOT NULL + AND ( + ( + NOT EXISTS (SELECT 1 FROM subscription_first_invoice_command_claims claim + WHERE claim.subscription_id = work.subscription_id) + AND NOT EXISTS (SELECT 1 FROM subscription_first_invoice_success_evidence success + WHERE success.subscription_id = work.subscription_id) + AND NOT EXISTS (SELECT 1 FROM subscription_first_invoice_no_send_cancellations release + WHERE release.invoice_id = invoice.invoice_id) + ) + OR + ( + EXISTS (SELECT 1 FROM subscription_first_invoice_command_claims claim + WHERE claim.subscription_id = work.subscription_id) + AND NOT EXISTS (SELECT 1 FROM subscription_first_invoice_success_evidence success + WHERE success.subscription_id = work.subscription_id) + AND NOT EXISTS (SELECT 1 FROM subscription_first_invoice_completions completion + WHERE completion.subscription_id = work.subscription_id) + AND EXISTS ( + SELECT 1 + FROM subscription_first_invoice_no_send_cancellations release + JOIN subscription_first_invoice_command_claims claim + ON claim.request_id = release.confirmation_request_id + AND claim.subscription_id = invoice.subscription_id + JOIN subscription_first_invoice_expired_before_post marker + ON marker.request_id = claim.request_id + JOIN subscription_first_invoice_authorizations auth + ON (auth.authorization_request_id, auth.request_id, auth.subscription_id) + = (claim.authorization_request_id, claim.request_id, claim.subscription_id) + JOIN subscription_lifecycle_attempts cancellation_attempt + ON (cancellation_attempt.request_id, cancellation_attempt.attempt_id) + = (operation.request_id, observation.attempt_id) + WHERE release.cancellation_request_id = operation.request_id + AND release.confirmation_request_id = claim.request_id + AND release.invoice_id = invoice.invoice_id + AND release.payment_intent_id = invoice.payment_intent_id + AND release.created_transaction_id = receipt.committed_transaction_id + AND release.created_transaction_id = txid_current() + AND release.read_started_at >= observation.observed_at + AND release.read_started_at >= cancellation_attempt.started_at + AND release.observed_at >= release.read_started_at + AND release.observed_at <= operation.created_at + AND release.observed_at < cancellation_attempt.expires_at + AND operation.created_at < cancellation_attempt.expires_at + AND operation.created_at - release.read_started_at + < operation.observation_age_millis * INTERVAL '1 millisecond' + AND claim.created_transaction_id <> marker.created_transaction_id + AND marker.created_transaction_id <> release.created_transaction_id + AND marker.observed_at >= auth.valid_until + AND release.read_started_at >= marker.observed_at + ) + ) + ) + )) THEN + RAISE EXCEPTION 'Canceled first-invoice provisioning requires exact terminal release and, for a claimed command, its committed no-send witness' USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; + +-- A signed success is terminally conflicting after either the original unclaimed cancellation or +-- a claimed cancellation whose exact no-send witness was committed with that terminal receipt. +CREATE OR REPLACE FUNCTION account_unclaimed_first_invoice_success_cancellation_fence() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE current_status VARCHAR; +BEGIN + SELECT status INTO STRICT current_status FROM subscription + WHERE subscription_id = NEW.subscription_id FOR UPDATE; + IF current_status = 'canceled' AND EXISTS ( + SELECT 1 FROM subscription_provisioning_work + WHERE subscription_id = NEW.subscription_id AND phase = 'CANCELED') THEN + RAISE EXCEPTION 'First-invoice success conflicts with retained terminal cancellation' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE OR REPLACE FUNCTION account_first_invoice_late_paid_conflict_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + current_row subscription%ROWTYPE; + first_invoice subscription_first_invoices%ROWTYPE; + confirmation subscription_first_invoice_confirmations%ROWTYPE; + inbox stripe_event_inbox%ROWTYPE; + cancellation subscription_lifecycle_operations%ROWTYPE; + receipt subscription_lifecycle_receipts%ROWTYPE; + provisioning subscription_provisioning_work%ROWTYPE; + paid_payload JSONB; + cancellation_payload JSONB; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Late first-invoice payment conflicts are retained' USING ERRCODE = '23514'; + ELSIF TG_OP = 'INSERT' THEN + -- The intake trigger takes this same row lock before retaining a signed success. A success + -- committed before cancellation blocks release; one committed after release reaches here. + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = NEW.subscription_id FOR UPDATE; + SELECT * INTO STRICT first_invoice FROM subscription_first_invoices WHERE subscription_id = NEW.subscription_id; + SELECT * INTO STRICT confirmation FROM subscription_first_invoice_confirmations + WHERE request_id = NEW.request_id AND subscription_id = NEW.subscription_id; + SELECT * INTO STRICT inbox FROM stripe_event_inbox WHERE provider_event_id = NEW.provider_event_id; + + paid_payload := convert_from(inbox.raw_payload, 'UTF8')::jsonb; + IF current_row.status <> 'canceled' + OR current_row.current_receipt_request_id IS NULL + OR current_row.lifecycle_inflight_request_id IS NOT NULL + OR current_row.provider_subscription_id IS DISTINCT FROM first_invoice.provider_subscription_id + OR (current_row.superseded_at IS NULL AND current_row.row_version <> NEW.cancellation_row_version) + OR (first_invoice.creation_request_id, first_invoice.tuple_digest, first_invoice.invoice_id, + first_invoice.payment_intent_id, first_invoice.provider_subscription_id, + first_invoice.provider_customer_id, first_invoice.provider_payment_method_id, + first_invoice.provider_price_id, first_invoice.provider_quantity, + first_invoice.amount, first_invoice.currency, first_invoice.livemode) + IS DISTINCT FROM (NEW.creation_request_id, NEW.tuple_digest, NEW.invoice_id, + NEW.payment_intent_id, NEW.provider_subscription_id, NEW.provider_customer_id, + NEW.provider_payment_method_id, NEW.provider_price_id, NEW.provider_quantity, + NEW.amount, NEW.currency, NEW.livemode) + OR (confirmation.lifecycle_request_id, confirmation.tuple_digest, confirmation.account_uuid) + IS DISTINCT FROM (NEW.lifecycle_request_id, NEW.tuple_digest, first_invoice.account_uuid) + OR inbox.event_type <> 'payment_intent.succeeded' + OR inbox.payload_sha256 <> NEW.event_payload_digest + OR inbox.livemode <> NEW.livemode + OR inbox.provider_event_id IS DISTINCT FROM paid_payload->>'id' + OR inbox.event_type IS DISTINCT FROM paid_payload->>'type' + OR paid_payload->>'livemode' IS DISTINCT FROM NEW.livemode::TEXT + OR paid_payload->'data'->'object'->>'object' IS DISTINCT FROM 'payment_intent' + OR paid_payload->'data'->'object'->>'status' IS DISTINCT FROM 'succeeded' + OR paid_payload->'data'->'object'->>'id' IS DISTINCT FROM NEW.payment_intent_id + OR paid_payload->'data'->'object'->>'customer' IS DISTINCT FROM NEW.provider_customer_id + OR paid_payload->'data'->'object'->>'payment_method' IS DISTINCT FROM NEW.provider_payment_method_id + OR paid_payload->'data'->'object'->>'amount' IS DISTINCT FROM NEW.amount::TEXT + OR paid_payload->'data'->'object'->>'amount_received' IS DISTINCT FROM NEW.amount::TEXT + OR paid_payload->'data'->'object'->>'currency' IS DISTINCT FROM NEW.currency + OR paid_payload->'data'->'object'->>'livemode' IS DISTINCT FROM NEW.livemode::TEXT + OR inbox.provider_created_at_epoch_seconds < floor(EXTRACT(EPOCH FROM confirmation.consented_at)) + OR NEW.observed_status <> 'succeeded' + OR NEW.observation_read_started_at < inbox.received_at + OR NEW.observation_observed_at < NEW.observation_read_started_at + OR NEW.observation_observed_at - NEW.observation_read_started_at >= INTERVAL '20 seconds' + OR NEW.observation_expires_at <> first_invoice.expires_at + OR NOT EXISTS ( + SELECT 1 + FROM subscription_provisioning_work work + JOIN subscription_lifecycle_operations canceled_operation + ON canceled_operation.request_id = current_row.current_receipt_request_id + AND canceled_operation.subscription_id = current_row.subscription_id + JOIN subscription_lifecycle_receipts canceled_receipt + ON canceled_receipt.request_id = canceled_operation.request_id + AND canceled_receipt.subscription_id = canceled_operation.subscription_id + JOIN subscription_lifecycle_observations cancellation_observation + ON (cancellation_observation.request_id, cancellation_observation.attempt_id, + cancellation_observation.evidence_digest) + = (canceled_receipt.request_id, canceled_receipt.attempt_id, + canceled_receipt.observation_digest) + JOIN subscription_provider_terminal_resolutions terminal + ON terminal.resolution_id = current_row.terminal_resolution_id + AND terminal.subscription_id = current_row.subscription_id + JOIN subscription_instrument_reservations reservation + ON reservation.subscription_id = current_row.subscription_id + WHERE work.request_id = first_invoice.creation_request_id + AND work.subscription_id = current_row.subscription_id + AND work.phase = 'CANCELED' + AND work.last_attempt_id IS NOT NULL + AND canceled_operation.state = 'COMMITTED' + AND canceled_operation.creation_request_id = first_invoice.creation_request_id + AND canceled_operation.tenant_id = first_invoice.tenant_id + AND canceled_operation.provider_subscription_id = first_invoice.provider_subscription_id + AND canceled_operation.provisioning_attempt_id IS NULL + AND canceled_operation.request_id = NEW.cancellation_request_id + AND canceled_operation.request_digest = canceled_receipt.request_digest + AND canceled_operation.request_digest = 'sha256:' || encode(sha256(canceled_operation.request_payload), 'hex') + AND canceled_receipt.status = 'canceled' + AND canceled_receipt.receipt_digest = NEW.cancellation_receipt_digest + AND canceled_receipt.subscription_row_version = NEW.cancellation_row_version + AND canceled_receipt.committed_transaction_id = NEW.cancellation_committed_transaction_id + AND canceled_receipt.committed_transaction_id <> txid_current() + AND canceled_receipt.provider_subscription_id = first_invoice.provider_subscription_id + AND canceled_receipt.plan_quote_digest = first_invoice.quote_digest + AND cancellation_observation.raw_status = 'canceled' + AND terminal.request_id = first_invoice.creation_request_id + AND terminal.outcome = 'CANCELED' + AND terminal.provider_subscription_id = first_invoice.provider_subscription_id + AND terminal.evidence_digest = cancellation_observation.evidence_digest + AND reservation.request_id = first_invoice.creation_request_id + AND reservation.terminal_resolution_id = terminal.resolution_id + AND reservation.released_at IS NOT NULL + AND convert_from(canceled_operation.request_payload, 'UTF8')::jsonb->>'schemaVersion' + = 'account-hosting-unpaid-first-invoice-cancellation/v1' + AND convert_from(canceled_operation.request_payload, 'UTF8')::jsonb->>'requestId' + = canceled_operation.request_id::TEXT + AND convert_from(canceled_operation.request_payload, 'UTF8')::jsonb->>'creationRequestId' + = first_invoice.creation_request_id::TEXT + AND convert_from(canceled_operation.request_payload, 'UTF8')::jsonb->>'expectedRowVersion' + = canceled_operation.expected_row_version::TEXT + AND convert_from(canceled_operation.request_payload, 'UTF8')::jsonb->>'providerSubscriptionId' + = first_invoice.provider_subscription_id + AND convert_from(canceled_operation.request_payload, 'UTF8')::jsonb->>'provisioningAttemptId' = '' + AND (current_row.superseded_at IS NOT NULL + OR canceled_receipt.subscription_row_version = current_row.row_version) + AND ( + NOT EXISTS (SELECT 1 FROM subscription_first_invoice_command_claims claim + WHERE claim.subscription_id = current_row.subscription_id) + OR EXISTS ( + SELECT 1 + FROM subscription_first_invoice_no_send_cancellations release + JOIN subscription_first_invoice_command_claims claim + ON claim.request_id = release.confirmation_request_id + AND claim.subscription_id = current_row.subscription_id + JOIN subscription_first_invoice_expired_before_post marker + ON marker.request_id = claim.request_id + JOIN subscription_first_invoice_authorizations auth + ON (auth.authorization_request_id, auth.request_id, + auth.subscription_id) + = (claim.authorization_request_id, claim.request_id, claim.subscription_id) + JOIN subscription_lifecycle_operations witness_operation + ON witness_operation.request_id = release.cancellation_request_id + AND witness_operation.subscription_id = current_row.subscription_id + JOIN subscription_lifecycle_receipts witness_receipt + ON witness_receipt.request_id = witness_operation.request_id + AND witness_receipt.subscription_id = witness_operation.subscription_id + JOIN subscription_lifecycle_observations witness_observation + ON (witness_observation.request_id, witness_observation.attempt_id, + witness_observation.evidence_digest) + = (witness_receipt.request_id, witness_receipt.attempt_id, + witness_receipt.observation_digest) + JOIN subscription_lifecycle_attempts witness_attempt + ON (witness_attempt.request_id, witness_attempt.attempt_id) + = (witness_operation.request_id, witness_observation.attempt_id) + WHERE release.cancellation_request_id = NEW.cancellation_request_id + AND release.confirmation_request_id = NEW.request_id + AND release.invoice_id = first_invoice.invoice_id + AND release.payment_intent_id = first_invoice.payment_intent_id + AND release.created_transaction_id = NEW.cancellation_committed_transaction_id + AND release.created_transaction_id = witness_receipt.committed_transaction_id + AND release.read_started_at >= witness_observation.observed_at + AND release.read_started_at >= witness_attempt.started_at + AND release.observed_at >= release.read_started_at + AND release.observed_at <= witness_operation.created_at + AND release.observed_at < witness_attempt.expires_at + AND witness_operation.created_at < witness_attempt.expires_at + AND witness_operation.created_at - release.read_started_at + < witness_operation.observation_age_millis * INTERVAL '1 millisecond' + AND marker.created_transaction_id <> release.created_transaction_id + AND marker.observed_at >= auth.valid_until + AND claim.created_transaction_id <> marker.created_transaction_id + AND witness_operation.state = 'COMMITTED' + AND witness_receipt.status = 'canceled' + AND witness_observation.raw_status = 'canceled' + ) + ) + ) + OR EXISTS (SELECT 1 FROM subscription_lifecycle_operator_outbox + WHERE request_id = current_row.current_receipt_request_id) + OR EXISTS (SELECT 1 FROM subscription_provisioning_operator_outbox + WHERE request_id = first_invoice.creation_request_id) + OR EXISTS (SELECT 1 FROM subscription_first_invoice_success_evidence + WHERE subscription_id = NEW.subscription_id) + OR EXISTS (SELECT 1 FROM subscription_first_invoice_completions + WHERE subscription_id = NEW.subscription_id) THEN + RAISE EXCEPTION 'Late first-invoice payment requires its exact verified success and committed unpaid cancellation' USING ERRCODE = '23514'; + END IF; + cancellation_payload := convert_from((SELECT request_payload FROM subscription_lifecycle_operations + WHERE request_id = NEW.cancellation_request_id), 'UTF8')::jsonb; + IF NEW.cancellation_request_id IS DISTINCT FROM current_row.current_receipt_request_id + OR NEW.cancellation_committed_transaction_id = txid_current() + OR cancellation_payload->>'schemaVersion' IS DISTINCT FROM 'account-hosting-unpaid-first-invoice-cancellation/v1' THEN + RAISE EXCEPTION 'Late first-invoice payment must retain the current committed unpaid cancellation' USING ERRCODE = '23514'; + END IF; + NEW.created_transaction_id := txid_current(); + RETURN NEW; + ELSE + RAISE EXCEPTION 'Late first-invoice payment conflicts are immutable' USING ERRCODE = '23514'; + END IF; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1046.8__guard_first_invoice_unpaid_cancellation.sql b/services/account-service/src/main/resources/db/migration/V1046.8__guard_first_invoice_unpaid_cancellation.sql new file mode 100644 index 0000000000..41aa8ef2bd --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1046.8__guard_first_invoice_unpaid_cancellation.sql @@ -0,0 +1,93 @@ +-- An exact retained success fences either unpaid checkout branch, including an invoice whose +-- first confirmation has not yet been claimed. When original consent exists, retain its floor. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_first_invoice_signed_success_retained(intent_id TEXT, provider_livemode BOOLEAN) +RETURNS BOOLEAN LANGUAGE SQL STABLE AS $$ + SELECT EXISTS ( + SELECT 1 + FROM subscription_first_invoices invoice + LEFT JOIN subscription_first_invoice_confirmations confirmation + ON confirmation.subscription_id = invoice.subscription_id + JOIN stripe_event_inbox inbox ON inbox.livemode = invoice.livemode + CROSS JOIN LATERAL ( + SELECT convert_from(inbox.raw_payload, 'UTF8')::jsonb AS event + ) payload + CROSS JOIN LATERAL ( + SELECT payload.event #> '{data,object}' AS intent + ) payment + WHERE invoice.payment_intent_id = intent_id + AND invoice.livemode = provider_livemode + AND inbox.event_type = 'payment_intent.succeeded' + AND payload.event->>'id' = inbox.provider_event_id + AND payload.event->>'type' = inbox.event_type + AND payload.event->'created' = to_jsonb(inbox.provider_created_at_epoch_seconds) + AND payload.event->'livemode' = to_jsonb(invoice.livemode) + AND payment.intent->>'object' = 'payment_intent' + AND payment.intent->>'status' = 'succeeded' + AND payment.intent->>'id' = invoice.payment_intent_id + AND payment.intent->>'customer' = invoice.provider_customer_id + AND payment.intent->>'payment_method' = invoice.provider_payment_method_id + AND payment.intent->'amount' = to_jsonb(invoice.amount) + AND payment.intent->'amount_received' = to_jsonb(invoice.amount) + AND payment.intent->>'currency' = invoice.currency + AND payment.intent->'livemode' = to_jsonb(invoice.livemode) + AND (confirmation.consented_at IS NULL + OR inbox.provider_created_at_epoch_seconds >= floor(EXTRACT(EPOCH FROM confirmation.consented_at))) + ); +$$; + +-- New markers carry the actual inserting transaction. Existing immutable markers stay intact. +CREATE OR REPLACE FUNCTION account_first_invoice_expired_before_post_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE claim_transaction BIGINT; authorization_expiry TIMESTAMPTZ; +BEGIN + SELECT c.created_transaction_id, a.valid_until INTO STRICT claim_transaction, authorization_expiry + FROM subscription_first_invoice_command_claims c + JOIN subscription_first_invoice_authorizations a USING (authorization_request_id, request_id, subscription_id) + WHERE c.request_id = NEW.request_id; + IF claim_transaction = txid_current() OR NEW.observed_at < authorization_expiry THEN + RAISE EXCEPTION 'First-invoice no-send evidence requires an independently committed claim and expired authorization' USING ERRCODE = '23514'; + END IF; + NEW.created_transaction_id := txid_current(); + RETURN NEW; +END; +$$; + +-- The transition and release share the subscription lock used by signed inbox intake. Require +-- a fresh snapshot after that lock so a raw writer cannot miss an independently committed event. +CREATE FUNCTION account_first_invoice_unpaid_cancellation_consistency() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE invoice subscription_first_invoices%ROWTYPE; +BEGIN + PERFORM 1 FROM subscription WHERE subscription_id = NEW.subscription_id FOR UPDATE; + SELECT * INTO invoice FROM subscription_first_invoices WHERE subscription_id = NEW.subscription_id; + IF NOT FOUND OR EXISTS (SELECT 1 FROM subscription_first_invoice_completions + WHERE subscription_id = NEW.subscription_id) THEN + RETURN NULL; + END IF; + + IF current_setting('transaction_isolation') <> 'read committed' THEN + RAISE EXCEPTION 'Unpaid first-invoice cancellation requires READ COMMITTED isolation' USING ERRCODE = '23514'; + END IF; + IF account_first_invoice_signed_success_retained(invoice.payment_intent_id, invoice.livemode) THEN + RAISE EXCEPTION 'Unpaid first-invoice cancellation conflicts with retained signed success' USING ERRCODE = '23514'; + END IF; + IF NOT EXISTS (SELECT 1 FROM subscription_provisioning_work + WHERE request_id = invoice.creation_request_id AND subscription_id = invoice.subscription_id + AND phase = 'CANCELED') THEN + RAISE EXCEPTION 'Unpaid first-invoice cancellation requires exact terminal provisioning work' USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; + +CREATE CONSTRAINT TRIGGER first_invoice_unpaid_subscription_cancellation + AFTER UPDATE ON subscription + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW WHEN (OLD.status <> 'canceled' AND NEW.status = 'canceled') + EXECUTE FUNCTION account_first_invoice_unpaid_cancellation_consistency(); + +CREATE CONSTRAINT TRIGGER first_invoice_unpaid_reservation_release + AFTER UPDATE ON subscription_instrument_reservations + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW WHEN (OLD.released_at IS NULL AND NEW.released_at IS NOT NULL) + EXECUTE FUNCTION account_first_invoice_unpaid_cancellation_consistency(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1046.9.0.1__order_reservation_conservation_deltas.sql b/services/account-service/src/main/resources/db/migration/V1046.9.0.1__order_reservation_conservation_deltas.sql new file mode 100644 index 0000000000..987fc9cc9c --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1046.9.0.1__order_reservation_conservation_deltas.sql @@ -0,0 +1,11 @@ +-- Immediate row-level conservation checks must observe their reservation deltas. +-- PostgreSQL fires same-event AFTER ROW triggers by name. Preserve the existing +-- named constraints and their default deferral so ordinary paired writes are unchanged. +-- [jooq ignore start] +ALTER TRIGGER account_tenant_capacity_reservation_conservation_insert + ON account_tenant_capacity_reservations + RENAME TO account_tenant_capacity_reservation_aggregate_insert; +ALTER TRIGGER account_tenant_capacity_reservation_conservation_update + ON account_tenant_capacity_reservations + RENAME TO account_tenant_capacity_reservation_aggregate_update; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1046.9.0.2__retain_first_invoice_late_paid_event_replays.sql b/services/account-service/src/main/resources/db/migration/V1046.9.0.2__retain_first_invoice_late_paid_event_replays.sql new file mode 100644 index 0000000000..a7737ae55d --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1046.9.0.2__retain_first_invoice_late_paid_event_replays.sql @@ -0,0 +1,64 @@ +-- Keep one immutable conflict per cancellation while retaining every accepted event identity. +CREATE TABLE subscription_first_invoice_late_paid_event_replays ( + provider_event_id VARCHAR(255) PRIMARY KEY + REFERENCES stripe_event_inbox(provider_event_id) ON DELETE RESTRICT, + subscription_id UUID NOT NULL + REFERENCES subscription_first_invoice_late_paid_conflicts(subscription_id) ON DELETE RESTRICT, + event_payload_digest VARCHAR(71) NOT NULL + CHECK (event_payload_digest ~ '^sha256:[0-9a-f]{64}$') +); + +CREATE INDEX idx_first_invoice_late_paid_event_replays_subscription + ON subscription_first_invoice_late_paid_event_replays(subscription_id); + +-- [jooq ignore start] +CREATE FUNCTION account_first_invoice_late_paid_event_replay_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + conflict subscription_first_invoice_late_paid_conflicts%ROWTYPE; + inbox stripe_event_inbox%ROWTYPE; + envelope JSONB; + payment JSONB; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Late first-invoice payment event links are retained' USING ERRCODE = '23514'; + END IF; + + SELECT * INTO STRICT conflict FROM subscription_first_invoice_late_paid_conflicts + WHERE subscription_id = NEW.subscription_id; + SELECT * INTO STRICT inbox FROM stripe_event_inbox WHERE provider_event_id = NEW.provider_event_id; + envelope := convert_from(inbox.raw_payload, 'UTF8')::jsonb; + payment := envelope->'data'->'object'; + + IF EXISTS ( + SELECT 1 FROM subscription_first_invoice_late_paid_conflicts + WHERE provider_event_id = NEW.provider_event_id + ) + OR inbox.event_type <> 'payment_intent.succeeded' + OR inbox.payload_sha256 IS DISTINCT FROM NEW.event_payload_digest + OR inbox.livemode IS DISTINCT FROM conflict.livemode + OR envelope->>'id' IS DISTINCT FROM inbox.provider_event_id + OR envelope->>'type' IS DISTINCT FROM inbox.event_type + OR envelope->'created' IS DISTINCT FROM to_jsonb(inbox.provider_created_at_epoch_seconds) + OR envelope->'livemode' IS DISTINCT FROM to_jsonb(conflict.livemode) + OR payment->>'object' IS DISTINCT FROM 'payment_intent' + OR payment->>'status' IS DISTINCT FROM 'succeeded' + OR payment->>'id' IS DISTINCT FROM conflict.payment_intent_id + OR payment->>'customer' IS DISTINCT FROM conflict.provider_customer_id + OR payment->>'payment_method' IS DISTINCT FROM conflict.provider_payment_method_id + OR payment->'amount' IS DISTINCT FROM to_jsonb(conflict.amount) + OR payment->'amount_received' IS DISTINCT FROM to_jsonb(conflict.amount) + OR payment->>'currency' IS DISTINCT FROM conflict.currency + OR payment->'livemode' IS DISTINCT FROM to_jsonb(conflict.livemode) THEN + RAISE EXCEPTION 'Late first-invoice payment event link refused' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_first_invoice_late_paid_event_replay_guard + BEFORE INSERT OR UPDATE OR DELETE ON subscription_first_invoice_late_paid_event_replays + FOR EACH ROW EXECUTE FUNCTION account_first_invoice_late_paid_event_replay_guard(); +CREATE TRIGGER account_first_invoice_late_paid_event_replay_no_truncate + BEFORE TRUNCATE ON subscription_first_invoice_late_paid_event_replays + FOR EACH STATEMENT EXECUTE FUNCTION account_first_invoice_late_paid_conflict_no_truncate(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1046.9.0.3__distinguish_unpaid_veto_from_paid_replay.sql b/services/account-service/src/main/resources/db/migration/V1046.9.0.3__distinguish_unpaid_veto_from_paid_replay.sql new file mode 100644 index 0000000000..cb8724c62b --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1046.9.0.3__distinguish_unpaid_veto_from_paid_replay.sql @@ -0,0 +1,60 @@ +-- Unpaid release is vetoed by exact signed success even if it predates consent. +-- Paid fulfillment and new links to a retained late-payment conflict retain the consent floor. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_first_invoice_signed_success_retained(intent_id TEXT, provider_livemode BOOLEAN) +RETURNS BOOLEAN LANGUAGE SQL STABLE AS $$ + SELECT EXISTS ( + SELECT 1 + FROM subscription_first_invoices invoice + JOIN stripe_event_inbox inbox ON inbox.livemode = invoice.livemode + CROSS JOIN LATERAL ( + SELECT convert_from(inbox.raw_payload, 'UTF8')::jsonb AS event + ) payload + CROSS JOIN LATERAL ( + SELECT payload.event #> '{data,object}' AS intent + ) payment + WHERE invoice.payment_intent_id = intent_id + AND invoice.livemode = provider_livemode + AND inbox.event_type = 'payment_intent.succeeded' + AND payload.event->>'id' = inbox.provider_event_id + AND payload.event->>'type' = inbox.event_type + AND payload.event->'created' = to_jsonb(inbox.provider_created_at_epoch_seconds) + AND payload.event->'livemode' = to_jsonb(invoice.livemode) + AND payment.intent->>'object' = 'payment_intent' + AND payment.intent->>'status' = 'succeeded' + AND payment.intent->>'id' = invoice.payment_intent_id + AND payment.intent->>'customer' = invoice.provider_customer_id + AND payment.intent->>'payment_method' = invoice.provider_payment_method_id + AND payment.intent->'amount' = to_jsonb(invoice.amount) + AND payment.intent->'amount_received' = to_jsonb(invoice.amount) + AND payment.intent->>'currency' = invoice.currency + AND payment.intent->'livemode' = to_jsonb(invoice.livemode) + ); +$$; + +CREATE FUNCTION account_first_invoice_late_paid_replay_consent_floor() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE original_consent TIMESTAMPTZ; event_created BIGINT; +BEGIN + SELECT confirmation.consented_at, inbox.provider_created_at_epoch_seconds + INTO STRICT original_consent, event_created + FROM subscription_first_invoice_late_paid_conflicts conflict + JOIN subscription_first_invoice_confirmations confirmation + ON confirmation.request_id = conflict.request_id + AND confirmation.subscription_id = conflict.subscription_id + AND confirmation.tuple_digest = conflict.tuple_digest + JOIN stripe_event_inbox inbox ON inbox.provider_event_id = NEW.provider_event_id + WHERE conflict.subscription_id = NEW.subscription_id; + + IF original_consent IS NULL + OR event_created < floor(EXTRACT(EPOCH FROM original_consent)) THEN + RAISE EXCEPTION 'Late first-invoice payment event predates original consent' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_first_invoice_late_paid_replay_consent_floor + BEFORE INSERT ON subscription_first_invoice_late_paid_event_replays + FOR EACH ROW EXECUTE FUNCTION account_first_invoice_late_paid_replay_consent_floor(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1046.9.0.4__enforce_first_invoice_evidence_at_use.sql b/services/account-service/src/main/resources/db/migration/V1046.9.0.4__enforce_first_invoice_evidence_at_use.sql new file mode 100644 index 0000000000..393bf48cb1 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1046.9.0.4__enforce_first_invoice_evidence_at_use.sql @@ -0,0 +1,314 @@ +-- Apply current evidence checks to new writes without modifying retained first-invoice records. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_first_invoice_command_claim_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE auth subscription_first_invoice_authorizations%ROWTYPE; consent subscription_first_invoice_confirmations%ROWTYPE; current_row RECORD; latest BIGINT; +BEGIN + SELECT * INTO STRICT auth FROM subscription_first_invoice_authorizations WHERE authorization_request_id = NEW.authorization_request_id; + SELECT * INTO STRICT consent FROM subscription_first_invoice_confirmations WHERE request_id = NEW.request_id; + SELECT s.status, s.row_version, w.phase INTO STRICT current_row FROM subscription s + JOIN subscription_provisioning_work w ON w.subscription_id = s.subscription_id + WHERE s.subscription_id = NEW.subscription_id AND s.superseded_at IS NULL FOR UPDATE OF s; + SELECT MAX(authorization_version) INTO latest FROM subscription_first_invoice_authorizations WHERE subscription_id = NEW.subscription_id; + IF auth.authorization_version <> latest OR auth.created_transaction_id = txid_current() + OR current_row.status <> 'provisioning' OR current_row.phase <> 'AWAITING_PAYMENT' OR current_row.row_version <> consent.expected_row_version + OR NEW.claimed_at < auth.consented_at OR NEW.claimed_at >= auth.valid_until THEN + RAISE EXCEPTION 'First-invoice command requires independently read latest unexpired authorization' USING ERRCODE = '23514'; + END IF; + IF clock_timestamp() >= auth.valid_until THEN + RAISE EXCEPTION 'First-invoice command authorization expired before database claim' + USING ERRCODE = '23514'; + END IF; + NEW.created_transaction_id := txid_current(); + RETURN NEW; +END; +$$; + +CREATE OR REPLACE FUNCTION account_first_invoice_success_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + intake stripe_event_inbox%ROWTYPE; + invoice subscription_first_invoices%ROWTYPE; + consented_at TIMESTAMPTZ; + envelope JSONB; + payload JSONB; +BEGIN + SELECT * INTO STRICT intake FROM stripe_event_inbox WHERE provider_event_id = NEW.provider_event_id; + SELECT * INTO STRICT invoice FROM subscription_first_invoices WHERE subscription_id = NEW.subscription_id; + envelope := convert_from(intake.raw_payload, 'UTF8')::JSONB; + payload := envelope #> '{data,object}'; + IF intake.event_type <> 'payment_intent.succeeded' OR intake.payload_sha256 <> NEW.event_payload_digest + OR intake.livemode <> invoice.livemode OR NEW.tuple_digest <> invoice.tuple_digest + OR payload->>'object' IS DISTINCT FROM 'payment_intent' OR payload->>'status' IS DISTINCT FROM 'succeeded' + OR payload->>'id' IS DISTINCT FROM invoice.payment_intent_id OR payload->>'customer' IS DISTINCT FROM invoice.provider_customer_id + OR payload->>'payment_method' IS DISTINCT FROM invoice.provider_payment_method_id OR payload->>'currency' IS DISTINCT FROM invoice.currency + OR payload->'amount' IS DISTINCT FROM to_jsonb(invoice.amount) OR payload->'amount_received' IS DISTINCT FROM to_jsonb(invoice.amount) + OR payload->'livemode' IS DISTINCT FROM to_jsonb(invoice.livemode) THEN + RAISE EXCEPTION 'First invoice requires exact signed successful payment tuple, not invoice.paid' USING ERRCODE = '23514'; + END IF; + SELECT consent.consented_at INTO STRICT consented_at + FROM subscription_first_invoice_confirmations consent + WHERE (consent.request_id, consent.subscription_id, consent.tuple_digest) + = (NEW.request_id, NEW.subscription_id, NEW.tuple_digest); + IF envelope->'created' IS DISTINCT FROM to_jsonb(intake.provider_created_at_epoch_seconds) + OR intake.provider_created_at_epoch_seconds < floor(EXTRACT(EPOCH FROM consented_at)) THEN + RAISE EXCEPTION 'First-invoice signed success requires a verified event at or after original consent' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE OR REPLACE FUNCTION account_first_invoice_expired_before_post_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE claim_transaction BIGINT; authorization_expiry TIMESTAMPTZ; +BEGIN + SELECT c.created_transaction_id, a.valid_until INTO STRICT claim_transaction, authorization_expiry + FROM subscription_first_invoice_command_claims c + JOIN subscription_first_invoice_authorizations a USING (authorization_request_id, request_id, subscription_id) + JOIN subscription s ON s.subscription_id = c.subscription_id + WHERE c.request_id = NEW.request_id FOR UPDATE OF s; + IF claim_transaction = txid_current() OR NEW.observed_at < authorization_expiry THEN + RAISE EXCEPTION 'First-invoice no-send evidence requires an independently committed claim and expired authorization' USING ERRCODE = '23514'; + END IF; + IF NEW.observed_at > clock_timestamp() THEN + RAISE EXCEPTION 'First-invoice no-send observation is later than the database clock' + USING ERRCODE = '23514'; + END IF; + NEW.created_transaction_id := txid_current(); + RETURN NEW; +END; +$$; + +CREATE OR REPLACE FUNCTION account_first_invoice_late_paid_conflict_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + current_row subscription%ROWTYPE; + first_invoice subscription_first_invoices%ROWTYPE; + confirmation subscription_first_invoice_confirmations%ROWTYPE; + inbox stripe_event_inbox%ROWTYPE; + cancellation subscription_lifecycle_operations%ROWTYPE; + receipt subscription_lifecycle_receipts%ROWTYPE; + provisioning subscription_provisioning_work%ROWTYPE; + paid_payload JSONB; + cancellation_payload JSONB; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Late first-invoice payment conflicts are retained' USING ERRCODE = '23514'; + ELSIF TG_OP = 'INSERT' THEN + -- The intake trigger takes this same row lock before retaining a signed success. A success + -- committed before cancellation blocks release; one committed after release reaches here. + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = NEW.subscription_id FOR UPDATE; + SELECT * INTO STRICT first_invoice FROM subscription_first_invoices WHERE subscription_id = NEW.subscription_id; + SELECT * INTO STRICT confirmation FROM subscription_first_invoice_confirmations + WHERE request_id = NEW.request_id AND subscription_id = NEW.subscription_id; + SELECT * INTO STRICT inbox FROM stripe_event_inbox WHERE provider_event_id = NEW.provider_event_id; + + paid_payload := convert_from(inbox.raw_payload, 'UTF8')::jsonb; + IF current_row.status <> 'canceled' + OR current_row.current_receipt_request_id IS NULL + OR current_row.lifecycle_inflight_request_id IS NOT NULL + OR current_row.provider_subscription_id IS DISTINCT FROM first_invoice.provider_subscription_id + OR (current_row.superseded_at IS NULL AND current_row.row_version <> NEW.cancellation_row_version) + OR (first_invoice.creation_request_id, first_invoice.tuple_digest, first_invoice.invoice_id, + first_invoice.payment_intent_id, first_invoice.provider_subscription_id, + first_invoice.provider_customer_id, first_invoice.provider_payment_method_id, + first_invoice.provider_price_id, first_invoice.provider_quantity, + first_invoice.amount, first_invoice.currency, first_invoice.livemode) + IS DISTINCT FROM (NEW.creation_request_id, NEW.tuple_digest, NEW.invoice_id, + NEW.payment_intent_id, NEW.provider_subscription_id, NEW.provider_customer_id, + NEW.provider_payment_method_id, NEW.provider_price_id, NEW.provider_quantity, + NEW.amount, NEW.currency, NEW.livemode) + OR (confirmation.lifecycle_request_id, confirmation.tuple_digest, confirmation.account_uuid) + IS DISTINCT FROM (NEW.lifecycle_request_id, NEW.tuple_digest, first_invoice.account_uuid) + OR inbox.event_type <> 'payment_intent.succeeded' + OR inbox.payload_sha256 <> NEW.event_payload_digest + OR inbox.livemode <> NEW.livemode + OR inbox.provider_event_id IS DISTINCT FROM paid_payload->>'id' + OR inbox.event_type IS DISTINCT FROM paid_payload->>'type' + OR paid_payload->>'livemode' IS DISTINCT FROM NEW.livemode::TEXT + OR paid_payload->'data'->'object'->>'object' IS DISTINCT FROM 'payment_intent' + OR paid_payload->'data'->'object'->>'status' IS DISTINCT FROM 'succeeded' + OR paid_payload->'data'->'object'->>'id' IS DISTINCT FROM NEW.payment_intent_id + OR paid_payload->'data'->'object'->>'customer' IS DISTINCT FROM NEW.provider_customer_id + OR paid_payload->'data'->'object'->>'payment_method' IS DISTINCT FROM NEW.provider_payment_method_id + OR paid_payload->'data'->'object'->>'amount' IS DISTINCT FROM NEW.amount::TEXT + OR paid_payload->'data'->'object'->>'amount_received' IS DISTINCT FROM NEW.amount::TEXT + OR paid_payload->'data'->'object'->>'currency' IS DISTINCT FROM NEW.currency + OR paid_payload->'data'->'object'->>'livemode' IS DISTINCT FROM NEW.livemode::TEXT + OR inbox.provider_created_at_epoch_seconds < floor(EXTRACT(EPOCH FROM confirmation.consented_at)) + OR NEW.observed_status <> 'succeeded' + OR NEW.observation_read_started_at < inbox.received_at + OR NEW.observation_observed_at < NEW.observation_read_started_at + OR NEW.observation_observed_at - NEW.observation_read_started_at >= INTERVAL '20 seconds' + OR NEW.observation_expires_at IS DISTINCT FROM NEW.observation_read_started_at + INTERVAL '20 seconds' + OR NEW.observation_observed_at >= NEW.observation_expires_at + OR NOT EXISTS ( + SELECT 1 + FROM subscription_provisioning_work work + JOIN subscription_lifecycle_operations canceled_operation + ON canceled_operation.request_id = current_row.current_receipt_request_id + AND canceled_operation.subscription_id = current_row.subscription_id + JOIN subscription_lifecycle_receipts canceled_receipt + ON canceled_receipt.request_id = canceled_operation.request_id + AND canceled_receipt.subscription_id = canceled_operation.subscription_id + JOIN subscription_lifecycle_observations cancellation_observation + ON (cancellation_observation.request_id, cancellation_observation.attempt_id, + cancellation_observation.evidence_digest) + = (canceled_receipt.request_id, canceled_receipt.attempt_id, + canceled_receipt.observation_digest) + JOIN subscription_provider_terminal_resolutions terminal + ON terminal.resolution_id = current_row.terminal_resolution_id + AND terminal.subscription_id = current_row.subscription_id + JOIN subscription_instrument_reservations reservation + ON reservation.subscription_id = current_row.subscription_id + WHERE work.request_id = first_invoice.creation_request_id + AND work.subscription_id = current_row.subscription_id + AND work.phase = 'CANCELED' + AND work.last_attempt_id IS NOT NULL + AND canceled_operation.state = 'COMMITTED' + AND canceled_operation.creation_request_id = first_invoice.creation_request_id + AND canceled_operation.tenant_id = first_invoice.tenant_id + AND canceled_operation.provider_subscription_id = first_invoice.provider_subscription_id + AND canceled_operation.provisioning_attempt_id IS NULL + AND canceled_operation.request_id = NEW.cancellation_request_id + AND canceled_operation.request_digest = canceled_receipt.request_digest + AND canceled_operation.request_digest = 'sha256:' || encode(sha256(canceled_operation.request_payload), 'hex') + AND canceled_receipt.status = 'canceled' + AND canceled_receipt.receipt_digest = NEW.cancellation_receipt_digest + AND canceled_receipt.subscription_row_version = NEW.cancellation_row_version + AND canceled_receipt.committed_transaction_id = NEW.cancellation_committed_transaction_id + AND canceled_receipt.committed_transaction_id <> txid_current() + AND canceled_receipt.provider_subscription_id = first_invoice.provider_subscription_id + AND canceled_receipt.plan_quote_digest = first_invoice.quote_digest + AND cancellation_observation.raw_status = 'canceled' + AND terminal.request_id = first_invoice.creation_request_id + AND terminal.outcome = 'CANCELED' + AND terminal.provider_subscription_id = first_invoice.provider_subscription_id + AND terminal.evidence_digest = cancellation_observation.evidence_digest + AND reservation.request_id = first_invoice.creation_request_id + AND reservation.terminal_resolution_id = terminal.resolution_id + AND reservation.released_at IS NOT NULL + AND convert_from(canceled_operation.request_payload, 'UTF8')::jsonb->>'schemaVersion' + = 'account-hosting-unpaid-first-invoice-cancellation/v1' + AND convert_from(canceled_operation.request_payload, 'UTF8')::jsonb->>'requestId' + = canceled_operation.request_id::TEXT + AND convert_from(canceled_operation.request_payload, 'UTF8')::jsonb->>'creationRequestId' + = first_invoice.creation_request_id::TEXT + AND convert_from(canceled_operation.request_payload, 'UTF8')::jsonb->>'expectedRowVersion' + = canceled_operation.expected_row_version::TEXT + AND convert_from(canceled_operation.request_payload, 'UTF8')::jsonb->>'providerSubscriptionId' + = first_invoice.provider_subscription_id + AND convert_from(canceled_operation.request_payload, 'UTF8')::jsonb->>'provisioningAttemptId' = '' + AND (current_row.superseded_at IS NOT NULL + OR canceled_receipt.subscription_row_version = current_row.row_version) + AND ( + NOT EXISTS (SELECT 1 FROM subscription_first_invoice_command_claims claim + WHERE claim.subscription_id = current_row.subscription_id) + OR EXISTS ( + SELECT 1 + FROM subscription_first_invoice_no_send_cancellations release + JOIN subscription_first_invoice_command_claims claim + ON claim.request_id = release.confirmation_request_id + AND claim.subscription_id = current_row.subscription_id + JOIN subscription_first_invoice_expired_before_post marker + ON marker.request_id = claim.request_id + JOIN subscription_first_invoice_authorizations auth + ON (auth.authorization_request_id, auth.request_id, + auth.subscription_id) + = (claim.authorization_request_id, claim.request_id, claim.subscription_id) + JOIN subscription_lifecycle_operations witness_operation + ON witness_operation.request_id = release.cancellation_request_id + AND witness_operation.subscription_id = current_row.subscription_id + JOIN subscription_lifecycle_receipts witness_receipt + ON witness_receipt.request_id = witness_operation.request_id + AND witness_receipt.subscription_id = witness_operation.subscription_id + JOIN subscription_lifecycle_observations witness_observation + ON (witness_observation.request_id, witness_observation.attempt_id, + witness_observation.evidence_digest) + = (witness_receipt.request_id, witness_receipt.attempt_id, + witness_receipt.observation_digest) + JOIN subscription_lifecycle_attempts witness_attempt + ON (witness_attempt.request_id, witness_attempt.attempt_id) + = (witness_operation.request_id, witness_observation.attempt_id) + WHERE release.cancellation_request_id = NEW.cancellation_request_id + AND release.confirmation_request_id = NEW.request_id + AND release.invoice_id = first_invoice.invoice_id + AND release.payment_intent_id = first_invoice.payment_intent_id + AND release.created_transaction_id = NEW.cancellation_committed_transaction_id + AND release.created_transaction_id = witness_receipt.committed_transaction_id + AND release.read_started_at >= witness_observation.observed_at + AND release.read_started_at >= witness_attempt.started_at + AND release.observed_at >= release.read_started_at + AND release.observed_at <= witness_operation.created_at + AND release.observed_at < witness_attempt.expires_at + AND witness_operation.created_at < witness_attempt.expires_at + AND witness_operation.created_at - release.read_started_at + < witness_operation.observation_age_millis * INTERVAL '1 millisecond' + AND marker.created_transaction_id <> release.created_transaction_id + AND marker.observed_at >= auth.valid_until + AND claim.created_transaction_id <> marker.created_transaction_id + AND witness_operation.state = 'COMMITTED' + AND witness_receipt.status = 'canceled' + AND witness_observation.raw_status = 'canceled' + ) + ) + ) + OR EXISTS (SELECT 1 FROM subscription_lifecycle_operator_outbox + WHERE request_id = current_row.current_receipt_request_id) + OR EXISTS (SELECT 1 FROM subscription_provisioning_operator_outbox + WHERE request_id = first_invoice.creation_request_id) + OR EXISTS (SELECT 1 FROM subscription_first_invoice_success_evidence + WHERE subscription_id = NEW.subscription_id) + OR EXISTS (SELECT 1 FROM subscription_first_invoice_completions + WHERE subscription_id = NEW.subscription_id) THEN + RAISE EXCEPTION 'Late first-invoice payment requires its exact verified success and committed unpaid cancellation' USING ERRCODE = '23514'; + END IF; + cancellation_payload := convert_from((SELECT request_payload FROM subscription_lifecycle_operations + WHERE request_id = NEW.cancellation_request_id), 'UTF8')::jsonb; + IF NEW.cancellation_request_id IS DISTINCT FROM current_row.current_receipt_request_id + OR NEW.cancellation_committed_transaction_id = txid_current() + OR cancellation_payload->>'schemaVersion' IS DISTINCT FROM 'account-hosting-unpaid-first-invoice-cancellation/v1' THEN + RAISE EXCEPTION 'Late first-invoice payment must retain the current committed unpaid cancellation' USING ERRCODE = '23514'; + END IF; + IF clock_timestamp() >= NEW.observation_expires_at THEN + RAISE EXCEPTION 'Late first-invoice payment observation expired before conflict insertion' + USING ERRCODE = '23514'; + END IF; + NEW.created_transaction_id := txid_current(); + RETURN NEW; + ELSE + RAISE EXCEPTION 'Late first-invoice payment conflicts are immutable' USING ERRCODE = '23514'; + END IF; +END; +$$; +-- Use the same exact numeric comparison for intake locking and the unpaid veto. +CREATE OR REPLACE FUNCTION account_first_invoice_success_intake_lock() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE event_payload JSONB; target_subscription UUID; +BEGIN + IF TG_OP <> 'INSERT' OR NEW.event_type <> 'payment_intent.succeeded' THEN + RETURN NEW; + END IF; + event_payload := convert_from(NEW.raw_payload, 'UTF8')::jsonb; + IF event_payload->>'id' IS DISTINCT FROM NEW.provider_event_id + OR event_payload->>'type' IS DISTINCT FROM NEW.event_type + OR event_payload->>'livemode' IS DISTINCT FROM NEW.livemode::TEXT + OR event_payload->'data'->'object'->>'object' IS DISTINCT FROM 'payment_intent' + OR event_payload->'data'->'object'->>'status' IS DISTINCT FROM 'succeeded' THEN + RETURN NEW; + END IF; + SELECT invoice.subscription_id INTO target_subscription + FROM subscription_first_invoices invoice + WHERE invoice.payment_intent_id = event_payload->'data'->'object'->>'id' + AND invoice.livemode = NEW.livemode + AND invoice.provider_customer_id = event_payload->'data'->'object'->>'customer' + AND invoice.provider_payment_method_id = event_payload->'data'->'object'->>'payment_method' + AND to_jsonb(invoice.amount) = event_payload->'data'->'object'->'amount' + AND to_jsonb(invoice.amount) = event_payload->'data'->'object'->'amount_received' + AND invoice.currency = event_payload->'data'->'object'->>'currency' + AND event_payload->'data'->'object'->>'livemode' = invoice.livemode::TEXT + LIMIT 1; + IF target_subscription IS NOT NULL THEN + PERFORM 1 FROM subscription WHERE subscription_id = target_subscription FOR UPDATE; + END IF; + RETURN NEW; +END; +$$; + +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1046.9.0.5__index_retained_first_invoice_success_identity.sql b/services/account-service/src/main/resources/db/migration/V1046.9.0.5__index_retained_first_invoice_success_identity.sql new file mode 100644 index 0000000000..8e31a38f8d --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1046.9.0.5__index_retained_first_invoice_success_identity.sql @@ -0,0 +1,97 @@ +-- Retain a lookup key for each success delivery independently of invoice capture or consent. +-- The original signed inbox row remains the complete evidence used by the unpaid veto. +CREATE TABLE stripe_first_invoice_success_lookup ( + provider_event_id VARCHAR PRIMARY KEY + REFERENCES stripe_event_inbox(provider_event_id) ON DELETE RESTRICT, + livemode BOOLEAN NOT NULL, + payment_intent_id VARCHAR(255) NOT NULL CHECK (payment_intent_id ~ '^pi_[A-Za-z0-9]+$') +); + +CREATE INDEX idx_stripe_first_invoice_success_lookup_intent + ON stripe_first_invoice_success_lookup (livemode, payment_intent_id); + +-- [jooq ignore start] +CREATE FUNCTION account_first_invoice_success_lookup_intent(raw_payload BYTEA) +RETURNS TEXT LANGUAGE SQL STABLE STRICT AS $$ + SELECT convert_from(raw_payload, 'UTF8')::jsonb #>> '{data,object,id}'; +$$; + +CREATE FUNCTION account_first_invoice_success_lookup_insert() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE intent_id TEXT; +BEGIN + intent_id := account_first_invoice_success_lookup_intent(NEW.raw_payload); + IF intent_id ~ '^pi_[A-Za-z0-9]+$' AND char_length(intent_id) <= 255 THEN + INSERT INTO stripe_first_invoice_success_lookup (provider_event_id, livemode, payment_intent_id) + VALUES (NEW.provider_event_id, NEW.livemode, intent_id); + END IF; + RETURN NEW; +END; +$$; + +-- Fence inbox inserts through backfill and trigger installation. Unparseable retained success +-- bytes abort the migration so malformed evidence cannot silently disappear from the veto. +LOCK TABLE stripe_event_inbox IN SHARE ROW EXCLUSIVE MODE; + +WITH retained AS MATERIALIZED ( + SELECT provider_event_id, livemode, account_first_invoice_success_lookup_intent(raw_payload) AS intent_id + FROM stripe_event_inbox + WHERE event_type = 'payment_intent.succeeded' +) +INSERT INTO stripe_first_invoice_success_lookup (provider_event_id, livemode, payment_intent_id) +SELECT provider_event_id, livemode, intent_id +FROM retained +WHERE intent_id ~ '^pi_[A-Za-z0-9]+$' AND char_length(intent_id) <= 255; + +CREATE TRIGGER first_invoice_success_lookup_insert + AFTER INSERT ON stripe_event_inbox + FOR EACH ROW WHEN (NEW.event_type = 'payment_intent.succeeded') + EXECUTE FUNCTION account_first_invoice_success_lookup_insert(); + +CREATE TRIGGER stripe_first_invoice_success_lookup_immutable + BEFORE UPDATE OR DELETE ON stripe_first_invoice_success_lookup + FOR EACH ROW EXECUTE FUNCTION stripe_event_inbox_no_mutation(); + +CREATE TRIGGER stripe_first_invoice_success_lookup_no_truncate + BEFORE TRUNCATE ON stripe_first_invoice_success_lookup + FOR EACH STATEMENT EXECUTE FUNCTION stripe_event_inbox_no_mutation(); + +CREATE OR REPLACE FUNCTION account_first_invoice_signed_success_retained(intent_id TEXT, provider_livemode BOOLEAN) +RETURNS BOOLEAN LANGUAGE SQL STABLE AS $$ + WITH candidates AS MATERIALIZED ( + SELECT inbox.provider_event_id, inbox.event_type, inbox.provider_created_at_epoch_seconds, + convert_from(inbox.raw_payload, 'UTF8')::jsonb AS event + FROM stripe_first_invoice_success_lookup lookup + JOIN stripe_event_inbox inbox ON inbox.provider_event_id = lookup.provider_event_id + WHERE lookup.payment_intent_id = intent_id + AND lookup.livemode = provider_livemode + AND inbox.livemode = provider_livemode + AND inbox.event_type = 'payment_intent.succeeded' + ) + SELECT EXISTS ( + SELECT 1 + FROM subscription_first_invoices invoice + CROSS JOIN candidates payload + CROSS JOIN LATERAL ( + SELECT payload.event #> '{data,object}' AS intent + ) payment + WHERE invoice.payment_intent_id = intent_id + AND invoice.livemode = provider_livemode + AND payload.event->>'id' = payload.provider_event_id + AND payload.event->>'type' = payload.event_type + AND payload.event->'created' = to_jsonb(payload.provider_created_at_epoch_seconds) + AND payload.event->'livemode' = to_jsonb(invoice.livemode) + AND payment.intent->>'object' = 'payment_intent' + AND payment.intent->>'status' = 'succeeded' + AND payment.intent->>'id' = invoice.payment_intent_id + AND payment.intent->>'customer' = invoice.provider_customer_id + AND payment.intent->>'payment_method' = invoice.provider_payment_method_id + AND payment.intent->'amount' = to_jsonb(invoice.amount) + AND payment.intent->'amount_received' = to_jsonb(invoice.amount) + AND payment.intent->>'currency' = invoice.currency + AND payment.intent->'livemode' = to_jsonb(invoice.livemode) + ); +$$; +-- [jooq ignore stop] + +DROP INDEX idx_stripe_event_inbox_first_invoice_success_mode_created; diff --git a/services/account-service/src/main/resources/db/migration/V1046.9.0.6__order_first_invoice_intake_capture_and_settlement.sql b/services/account-service/src/main/resources/db/migration/V1046.9.0.6__order_first_invoice_intake_capture_and_settlement.sql new file mode 100644 index 0000000000..d03dbc8f08 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1046.9.0.6__order_first_invoice_intake_capture_and_settlement.sql @@ -0,0 +1,96 @@ +-- [jooq ignore start] +-- Refuse installation while any old-order writer is active. Waiting while holding one +-- relation lock could otherwise conflict with the old multi-table write order. +LOCK TABLE stripe_event_inbox, subscription, subscription_first_invoices, subscription_instrument_reservations + IN SHARE ROW EXCLUSIVE MODE NOWAIT; + +CREATE FUNCTION account_lock_first_invoice_intent(intent_id TEXT, provider_livemode BOOLEAN) +RETURNS VOID LANGUAGE plpgsql VOLATILE STRICT AS $$ +BEGIN + PERFORM pg_advisory_xact_lock(hashtextextended( + 'account-first-invoice-intent:' || provider_livemode::TEXT || ':' || intent_id, 0)); +END; +$$; + +-- Intake has no dependency on a committed invoice or on an owner row. A hash collision +-- only makes independent keys wait; the veto still checks the complete exact tuple. +CREATE OR REPLACE FUNCTION account_first_invoice_success_intake_lock() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE intent_id TEXT; +BEGIN + intent_id := account_first_invoice_success_lookup_intent(NEW.raw_payload); + IF intent_id ~ '^pi_[A-Za-z0-9]+$' AND char_length(intent_id) <= 255 THEN + PERFORM account_lock_first_invoice_intent(intent_id, NEW.livemode); + END IF; + RETURN NEW; +END; +$$; + +DROP TRIGGER first_invoice_success_intake_lock ON stripe_event_inbox; +CREATE TRIGGER first_invoice_success_intake_lock + BEFORE INSERT ON stripe_event_inbox + FOR EACH ROW WHEN (NEW.event_type = 'payment_intent.succeeded') + EXECUTE FUNCTION account_first_invoice_success_intake_lock(); + +-- The existing BEFORE INSERT source guard already locks the subscription. Capture has +-- no success veto; it makes the immutable linkage available for subsequent reconciliation. +CREATE FUNCTION account_first_invoice_capture_intent_lock() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + PERFORM account_lock_first_invoice_intent(NEW.payment_intent_id, NEW.livemode); + RETURN NEW; +END; +$$; + +CREATE TRIGGER first_invoice_capture_intent_lock + AFTER INSERT ON subscription_first_invoices + FOR EACH ROW EXECUTE FUNCTION account_first_invoice_capture_intent_lock(); + +-- Both settlement paths and the deferred SQL guard call this after locking the subscription. +-- Intake never requests that row, so waiting on the intent cannot invert the owner lock order. +CREATE OR REPLACE FUNCTION account_first_invoice_signed_success_retained(intent_id TEXT, provider_livemode BOOLEAN) +RETURNS BOOLEAN LANGUAGE plpgsql VOLATILE AS $$ +DECLARE success_retained BOOLEAN; +BEGIN + IF current_setting('transaction_isolation') <> 'read committed' THEN + RAISE EXCEPTION 'Unpaid first-invoice cancellation requires READ COMMITTED isolation' USING ERRCODE = '23514'; + END IF; + PERFORM account_lock_first_invoice_intent(intent_id, provider_livemode); + + -- Execute the evidence read in a separate statement so it sees an intake commit that + -- released the lock. A STABLE function would keep the caller's pre-wait snapshot. + WITH candidates AS MATERIALIZED ( + SELECT inbox.provider_event_id, inbox.event_type, inbox.provider_created_at_epoch_seconds, + convert_from(inbox.raw_payload, 'UTF8')::jsonb AS event + FROM stripe_first_invoice_success_lookup lookup + JOIN stripe_event_inbox inbox ON inbox.provider_event_id = lookup.provider_event_id + WHERE lookup.payment_intent_id = intent_id + AND lookup.livemode = provider_livemode + AND inbox.livemode = provider_livemode + AND inbox.event_type = 'payment_intent.succeeded' + ) + SELECT EXISTS ( + SELECT 1 + FROM subscription_first_invoices invoice + CROSS JOIN candidates payload + CROSS JOIN LATERAL ( + SELECT payload.event #> '{data,object}' AS intent + ) payment + WHERE invoice.payment_intent_id = intent_id + AND invoice.livemode = provider_livemode + AND payload.event->>'id' = payload.provider_event_id + AND payload.event->>'type' = payload.event_type + AND payload.event->'created' = to_jsonb(payload.provider_created_at_epoch_seconds) + AND payload.event->'livemode' = to_jsonb(invoice.livemode) + AND payment.intent->>'object' = 'payment_intent' + AND payment.intent->>'status' = 'succeeded' + AND payment.intent->>'id' = invoice.payment_intent_id + AND payment.intent->>'customer' = invoice.provider_customer_id + AND payment.intent->>'payment_method' = invoice.provider_payment_method_id + AND payment.intent->'amount' = to_jsonb(invoice.amount) + AND payment.intent->'amount_received' = to_jsonb(invoice.amount) + AND payment.intent->>'currency' = invoice.currency + AND payment.intent->'livemode' = to_jsonb(invoice.livemode) + ) INTO success_retained; + RETURN success_retained; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1046.9.0.7__retain_original_paid_capacity_cutoff.sql b/services/account-service/src/main/resources/db/migration/V1046.9.0.7__retain_original_paid_capacity_cutoff.sql new file mode 100644 index 0000000000..d840d39096 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1046.9.0.7__retain_original_paid_capacity_cutoff.sql @@ -0,0 +1,6 @@ +-- The existing evaluation guard makes this column immutable with the canonical evidence. +-- Earlier evaluations keep NULL and cannot authorize fresh paid capacity mutations. +ALTER TABLE account_tenant_capacity_evaluations + ADD COLUMN original_paid_cutoff TIMESTAMPTZ, + ADD CONSTRAINT account_tenant_capacity_original_paid_cutoff_check + CHECK (original_paid_cutoff >= expires_at); diff --git a/services/account-service/src/main/resources/db/migration/V1046.9.0.8__prove_original_first_invoice_no_send_creation.sql b/services/account-service/src/main/resources/db/migration/V1046.9.0.8__prove_original_first_invoice_no_send_creation.sql new file mode 100644 index 0000000000..8ce48baaba --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1046.9.0.8__prove_original_first_invoice_no_send_creation.sql @@ -0,0 +1,49 @@ +-- A retained transaction ID can date from a migration. Only a fresh guarded insert +-- can attest to the original marker transaction. Existing receipts are unaffected. +-- [jooq ignore start] +LOCK TABLE subscription_first_invoice_expired_before_post, + subscription_first_invoice_no_send_cancellations IN ACCESS EXCLUSIVE MODE NOWAIT; +-- [jooq ignore stop] + +ALTER TABLE subscription_first_invoice_expired_before_post + ADD COLUMN original_creation_proven BOOLEAN NOT NULL DEFAULT FALSE; + +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_first_invoice_expired_before_post_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE claim_transaction BIGINT; authorization_expiry TIMESTAMPTZ; +BEGIN + SELECT c.created_transaction_id, a.valid_until INTO STRICT claim_transaction, authorization_expiry + FROM subscription_first_invoice_command_claims c + JOIN subscription_first_invoice_authorizations a USING (authorization_request_id, request_id, subscription_id) + JOIN subscription s ON s.subscription_id = c.subscription_id + WHERE c.request_id = NEW.request_id FOR UPDATE OF s; + IF claim_transaction = txid_current() OR NEW.observed_at < authorization_expiry THEN + RAISE EXCEPTION 'First-invoice no-send evidence requires an independently committed claim and expired authorization' USING ERRCODE = '23514'; + END IF; + IF NEW.observed_at > clock_timestamp() THEN + RAISE EXCEPTION 'First-invoice no-send observation is later than the database clock' + USING ERRCODE = '23514'; + END IF; + NEW.created_transaction_id := txid_current(); + NEW.original_creation_proven := TRUE; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_first_invoice_no_send_cancellation_creation_proof() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM subscription_first_invoice_expired_before_post + WHERE request_id = NEW.confirmation_request_id AND original_creation_proven + ) THEN + RAISE EXCEPTION 'Claimed first-invoice cancellation requires proof of original no-send marker creation' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER first_invoice_no_send_cancellation_creation_proof + BEFORE INSERT ON subscription_first_invoice_no_send_cancellations + FOR EACH ROW EXECUTE FUNCTION account_first_invoice_no_send_cancellation_creation_proof(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1046.9__bound_late_first_invoice_payment_observation.sql b/services/account-service/src/main/resources/db/migration/V1046.9__bound_late_first_invoice_payment_observation.sql new file mode 100644 index 0000000000..23e1dd953c --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1046.9__bound_late_first_invoice_payment_observation.sql @@ -0,0 +1,200 @@ +-- Preserve prior conflict rows while separating observation freshness from checkout expiry. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_first_invoice_late_paid_conflict_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + current_row subscription%ROWTYPE; + first_invoice subscription_first_invoices%ROWTYPE; + confirmation subscription_first_invoice_confirmations%ROWTYPE; + inbox stripe_event_inbox%ROWTYPE; + cancellation subscription_lifecycle_operations%ROWTYPE; + receipt subscription_lifecycle_receipts%ROWTYPE; + provisioning subscription_provisioning_work%ROWTYPE; + paid_payload JSONB; + cancellation_payload JSONB; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Late first-invoice payment conflicts are retained' USING ERRCODE = '23514'; + ELSIF TG_OP = 'INSERT' THEN + -- The intake trigger takes this same row lock before retaining a signed success. A success + -- committed before cancellation blocks release; one committed after release reaches here. + SELECT * INTO STRICT current_row FROM subscription WHERE subscription_id = NEW.subscription_id FOR UPDATE; + SELECT * INTO STRICT first_invoice FROM subscription_first_invoices WHERE subscription_id = NEW.subscription_id; + SELECT * INTO STRICT confirmation FROM subscription_first_invoice_confirmations + WHERE request_id = NEW.request_id AND subscription_id = NEW.subscription_id; + SELECT * INTO STRICT inbox FROM stripe_event_inbox WHERE provider_event_id = NEW.provider_event_id; + + paid_payload := convert_from(inbox.raw_payload, 'UTF8')::jsonb; + IF current_row.status <> 'canceled' + OR current_row.current_receipt_request_id IS NULL + OR current_row.lifecycle_inflight_request_id IS NOT NULL + OR current_row.provider_subscription_id IS DISTINCT FROM first_invoice.provider_subscription_id + OR (current_row.superseded_at IS NULL AND current_row.row_version <> NEW.cancellation_row_version) + OR (first_invoice.creation_request_id, first_invoice.tuple_digest, first_invoice.invoice_id, + first_invoice.payment_intent_id, first_invoice.provider_subscription_id, + first_invoice.provider_customer_id, first_invoice.provider_payment_method_id, + first_invoice.provider_price_id, first_invoice.provider_quantity, + first_invoice.amount, first_invoice.currency, first_invoice.livemode) + IS DISTINCT FROM (NEW.creation_request_id, NEW.tuple_digest, NEW.invoice_id, + NEW.payment_intent_id, NEW.provider_subscription_id, NEW.provider_customer_id, + NEW.provider_payment_method_id, NEW.provider_price_id, NEW.provider_quantity, + NEW.amount, NEW.currency, NEW.livemode) + OR (confirmation.lifecycle_request_id, confirmation.tuple_digest, confirmation.account_uuid) + IS DISTINCT FROM (NEW.lifecycle_request_id, NEW.tuple_digest, first_invoice.account_uuid) + OR inbox.event_type <> 'payment_intent.succeeded' + OR inbox.payload_sha256 <> NEW.event_payload_digest + OR inbox.livemode <> NEW.livemode + OR inbox.provider_event_id IS DISTINCT FROM paid_payload->>'id' + OR inbox.event_type IS DISTINCT FROM paid_payload->>'type' + OR paid_payload->>'livemode' IS DISTINCT FROM NEW.livemode::TEXT + OR paid_payload->'data'->'object'->>'object' IS DISTINCT FROM 'payment_intent' + OR paid_payload->'data'->'object'->>'status' IS DISTINCT FROM 'succeeded' + OR paid_payload->'data'->'object'->>'id' IS DISTINCT FROM NEW.payment_intent_id + OR paid_payload->'data'->'object'->>'customer' IS DISTINCT FROM NEW.provider_customer_id + OR paid_payload->'data'->'object'->>'payment_method' IS DISTINCT FROM NEW.provider_payment_method_id + OR paid_payload->'data'->'object'->>'amount' IS DISTINCT FROM NEW.amount::TEXT + OR paid_payload->'data'->'object'->>'amount_received' IS DISTINCT FROM NEW.amount::TEXT + OR paid_payload->'data'->'object'->>'currency' IS DISTINCT FROM NEW.currency + OR paid_payload->'data'->'object'->>'livemode' IS DISTINCT FROM NEW.livemode::TEXT + OR inbox.provider_created_at_epoch_seconds < floor(EXTRACT(EPOCH FROM confirmation.consented_at)) + OR NEW.observed_status <> 'succeeded' + OR NEW.observation_read_started_at < inbox.received_at + OR NEW.observation_observed_at < NEW.observation_read_started_at + OR NEW.observation_observed_at - NEW.observation_read_started_at >= INTERVAL '20 seconds' + OR NEW.observation_expires_at IS DISTINCT FROM NEW.observation_read_started_at + INTERVAL '20 seconds' + OR NEW.observation_observed_at >= NEW.observation_expires_at + OR NOT EXISTS ( + SELECT 1 + FROM subscription_provisioning_work work + JOIN subscription_lifecycle_operations canceled_operation + ON canceled_operation.request_id = current_row.current_receipt_request_id + AND canceled_operation.subscription_id = current_row.subscription_id + JOIN subscription_lifecycle_receipts canceled_receipt + ON canceled_receipt.request_id = canceled_operation.request_id + AND canceled_receipt.subscription_id = canceled_operation.subscription_id + JOIN subscription_lifecycle_observations cancellation_observation + ON (cancellation_observation.request_id, cancellation_observation.attempt_id, + cancellation_observation.evidence_digest) + = (canceled_receipt.request_id, canceled_receipt.attempt_id, + canceled_receipt.observation_digest) + JOIN subscription_provider_terminal_resolutions terminal + ON terminal.resolution_id = current_row.terminal_resolution_id + AND terminal.subscription_id = current_row.subscription_id + JOIN subscription_instrument_reservations reservation + ON reservation.subscription_id = current_row.subscription_id + WHERE work.request_id = first_invoice.creation_request_id + AND work.subscription_id = current_row.subscription_id + AND work.phase = 'CANCELED' + AND work.last_attempt_id IS NOT NULL + AND canceled_operation.state = 'COMMITTED' + AND canceled_operation.creation_request_id = first_invoice.creation_request_id + AND canceled_operation.tenant_id = first_invoice.tenant_id + AND canceled_operation.provider_subscription_id = first_invoice.provider_subscription_id + AND canceled_operation.provisioning_attempt_id IS NULL + AND canceled_operation.request_id = NEW.cancellation_request_id + AND canceled_operation.request_digest = canceled_receipt.request_digest + AND canceled_operation.request_digest = 'sha256:' || encode(sha256(canceled_operation.request_payload), 'hex') + AND canceled_receipt.status = 'canceled' + AND canceled_receipt.receipt_digest = NEW.cancellation_receipt_digest + AND canceled_receipt.subscription_row_version = NEW.cancellation_row_version + AND canceled_receipt.committed_transaction_id = NEW.cancellation_committed_transaction_id + AND canceled_receipt.committed_transaction_id <> txid_current() + AND canceled_receipt.provider_subscription_id = first_invoice.provider_subscription_id + AND canceled_receipt.plan_quote_digest = first_invoice.quote_digest + AND cancellation_observation.raw_status = 'canceled' + AND terminal.request_id = first_invoice.creation_request_id + AND terminal.outcome = 'CANCELED' + AND terminal.provider_subscription_id = first_invoice.provider_subscription_id + AND terminal.evidence_digest = cancellation_observation.evidence_digest + AND reservation.request_id = first_invoice.creation_request_id + AND reservation.terminal_resolution_id = terminal.resolution_id + AND reservation.released_at IS NOT NULL + AND convert_from(canceled_operation.request_payload, 'UTF8')::jsonb->>'schemaVersion' + = 'account-hosting-unpaid-first-invoice-cancellation/v1' + AND convert_from(canceled_operation.request_payload, 'UTF8')::jsonb->>'requestId' + = canceled_operation.request_id::TEXT + AND convert_from(canceled_operation.request_payload, 'UTF8')::jsonb->>'creationRequestId' + = first_invoice.creation_request_id::TEXT + AND convert_from(canceled_operation.request_payload, 'UTF8')::jsonb->>'expectedRowVersion' + = canceled_operation.expected_row_version::TEXT + AND convert_from(canceled_operation.request_payload, 'UTF8')::jsonb->>'providerSubscriptionId' + = first_invoice.provider_subscription_id + AND convert_from(canceled_operation.request_payload, 'UTF8')::jsonb->>'provisioningAttemptId' = '' + AND (current_row.superseded_at IS NOT NULL + OR canceled_receipt.subscription_row_version = current_row.row_version) + AND ( + NOT EXISTS (SELECT 1 FROM subscription_first_invoice_command_claims claim + WHERE claim.subscription_id = current_row.subscription_id) + OR EXISTS ( + SELECT 1 + FROM subscription_first_invoice_no_send_cancellations release + JOIN subscription_first_invoice_command_claims claim + ON claim.request_id = release.confirmation_request_id + AND claim.subscription_id = current_row.subscription_id + JOIN subscription_first_invoice_expired_before_post marker + ON marker.request_id = claim.request_id + JOIN subscription_first_invoice_authorizations auth + ON (auth.authorization_request_id, auth.request_id, + auth.subscription_id) + = (claim.authorization_request_id, claim.request_id, claim.subscription_id) + JOIN subscription_lifecycle_operations witness_operation + ON witness_operation.request_id = release.cancellation_request_id + AND witness_operation.subscription_id = current_row.subscription_id + JOIN subscription_lifecycle_receipts witness_receipt + ON witness_receipt.request_id = witness_operation.request_id + AND witness_receipt.subscription_id = witness_operation.subscription_id + JOIN subscription_lifecycle_observations witness_observation + ON (witness_observation.request_id, witness_observation.attempt_id, + witness_observation.evidence_digest) + = (witness_receipt.request_id, witness_receipt.attempt_id, + witness_receipt.observation_digest) + JOIN subscription_lifecycle_attempts witness_attempt + ON (witness_attempt.request_id, witness_attempt.attempt_id) + = (witness_operation.request_id, witness_observation.attempt_id) + WHERE release.cancellation_request_id = NEW.cancellation_request_id + AND release.confirmation_request_id = NEW.request_id + AND release.invoice_id = first_invoice.invoice_id + AND release.payment_intent_id = first_invoice.payment_intent_id + AND release.created_transaction_id = NEW.cancellation_committed_transaction_id + AND release.created_transaction_id = witness_receipt.committed_transaction_id + AND release.read_started_at >= witness_observation.observed_at + AND release.read_started_at >= witness_attempt.started_at + AND release.observed_at >= release.read_started_at + AND release.observed_at <= witness_operation.created_at + AND release.observed_at < witness_attempt.expires_at + AND witness_operation.created_at < witness_attempt.expires_at + AND witness_operation.created_at - release.read_started_at + < witness_operation.observation_age_millis * INTERVAL '1 millisecond' + AND marker.created_transaction_id <> release.created_transaction_id + AND marker.observed_at >= auth.valid_until + AND claim.created_transaction_id <> marker.created_transaction_id + AND witness_operation.state = 'COMMITTED' + AND witness_receipt.status = 'canceled' + AND witness_observation.raw_status = 'canceled' + ) + ) + ) + OR EXISTS (SELECT 1 FROM subscription_lifecycle_operator_outbox + WHERE request_id = current_row.current_receipt_request_id) + OR EXISTS (SELECT 1 FROM subscription_provisioning_operator_outbox + WHERE request_id = first_invoice.creation_request_id) + OR EXISTS (SELECT 1 FROM subscription_first_invoice_success_evidence + WHERE subscription_id = NEW.subscription_id) + OR EXISTS (SELECT 1 FROM subscription_first_invoice_completions + WHERE subscription_id = NEW.subscription_id) THEN + RAISE EXCEPTION 'Late first-invoice payment requires its exact verified success and committed unpaid cancellation' USING ERRCODE = '23514'; + END IF; + cancellation_payload := convert_from((SELECT request_payload FROM subscription_lifecycle_operations + WHERE request_id = NEW.cancellation_request_id), 'UTF8')::jsonb; + IF NEW.cancellation_request_id IS DISTINCT FROM current_row.current_receipt_request_id + OR NEW.cancellation_committed_transaction_id = txid_current() + OR cancellation_payload->>'schemaVersion' IS DISTINCT FROM 'account-hosting-unpaid-first-invoice-cancellation/v1' THEN + RAISE EXCEPTION 'Late first-invoice payment must retain the current committed unpaid cancellation' USING ERRCODE = '23514'; + END IF; + NEW.created_transaction_id := txid_current(); + RETURN NEW; + ELSE + RAISE EXCEPTION 'Late first-invoice payment conflicts are immutable' USING ERRCODE = '23514'; + END IF; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1046__account_capacity_attempt_write_freshness.sql b/services/account-service/src/main/resources/db/migration/V1046__account_capacity_attempt_write_freshness.sql new file mode 100644 index 0000000000..0b25acddac --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1046__account_capacity_attempt_write_freshness.sql @@ -0,0 +1,28 @@ +-- Add a write-time fence without rewriting retained reservations, evaluations or prior guards. +-- Expiry never releases a hold. Existing attempt replay and recovery remain valid after expiry. +-- [jooq ignore start] +CREATE FUNCTION account_tenant_capacity_attempt_freshness_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + evaluation account_tenant_capacity_evaluations%ROWTYPE; + observed_at TIMESTAMPTZ; +BEGIN + IF TG_OP = 'UPDATE' AND NEW.admission_attempt_id IS NOT DISTINCT FROM OLD.admission_attempt_id THEN + RETURN NEW; + END IF; + SELECT * INTO evaluation FROM account_tenant_capacity_evaluations + WHERE evaluation_identity = NEW.evaluation_identity FOR SHARE; + -- Capture only after the evaluation lock. CURRENT_TIMESTAMP is frozen before lock waits. + observed_at := clock_timestamp(); + IF NOT FOUND OR evaluation.evaluated_at > observed_at + OR evaluation.expires_at <= observed_at OR NEW.expires_at <= observed_at THEN + RAISE EXCEPTION 'Capacity admission attempt is stale at the reservation write boundary' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE CONSTRAINT TRIGGER account_tenant_capacity_attempt_freshness + AFTER INSERT OR UPDATE ON account_tenant_capacity_reservations + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_attempt_freshness_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java index 89d0004ea5..b34266469d 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java @@ -8,6 +8,7 @@ import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.time.Clock; import java.time.Duration; import java.time.Instant; @@ -94,6 +95,7 @@ import net.firedevops.firemud.test.TestContainerImages; import org.jooq.DSLContext; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -127,6 +129,8 @@ "firemud.mail.verification-url=https://account.test/verify-email?token=%s" }) class AccountApplicationIntegrationTest { + @TempDir Path invoiceCheckoutDirectory; + private static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient(); @Container @@ -1415,20 +1419,7 @@ private CanonicalPublicJoinFixture(boolean usePaid, Account existingAccount) { paid = integration.net.firedevops.firemud.accountservice.repository .CanonicalHostingSubscriptionTestFixture.create(dataSource); - var claim = - paid.service() - .claimProvisioning(paid.creation().requestId(), 1, UUID.randomUUID()) - .claim(); - assertThat( - paid.service() - .reconcile( - UUID.randomUUID(), - paid.creation().requestId(), - claim.subscriptionRowVersion(), - paid.providerId(), - claim.attemptId()) - .outcome()) - .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Outcome.COMMITTED); + paid.withCheckoutDirectory(invoiceCheckoutDirectory).completeFirstInvoice(); hosting = paid.lifecycleRepository(); observer = paid.observer(); tenantId = paid.tenantId(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityCurrentnessIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityCurrentnessIntegrationTest.java index beacf29af4..61116f6ef3 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityCurrentnessIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityCurrentnessIntegrationTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.nio.file.Path; import java.time.Duration; import java.time.Instant; import java.util.List; @@ -29,6 +30,7 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; @@ -36,6 +38,8 @@ /** Canonical hosting lifecycle/source currentness and separate realm-grant tombstone/CAS proof. */ class AccountAuthorityCurrentnessIntegrationTest { + @TempDir Path invoiceCheckoutDirectory; + private static final AccountPostgresIntegrationFixture postgres = new AccountPostgresIntegrationFixture(); @@ -65,21 +69,16 @@ void subscriptionAndRealmGrantMutationsAdvanceCurrentnessAndKeepRevocationTombst DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); var fixture = CanonicalHostingSubscriptionTestFixture.create(dataSource); - var claim = - fixture - .service() - .claimProvisioning(fixture.creation().requestId(), 1, UUID.randomUUID()) - .claim(); - UUID initialRequest = UUID.randomUUID(); var initialCommit = + fixture.withCheckoutDirectory(invoiceCheckoutDirectory).completeFirstInvoice(); + UUID initialRequest = initialCommit.requestId(); + long initialExpectedVersion = fixture - .service() - .reconcile( - initialRequest, - fixture.creation().requestId(), - claim.subscriptionRowVersion(), - fixture.providerId(), - claim.attemptId()); + .dsl() + .fetchSingle( + "SELECT expected_row_version FROM subscription_lifecycle_operations WHERE request_id = ?", + initialRequest) + .get(0, Long.class); assertThat(initialCommit.outcome()).isEqualTo(Outcome.COMMITTED); var initial = fixture.service().readCurrent(fixture.tenantId()); assertThat(initial.entitlementVersion()).isOne(); @@ -91,9 +90,9 @@ void subscriptionAndRealmGrantMutationsAdvanceCurrentnessAndKeepRevocationTombst .reconcile( initialRequest, fixture.creation().requestId(), - claim.subscriptionRowVersion(), + initialExpectedVersion, fixture.providerId(), - claim.attemptId())) + null)) .isEqualTo(initialCommit); assertThat(fixture.transport().reads()).isEqualTo(initialReads); var initialRetry = fixture.service().readCurrent(fixture.tenantId()); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java index 7ec610ae97..ac285a5cdf 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java @@ -268,7 +268,7 @@ void migrationRetainsV1AndStoresExactV2ScopeAndPendingIntentWithoutMembershipOrE } @Test - void capacityUpgradeFromParent1036Through1040PreservesCanonicalRowsAndHistory() { + void firstInvoiceAndCapacityUpgradeFromParent1036Through1041PreservesCanonicalRowsAndHistory() { String schema = createSchema("canonical_join_scope_"); DriverManagerDataSource dataSource = postgres.dataSource(schema); Flyway parent = accountFlyway(dataSource, schema, "1036"); @@ -338,30 +338,41 @@ void capacityUpgradeFromParent1036Through1040PreservesCanonicalRowsAndHistory() .contains("V1036__hosting_subscription_terminal_resolution.sql") .doesNotContain( "V1037__canonical_join_failure_and_attempt_diagnostics.sql", - "V1038__canonical_join_existing_membership_terminal.sql"); + "V1038__canonical_join_existing_membership_terminal.sql", + "V1041__hosting_first_invoice_completion.sql", + "V1040__account_tenant_capacity_owner.sql"); - Flyway current = accountFlyway(dataSource, schema, "1040"); + Flyway current = accountFlyway(dataSource, schema, "1041"); current.migrate(); current.validate(); assertThat(current.info().current().getVersion()) - .isEqualTo(MigrationVersion.fromVersion("1040")); + .isEqualTo(MigrationVersion.fromVersion("1041")); List> upgradedHistory = flywayHistory(setupDsl); - assertThat(upgradedHistory).hasSize(parentHistory.size() + 4); + assertThat(upgradedHistory).hasSize(parentHistory.size() + 11); assertThat(upgradedHistory.subList(0, parentHistory.size())) .containsExactlyElementsOf(parentHistory); List> addedHistory = upgradedHistory.subList(parentHistory.size(), upgradedHistory.size()); assertThat(addedHistory) .extracting(row -> row.get("version")) - .containsExactly("1037", "1038", "1039", "1040"); + .containsExactly( + "1037", "1038", "1039", "1040", "1040.1", "1040.2", "1040.3", "1040.4", "1040.5", + "1040.6", "1041"); assertThat(addedHistory) .extracting(row -> row.get("script")) .containsExactly( "V1037__canonical_join_failure_and_attempt_diagnostics.sql", "V1038__canonical_join_existing_membership_terminal.sql", "V1039__hosting_unclaimed_wallet_settlement.sql", - "V1040__account_tenant_capacity_owner.sql"); + "V1040__account_tenant_capacity_owner.sql", + "V1040.1__account_capacity_origin_decisions.sql", + "V1040.2__bound_capacity_origin_refusals.sql", + "V1040.3__validate_only_inserted_refusal_budgets.sql", + "V1040.4__unique_capacity_origin_attempt.sql", + "V1040.5__arbitrate_origin_identity_before_refusal_budget.sql", + "V1040.6__index_retained_capacity_refusal_slots.sql", + "V1041__hosting_first_invoice_completion.sql"); assertThat(addedHistory) .allSatisfy(row -> { assertThat(row.get("checksum")).isNotNull(); @@ -385,11 +396,11 @@ void capacityUpgradeFromParent1036Through1040PreservesCanonicalRowsAndHistory() List installedConstraints = setupDsl .fetch( - "SELECT constraint_row.conname FROM pg_constraint constraint_row " - + "JOIN pg_class table_row ON table_row.oid = constraint_row.conrelid " - + "JOIN pg_namespace schema_row ON schema_row.oid = table_row.relnamespace " - + "WHERE schema_row.nspname = ? AND table_row.relname = 'account_join_operations' " - + "AND constraint_row.contype = 'c' AND constraint_row.convalidated", + "SELECT constraint_row.conname FROM pg_constraint constraint_row JOIN pg_class" + + " table_row ON table_row.oid = constraint_row.conrelid JOIN pg_namespace" + + " schema_row ON schema_row.oid = table_row.relnamespace WHERE" + + " schema_row.nspname = ? AND table_row.relname = 'account_join_operations'" + + " AND constraint_row.contype = 'c' AND constraint_row.convalidated", schema) .getValues(0, String.class); assertThat(installedConstraints) @@ -401,12 +412,12 @@ void capacityUpgradeFromParent1036Through1040PreservesCanonicalRowsAndHistory() assertThat( Objects.requireNonNull( setupDsl.fetchOne( - "SELECT count(*) FROM pg_trigger trigger_row " - + "JOIN pg_class table_row ON table_row.oid = trigger_row.tgrelid " - + "JOIN pg_namespace schema_row ON schema_row.oid = table_row.relnamespace " - + "WHERE schema_row.nspname = ? AND table_row.relname = 'account_join_operations' " - + "AND trigger_row.tgname = 'account_join_operation_identity_guard' " - + "AND trigger_row.tgenabled = 'O' AND NOT trigger_row.tgisinternal", + "SELECT count(*) FROM pg_trigger trigger_row JOIN pg_class table_row ON" + + " table_row.oid = trigger_row.tgrelid JOIN pg_namespace schema_row ON" + + " schema_row.oid = table_row.relnamespace WHERE schema_row.nspname =" + + " ? AND table_row.relname = 'account_join_operations' AND" + + " trigger_row.tgname = 'account_join_operation_identity_guard' AND" + + " trigger_row.tgenabled = 'O' AND NOT trigger_row.tgisinternal", schema)) .get(0, Long.class)) .isEqualTo(1L); @@ -434,7 +445,8 @@ void capacityUpgradeFromParent1036Through1040PreservesCanonicalRowsAndHistory() requestId); assertThatThrownBy(() -> setupDsl.execute( - "UPDATE account_join_operations SET verified_caller_binding = ? WHERE request_id = ?", + "UPDATE account_join_operations SET verified_caller_binding = ? WHERE request_id =" + + " ?", "changed-migration-caller", requestId)) .isInstanceOfSatisfying( @@ -479,7 +491,8 @@ void expiredScopeCleanupSkipsImmutableV2BeforeLimitingV1Batch() { Long v1AccountId = Objects.requireNonNull( setupDsl.fetchOne( - "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?)" + + " RETURNING id", "scope-cleanup-v1-account", "scope-cleanup-v1@example.test", "test-hash")) @@ -613,7 +626,8 @@ void definitiveFailureRetainsOriginalIntentAndOptionalPolicyAndExactlyReplaysWit assertThatThrownBy(() -> f.dsl() .execute( - "UPDATE account_join_operations SET updated_at = CURRENT_TIMESTAMP WHERE request_id = ?", + "UPDATE account_join_operations SET updated_at = CURRENT_TIMESTAMP WHERE" + + " request_id = ?", f.requestId())) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThat(f.bytes()).isEqualTo(retained); @@ -773,7 +787,8 @@ void sqlGuardsRefuseRetryableTerminalOutcomesPolicyDowngradeInventedProofAndTerm "entitlement_authority_availability = 'UNAVAILABLE'", "entitlement_version = 24", "request_digest = NULL", - "last_attempt_authority_availability = 'UNAVAILABLE', last_attempt_failure_code = NULL")) { + "last_attempt_authority_availability = 'UNAVAILABLE', last_attempt_failure_code =" + + " NULL")) { assertThatThrownBy(() -> f.dsl() .execute( @@ -848,7 +863,8 @@ private JournalFixture journalFixture() { var account = Objects.requireNonNull( setup.fetchOne( - "INSERT INTO accounts (username, email, password_hash) VALUES ('journal-player', 'journal@example.test', 'controlled-hash') RETURNING id, account_uuid")); + "INSERT INTO accounts (username, email, password_hash) VALUES ('journal-player'," + + " 'journal@example.test', 'controlled-hash') RETURNING id, account_uuid")); long privateAccountId = account.get("id", Long.class); UUID accountId = account.get("account_uuid", UUID.class); var fresh = new FreshTenantIdentityAssociationRepository(owner, "prod"); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java index 2571eb1036..2ec5f897d0 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java @@ -27,6 +27,7 @@ import java.security.MessageDigest; import java.time.Clock; import java.time.Duration; +import java.time.Instant; import java.time.ZoneOffset; import java.util.Arrays; import java.util.Base64; @@ -1105,10 +1106,10 @@ void lostExpiredEvaluationDenialSettlesThroughReadOnlyRecoveryAndReplaysOffline( @Test void accountGeneratedUnavailableKeepsExactGameSessionReserveUnsettled() throws Exception { - // Only Account's capacity owner sees the advanced clock. The Game Session request, - // lease and credential remain current, so the real coordinator reaches Account after precharge. - try (Session session = session(Clock.offset(CLOCK, Duration.ofSeconds(60))); - OriginalNewCredential credential = session.issue()) { + try (Session session = session(); + OriginalNewCredential credential = session.issue(); + var worker = Executors.newSingleThreadExecutor(); + var lock = session.account.dataSource.getConnection()) { var request = session.capacityRequest; assertThat(request.evidence().permitsCreation()).isTrue(); byte[] candidate = session.gs.physicalSession(); @@ -1119,8 +1120,28 @@ void accountGeneratedUnavailableKeepsExactGameSessionReserveUnsettled() throws E + " FROM game_session_capacity_evidence_charge WHERE admission_attempt_id=?"; assertThat(session.gs.dsl().fetchOne(chargeLookup, request.admissionAttemptId())).isNull(); - var uncertain = assertThrows(IllegalStateException.class, () -> session.complete(request)); - assertThat(uncertain).isNotInstanceOf(CapacityRefusedException.class); + int blocker = lockGameSessionUsage(lock, request.identity().tenantId()); + // Start the worker thread before narrowing the window for reaching the actual SQL lock. + worker.submit(() -> {}).get(5, TimeUnit.SECONDS); + waitForDatabaseTime(session.dsl, request.evidence().expiresAt().minusSeconds(3)); + var result = worker.submit(() -> session.complete(request)); + try { + requireUsageWaitBeforeExpiry(session.dsl, blocker, request.evidence().expiresAt()); + // The actual Account owner is waiting on the held row, after Game Session precharges. + assertThat(session.gs.dsl().fetchOne(chargeLookup, request.admissionAttemptId())) + .isNotNull(); + waitForDatabaseTime(session.dsl, request.evidence().expiresAt()); + } finally { + lock.rollback(); + } + var uncertain = + assertThrows( + java.util.concurrent.ExecutionException.class, + () -> result.get(3, TimeUnit.SECONDS)) + .getCause(); + assertThat(uncertain) + .isInstanceOf(IllegalStateException.class) + .isNotInstanceOf(CapacityRefusedException.class); assertThat(uncertain.getCause()).isInstanceOf(StatusRuntimeException.class); assertCapacityFailure( (StatusRuntimeException) uncertain.getCause(), @@ -1469,12 +1490,193 @@ private static void assertExactAccountDenial( @Test void exactRetainedEvaluationOutsideOwnerWindowIsStaleWithoutOwnerMutation() throws Exception { - try (Session session = session(Clock.offset(CLOCK, Duration.ofSeconds(60)))) { + try (Session session = session()) { + waitForDatabaseTime(session.dsl, session.capacityRequest.evidence().expiresAt()); assertCapacityRefusalWithoutMutation( session, session.capacityRequest, Status.Code.UNAVAILABLE, "CAPACITY_ADMISSION_STALE"); } } + @Test + void capacityOwnerAcceptsFreshEvidenceWhenItsApplicationClockTrailsPostgres() throws Exception { + try (Session session = session()) { + var evidence = session.capacityRequest.evidence(); + Instant callerNotBefore = + Instant.ofEpochSecond( + session.account.committedCandidate.identity().notBeforeEpochSecond()); + Clock behindEvidence = Clock.fixed(evidence.evaluatedAt().minusNanos(1), ZoneOffset.UTC); + assertThat(behindEvidence.instant()) + .isAfterOrEqualTo(callerNotBefore) + .isBefore(evidence.evaluatedAt()); + assertThat(AccountTenantCapacityRepository.databaseNow(session.dsl)) + .isAfterOrEqualTo(evidence.evaluatedAt()); + + var owner = session.account.capacityOwner(behindEvidence); + var result = owner.commit(session.capacityRequest, GS); + + assertThat(result.state()).isEqualTo(TenantCapacityAdmission.State.RESERVED); + var usage = + session.dsl.fetchSingle( + "SELECT held_units, used_units FROM account_tenant_capacity_usage " + + "WHERE tenant_uuid = ? AND owner_service = 'game-session-service'", + result.identity().tenantId()); + assertThat(usage.get("held_units", Long.class)).isEqualTo(1L); + assertThat(usage.get("used_units", Long.class)).isZero(); + } + } + + @Test + void applicationAuthorityCutoffAfterReservationStagingRollsBackWhileDatabaseEvidenceIsFresh() + throws Exception { + try (Session session = session()) { + var request = session.retainControlledEvaluation(true, null); + var evidence = request.evidence(); + var caller = session.account.committedCandidate.identity(); + Instant stillCurrent = evidence.evaluatedAt().minusNanos(1); + assertThat(stillCurrent) + .isAfterOrEqualTo(Instant.ofEpochSecond(caller.notBeforeEpochSecond())) + .isBefore(evidence.evaluatedAt()); + Instant callerCutoff = Instant.ofEpochSecond(caller.expiresAtEpochSecond()); + var parsed = + RuntimePlayerAdmissionEntitlementEvidence.parseCanonical(evidence.canonicalBytes()); + Instant scopeCutoff = + session.account.retainedCanonicalConnectScopeCutoff( + parsed.verifiedConnectScopeTokenHash()); + Instant appCutoff = callerCutoff.isBefore(scopeCutoff) ? callerCutoff : scopeCutoff; + assertThat(stillCurrent).isBefore(appCutoff); + assertThat(AccountTenantCapacityRepository.databaseNow(session.dsl)) + .isBefore(evidence.expiresAt()); + String before = session.capacityImage() + session.capacityDecisionImage(); + var staged = new java.util.concurrent.atomic.AtomicBoolean(); + Clock appClock = org.mockito.Mockito.mock(Clock.class); + org.mockito.Mockito.when(appClock.instant()) + .thenAnswer(ignored -> { + if (!org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) return stillCurrent; + // session.dsl is backed by TransactionAwareDataSourceProxy over the very same data + // source used by capacityOwner; only the enlisted thread can see the staged row. + boolean reservationStaged = + session.dsl.fetchExists( + DSL.selectOne() + .from(DSL.table("account_tenant_capacity_reservations")) + .where( + DSL.field("request_id", UUID.class) + .eq(request.identity().requestId()))); + if (!reservationStaged) return stillCurrent; + assertThat(AccountTenantCapacityRepository.databaseNow(session.dsl)) + .isBefore(evidence.expiresAt()); + staged.set(true); + return appCutoff; + }); + + assertThatThrownBy(() -> session.account.capacityOwner(appClock).commit(request, GS)) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> assertThat(failure.code()).isEqualTo(Failure.ENTITLEMENT_UNAVAILABLE)); + assertThat(staged).isTrue(); + assertThat(session.capacityImage() + session.capacityDecisionImage()).isEqualTo(before); + + var stillEligible = session.account.capacityOwner(Clock.fixed(stillCurrent, ZoneOffset.UTC)); + assertThat(stillEligible.commit(request, GS).state()) + .isEqualTo(TenantCapacityAdmission.State.RESERVED); + } + } + + @Test + void actualUsageLockWaitAcrossExpiryCannotCreateAReservationEvenWithAFrozenOwnerClock() + throws Exception { + try (Session session = session(); + var worker = Executors.newSingleThreadExecutor(); + var lock = session.account.dataSource.getConnection()) { + // Exercise the same owner, transaction, and SQL path on the worker before timing the + // actual lock wait. Non-creating evidence makes the warm-up refuse without a reservation. + var warmup = session.retainControlledEvaluation(false, null); + var warmupOwner = session.account.capacityOwner(CLOCK); + assertThatThrownBy( + () -> worker.submit(() -> warmupOwner.commit(warmup, GS)).get(5, TimeUnit.SECONDS)) + .hasCauseInstanceOf(AccountTenantCapacityRepository.CapacityException.class) + .hasStackTraceContaining("TENANT_BILLING_BLOCKED"); + int blocker = lockGameSessionUsage(lock, warmup.identity().tenantId()); + var request = session.retainControlledEvaluation(true, null); + String before = session.capacityImage(); + var owner = + session.account.capacityOwner( + Clock.fixed(request.evidence().evaluatedAt(), ZoneOffset.UTC)); + // The owner has a five-second transaction budget. Start within it, with enough + // time for the physical row wait to register before the retained evidence expires. + var expiry = request.evidence().expiresAt(); + waitForDatabaseTime(session.dsl, expiry.minusSeconds(3)); + Instant beforeSubmit = AccountTenantCapacityRepository.databaseNow(session.dsl); + assertThat(beforeSubmit).as("database time before submitting the owner").isBefore(expiry); + var result = worker.submit(() -> owner.commit(request, GS)); + try { + requireUsageWaitBeforeExpiry(session.dsl, blocker, request.evidence().expiresAt()); + waitForDatabaseTime(session.dsl, request.evidence().expiresAt()); + } finally { + lock.rollback(); + } + assertThatThrownBy(() -> result.get(3, TimeUnit.SECONDS)) + .hasCauseInstanceOf(AccountTenantCapacityRepository.CapacityException.class) + .hasStackTraceContaining("CAPACITY_ADMISSION_STALE"); + assertThat(session.capacityImage()).isEqualTo(before); + assertThat(session.dsl.fetchCount(DSL.table("account_tenant_capacity_reservations"))) + .isZero(); + } + } + + private static int lockGameSessionUsage(java.sql.Connection lock, UUID tenantId) + throws java.sql.SQLException { + lock.setAutoCommit(false); + int blocker; + try (var statement = lock.createStatement(); + var pid = statement.executeQuery("SELECT pg_backend_pid()")) { + assertThat(pid.next()).isTrue(); + blocker = pid.getInt(1); + } + try (var statement = + lock.prepareStatement( + "SELECT * FROM account_tenant_capacity_usage WHERE tenant_uuid = ? " + + "AND owner_service = 'game-session-service' FOR UPDATE")) { + statement.setObject(1, tenantId); + try (var usage = statement.executeQuery()) { + assertThat(usage.next()).isTrue(); + } + } + return blocker; + } + + private static void requireUsageWaitBeforeExpiry(DSLContext dsl, int blocker, Instant expiry) + throws InterruptedException { + long waitUntil = System.nanoTime() + TimeUnit.SECONDS.toNanos(2); + java.time.OffsetDateTime waitStartedAt; + do { + waitStartedAt = + dsl.fetchSingle( + "SELECT min(waiter.waitstart) FROM pg_locks waiter " + + "JOIN pg_stat_activity activity ON activity.pid = waiter.pid " + + "WHERE NOT waiter.granted AND ? = ANY(pg_blocking_pids(waiter.pid)) " + + "AND activity.query LIKE 'SELECT * FROM account_tenant_capacity_usage%'", + blocker) + .get(0, java.time.OffsetDateTime.class); + if (waitStartedAt == null) Thread.sleep(10); + } while (waitStartedAt == null && System.nanoTime() < waitUntil); + assertThat(waitStartedAt).as("the actual owner must wait on the held usage row").isNotNull(); + assertThat(waitStartedAt.toInstant()) + .as("the database recorded the usage lock wait starting before expiry") + .isBefore(expiry); + } + + private static void waitForDatabaseTime(DSLContext dsl, Instant target) { + dsl.fetchSingle( + "SELECT pg_sleep(GREATEST(0, extract(epoch FROM (?::timestamptz - clock_timestamp()))))", + AccountTenantCapacityRepository.at(target)); + assertThat( + dsl.fetchSingle("SELECT clock_timestamp()") + .get(0, java.time.OffsetDateTime.class) + .toInstant()) + .isAfterOrEqualTo(target.truncatedTo(java.time.temporal.ChronoUnit.MICROS)); + } + private static void assertCapacityRefusalWithoutMutation( Session session, TenantCapacityAdmission.Request request, Status.Code status, String code) throws Exception { @@ -1982,8 +2184,8 @@ private TenantCapacityAdmission.Request retainControlledEvaluation( facts, (Map) fields.get("sourceReferences"), CLOCK.instant()); - serializable.executeWithoutResult( - ignored -> new AccountTenantCapacityRepository(dsl).retainPlayerEvaluation(evaluation)); + serializable.executeWithoutResult(ignored -> + new AccountTenantCapacityRepository(dsl).retainPlayerEvaluation(evaluation, null)); return new TenantCapacityAdmission.Request( original.identity(), original.admissionAttemptId(), diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java index a9118d262b..7d72f9fa2d 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java @@ -2174,6 +2174,15 @@ void beginPlayerEntitlementLoginRevocation() { AccountGameplayTokenIdentityFenceRepository.revocationDigest(identity, requestId))); } + Instant retainedCanonicalConnectScopeCutoff(String scopeTokenHash) { + return Objects.requireNonNull( + serializable.execute(status -> + connectScopes + .findCanonicalEvidenceByTokenHash(scopeTokenHash) + .map(evidence -> Instant.parse(evidence.connectScopeExpiresAt())) + .orElseThrow())); + } + net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner playerEntitlementOwner(CanonicalGameplayAdmissionDecisionReadClient protectedTargets) { var scopes = diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java index fcb539a456..732081a2fb 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java @@ -12,8 +12,11 @@ import com.stripe.net.BaseAddress; import com.stripe.net.RequestOptions; import com.stripe.net.StripeResponseGetter; +import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture; import java.io.InputStream; import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.time.Clock; import java.time.Duration; import java.time.Instant; @@ -28,7 +31,8 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; -import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.client.StripeHostingFirstInvoicePaymentClient.Observation; import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionProvisioner; import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource.Category; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Disposition; @@ -38,8 +42,8 @@ import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.OwnerFence; import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.ProducerEvidence; import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.FenceRejectedException; -import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionLifecycleService; import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionProvisioningService; +import net.firedevops.firemud.accountservice.service.StripeWebhookIntakeService; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; @@ -51,9 +55,13 @@ import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; @@ -64,6 +72,8 @@ /** Actual owner/SDK composition with controlled enrollment publications and provider transport. */ @Testcontainers(disabledWithoutDocker = true) class AccountHostingSubscriptionDispatchPostgresIntegrationTest { + @TempDir Path invoiceCheckoutDirectory; + private static final String DIGEST = "sha256:" + "a".repeat(64); private static final AtomicLong GAME_ROWS = new AtomicLong(90000); @@ -71,6 +81,180 @@ class AccountHostingSubscriptionDispatchPostgresIntegrationTest { private static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void firstRetainedExactSignedSuccessBlocksBothUnpaidCancellationPaths(boolean claimed) + throws Exception { + var source = unpaidCancellationDataSource(null); + var f = CanonicalHostingSubscriptionTestFixture.create(source); + var checkout = f.withCheckoutDirectory(invoiceCheckoutDirectory).awaitFirstInvoice(); + if (claimed) { + checkout.claimExpiredBeforePost(CanonicalHostingSubscriptionTestFixture.BILLING_PASSWORD); + } + var signed = checkout.signedSuccess(); + var intake = + new StripeWebhookIntakeService( + checkout.verifier(), + new StripeEventInboxRepository(f.dsl()), + new DataSourceTransactionManager(source)); + var retained = intake.accept(signed.payload(), signed.signature()); + var redelivery = checkout.signWebhookPayload(signed.payload() + "\n"); + assertThat(intake.accept(redelivery.payload(), redelivery.signature())).isEqualTo(retained); + + f.providerStatus("canceled"); + var canceled = + f.service() + .reconcileUnpaidFirstInvoiceCancellation( + UUID.randomUUID(), + f.creation().requestId(), + unpaidRowVersion(f, checkout), + f.providerId()); + + assertThat(canceled.outcome()).isEqualTo(Outcome.RECONCILING); + assertUnpaidReservationHeld(f); + assertThat(f.dsl().fetchCount(DSL.table("subscription_first_invoice_success_evidence"))) + .isZero(); + assertThat(f.dsl().fetchCount(DSL.table("subscription_first_invoice_no_send_cancellations"))) + .isZero(); + assertThat(f.dsl().fetchCount(DSL.table("stripe_event_inbox"))).isOne(); + assertThat( + f.dsl().fetchSingle("SELECT raw_payload FROM stripe_event_inbox").get(0, byte[].class)) + .isEqualTo(signed.payload().getBytes(StandardCharsets.UTF_8)); + } + + @Test + void rawCancellationRejectsStaleSnapshotAndSeesExactInboxSuccessAtReadCommitted() + throws Exception { + var source = unpaidCancellationDataSource(null); + var f = CanonicalHostingSubscriptionTestFixture.create(source); + var checkout = f.withCheckoutDirectory(invoiceCheckoutDirectory).awaitFirstInvoice(); + var signed = checkout.signedSuccess(); + var verified = checkout.verifier().verify(signed.payload(), signed.signature()); + var repeatableRead = new TransactionTemplate(new DataSourceTransactionManager(source)); + repeatableRead.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + var independent = new TransactionTemplate(new DataSourceTransactionManager(source)); + independent.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + + assertThatThrownBy(() -> + repeatableRead.executeWithoutResult(status -> { + assertThat(f.dsl().fetchCount(DSL.table("stripe_event_inbox"))).isZero(); + in( + independent, + () -> new StripeEventInboxRepository(f.dsl()).retainOrReplay(verified)); + assertThat(f.dsl().fetchCount(DSL.table("stripe_event_inbox"))).isZero(); + rawUnpaidCancellation(f); + })) + .hasMessageContaining("Unpaid first-invoice cancellation requires READ COMMITTED"); + + assertThatThrownBy( + () -> f.transaction().executeWithoutResult(status -> rawUnpaidCancellation(f))) + .hasMessageContaining( + "Unpaid first-invoice cancellation conflicts with retained signed success"); + assertThat(f.dsl().fetchCount(DSL.table("stripe_event_inbox"))).isOne(); + assertUnpaidReservationHeld(f); + } + + @Test + void newNoSendMarkerUsesItsActualTransactionIdentityAndUpgradePreservesRetainedMarker() { + var source = unpaidCancellationDataSource("1046.7"); + var f = CanonicalHostingSubscriptionTestFixture.create(source); + var checkout = f.withCheckoutDirectory(invoiceCheckoutDirectory).awaitFirstInvoice(); + checkout.claimExpiredBeforePost(CanonicalHostingSubscriptionTestFixture.BILLING_PASSWORD); + String markerImage = + f.dsl() + .fetchSingle( + "SELECT row_to_json(m)::text || ':' || xmin::text FROM subscription_first_invoice_expired_before_post m") + .get(0, String.class); + migrate(source, Objects.requireNonNull(source.getSchema()), null); + assertThat( + f.dsl() + .fetchSingle( + "SELECT row_to_json(m)::text || ':' || xmin::text FROM subscription_first_invoice_expired_before_post m") + .get(0, String.class)) + .isEqualTo(markerImage); + + var another = CanonicalHostingSubscriptionTestFixture.create(source); + var open = another.withCheckoutDirectory(invoiceCheckoutDirectory).awaitFirstInvoice(); + var dispatch = + open.prepareConfirmationDispatch(CanonicalHostingSubscriptionTestFixture.BILLING_PASSWORD); + in( + another.transaction(), + () -> open.payments().claimCommand(dispatch, open.invoice().ownerAccountId())); + Long claimTransaction = + another + .dsl() + .fetchSingle( + "SELECT created_transaction_id FROM subscription_first_invoice_command_claims WHERE request_id = ?", + dispatch.requestId()) + .get(0, Long.class); + + another + .transaction() + .executeWithoutResult(status -> { + Long currentTransaction = + another.dsl().fetchSingle("SELECT txid_current()").get(0, Long.class); + assertThat( + another + .dsl() + .fetchSingle( + "INSERT INTO subscription_first_invoice_expired_before_post (request_id, observed_at, created_transaction_id) " + + "VALUES (?, ?::timestamptz, ?) RETURNING created_transaction_id", + dispatch.requestId(), + dispatch.validUntil().atOffset(ZoneOffset.UTC), + claimTransaction) + .get(0, Long.class)) + .isEqualTo(currentTransaction) + .isNotEqualTo(claimTransaction); + }); + } + + private static DriverManagerDataSource unpaidCancellationDataSource(String target) { + String schema = "hosting_unpaid_cancel_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + source.setSchema(schema); + migrate(source, schema, target); + return source; + } + + private static long unpaidRowVersion( + CanonicalHostingSubscriptionTestFixture.Fixture f, + CanonicalHostingSubscriptionTestFixture.FirstInvoiceCheckout checkout) { + return in( + f.transaction(), + () -> checkout.payments().ownerRowVersion(f.creation().subscriptionId(), f.accountUuid())); + } + + private static void rawUnpaidCancellation(CanonicalHostingSubscriptionTestFixture.Fixture f) { + f.dsl().execute("SET CONSTRAINTS first_invoice_unpaid_subscription_cancellation IMMEDIATE"); + f.dsl() + .execute( + "UPDATE subscription SET status = 'canceled', row_version = row_version + 1 WHERE subscription_id = ?", + f.creation().subscriptionId()); + } + + private static void assertUnpaidReservationHeld( + CanonicalHostingSubscriptionTestFixture.Fixture f) { + assertThat( + f.dsl() + .fetchSingle( + "SELECT status FROM subscription WHERE subscription_id = ?", + f.creation().subscriptionId()) + .get(0, String.class)) + .isEqualTo("provisioning"); + assertThat( + f.dsl() + .fetchSingle( + "SELECT released_at FROM subscription_instrument_reservations WHERE subscription_id = ?", + f.creation().subscriptionId()) + .get(0)) + .isNull(); + assertThat(f.dsl().fetchCount(DSL.table("subscription_lifecycle_operations"))).isZero(); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provider_terminal_resolutions"))) + .isZero(); + } + @Test void upgradeRetainsPriorAttemptOneAndAddsOnlyNonAuthorizingUnknownGuard() { Fixture f = fixture("1030"); @@ -145,13 +329,15 @@ void upgradeRetainsControlledUnclaimedWorkWithoutInventingDispatchHistory() { .isEqualTo(retained); assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_attempts"))).isZero(); assertThat(f.dsl().fetchCount(DSL.table("subscription_provider_dispatch_claim"))).isZero(); + var provisioning = service(f); var first = claim(f, 1); assertThat(first.attemptNumber()).isOne(); - f.transport().duringCreate = f.transport()::confirmFirstInvoice; var result = - (AccountHostingSubscriptionProvisioningService.Committed) - service(f).provision(first, UUID.randomUUID(), UUID.randomUUID()); - assertThat(result.current().current().providerSubscriptionId()).isEqualTo("sub_exact"); + (AccountHostingSubscriptionProvisioningService.AwaitingPayment) + provisioning.provision(first, UUID.randomUUID()); + assertThat(result.invoice().providerSubscriptionId()).isEqualTo("sub_exact"); + assertThat(result.invoice().subscriptionId()).isEqualTo(f.creation().subscriptionId()); + assertThat(f.dsl().fetchCount(DSL.table("subscription_lifecycle_receipts"))).isZero(); assertThat(f.transport().creates).isOne(); assertThat( Objects.requireNonNull( @@ -335,16 +521,15 @@ void recoveredUndispatchedAttemptMayOwnFirstDispatchButReplayAndExpiredReadbackC @Test void expiredUndispatchedFirstClaimRecoversThroughExactlyOneInitialCreate() { Fixture f = fixture("1032"); + var provisioning = service(f); var first = claim(f, 1); awaitProvisioningTime(f, "retry_at"); var second = claim(f, first.subscriptionRowVersion()); - f.transport().duringCreate = f.transport()::confirmFirstInvoice; var result = - (AccountHostingSubscriptionProvisioningService.Committed) - service(f).provision(second, UUID.randomUUID(), UUID.randomUUID()); - assertThat(result.current().current().providerSubscriptionId()).isEqualTo("sub_exact"); - assertThat(result.current().current().subscriptionId()) - .isEqualTo(f.creation().subscriptionId()); + (AccountHostingSubscriptionProvisioningService.AwaitingPayment) + provisioning.provision(second, UUID.randomUUID()); + assertThat(result.invoice().providerSubscriptionId()).isEqualTo("sub_exact"); + assertThat(result.invoice().subscriptionId()).isEqualTo(f.creation().subscriptionId()); assertThat(f.transport().creates).isEqualTo(1); var dispatch = Objects.requireNonNull( @@ -377,75 +562,96 @@ void dispatchIdentityBindingClassificationAndTimeCannotChangeOrDisappear() { } @Test - void paymentRequiredSdkCreateCannotCommitUntilProviderConfirmsFirstInvoice() { + void realInitialSdkCreateOnlyLinksAwaitingInvoiceAndCannotCommitHostingAuthority() { Fixture f = fixture("1032"); - var first = claim(f, 1); - UUID lifecycleRequest = UUID.randomUUID(); - var pending = - (AccountHostingSubscriptionProvisioningService.Reconciling) - service(f).provision(first, UUID.randomUUID(), lifecycleRequest); - assertThat(pending.transition().outcome()).isEqualTo(Outcome.RECONCILING); - assertThat(pending.transition().reason()).isEqualTo("UNMAPPED_PROVIDER_STATUS"); + var provisioning = service(f); + var result = + (AccountHostingSubscriptionProvisioningService.AwaitingPayment) + provisioning.provision(claim(f, 1), UUID.randomUUID()); + assertThat(result.invoice().providerSubscriptionId()).isEqualTo("sub_exact"); + assertThat(result.invoice().subscriptionId()).isEqualTo(f.creation().subscriptionId()); + assertThat(f.transport().creates).isEqualTo(1); + assertThat(f.transport().subscriptionReads).isGreaterThanOrEqualTo(2); assertThat(f.dsl().fetchCount(DSL.table("subscription_lifecycle_receipts"))).isZero(); + assertThat( + Objects.requireNonNull(f.dsl().fetchOne("SELECT status FROM subscription")) + .get("status", String.class)) + .isEqualTo("provisioning"); assertThat( Objects.requireNonNull( - f.dsl() - .fetchOne( - "SELECT status, provider_subscription_id FROM subscription WHERE subscription_id = ?", - f.creation().subscriptionId())) - .intoMap()) - .containsEntry("status", "provisioning") - .containsEntry("provider_subscription_id", null); - assertThat(f.transport().creates).isOne(); - - f.transport().confirmFirstInvoice(); - f.clock().now = f.clock().instant().plusSeconds(1); - var lifecycle = lifecycle(f, new com.stripe.StripeClient(f.transport())); - var transition = - lifecycle.reconcile( - lifecycleRequest, - f.creation().requestId(), - first.subscriptionRowVersion(), - "sub_exact", - first.attemptId()); - assertThat(transition.outcome()).isEqualTo(Outcome.COMMITTED); - var current = lifecycle.readCurrent(f.creation().tenantId()).current(); - assertThat(current.providerSubscriptionId()).isEqualTo("sub_exact"); - assertThat(current.subscriptionId()).isEqualTo(f.creation().subscriptionId()); - assertThat(current.status()).isEqualTo("active"); - assertThat(f.transport().creates).isEqualTo(1); - assertThat(f.transport().subscriptionReads).isGreaterThanOrEqualTo(3); + f.dsl().fetchOne("SELECT phase FROM subscription_provisioning_work")) + .get("phase", String.class)) + .isEqualTo("AWAITING_PAYMENT"); } @Test - void committedTransitionSurvivesUnavailableIndependentReadback() { + void lostProvisionResponseReplaysRetainedInvoiceWithoutProviderIo() { Fixture f = fixture("1032"); - f.transport().duringCreate = f.transport()::confirmFirstInvoice; - // The first two reads locate the subscription and supply the lifecycle observation. - f.transport().failSubscriptionRead = 3; - UUID lifecycleRequest = UUID.randomUUID(); + var provisioning = service(f); + var originalClaim = claim(f, 1); + // Retain the first result as a test oracle while simulating a lost caller response. + var original = + (AccountHostingSubscriptionProvisioningService.AwaitingPayment) + provisioning.provision(originalClaim, UUID.randomUUID()); + assertThat( + Objects.requireNonNull( + f.dsl() + .fetchOne( + "SELECT phase FROM subscription_provisioning_work WHERE request_id = ?", + f.creation().requestId())) + .get("phase", String.class)) + .isEqualTo("AWAITING_PAYMENT"); - var result = - (AccountHostingSubscriptionProvisioningService.ReadbackUnavailable) - service(f).provision(claim(f, 1), UUID.randomUUID(), lifecycleRequest); + var retainedImage = + f.dsl() + .fetchSingle( + "SELECT row_to_json(i)::text || ':' || xmin::text FROM subscription_first_invoices i") + .get(0, String.class); + var dispatchImage = + f.dsl() + .fetchSingle( + "SELECT row_to_json(c)::text || ':' || xmin::text FROM subscription_provider_dispatch_claim c") + .get(0, String.class); + var providerCalls = + List.of( + f.transport().requests, + f.transport().creates, + f.transport().searches, + f.transport().lists, + f.transport().subscriptionReads); - assertThat(result.transition().requestId()).isEqualTo(lifecycleRequest); - assertThat(result.transition().outcome()).isEqualTo(Outcome.COMMITTED); - assertThat(f.transport().subscriptionReads).isEqualTo(3); - assertThat(f.dsl().fetchCount(DSL.table("subscription_lifecycle_receipts"))).isOne(); + var replay = + (AccountHostingSubscriptionProvisioningService.AwaitingPayment) + provisioning.provision(originalClaim, UUID.randomUUID()); - var current = - lifecycle(f, new com.stripe.StripeClient(f.transport())) - .readCurrent(f.creation().tenantId()); - assertThat(current.receiptRequestId()).isEqualTo(lifecycleRequest); - assertThat(current.current().rowVersion()).isEqualTo(result.transition().committedRowVersion()); - assertThat(current.current().providerSubscriptionId()).isEqualTo("sub_exact"); - assertThat(f.transport().creates).isOne(); + assertThat(replay).isEqualTo(original); + assertThat( + f.dsl() + .fetchSingle( + "SELECT row_to_json(i)::text || ':' || xmin::text FROM subscription_first_invoices i") + .get(0, String.class)) + .isEqualTo(retainedImage); + assertThat( + f.dsl() + .fetchSingle( + "SELECT row_to_json(c)::text || ':' || xmin::text FROM subscription_provider_dispatch_claim c") + .get(0, String.class)) + .isEqualTo(dispatchImage); + assertThat( + List.of( + f.transport().requests, + f.transport().creates, + f.transport().searches, + f.transport().lists, + f.transport().subscriptionReads)) + .isEqualTo(providerCalls); + assertThat(f.dsl().fetchCount(DSL.table("subscription_lifecycle_receipts"))).isZero(); } @Test void liveFinalBudgetDispatchSurvivesDisplayRefreshAndCompetingClaim() { Fixture f = fixture("1032"); + var provisioning = service(f); var first = claim(f, 1); awaitProvisioningTime(f, "retry_at"); var second = claim(f, first.subscriptionRowVersion()); @@ -467,54 +673,82 @@ void liveFinalBudgetDispatchSurvivesDisplayRefreshAndCompetingClaim() { assertThat(competing.claim()).isNull(); assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))) .isZero(); - f.transport().confirmFirstInvoice(); }; var result = - (AccountHostingSubscriptionProvisioningService.Committed) - service(f).provision(finalClaim, UUID.randomUUID(), UUID.randomUUID()); - assertThat(result.current().current().providerSubscriptionId()).isEqualTo("sub_exact"); + (AccountHostingSubscriptionProvisioningService.AwaitingPayment) + provisioning.provision(finalClaim, UUID.randomUUID()); + assertThat(result.invoice().providerSubscriptionId()).isEqualTo("sub_exact"); assertThat(f.transport().creates).isOne(); assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_attempts"))).isEqualTo(3); assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))).isZero(); - assertThat(f.dsl().fetchCount(DSL.table("subscription_lifecycle_receipts"))).isOne(); + assertThat(f.dsl().fetchCount(DSL.table("subscription_lifecycle_receipts"))).isZero(); } @Test void lostCreateResponseRecoversAfterTransientEmptySearchWithoutRecreating() { Fixture f = fixture("1032"); + var provisioning = service(f); f.transport().loseCreateResponse = true; var first = claim(f, 1); + var firstDispatch = new AtomicReference(); + f.transport().duringCreate = () -> firstDispatch.set(prepareAndRead(f, first)); var lost = (AccountHostingSubscriptionProvisioningService.Pending) - service(f).provision(first, UUID.randomUUID(), UUID.randomUUID()); + provisioning.provision(first, UUID.randomUUID()); assertThat(lost.disposition()).isEqualTo(Disposition.WAITING); assertThat(((StripeHostingSubscriptionProvisioner.Pending) lost.providerResult()).reason()) .isEqualTo("PROVIDER_OUTCOME_UNKNOWN"); assertThat(f.transport().creates).isEqualTo(1); - f.transport().confirmFirstInvoice(); + Instant originalProviderCreation = f.transport().providerCreatedAt; + assertThat(originalProviderCreation).isNotNull(); f.transport().emptySearchesRemaining = 1; awaitProvisioningTime(f, "retry_at"); var second = claim(f, first.subscriptionRowVersion()); + var secondDispatch = prepareAndRead(f, second); var result = - (AccountHostingSubscriptionProvisioningService.Committed) - service(f).provision(second, UUID.randomUUID(), UUID.randomUUID()); - assertThat(result.current().current().providerSubscriptionId()).isEqualTo("sub_exact"); + (AccountHostingSubscriptionProvisioningService.AwaitingPayment) + provisioning.provision(second, UUID.randomUUID()); + assertThat(result.invoice().providerSubscriptionId()).isEqualTo("sub_exact"); + assertThat(f.clock().instant()).isAfter(originalProviderCreation); + assertThat(result.invoice().expiresAt()) + .isEqualTo(originalProviderCreation.plus(Duration.ofHours(23))); assertThat(f.transport().creates).isEqualTo(1); assertThat(f.transport().searches).isEqualTo(2); assertThat(f.transport().lists).isEqualTo(1); assertThat(f.dsl().fetchCount(DSL.table("subscription_provider_dispatch_claim"))).isOne(); assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))).isZero(); + int providerRequests = f.transport().requests; + assertThat(provisioning.provision(second, UUID.randomUUID())).isEqualTo(result); + assertThatThrownBy(() -> provisioning.provision(first, UUID.randomUUID())) + .isInstanceOf(FenceRejectedException.class); + var invoices = new AccountHostingFirstInvoicePaymentRepository(f.dsl(), f.intents(), f.clock()); + var observation = mock(Observation.class); + when(observation.invoiceId()).thenReturn(result.invoice().invoiceId()); + when(observation.paymentIntentId()).thenReturn(result.invoice().paymentIntentId()); + var originalDispatch = Objects.requireNonNull(firstDispatch.get()); + assertThatThrownBy(() -> + f.tx() + .execute(status -> + invoices.retainAwaitingPayment(originalDispatch, "sub_exact", observation))) + .isInstanceOf(FenceRejectedException.class); + var retained = + f.tx() + .execute( + status -> invoices.retainAwaitingPayment(secondDispatch, "sub_exact", observation)); + assertThat(retained).isEqualTo(result.invoice()); + assertThat(f.transport().requests).isEqualTo(providerRequests); } @Test void prolongedEmptySearchAfterLostCreateStopsWithOneOperatorItemAndHeldReservation() { Fixture f = fixture("1032"); + var provisioning = service(f); f.transport().loseCreateResponse = true; var first = claim(f, 1); var lost = (AccountHostingSubscriptionProvisioningService.Pending) - service(f).provision(first, UUID.randomUUID(), UUID.randomUUID()); + provisioning.provision(first, UUID.randomUUID()); assertThat(lost.disposition()).isEqualTo(Disposition.WAITING); assertThat(((StripeHostingSubscriptionProvisioner.Pending) lost.providerResult()).reason()) .isEqualTo("PROVIDER_OUTCOME_UNKNOWN"); @@ -527,7 +761,7 @@ void prolongedEmptySearchAfterLostCreateStopsWithOneOperatorItemAndHeldReservati previous = claim(f, previous.subscriptionRowVersion()); var pending = (AccountHostingSubscriptionProvisioningService.Pending) - service(f).provision(previous, UUID.randomUUID(), UUID.randomUUID()); + provisioning.provision(previous, UUID.randomUUID()); assertThat(pending.disposition()) .isEqualTo(attempt == 3 ? Disposition.TERMINAL_FAILURE : Disposition.WAITING); assertThat(pending.providerResult()) @@ -580,7 +814,8 @@ void prolongedEmptySearchAfterLostCreateStopsWithOneOperatorItemAndHeldReservati @Test void displayRefreshAfterClaimRefusesDispatchButRetainedWorkReachesOperatorDeadline() { - Fixture f = fixture("1032", Duration.ofSeconds(5)); + Fixture f = fixture(null, Duration.ofSeconds(5)); + var provisioning = migratedService(f); var original = claim(f, 1); var originalRows = f.dsl().fetch("SELECT * FROM subscription_create_operations").intoMaps(); var reservation = @@ -592,7 +827,7 @@ void displayRefreshAfterClaimRefusesDispatchButRetainedWorkReachesOperatorDeadli .isInstanceOf(FenceRejectedException.class); var refused = (AccountHostingSubscriptionProvisioningService.Pending) - service(f).provision(original, UUID.randomUUID(), UUID.randomUUID()); + provisioning.provision(original, UUID.randomUUID()); assertThat(refused.disposition()).isEqualTo(Disposition.WAITING); assertThat(refused.providerResult()) .isEqualTo( @@ -845,21 +1080,29 @@ private static void awaitDatabaseTime(Fixture f, Instant deadline) { } private static AccountHostingSubscriptionProvisioningService service(Fixture f) { + migrate(f.source(), f.schema(), null); + return migratedService(f); + } + + private static AccountHostingSubscriptionProvisioningService migratedService(Fixture f) { + f.dsl() + .execute( + "INSERT INTO account_hosting_billing_policy_values (provider_price_id, policy_version, quantity, amount, currency) " + + "VALUES (?, 1, ?, 2400, 'usd') ON CONFLICT DO NOTHING", + f.creation().planQuote().providerPriceId(), + f.creation().planQuote().providerQuantity()); + f.dsl() + .execute( + "INSERT INTO account_hosting_billing_policy_current VALUES (?, 1) ON CONFLICT DO NOTHING", + f.creation().planQuote().providerPriceId()); var stripe = new com.stripe.StripeClient(f.transport()); return new AccountHostingSubscriptionProvisioningService( f.owner(), new StripeHostingSubscriptionProvisioner( stripe, f.clock(), false, Duration.ofMillis(250), Duration.ofSeconds(1)), - lifecycle(f, stripe), - new DataSourceTransactionManager(f.source())); - } - - private static AccountHostingSubscriptionLifecycleService lifecycle( - Fixture f, com.stripe.StripeClient stripe) { - return new AccountHostingSubscriptionLifecycleService( - f.owner(), - new StripeHostingSubscriptionObserver( + new net.firedevops.firemud.accountservice.client.StripeHostingFirstInvoicePaymentClient( stripe, f.clock(), Duration.ofMillis(250), Duration.ofSeconds(1)), + new AccountHostingFirstInvoicePaymentRepository(f.dsl(), f.intents(), f.clock()), new DataSourceTransactionManager(f.source())); } @@ -1012,7 +1255,7 @@ private static Fixture fixture(String target, Duration absoluteTimeout) { false); var transport = new Transport(creation, instrument.providerPaymentMethodId(), clock); return new Fixture( - source, schema, dsl, transaction, creation, lifecycleOwner, clock, transport); + source, schema, dsl, intents, transaction, creation, lifecycleOwner, clock, transport); } private static UUID enroll(DSLContext dsl, TransactionTemplate tx, long suffix) { @@ -1123,6 +1366,7 @@ private record Fixture( DriverManagerDataSource source, String schema, DSLContext dsl, + AccountSubscriptionIntentRepository intents, TransactionTemplate tx, AccountSubscriptionCreationRecord creation, AccountHostingSubscriptionLifecycleRepository owner, @@ -1157,7 +1401,7 @@ private static final class Transport implements StripeResponseGetter { private final String paymentMethod; private final Clock clock; private boolean exists; - private boolean firstInvoiceConfirmed; + private Instant providerCreatedAt; private boolean loseCreateResponse; private Runnable duringCreate; private int emptySearchesRemaining; @@ -1166,7 +1410,7 @@ private static final class Transport implements StripeResponseGetter { private int lists; private int creates; private int subscriptionReads; - private int failSubscriptionRead; + private int requests; private Transport( AccountSubscriptionCreationRecord creation, String paymentMethod, Clock clock) { @@ -1188,6 +1432,7 @@ public T request( throws StripeException { assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + requests++; String response; if (path.equals("/v1/customers/" + creation.providerCustomerId())) { response = @@ -1233,8 +1478,10 @@ public T request( "{\"object\":\"list\",\"has_more\":false,\"data\":[" + (visible ? subscription() : "") + "]}"; - } else if ("/v1/subscriptions".equals(path) && method == RequestMethod.POST) { + } else if (path.equals("/v1/subscriptions") && method == RequestMethod.POST) { creates++; + if (!exists) + providerCreatedAt = clock.instant().truncatedTo(java.time.temporal.ChronoUnit.SECONDS); exists = true; assertThat(options.getIdempotencyKey()) .isEqualTo(creation.subscriptionProvisioningRequestId().toString()); @@ -1258,12 +1505,26 @@ public T request( if (loseCreateResponse) { throw org.mockito.Mockito.mock(StripeException.class); } - response = subscription("incomplete"); + response = subscription(); + } else if (path.equals("/v1/invoices/in_exact")) { + response = + "{\"object\":\"invoice\",\"id\":\"in_exact\",\"customer\":\"" + + creation.providerCustomerId() + + "\",\"livemode\":false,\"billing_reason\":\"subscription_create\",\"parent\":{\"subscription_details\":{\"subscription\":\"sub_exact\"}}," + + "\"total\":2400,\"starting_balance\":0,\"amount_due\":2400,\"amount_paid\":0,\"amount_remaining\":2400,\"currency\":\"usd\",\"status\":\"open\"," + + "\"lines\":{\"has_more\":false,\"data\":[{\"object\":\"line_item\",\"amount\":2400,\"currency\":\"usd\",\"quantity\":" + + creation.planQuote().providerQuantity() + + ",\"pricing\":{\"type\":\"price_details\",\"price_details\":{\"price\":\"" + + creation.planQuote().providerPriceId() + + "\"}}}]},\"payments\":{\"has_more\":false,\"data\":[{\"payment\":{\"type\":\"payment_intent\",\"payment_intent\":{" + + "\"object\":\"payment_intent\",\"id\":\"pi_exact\",\"customer\":\"" + + creation.providerCustomerId() + + "\",\"payment_method\":\"" + + paymentMethod + + "\",\"livemode\":false,\"amount\":2400,\"currency\":\"usd\"," + + "\"confirmation_method\":\"automatic\",\"status\":\"requires_confirmation\"}}}]}}"; } else if (path.equals("/v1/subscriptions/sub_exact")) { subscriptionReads++; - if (subscriptionReads == failSubscriptionRead) { - throw mock(StripeException.class); - } response = subscription(); } else { throw new AssertionError("Unexpected provider path " + path); @@ -1271,23 +1532,14 @@ public T request( return (T) com.stripe.net.ApiResource.GSON.fromJson(response, type); } - private void confirmFirstInvoice() { - assertThat(exists).isTrue(); - firstInvoiceConfirmed = true; - } - private String subscription() { - return subscription(firstInvoiceConfirmed ? "active" : "incomplete"); - } - - private String subscription(String status) { return "{\"object\":\"subscription\",\"id\":\"sub_exact\",\"customer\":\"" + creation.providerCustomerId() + "\",\"default_payment_method\":\"" + paymentMethod - + "\",\"livemode\":false,\"status\":\"" - + status - + "\",\"cancel_at_period_end\":false," + + "\",\"livemode\":false,\"status\":\"incomplete\",\"latest_invoice\":\"in_exact\",\"created\":" + + Objects.requireNonNull(providerCreatedAt).getEpochSecond() + + ",\"cancel_at_period_end\":false," + "\"metadata\":{\"firemud_metadata_schema_version\":\"1\",\"firemud_operation_type\":\"subscription_provisioning\"," + "\"firemud_operation_id\":\"" + creation.subscriptionProvisioningRequestId() diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecyclePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecyclePostgresIntegrationTest.java index f41d1ae7cb..338cb14f5e 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecyclePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecyclePostgresIntegrationTest.java @@ -12,13 +12,18 @@ import com.stripe.net.RequestOptions; import com.stripe.net.StripeResponseGetter; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture; +import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture.ControlledFirstInvoiceTransport; +import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture.MutableClock; import java.io.InputStream; import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.sql.SQLException; import java.time.Clock; import java.time.Duration; import java.time.Instant; -import java.time.ZoneId; +import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.List; @@ -31,6 +36,7 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.client.StripeHostingFirstInvoicePaymentClient; import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy.RecoveryTiming; @@ -42,6 +48,7 @@ import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.OwnerFence; import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.ProducerEvidence; import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionLifecycleService; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; @@ -53,9 +60,16 @@ import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.core.Ordered; 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.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; @@ -63,12 +77,16 @@ import org.testcontainers.junit.jupiter.Testcontainers; /** - * Actual PostgreSQL + actual Stripe SDK over CONTROLLED read-only transport. Creator/consent and - * customer/wallet enrollment are controlled source inputs, not qualification of their live issuers. - * No trigger is disabled, no confirmed SDK value is fabricated, and no remote Stripe call is made. + * Actual PostgreSQL + actual Stripe SDK over CONTROLLED transport. Initial positive authority uses + * real primary reauthentication, exact billing consent and a verified test-signed first invoice. + * Creator/customer/wallet, policy and signing-key inputs are controlled, not live Stripe or + * protected production-custody qualification. No trigger is disabled, no confirmed SDK value is + * fabricated, and no remote Stripe call is made. */ @Testcontainers(disabledWithoutDocker = true) class AccountHostingSubscriptionLifecyclePostgresIntegrationTest { + @TempDir Path invoiceCheckoutDirectory; + private static final String DIGEST = "sha256:" + "a".repeat(64); private static final AtomicLong ROWS = new AtomicLong(10_000); @@ -78,20 +96,48 @@ class AccountHostingSubscriptionLifecyclePostgresIntegrationTest { @Test void actualSdkReadCommitsExactMappingReceiptCanonicalStreamsAndConsistentReaderThenReplays() { - Context c = context("1030"); + Context c = context("latest"); Fixture f = fixture(c); - var claim = claim(f); - UUID request = UUID.randomUUID(); + var claim = paidClaim(f); + UUID request = claim.lifecycleRequestId(); var committed = f.service() .reconcile( request, f.creation().requestId(), - claim.subscriptionRowVersion(), + claim.expectedRowVersion(), f.providerId(), - claim.attemptId()); + null); assertThat(committed.outcome()).isEqualTo(Outcome.COMMITTED); - assertThat(committed.committedRowVersion()).isEqualTo(4); + assertThat(committed.committedRowVersion()).isEqualTo(5); + assertThat( + in( + c, + () -> + new AccountHostingFirstInvoicePaymentRepository(c.dsl(), c.intents(), f.clock()) + .completed(f.creation().subscriptionId(), request))) + .isTrue(); + assertThat( + one( + c, + "SELECT completion.committed_transaction_id = receipt.committed_transaction_id AND audit.xmin::text::bigint = (completion.committed_transaction_id & 4294967295::bigint) AS same_transaction " + + "FROM subscription_first_invoice_completions completion JOIN subscription_lifecycle_receipts receipt " + + "ON receipt.request_id = completion.lifecycle_request_id JOIN account_audit_outbox audit " + + "ON audit.audit_event_id = completion.audit_event_id WHERE completion.lifecycle_request_id = ?", + request) + .get("same_transaction", Boolean.class)) + .isTrue(); + for (String table : + List.of( + "subscription_first_invoices", + "subscription_first_invoice_confirmations", + "subscription_first_invoice_dispatches", + "subscription_first_invoice_success_evidence", + "subscription_first_invoice_completions")) { + assertSqlState( + "23514", + () -> c.setup().execute("UPDATE " + table + " SET subscription_id = subscription_id")); + } var current = f.service().readCurrent(f.creation().tenantId()); assertThat(current.subscriptionStatus()).isEqualTo(Status.ACTIVE); assertThat(current.gameplayAvailable()).isTrue(); @@ -131,7 +177,12 @@ void actualSdkReadCommitsExactMappingReceiptCanonicalStreamsAndConsistentReaderT int reads = f.transport().reads; assertThat( f.service() - .reconcile(request, f.creation().requestId(), 2, f.providerId(), claim.attemptId())) + .reconcile( + request, + f.creation().requestId(), + claim.expectedRowVersion(), + f.providerId(), + null)) .isEqualTo(committed); assertThat(f.transport().reads).isEqualTo(reads); assertThat(count(c, "subscription_lifecycle_receipts")).isOne(); @@ -139,32 +190,545 @@ void actualSdkReadCommitsExactMappingReceiptCanonicalStreamsAndConsistentReaderT assertThat(count(c, "account_authority_outbox_events")).isOne(); assertThatThrownBy(() -> f.service() - .reconcile(request, f.creation().requestId(), 2, "sub_other", claim.attemptId())) + .reconcile( + request, + f.creation().requestId(), + claim.expectedRowVersion(), + "sub_other", + null)) .hasMessageContaining("IDEMPOTENCY_CONFLICT"); assertThat(f.transport().reads).isEqualTo(reads); } + @ParameterizedTest + @ValueSource(strings = {"1046", "latest"}) + void confirmedWorkRejectsMissingOrMismatchedFirstInvoiceCompletionAndRollsBackFulfillment( + String migrationTarget) throws StripeException { + for (String fault : List.of("missing", "tuple", "receipt", "transaction")) { + Context c = context(migrationTarget); + Fixture f = fixture(c); + var claim = migrationTarget.equals("1046") ? paidClaimAt1046(f) : paidClaim(f); + var prepared = + in( + c, + () -> + f.owner() + .prepare( + claim.lifecycleRequestId(), + f.creation().requestId(), + claim.expectedRowVersion(), + f.providerId(), + null)); + var sdk = f.observer().observe(prepared.binding()); + List before = firstInvoiceImage(c); + // PostgreSQL orders same-kind triggers by name. This fault runs after the genuine + // first_invoice_completion validator, changing only otherwise schema-valid evidence. + // All production validators, foreign keys and deferred guards remain enabled. + String mutation = + switch (fault) { + case "missing" -> "RETURN NULL;"; + case "tuple" -> + "NEW.tuple_digest := 'sha256:' || repeat(CASE WHEN NEW.tuple_digest = 'sha256:' || repeat('b', 64) THEN 'c' ELSE 'b' END, 64);"; + case "receipt" -> + "NEW.receipt_digest := 'sha256:' || repeat(CASE WHEN NEW.receipt_digest = 'sha256:' || repeat('b', 64) THEN 'c' ELSE 'b' END, 64);"; + case "transaction" -> + "NEW.committed_transaction_id := NEW.committed_transaction_id + 1;"; + default -> throw new AssertionError("Unknown completion fault: " + fault); + }; + c.setup() + .execute( + "CREATE FUNCTION reject_exact_first_invoice_completion() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN " + + mutation + + " RETURN NEW; END; $$"); + c.setup() + .execute( + "CREATE TRIGGER zz_first_invoice_completion_fault BEFORE INSERT ON subscription_first_invoice_completions FOR EACH ROW EXECUTE FUNCTION reject_exact_first_invoice_completion()"); + AtomicInteger applied = new AtomicInteger(); + // V1046.1 rejects a missing completion at the earlier subscription consistency event. + // Keep the older frontier to witness the provisioning predicate independently; malformed + // completions still reach that exact predicate on both frontiers. Neither guard is disabled. + String expectedDiagnostic = + migrationTarget.equals("latest") && fault.equals("missing") + ? "Current positive hosting subscription requires exact first-invoice completion" + : "Provisioning confirmation lacks its exact lifecycle receipt"; + assertSqlState( + "23514", + expectedDiagnostic, + () -> + in( + c, + () -> { + var result = f.owner().apply(prepared, sdk); + assertThat(result.outcome()).isEqualTo(Outcome.COMMITTED); + assertThat(c.dsl().fetchCount(DSL.table("subscription_lifecycle_receipts"))) + .isOne(); + assertThat( + c.dsl() + .fetchCount(DSL.table("account_tenant_entitlement_outbox_events"))) + .isOne(); + assertThat(c.dsl().fetchCount(DSL.table("account_authority_outbox_events"))) + .isOne(); + applied.incrementAndGet(); + return result; + })); + assertThat(applied).as(fault).hasValue(1); + assertThat(firstInvoiceImage(c)).as(fault).isEqualTo(before); + assertThat( + one( + c, + "SELECT phase FROM subscription_provisioning_work WHERE request_id = ?", + f.creation().requestId()) + .get("phase", String.class)) + .isEqualTo("AWAITING_PAYMENT"); + } + } + + @Test + void originalProvisioningClaimStillCannotConfirmWithoutItsExactLifecycleReceipt() { + Context c = context("latest"); + Fixture f = fixture(c); + claim(f); + List before = firstInvoiceImage(c); + assertSqlState( + "23514", + "Provisioning confirmation lacks its exact lifecycle receipt", + () -> + in( + c, + () -> + c.dsl() + .execute( + "UPDATE subscription_provisioning_work SET phase = 'CONFIRMED', row_version = row_version + 1 WHERE request_id = ?", + f.creation().requestId()))); + assertThat(firstInvoiceImage(c)).isEqualTo(before); + } + + @Test + void providerActiveOrTrialingWithoutFirstInvoiceConsentCannotCreateHostingAuthority() { + for (String status : List.of("active", "trialing")) { + Context c = context("latest"); + Fixture f = fixture(c); + f.transport().json = response(f, status); + var claim = claim(f); + assertThatThrownBy(() -> + f.service() + .reconcile( + UUID.randomUUID(), + f.creation().requestId(), + claim.subscriptionRowVersion(), + f.providerId(), + claim.attemptId())) + .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class) + .hasMessageContaining("first-invoice"); + for (String table : + List.of( + "subscription_first_invoices", + "subscription_first_invoice_confirmations", + "subscription_first_invoice_dispatches", + "subscription_first_invoice_completions", + "subscription_lifecycle_receipts", + "account_tenant_entitlement_outbox_events")) { + assertThat(count(c, table)).as(table).isZero(); + } + assertThat( + one( + c, + "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", + f.creation().requestId()) + .get("released_at")) + .isNull(); + assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + } + } + + @Test + void lateSignedSuccessCompletesConsumedAuthorizationWithoutAnotherProviderConfirmation() { + Context c = context("latest"); + Fixture f = fixture(c); + var checkout = + CanonicalHostingSubscriptionTestFixture.prepareFirstInvoice( + invoiceCheckoutDirectory, + c.source(), + c.dsl(), + c.tx(), + f.creation(), + f.instrument(), + f.providerId(), + f.clock(), + f.owner()); + var authorized = checkout.authorize(CanonicalHostingSubscriptionTestFixture.BILLING_PASSWORD); + var generations = new AccountAuthorityGenerationRepository(c.dsl()); + var accountScope = + AccountAuthorityGenerationRepository.AuthorityScope.account( + f.creation().owner().accountUuid()); + var authorityBefore = in(c, () -> generations.read(accountScope)); + var accounts = + new AccountRepository( + c.dsl(), + new AccountAuthoritySourceEvidenceRepository( + c.dsl(), generations, new AccountAuthorityOutboxRepository(c.dsl()))); + in( + c, + () -> { + var account = + accounts.findByAccountUuidForUpdate(f.creation().owner().accountUuid()).orElseThrow(); + account.setRole("admin"); + return accounts.save(account); + }); + assertThat(in(c, () -> generations.read(accountScope)).generation()) + .isGreaterThan(authorityBefore.generation()); + // This generic source advance cannot renew actor/charge authority, but cannot erase an already + // consumed exact payment authorization or prevent read-only signed outcome reconciliation. + f.clock().advance(Duration.ofSeconds(301)); + assertThat(f.clock().instant()).isAfter(authorized.validUntil()); + var success = checkout.retainSignedSuccess(); + assertThat(success.requestId()).isEqualTo(authorized.requestId()); + assertThat(success.providerIdempotencyId()).isEqualTo(authorized.providerIdempotencyId()); + assertThat( + f.service() + .reconcile( + success.lifecycleRequestId(), + f.creation().requestId(), + success.expectedRowVersion(), + f.providerId(), + null) + .outcome()) + .isEqualTo(Outcome.COMMITTED); + assertThat(f.service().readCurrent(f.creation().tenantId()).receiptRequestId()) + .isEqualTo(success.lifecycleRequestId()); + assertThat( + in( + c, + () -> + checkout + .payments() + .completed(f.creation().subscriptionId(), success.lifecycleRequestId()))) + .isTrue(); + assertThat(checkout.confirmations()).isOne(); + assertThatThrownBy(() -> + checkout + .provider() + .confirm( + authorized, + () -> { + throw new AssertionError( + "Expired consent must not request a provider command claim"); + })) + .hasMessageContaining("consent"); + assertThat(checkout.confirmations()).isOne(); + assertThat(count(c, "subscription_first_invoice_dispatches")).isOne(); + assertThat(count(c, "subscription_first_invoice_completions")).isOne(); + } + + @Test + void firstInvoiceConsentHonorsTheConfiguredIssuingClockSkew() { + Context c = context("latest"); + Fixture f = fixture(c); + var checkout = + CanonicalHostingSubscriptionTestFixture.prepareFirstInvoice( + invoiceCheckoutDirectory, + c.source(), + c.dsl(), + c.tx(), + f.creation(), + f.instrument(), + f.providerId(), + f.clock(), + f.owner()); + f.clock().advance(Duration.ofSeconds(30)); + var dispatch = + checkout.prepareConfirmationDispatch( + CanonicalHostingSubscriptionTestFixture.BILLING_PASSWORD, + () -> f.clock().advance(Duration.ofSeconds(-30))); + var retained = + one( + c, + "SELECT consent.consented_at, auth.consented_at, auth.valid_until, " + + "proof.issued_at FROM subscription_first_invoice_confirmations consent " + + "JOIN subscription_first_invoice_authorizations auth USING (request_id) " + + "JOIN account_recent_reauthentication_evidence proof " + + "ON proof.evidence_id = auth.reauthentication_evidence_id " + + "WHERE consent.request_id = ?", + dispatch.requestId()); + var issuedAt = retained.get(3, java.time.OffsetDateTime.class).toInstant(); + assertThat(retained.get(0, java.time.OffsetDateTime.class).toInstant()) + .isEqualTo(issuedAt.minusSeconds(30)); + assertThat(retained.get(1, java.time.OffsetDateTime.class).toInstant()) + .isEqualTo(issuedAt.minusSeconds(30)); + assertThat(retained.get(2, java.time.OffsetDateTime.class).toInstant()) + .isEqualTo(issuedAt.plusSeconds(270)); + assertThat(checkout.confirmations()).isZero(); + } + + @Test + void commandClaimUsesTheDatabaseAuthorizationDeadline() { + Context c = context("latest"); + Fixture f = fixture(c); + var checkout = + CanonicalHostingSubscriptionTestFixture.prepareFirstInvoice( + invoiceCheckoutDirectory, + c.source(), + c.dsl(), + c.tx(), + f.creation(), + f.instrument(), + f.providerId(), + f.clock(), + f.owner()); + var databaseNow = one(c, "SELECT clock_timestamp()").get(0, OffsetDateTime.class).toInstant(); + f.clock().advance(Duration.between(f.clock().instant(), databaseNow.minusSeconds(300))); + var dispatch = + checkout.prepareConfirmationDispatch( + CanonicalHostingSubscriptionTestFixture.BILLING_PASSWORD); + assertThat(f.clock().instant()).isBefore(dispatch.validUntil()); + assertThat(dispatch.validUntil()).isBefore(databaseNow); + assertSqlState( + "23514", + "First-invoice command authorization expired before database claim", + () -> + in( + c, + () -> + checkout + .payments() + .claimCommand(dispatch, checkout.invoice().ownerAccountId()))); + assertThat(count(c, "subscription_first_invoice_command_claims")).isZero(); + assertThat(checkout.confirmations()).isZero(); + } + + @Test + void signedSuccessJournalUsesTheExactOriginalConsentSecond() throws Exception { + Context c = context("latest"); + Fixture f = fixture(c); + var checkout = + CanonicalHostingSubscriptionTestFixture.prepareFirstInvoice( + invoiceCheckoutDirectory, + c.source(), + c.dsl(), + c.tx(), + f.creation(), + f.instrument(), + f.providerId(), + f.clock(), + f.owner()); + var dispatch = checkout.authorize(CanonicalHostingSubscriptionTestFixture.BILLING_PASSWORD); + var consent = + one( + c, + "SELECT consented_at FROM subscription_first_invoice_confirmations WHERE request_id = ?", + dispatch.requestId()) + .get(0, OffsetDateTime.class); + var signed = checkout.signedSuccess(); + var sameSecond = checkout.verifier().verify(signed.payload(), signed.signature()); + assertThat(sameSecond.eventCreatedAtEpochSeconds()).isEqualTo(consent.toEpochSecond()); + var earlier = + checkout.signWebhookPayload( + signed + .payload() + .replace("evt_", "evt_before_consent_") + .replace( + "\"created\":" + sameSecond.eventCreatedAtEpochSeconds() + ",", + "\"created\":" + (consent.toEpochSecond() - 1) + ",")); + var verified = checkout.verifier().verify(earlier.payload(), earlier.signature()); + in(c, () -> new StripeEventInboxRepository(c.dsl()).retainOrReplay(verified)); + assertThat( + one( + c, + "SELECT account_first_invoice_signed_success_retained(?, false)", + checkout.invoice().paymentIntentId()) + .get(0, Boolean.class)) + .isTrue(); + assertSqlState( + "23514", + "First-invoice signed success requires a verified event at or after original consent", + () -> + c.setup() + .execute( + "INSERT INTO subscription_first_invoice_success_evidence " + + "(request_id, subscription_id, provider_event_id, event_payload_digest, " + + "tuple_digest, observed_at) VALUES (?, ?, ?, ?, ?, clock_timestamp())", + dispatch.requestId(), + checkout.invoice().subscriptionId(), + verified.providerEventId(), + verified.payloadSha256(), + checkout.invoice().digest())); + assertThat(count(c, "subscription_first_invoice_success_evidence")).isZero(); + assertThat(checkout.retainSignedSuccess().requestId()).isEqualTo(dispatch.requestId()); + assertThat(count(c, "subscription_first_invoice_success_evidence")).isOne(); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void unpaidVetoUsesRetainedSuccessIdentityAcrossUpgrade(boolean quotedAmount) throws Exception { + Context c = context("1046.9.0.4"); + Fixture f = fixture(c); + var checkout = + CanonicalHostingSubscriptionTestFixture.prepareFirstInvoice( + invoiceCheckoutDirectory, + c.source(), + c.dsl(), + c.tx(), + f.creation(), + f.instrument(), + f.providerId(), + f.clock(), + f.owner()); + var original = checkout.signedSuccessAt(f.clock().instant().minusSeconds(60)); + String amounts = "\"amount\":2400,\"amount_received\":2400,"; + assertThat(original.payload()).contains(amounts); + var signed = + quotedAmount + ? checkout.signWebhookPayload( + original + .payload() + .replace(amounts, "\"amount\":\"2400\",\"amount_received\":2400,")) + : original; + var verified = checkout.verifier().verify(signed.payload(), signed.signature()); + var inbox = new StripeEventInboxRepository(c.dsl()); + in(c, () -> inbox.retainOrReplay(verified)); + String retainedRows = + "SELECT provider_event_id, encode(raw_payload, 'hex'), payload_sha256, xmin::text " + + "FROM stripe_event_inbox ORDER BY provider_event_id"; + var before = c.setup().fetch(retainedRows); + + configuration(c).target("1046.9.0.5").load().migrate(); + + assertThat(c.setup().fetch(retainedRows)).isEqualTo(before); + var lookup = + c.setup() + .fetch( + "SELECT provider_event_id FROM stripe_first_invoice_success_lookup " + + "WHERE livemode = false AND payment_intent_id = ?", + checkout.invoice().paymentIntentId()); + assertThat(lookup.getValues(0, String.class)).containsExactly(verified.providerEventId()); + assertThat( + one( + c, + "SELECT account_first_invoice_signed_success_retained(?, false)", + checkout.invoice().paymentIntentId()) + .get(0, Boolean.class)) + .isEqualTo(!quotedAmount); + assertThat(in(c, () -> inbox.retainOrReplay(verified)).rawPayload()) + .isEqualTo(signed.payload()); + assertThat(count(c, "stripe_first_invoice_success_lookup")).isOne(); + } + + @Test + void authorizationExpiryAfterCommittedCommandClaimRetainsImmutableNoSendEvidence() { + Context c = context("latest"); + Fixture f = fixture(c); + var checkout = + CanonicalHostingSubscriptionTestFixture.prepareFirstInvoice( + invoiceCheckoutDirectory, + c.source(), + c.dsl(), + c.tx(), + f.creation(), + f.instrument(), + f.providerId(), + f.clock(), + f.owner()); + var observation = + checkout.claimExpiredBeforePost( + CanonicalHostingSubscriptionTestFixture.BILLING_PASSWORD, + noSend -> { + assertThat(count(c, "subscription_first_invoice_command_claims")).isOne(); + assertSqlState( + "23514", + "First-invoice no-send observation is later than the database clock", + () -> + c.setup() + .execute( + "INSERT INTO subscription_first_invoice_expired_before_post " + + "(request_id, observed_at) " + + "VALUES (?, clock_timestamp() + INTERVAL '1 day')", + noSend.requestId())); + assertThat(count(c, "subscription_first_invoice_expired_before_post")).isZero(); + }); + var retained = + one( + c, + "SELECT evidence.request_id, evidence.observed_at, claim.claimed_at, auth.valid_until " + + "FROM subscription_first_invoice_expired_before_post evidence " + + "JOIN subscription_first_invoice_command_claims claim USING (request_id) " + + "JOIN subscription_first_invoice_authorizations auth " + + "USING (authorization_request_id) WHERE evidence.request_id = ?", + observation.requestId()); + assertThat(retained.get("request_id", UUID.class)).isEqualTo(observation.requestId()); + assertThat(retained.get(1, java.time.OffsetDateTime.class).toInstant()) + .isEqualTo(observation.observedAt()); + assertThat(retained.get(2, java.time.OffsetDateTime.class).toInstant()) + .isBefore(observation.observedAt()); + assertThat(retained.get(3, java.time.OffsetDateTime.class).toInstant()) + .isEqualTo(observation.observedAt()); + assertThat(count(c, "subscription_first_invoice_expired_before_post")).isOne(); + assertThat(checkout.confirmations()).isZero(); + assertThat( + one( + c, + "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", + f.creation().requestId()) + .get("released_at")) + .isNull(); + assertThat( + one( + c, + "SELECT phase FROM subscription_provisioning_work WHERE request_id = ?", + f.creation().requestId()) + .get("phase", String.class)) + .isEqualTo("AWAITING_PAYMENT"); + + for (String sql : + List.of( + "UPDATE subscription_first_invoice_expired_before_post SET observed_at = observed_at", + "DELETE FROM subscription_first_invoice_expired_before_post", + "TRUNCATE subscription_first_invoice_expired_before_post, subscription_first_invoice_no_send_cancellations")) { + assertSqlState("23514", () -> c.setup().execute(sql)); + } + } + @Test void trialUsesRetainedQuoteWithoutTodaysCatalogAndSqlShapedRowsAloneNeverAuthorize() { - Context c = context("1030"); + Context c = context("latest"); Fixture f = fixture(c); assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); assertThat(f.transport().reads).isZero(); - f.transport().json = response(f, "trialing"); + f.transport().json = response(f, "active"); var emptyCatalogRepository = new AccountSubscriptionIntentRepository(c.dsl(), new AccountHostingPlanCatalog(List.of())); var owner = owner(c, f.clock(), emptyCatalogRepository); var service = service(c, owner, f.transport(), f.clock()); - var claim = service.claimProvisioning(f.creation().requestId(), 1, UUID.randomUUID()).claim(); + var claim = paidClaim(f); + assertThat( + service + .reconcile( + claim.lifecycleRequestId(), + f.creation().requestId(), + claim.expectedRowVersion(), + f.providerId(), + null) + .outcome()) + .isEqualTo(Outcome.COMMITTED); + assertThat( + in( + c, + () -> + new AccountHostingFirstInvoicePaymentRepository(c.dsl(), c.intents(), f.clock()) + .completed(f.creation().subscriptionId(), claim.lifecycleRequestId()))) + .isTrue(); + f.transport().json = response(f, "trialing"); + long currentVersion = + c.intents().findCurrentByTenant(f.creation().tenantId()).orElseThrow().rowVersion(); assertThat( service .reconcile( UUID.randomUUID(), f.creation().requestId(), - 2, + currentVersion, f.providerId(), - claim.attemptId()) + null) .outcome()) .isEqualTo(Outcome.COMMITTED); assertThat(service.readCurrent(f.creation().tenantId()).subscriptionStatus()) @@ -195,16 +759,80 @@ void trialUsesRetainedQuoteWithoutTodaysCatalogAndSqlShapedRowsAloneNeverAuthori f.creation().owner().accountUuid())); } - @Test - void rawSqlActiveMappingWithoutGenuineClaimAndReceiptCannotBecomeAReadOrLifecycleSource() { - Context c = context("1030"); + @ParameterizedTest + @ValueSource(strings = {"trialing", "active", "past_due", "grace"}) + void populatedPreCompletionSchemaRefusesActivationWithoutRewritingPositiveRows(String status) { + Context c = context("1040"); Fixture f = fixture(c); + retainUnqualifiedPositive(f, status); + assertThat(c.intents().findCurrentByTenant(f.creation().tenantId()).orElseThrow().status()) + .isEqualTo(status); + // Controlled schema-valid predecessor data, not a genuine historical signed receipt. + var before = + one( + c, + "SELECT to_jsonb(s)::text, xmin::text FROM subscription s WHERE subscription_id = ?", + f.creation().subscriptionId()); + var history = c.setup().fetch("SELECT * FROM subscription_provider_history").intoMaps(); + configuration(c).target("1046").load().migrate(); + List evidenceBefore = firstInvoiceImage(c); + var flywayBefore = + c.setup().fetch("SELECT * FROM flyway_schema_history ORDER BY installed_rank").intoMaps(); + assertSqlState( + "23514", + "Retained positive hosting subscriptions", + () -> configuration(c).target("1046.1").load().migrate()); + assertThat( + c.setup() + .fetch("SELECT * FROM flyway_schema_history ORDER BY installed_rank") + .intoMaps()) + .isEqualTo(flywayBefore); + assertThatThrownBy(() -> inspectRetainedPositivePrerequisite(f)) + .hasMessageContaining("HOSTING_ACTIVATION_UNAVAILABLE"); + assertThat( + one( + c, + "SELECT to_jsonb(s)::text, xmin::text FROM subscription s WHERE subscription_id =" + + " ?", + f.creation().subscriptionId())) + .isEqualTo(before); + assertThat(c.setup().fetch("SELECT * FROM subscription_provider_history").intoMaps()) + .isEqualTo(history); + assertThat(firstInvoiceImage(c)).isEqualTo(evidenceBefore); + assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + assertThatThrownBy(() -> + f.service() + .reconcile(UUID.randomUUID(), f.creation().requestId(), 2, f.providerId(), null)) + .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class); + assertThat(f.transport().reads).isZero(); + assertThat(count(c, "subscription_lifecycle_receipts")).isZero(); + assertThat(count(c, "account_tenant_authority_source_records")).isZero(); + } + + @Test + void completedAndNegativeSubscriptionsDoNotFailRetainedPositivePrerequisite() { + for (String status : List.of("active", "canceled")) { + Context c = context("latest"); + Fixture f = fixture(c); + f.transport().json = response(f, status); + activate(f); + List before = firstInvoiceImage(c); + inspectRetainedPositivePrerequisite(f); + assertThat(firstInvoiceImage(c)).isEqualTo(before); + } + } + + private static void retainUnqualifiedPositive(Fixture f, String status) { + Context c = f.context(); c.tx() .executeWithoutResult(s -> { c.dsl() .execute( - "INSERT INTO subscription_provider_history (provider_subscription_id, subscription_id, operation_kind, request_id, " - + "provider_operation_id, role, effective_at, evidence_digest) VALUES (?, ?, 'SUBSCRIPTION_PROVISIONING', ?, ?, 'canonical', ?::timestamptz, ?)", + "INSERT INTO subscription_provider_history (provider_subscription_id," + + " subscription_id, operation_kind, request_id, provider_operation_id," + + " role, effective_at, evidence_digest) VALUES (?, ?," + + " 'SUBSCRIPTION_PROVISIONING', ?, ?, 'canonical', ?::timestamptz, ?)", f.providerId(), f.creation().subscriptionId(), f.creation().requestId(), @@ -213,26 +841,284 @@ void rawSqlActiveMappingWithoutGenuineClaimAndReceiptCannotBecomeAReadOrLifecycl DIGEST); c.dsl() .execute( - "UPDATE subscription SET status = 'active', provider_subscription_id = ?, row_version = row_version + 1 WHERE subscription_id = ?", + "UPDATE subscription SET status = ?, provider_subscription_id = ?," + + " row_version = row_version + 1 WHERE subscription_id = ?", + status, f.providerId(), f.creation().subscriptionId()); }); + } + + @ParameterizedTest + @ValueSource(strings = {"trialing", "active", "past_due", "grace"}) + void committedPositiveWithoutCompletionIsRejectedAfterUpgrade(String status) { + Context c = context("latest"); + Fixture f = fixture(c); + List before = firstInvoiceImage(c); + assertSqlState( + "23514", + "Current positive hosting subscription", + () -> retainUnqualifiedPositive(f, status)); + assertThat(firstInvoiceImage(c)).isEqualTo(before); assertThat(c.intents().findCurrentByTenant(f.creation().tenantId()).orElseThrow().status()) + .isEqualTo("pending"); + } + + @Test + void genuineSameTransactionCompletionRemainsImmutableAfterUpgrade() { + Context c = context("latest"); + Fixture f = fixture(c); + activate(f); + assertThat(count(c, "subscription_first_invoice_completions")).isOne(); + List before = firstInvoiceImage(c); + for (String sql : + List.of( + "DELETE FROM subscription", + "DELETE FROM subscription_first_invoice_completions", + "UPDATE subscription_first_invoice_completions SET committed_at = committed_at", + "TRUNCATE subscription_first_invoice_completions")) { + assertThatThrownBy(() -> c.setup().execute(sql)) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(firstInvoiceImage(c)).isEqualTo(before); + } + } + + @Test + void upgradeWaitsForAnExistingWriterAndRefusesItsCommittedCompletionGap() throws Exception { + Context c = context("1046"); + Fixture existing = fixture(c); + assertThat( + c.intents().findCurrentByTenant(existing.creation().tenantId()).orElseThrow().status()) + .isEqualTo("pending"); + String migrationName = "hosting_gate_" + UUID.randomUUID().toString().replace("-", ""); + String migrationSql = retainedPositiveGateMigrationSql(); + try (var workers = Executors.newVirtualThreadPerTaskExecutor()) { + var migration = + in( + c, + () -> { + retainUnqualifiedPositive(existing, "active"); + int writerPid = + c.dsl().fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class); + var result = + workers.submit(() -> { + try (var connection = c.source().getConnection(); + var sql = connection.createStatement()) { + connection.setAutoCommit(false); + DSL.using(connection, SQLDialect.POSTGRES) + .execute( + "SELECT set_config('application_name', ?, true)", migrationName); + assertThatThrownBy(() -> sql.execute(migrationSql)) + .isInstanceOfSatisfying( + SQLException.class, + failure -> { + assertThat(failure.getSQLState()).isEqualTo("23514"); + assertThat(failure.getMessage()) + .contains( + "Retained positive hosting subscriptions require evidence-preserving resolution before upgrade"); + }); + connection.rollback(); + } + return null; + }); + try { + awaitSubscriptionWriterLock(c, migrationName); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new AssertionError( + "Interrupted while waiting for the migration lock", interrupted); + } + assertThat( + one( + c, + "SELECT ? = ANY(pg_blocking_pids(pid)) FROM pg_stat_activity " + + "WHERE application_name = ?", + writerPid, + migrationName) + .get(0, Boolean.class)) + .isTrue(); + return result; + }); + migration.get(5, TimeUnit.SECONDS); + } + assertThat( + c.intents().findCurrentByTenant(existing.creation().tenantId()).orElseThrow().status()) .isEqualTo("active"); - assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) - .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); - assertThatThrownBy(() -> - f.service() - .reconcile(UUID.randomUUID(), f.creation().requestId(), 2, f.providerId(), null)) - .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class); - assertThat(f.transport().reads).isZero(); - assertThat(count(c, "subscription_lifecycle_receipts")).isZero(); - assertThat(count(c, "account_tenant_authority_source_records")).isZero(); + assertThat(count(c, "subscription_first_invoice_completions")).isZero(); + assertThat( + one( + c, + "SELECT count(*) FROM pg_trigger WHERE tgrelid = 'subscription'::regclass " + + "AND tgname = 'account_hosting_positive_completion_consistency'") + .get(0, Long.class)) + .isZero(); } @Test - void hostingExtendsExistingDemoStreamsWithoutRewritingOrReinterpretingDemoEvidence() { - Context c = context("1030"); + void upgradeSerializesConcurrentInsertAndUpdateThenEnforcesFinalCompletion() throws Exception { + Context c = context("1046"); + Fixture existing = fixture(c); + String writerName = "hosting_gate_" + UUID.randomUUID().toString().replace("-", ""); + try (var workers = Executors.newVirtualThreadPerTaskExecutor(); + var migration = c.source().getConnection()) { + migration.setAutoCommit(false); + try (var sql = migration.createStatement()) { + sql.execute(retainedPositiveGateMigrationSql()); + } + var update = + workers.submit(() -> { + assertSqlState( + "23514", + "Current positive hosting subscription", + () -> + c.tx() + .executeWithoutResult(ignored -> { + c.dsl() + .execute( + "SELECT set_config('application_name', ?, true), set_config('statement_timeout', '10s', true)", + writerName + "_update"); + retainUnqualifiedPositive(existing, "active"); + })); + }); + var insert = + workers.submit(() -> + in( + c, + () -> { + c.dsl() + .execute( + "SELECT set_config('application_name', ?, true), set_config('statement_timeout', '10s', true)", + writerName + "_insert"); + return fixture(c); + })); + awaitSubscriptionWriterLock(c, writerName + "_update"); + awaitSubscriptionWriterLock(c, writerName + "_insert"); + migration.commit(); + update.get(5, TimeUnit.SECONDS); + Fixture pending = insert.get(5, TimeUnit.SECONDS); + assertThat( + c.intents().findCurrentByTenant(pending.creation().tenantId()).orElseThrow().status()) + .isEqualTo("pending"); + assertThat( + c.intents() + .findCurrentByTenant(existing.creation().tenantId()) + .orElseThrow() + .status()) + .isEqualTo("pending"); + assertThat(count(c, "subscription_first_invoice_completions")).isZero(); + // Failed UPDATE cannot leave its inserted provider mapping behind. The successful INSERT + // is an ordinary pending subscription, not synthesized payment or migration authority. + assertThat(c.setup().fetchCount(DSL.table("subscription_provider_history"))).isZero(); + } + } + + @Test + void signedSuccessWithIntegralDecimalAmountsWaitsForTheExactIntentLock() throws Exception { + Context c = context("latest"); + Fixture f = fixture(c); + var checkout = + CanonicalHostingSubscriptionTestFixture.prepareFirstInvoice( + invoiceCheckoutDirectory, + c.source(), + c.dsl(), + c.tx(), + f.creation(), + f.instrument(), + f.providerId(), + f.clock(), + f.owner()); + String amounts = "\"amount\":2400,\"amount_received\":2400,"; + String originalPayload = checkout.signedSuccess().payload(); + assertThat(originalPayload).contains(amounts); + var signed = + checkout.signWebhookPayload( + originalPayload.replace(amounts, "\"amount\":2400.0,\"amount_received\":2400.00,")); + var verified = checkout.verifier().verify(signed.payload(), signed.signature()); + var inbox = new StripeEventInboxRepository(c.dsl()); + String writerName = "signed_intake_" + UUID.randomUUID().toString().replace("-", ""); + StripeEventInboxRecord retained; + try (var workers = Executors.newVirtualThreadPerTaskExecutor(); + var lock = c.source().getConnection()) { + lock.setAutoCommit(false); + var locker = DSL.using(lock, SQLDialect.POSTGRES); + locker.fetchSingle( + "SELECT account_lock_first_invoice_intent(?, ?)", + checkout.invoice().paymentIntentId(), + checkout.invoice().livemode()); + int lockerPid = locker.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class); + var receipt = + workers.submit(() -> + in( + c, + () -> { + c.dsl() + .execute( + "SELECT set_config('application_name', ?, true), set_config('statement_timeout', '10s', true)", + writerName); + return inbox.retainOrReplay(verified); + })); + awaitFirstInvoiceIntentBlockedBy(c, lockerPid); + assertThat( + one( + c, + "SELECT ? = ANY(pg_blocking_pids(pid)) FROM pg_stat_activity " + + "WHERE application_name = ?", + lockerPid, + writerName) + .get(0, Boolean.class)) + .isTrue(); + assertThat(count(c, "stripe_event_inbox")).isZero(); + lock.rollback(); + retained = receipt.get(5, TimeUnit.SECONDS); + } + assertThat(retained.providerEventId()).isEqualTo(verified.providerEventId()); + assertThat(retained.rawPayload()).isEqualTo(signed.payload()); + assertThat(in(c, () -> inbox.retainOrReplay(verified))).isEqualTo(retained); + assertThat(count(c, "stripe_event_inbox")).isOne(); + } + + private static String retainedPositiveGateMigrationSql() throws java.io.IOException { + try (var resource = + Objects.requireNonNull( + AccountHostingSubscriptionLifecyclePostgresIntegrationTest.class.getResourceAsStream( + "/db/migration/V1046.1__hosting_retained_positive_completion_gate.sql"))) { + return new String(resource.readAllBytes(), StandardCharsets.UTF_8); + } + } + + private static void awaitSubscriptionWriterLock(Context c, String applicationName) + throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + do { + Boolean waiting = + Objects.requireNonNull( + c.setup() + .fetchOne( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE application_name = ? " + + "AND wait_event_type = 'Lock')", + applicationName)) + .get(0, Boolean.class); + if (Boolean.TRUE.equals(waiting)) return; + Thread.sleep(10); + } while (System.nanoTime() < deadline); + throw new AssertionError("Concurrent subscription writer never reached the migration lock"); + } + + private static void inspectRetainedPositivePrerequisite(Fixture f) { + Context c = f.context(); + var readOnly = new TransactionTemplate(Objects.requireNonNull(c.tx().getTransactionManager())); + readOnly.setReadOnly(true); + readOnly.setTimeout(5); + readOnly.executeWithoutResult(ignored -> { + assertThat(c.dsl().fetchSingle("SHOW transaction_read_only").get(0, String.class)) + .isEqualTo("on"); + f.owner().requireNoRetainedPositiveCompletionGaps(2); + }); + } + + @Test + void hostingExtendsExistingDemoStreamsWithoutRewritingOrReinterpretingDemoEvidence() { + Context c = context("latest"); Fixture f = fixture(c); var identity = new FreshTenantIdentityAssociationRepository(c.dsl(), "prod"); var generations = new AccountAuthorityGenerationRepository(c.dsl()); @@ -269,6 +1155,11 @@ void hostingExtendsExistingDemoStreamsWithoutRewritingOrReinterpretingDemoEviden "SELECT payload FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ? AND tenant_billing_sequence = 1", source.canonicalTenantId()) .get("payload", byte[].class); + var authorityStreamKeys = + c.setup() + .fetch( + "SELECT outbox_stream_key FROM account_authority_outbox_streams ORDER BY outbox_stream_key") + .getValues(0, String.class); activate(f); var current = f.service().readCurrent(source.canonicalTenantId()); assertThat(current.entitlementVersion()).isEqualTo(2); @@ -289,17 +1180,29 @@ void hostingExtendsExistingDemoStreamsWithoutRewritingOrReinterpretingDemoEviden .get("payload", byte[].class)) .isEqualTo(demoEvent); assertThat(count(c, "account_tenant_entitlement_outbox_streams")).isOne(); - assertThat(count(c, "account_authority_outbox_streams")).isOne(); + assertThat( + c.setup() + .fetch( + "SELECT outbox_stream_key FROM account_authority_outbox_streams ORDER BY outbox_stream_key") + .getValues(0, String.class)) + .containsExactlyElementsOf(authorityStreamKeys); + assertThat( + one( + c, + "SELECT last_sequence FROM account_authority_outbox_streams WHERE outbox_stream_key = ?", + TenantAuthorityEventV1Codec.streamKey(source.canonicalTenantId())) + .get("last_sequence", Long.class)) + .isEqualTo(current.tenantAuthorityEvent().outboxSequence()); assertThat(count(c, "account_tenant_authority_source_records")).isOne(); } @Test void concurrentSameRequestObservesOneInflightOwnerAndReplaysOneCommittedTransition() throws Exception { - Context c = context("1030"); + Context c = context("latest"); Fixture f = fixture(c); - var claim = claim(f); - UUID request = UUID.randomUUID(); + var claim = paidClaim(f); + UUID request = claim.lifecycleRequestId(); CountDownLatch reading = new CountDownLatch(1); CountDownLatch completeRead = new CountDownLatch(1); f.transport().duringRead = @@ -313,12 +1216,20 @@ void concurrentSameRequestObservesOneInflightOwnerAndReplaysOneCommittedTransiti executor.submit(() -> f.service() .reconcile( - request, f.creation().requestId(), 2, f.providerId(), claim.attemptId())); + request, + f.creation().requestId(), + claim.expectedRowVersion(), + f.providerId(), + null)); assertThat(reading.await(5, TimeUnit.SECONDS)).isTrue(); assertThat( f.service() .reconcile( - request, f.creation().requestId(), 2, f.providerId(), claim.attemptId()) + request, + f.creation().requestId(), + claim.expectedRowVersion(), + f.providerId(), + null) .outcome()) .isEqualTo(Outcome.RECONCILING); completeRead.countDown(); @@ -327,7 +1238,11 @@ void concurrentSameRequestObservesOneInflightOwnerAndReplaysOneCommittedTransiti assertThat( f.service() .reconcile( - request, f.creation().requestId(), 2, f.providerId(), claim.attemptId())) + request, + f.creation().requestId(), + claim.expectedRowVersion(), + f.providerId(), + null)) .isEqualTo(committed); assertThat(f.transport().reads).isOne(); assertThat(count(c, "subscription_lifecycle_receipts")).isOne(); @@ -340,7 +1255,7 @@ void concurrentSameRequestObservesOneInflightOwnerAndReplaysOneCommittedTransiti @Test void providerIdMetadataCustomerInstrumentPriceQuantityAndUnknownStatusesCannotBecomeAuthority() { - Context c = context("1030"); + Context c = context("latest"); for (String mismatch : List.of("id", "metadata", "customer", "instrument", "price", "quantity", "unknown")) { Fixture f = fixture(c); @@ -391,14 +1306,19 @@ void providerIdMetadataCustomerInstrumentPriceQuantityAndUnknownStatusesCannotBe @Test void providerExceptionIsNotAbsenceAndSameRequestRecoversWithoutAnotherProviderIdentity() { - Context c = context("1030"); + Context c = context("latest"); Fixture f = fixture(c); - var claim = claim(f); - UUID request = UUID.randomUUID(); + var claim = paidClaim(f); + UUID request = claim.lifecycleRequestId(); f.transport().failure = mock(StripeException.class); assertThat( f.service() - .reconcile(request, f.creation().requestId(), 2, f.providerId(), claim.attemptId()) + .reconcile( + request, + f.creation().requestId(), + claim.expectedRowVersion(), + f.providerId(), + null) .outcome()) .isEqualTo(Outcome.RECONCILING); assertThat(count(c, "subscription_provider_terminal_resolutions")).isZero(); @@ -413,7 +1333,12 @@ void providerExceptionIsNotAbsenceAndSameRequestRecoversWithoutAnotherProviderId f.clock().advance(Duration.ofSeconds(2)); assertThat( f.service() - .reconcile(request, f.creation().requestId(), 2, f.providerId(), claim.attemptId()) + .reconcile( + request, + f.creation().requestId(), + claim.expectedRowVersion(), + f.providerId(), + null) .outcome()) .isEqualTo(Outcome.COMMITTED); assertThat(count(c, "subscription_create_operations")).isOne(); @@ -424,17 +1349,12 @@ void providerExceptionIsNotAbsenceAndSameRequestRecoversWithoutAnotherProviderId @Test void walletDisplayAdvanceDuringSdkReadPreservesBindingAndStaleRowOwnerInputsRejectBeforeRead() { - Context c = context("1030"); + Context c = context("latest"); Fixture f = fixture(c); - var claim = claim(f); + var claim = paidClaim(f); assertThatThrownBy(() -> f.service() - .reconcile( - UUID.randomUUID(), - f.creation().requestId(), - 1, - f.providerId(), - claim.attemptId())) + .reconcile(UUID.randomUUID(), f.creation().requestId(), 1, f.providerId(), null)) .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class); assertThat(f.transport().reads).isZero(); var wrongOwner = @@ -471,11 +1391,11 @@ void walletDisplayAdvanceDuringSdkReadPreservesBindingAndStaleRowOwnerInputsReje assertThat( f.service() .reconcile( - UUID.randomUUID(), + claim.lifecycleRequestId(), f.creation().requestId(), - 2, + claim.expectedRowVersion(), f.providerId(), - claim.attemptId()) + null) .outcome()) .isEqualTo(Outcome.COMMITTED); assertThat( @@ -500,18 +1420,27 @@ void walletDisplayAdvanceDuringSdkReadPreservesBindingAndStaleRowOwnerInputsReje @Test void deferredSqlFailureRollsBackMappingObservationReceiptGenerationAndBothEventsThenRetryRecovers() { - Context c = context("1030"); + Context c = context("latest"); Fixture f = fixture(c); - var claim = claim(f); - UUID request = UUID.randomUUID(); + var claim = paidClaim(f); + UUID request = claim.lifecycleRequestId(); var prepared = in( c, () -> f.owner() .prepare( - request, f.creation().requestId(), 2, f.providerId(), claim.attemptId())); + request, + f.creation().requestId(), + claim.expectedRowVersion(), + f.providerId(), + null)); var actualSdk = f.observer().observe(prepared.binding()); + var mappingBefore = + c.setup() + .fetch( + "SELECT row_to_json(h)::text AS value, xmin::text AS xmin FROM subscription_provider_history h") + .intoMaps(); assertSqlState( "23514", () -> @@ -535,7 +1464,6 @@ void walletDisplayAdvanceDuringSdkReadPreservesBindingAndStaleRowOwnerInputsReje })); for (String table : List.of( - "subscription_provider_history", "subscription_lifecycle_observations", "subscription_lifecycle_receipts", "account_tenant_entitlement_outbox_events", @@ -543,6 +1471,21 @@ void walletDisplayAdvanceDuringSdkReadPreservesBindingAndStaleRowOwnerInputsReje "account_tenant_authority_source_records")) { assertThat(count(c, table)).as(table).isZero(); } + assertThat(count(c, "subscription_provider_history")).isOne(); + assertThat( + c.setup() + .fetch( + "SELECT row_to_json(h)::text AS value, xmin::text AS xmin FROM subscription_provider_history h") + .intoMaps()) + .isEqualTo(mappingBefore); + assertThat( + one( + c, + "SELECT count(*) FROM account_audit_outbox WHERE event_type = 'HOSTING_FIRST_INVOICE_COMPLETED'") + .get(0, Long.class)) + .isZero(); + assertThat(count(c, "subscription_first_invoice_success_evidence")).isOne(); + assertThat(count(c, "subscription_first_invoice_completions")).isZero(); assertThat( one( c, @@ -560,128 +1503,1354 @@ void walletDisplayAdvanceDuringSdkReadPreservesBindingAndStaleRowOwnerInputsReje f.clock().advance(Duration.ofSeconds(12)); assertThat( f.service() - .reconcile(request, f.creation().requestId(), 2, f.providerId(), claim.attemptId()) + .reconcile( + request, + f.creation().requestId(), + claim.expectedRowVersion(), + f.providerId(), + null) + .outcome()) + .isEqualTo(Outcome.COMMITTED); + assertThat(f.service().readCurrent(f.creation().tenantId()).tenantBillingSequence()).isOne(); + } + + @Test + void databaseGuardRejectsUnauditedOwnerUpdateDuringSdkTransport() { + Context c = context("latest"); + Fixture f = fixture(c); + var claim = claim(f); + // The actual database refuses an unaudited transfer. Preserve that guard rather than + // manufacturing an owner change that this source boundary cannot legitimately produce. + f.transport().duringRead = + () -> + c.tx() + .executeWithoutResult(s -> + c.dsl() + .execute( + "UPDATE account_tenant_billing_owners SET owner_version = owner_version + 1, owner_generation = ? WHERE tenant_uuid = ?", + UUID.randomUUID(), + f.creation().tenantId())); + UUID reconciliationRequest = UUID.randomUUID(); + assertSqlState( + "23514", + () -> + f.service() + .reconcile( + reconciliationRequest, + f.creation().requestId(), + 2, + f.providerId(), + claim.attemptId())); + assertThat(count(c, "subscription_lifecycle_receipts")).isZero(); + assertThat(count(c, "subscription_provider_history")).isZero(); + assertThat(count(c, "account_authority_outbox_events")).isZero(); + assertThat( + one( + c, + "SELECT state FROM subscription_lifecycle_operations WHERE request_id = ?", + reconciliationRequest) + .get("state", String.class)) + .isEqualTo("PENDING"); + assertThat( + one( + c, + "SELECT lifecycle_inflight_request_id FROM subscription WHERE subscription_id = ?", + f.creation().subscriptionId()) + .get("lifecycle_inflight_request_id", UUID.class)) + .isEqualTo(reconciliationRequest); + assertThat( + one( + c, + "SELECT current_receipt_request_id FROM subscription WHERE subscription_id = ?", + f.creation().subscriptionId()) + .get("current_receipt_request_id", UUID.class)) + .isNull(); + assertThat( + one( + c, + "SELECT owner_version FROM account_tenant_billing_owners WHERE tenant_uuid = ?", + f.creation().tenantId()) + .get("owner_version", Long.class)) + .isEqualTo(f.creation().owner().version()); + assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + } + + @Test + void realInitialCanceledEvidenceRetiresOnlyItsHoldAndCommittedReceiptCannotBeDetached() { + Context c = context("latest"); + Fixture f = fixture(c); + f.transport().json = response(f, "canceled"); + var claim = claim(f); + assertThat( + f.service() + .reconcile( + UUID.randomUUID(), + f.creation().requestId(), + 2, + f.providerId(), + claim.attemptId()) + .outcome()) + .isEqualTo(Outcome.COMMITTED); + assertThat(f.service().readCurrent(f.creation().tenantId()).gameplayAvailable()).isFalse(); + assertThat(count(c, "subscription_provider_terminal_resolutions")).isOne(); + assertThat( + one( + c, + "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", + f.creation().requestId()) + .get("released_at")) + .isNotNull(); + assertSqlState( + "23514", + () -> + c.setup() + .execute( + "UPDATE subscription SET current_receipt_request_id = NULL, row_version = row_version + 1 WHERE subscription_id = ?", + f.creation().subscriptionId())); + assertThat(f.service().readCurrent(f.creation().tenantId()).subscriptionStatus()) + .isEqualTo(Status.CANCELED); + } + + @Test + void unclaimedFirstInvoiceCancellationKeepsAmbiguityHeldThenReleasesExactReservation() { + Context c = context("1046.1"); + Fixture f = fixture(c); + var checkout = + CanonicalHostingSubscriptionTestFixture.prepareFirstInvoice( + invoiceCheckoutDirectory, + c.source(), + c.dsl(), + c.tx(), + f.creation(), + f.instrument(), + f.providerId(), + f.clock(), + f.owner()); + UUID subscriptionId = checkout.invoice().subscriptionId(); + UUID creationId = checkout.invoice().creationRequestId(); + UUID cancellationId = UUID.randomUUID(); + long version = + in( + c, + () -> + checkout + .payments() + .ownerRowVersion(subscriptionId, checkout.invoice().ownerAccountId())); + List beforeUpgrade = firstInvoiceImage(c); + configuration(c).target("1046.2").load().migrate(); + assertThat(firstInvoiceImage(c)).isEqualTo(beforeUpgrade); + assertSqlState( + "23514", + "Canceled first-invoice provisioning requires exact unclaimed terminal release", + () -> + c.tx() + .executeWithoutResult(ignored -> + c.dsl() + .execute( + "UPDATE subscription_provisioning_work SET phase = 'CANCELED', row_version = row_version + 1 WHERE request_id = ?", + creationId))); + configuration(c).load().migrate(); + for (String providerState : List.of("active", "incomplete", "canceled")) { + f.transport().json = response(f, providerState); + f.terminalInvoiceTransport().terminalInvoiceStatus("open"); + assertThat( + f.service() + .reconcileUnpaidFirstInvoiceCancellation( + cancellationId, creationId, version, f.providerId()) + .outcome()) + .isEqualTo(Outcome.RECONCILING); + assertThat(count(c, "subscription_lifecycle_operations")).isZero(); + assertThat(count(c, "subscription_provider_terminal_resolutions")).isZero(); + assertThat( + one( + c, + "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", + creationId) + .get("released_at")) + .isNull(); + assertThat( + one( + c, + "SELECT row_version FROM subscription WHERE subscription_id = ?", + subscriptionId) + .get("row_version", Long.class)) + .isEqualTo(version); + } + + f.terminalInvoiceTransport().terminalInvoiceStatus("void"); + f.terminalInvoiceTransport().terminalIntentUnassigned(true); + assertThat( + f.service() + .reconcileUnpaidFirstInvoiceCancellation( + cancellationId, creationId, version, f.providerId()) + .outcome()) + .isEqualTo(Outcome.RECONCILING); + assertThat(count(c, "subscription_lifecycle_operations")).isZero(); + assertThat(count(c, "subscription_provider_terminal_resolutions")).isZero(); + + f.terminalInvoiceTransport().terminalIntentUnassigned(false); + var committed = + f.service() + .reconcileUnpaidFirstInvoiceCancellation( + cancellationId, creationId, version, f.providerId()); + assertThat(committed.outcome()).isEqualTo(Outcome.COMMITTED); + var settled = + one( + c, + "SELECT w.phase, s.status, s.current_receipt_request_id, r.released_at, t.outcome, " + + "t.evidence_digest, receipt.observation_digest " + + "FROM subscription s JOIN subscription_provisioning_work w USING (subscription_id) " + + "JOIN subscription_instrument_reservations r ON r.subscription_id = s.subscription_id " + + "JOIN subscription_provider_terminal_resolutions t ON t.resolution_id = s.terminal_resolution_id " + + "AND r.terminal_resolution_id = t.resolution_id " + + "JOIN subscription_lifecycle_receipts receipt ON receipt.request_id = s.current_receipt_request_id " + + "WHERE s.subscription_id = ?", + subscriptionId); + assertThat(settled.get("phase", String.class)).isEqualTo("CANCELED"); + assertThat(settled.get("status", String.class)).isEqualTo("canceled"); + assertThat(settled.get("current_receipt_request_id", UUID.class)).isEqualTo(cancellationId); + assertThat(settled.get("released_at")).isNotNull(); + assertThat(settled.get("outcome", String.class)).isEqualTo("CANCELED"); + assertThat(settled.get("evidence_digest", String.class)) + .isEqualTo(settled.get("observation_digest", String.class)); + assertThat(count(c, "subscription_first_invoice_command_claims")).isZero(); + assertThat(count(c, "subscription_first_invoice_success_evidence")).isZero(); + assertThat(count(c, "subscription_first_invoice_completions")).isZero(); + assertThat(checkout.confirmations()).isZero(); + var current = f.service().readCurrent(f.creation().tenantId()); + assertThat(current.subscriptionStatus()).isEqualTo(Status.CANCELED); + assertThat(current.gameplayAvailable()).isFalse(); + int providerReads = f.transport().reads; + assertThat( + f.service() + .reconcileUnpaidFirstInvoiceCancellation( + cancellationId, creationId, version, f.providerId())) + .isEqualTo(committed); + assertThat(f.transport().reads).isEqualTo(providerReads); + assertThat(count(c, "subscription_provider_terminal_resolutions")).isOne(); + String invoiceRead = "/v1/invoices/" + checkout.invoice().invoiceId(); + assertThat(f.terminalInvoiceTransport().readPaths()) + .containsExactly( + invoiceRead, + invoiceRead, + invoiceRead, + "/v1/payment_intents/" + checkout.invoice().paymentIntentId()); + assertThat(f.terminalInvoiceTransport().confirmations()).isZero(); + } + + @Test + void migratedNoSendMarkerWithoutOriginalCreationProofKeepsClaimAndReservationHeld() { + Context c = context("1046.4"); + Fixture f = fixture(c); + var checkout = + CanonicalHostingSubscriptionTestFixture.prepareFirstInvoice( + invoiceCheckoutDirectory, + c.source(), + c.dsl(), + c.tx(), + f.creation(), + f.instrument(), + f.providerId(), + f.clock(), + f.owner()); + var marker = + checkout.claimExpiredBeforePost(CanonicalHostingSubscriptionTestFixture.BILLING_PASSWORD); + configuration(c).target("1046.9.0.7").load().migrate(); + String markerSelect = + "SELECT request_id, observed_at, created_transaction_id " + + "FROM subscription_first_invoice_expired_before_post WHERE request_id = ?"; + var markerBefore = one(c, markerSelect, marker.requestId()); + + configuration(c).target("latest").load().migrate(); + + assertThat(one(c, markerSelect, marker.requestId()).intoMap()) + .isEqualTo(markerBefore.intoMap()); + assertThat( + one( + c, + "SELECT original_creation_proven FROM subscription_first_invoice_expired_before_post WHERE request_id = ?", + marker.requestId()) + .get(0, Boolean.class)) + .isFalse(); + long version = + in( + c, + () -> + checkout + .payments() + .ownerRowVersion( + f.creation().subscriptionId(), checkout.invoice().ownerAccountId())); + f.transport().json = response(f, "canceled"); + int subscriptionReads = f.transport().reads; + assertThatThrownBy(() -> + f.service() + .reconcileUnpaidFirstInvoiceCancellation( + UUID.randomUUID(), f.creation().requestId(), version, f.providerId())) + .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class) + .hasMessageContaining("committed no-send evidence"); + assertThat(f.transport().reads).isEqualTo(subscriptionReads); + assertThat(f.terminalInvoiceTransport().reads()).isZero(); + + assertSqlState( + "23514", + "Claimed first-invoice cancellation requires proof of original no-send marker creation", + () -> + c.setup() + .execute( + "INSERT INTO subscription_first_invoice_no_send_cancellations " + + "(cancellation_request_id, confirmation_request_id, invoice_id, payment_intent_id, " + + "read_started_at, observed_at) " + + "VALUES (?, ?, ?, ?, clock_timestamp(), clock_timestamp())", + UUID.randomUUID(), + marker.requestId(), + checkout.invoice().invoiceId(), + checkout.invoice().paymentIntentId())); + assertThat(count(c, "subscription_first_invoice_command_claims")).isOne(); + assertThat(count(c, "subscription_first_invoice_no_send_cancellations")).isZero(); + assertThat(count(c, "subscription_provider_terminal_resolutions")).isZero(); + assertThat( + one( + c, + "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", + f.creation().requestId()) + .get("released_at")) + .isNull(); + } + + @Test + void terminalUnpaidCutoffRollsBackFreshOwnerCommitAndPreservesExactReplay() { + Context c = context("latest"); + Fixture f = fixture(c); + var checkout = + CanonicalHostingSubscriptionTestFixture.prepareFirstInvoice( + invoiceCheckoutDirectory, + c.source(), + c.dsl(), + c.tx(), + f.creation(), + f.instrument(), + f.providerId(), + f.clock(), + f.owner()); + checkout.claimExpiredBeforePost(CanonicalHostingSubscriptionTestFixture.BILLING_PASSWORD); + UUID creationId = f.creation().requestId(); + UUID cancellationId = UUID.randomUUID(); + long version = + in( + c, + () -> + checkout + .payments() + .ownerRowVersion( + f.creation().subscriptionId(), checkout.invoice().ownerAccountId())); + f.transport().json = response(f, "canceled"); + f.clock() + .advanceToAtLeast( + one(c, "SELECT clock_timestamp()").get(0, OffsetDateTime.class).toInstant()); + var cutoff = f.clock().instant().plusSeconds(15).atOffset(ZoneOffset.UTC); + var initialImage = firstInvoiceImage(c); + var transactions = + new DataSourceTransactionManager(c.source()) { + private static final long serialVersionUID = 1L; + + @Override + protected void prepareSynchronization( + DefaultTransactionStatus status, TransactionDefinition definition) { + super.prepareSynchronization(status, definition); + if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_READ_COMMITTED) + return; + TransactionSynchronizationManager.registerSynchronization( + new TransactionSynchronization() { + @Override + public int getOrder() { + return Ordered.HIGHEST_PRECEDENCE; + } + + @Override + public void beforeCommit(boolean readOnly) { + assertThat( + c.dsl() + .fetchExists( + DSL.selectOne() + .from("subscription_lifecycle_receipts") + .where("request_id = ?", cancellationId))) + .isTrue(); + assertThat( + c.dsl() + .fetchSingle("SELECT clock_timestamp()") + .get(0, OffsetDateTime.class)) + .isBefore(cutoff); + c.dsl().execute("SELECT pg_sleep_until(?::timestamptz)", cutoff); + } + }); + } + }; + var service = + new AccountHostingSubscriptionLifecycleService( + f.owner(), + f.observer(), + transactions, + new StripeHostingFirstInvoicePaymentClient( + new com.stripe.StripeClient(f.terminalInvoiceTransport()), + f.clock(), + Duration.ofMillis(250), + Duration.ofSeconds(1))); + + assertThatThrownBy(() -> + service.reconcileUnpaidFirstInvoiceCancellation( + cancellationId, creationId, version, f.providerId())) + .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class) + .hasMessage("Terminal unpaid first-invoice observation expired before owner commit"); + assertThat(firstInvoiceImage(c)).isEqualTo(initialImage); + assertThat(count(c, "subscription_lifecycle_operations")).isZero(); + assertThat(count(c, "subscription_lifecycle_receipts")).isZero(); + assertThat(count(c, "subscription_provider_terminal_resolutions")).isZero(); + + f.clock().advanceToAtLeast(cutoff.toInstant().plusSeconds(1)); + var committed = + f.service() + .reconcileUnpaidFirstInvoiceCancellation( + cancellationId, creationId, version, f.providerId()); + assertThat(committed.outcome()).isEqualTo(Outcome.COMMITTED); + assertThat(count(c, "subscription_provider_terminal_resolutions")).isOne(); + int providerReads = f.transport().reads; + int terminalReads = f.terminalInvoiceTransport().readPaths().size(); + f.clock().advance(Duration.ofSeconds(16)); + assertThat( + service.reconcileUnpaidFirstInvoiceCancellation( + cancellationId, creationId, version, f.providerId())) + .isEqualTo(committed); + assertThat(f.transport().reads).isEqualTo(providerReads); + assertThat(f.terminalInvoiceTransport().readPaths()).hasSize(terminalReads); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void exactTerminalInvoiceAndIntentSettleOnlyClaimWithRetainedNoSendWitness( + boolean unassignedMethod) { + Context c = context("latest"); + Fixture f = fixture(c); + var checkout = + CanonicalHostingSubscriptionTestFixture.prepareFirstInvoice( + invoiceCheckoutDirectory, + c.source(), + c.dsl(), + c.tx(), + f.creation(), + f.instrument(), + f.providerId(), + f.clock(), + f.owner()); + var witness = + checkout.claimExpiredBeforePost(CanonicalHostingSubscriptionTestFixture.BILLING_PASSWORD); + var witnessImage = + c.setup() + .fetch( + "SELECT request_id, observed_at FROM subscription_first_invoice_expired_before_post " + + "WHERE request_id = ?", + witness.requestId()) + .intoMaps(); + var claimImage = + c.setup() + .fetch( + "SELECT * FROM subscription_first_invoice_command_claims WHERE request_id = ?", + witness.requestId()) + .intoMaps(); + assertThat( + one( + c, + "SELECT original_creation_proven FROM subscription_first_invoice_expired_before_post WHERE request_id = ?", + witness.requestId()) + .get(0, Boolean.class)) + .isTrue(); + assertThat(witnessImage).hasSize(1); + assertThat(claimImage).hasSize(1); + assertThat(count(c, "subscription_first_invoice_command_claims")).isOne(); + assertThat(checkout.confirmations()).isZero(); + assertThat(count(c, "subscription_first_invoice_no_send_cancellations")).isZero(); + long version = + in( + c, + () -> + checkout + .payments() + .ownerRowVersion( + f.creation().subscriptionId(), checkout.invoice().ownerAccountId())); + f.transport().json = response(f, "canceled"); + + f.terminalInvoiceTransport().terminalIntentUnassigned(unassignedMethod); + var committed = + f.service() + .reconcileUnpaidFirstInvoiceCancellation( + UUID.randomUUID(), f.creation().requestId(), version, f.providerId()); + + assertThat(committed.outcome()).isEqualTo(Outcome.COMMITTED); + assertThat(count(c, "subscription_provider_terminal_resolutions")).isOne(); + assertThat(count(c, "subscription_first_invoice_command_claims")).isOne(); + assertThat( + one( + c, + "SELECT j.confirmation_request_id FROM subscription_first_invoice_no_send_cancellations j " + + "JOIN subscription_lifecycle_receipts r ON r.request_id = j.cancellation_request_id " + + "AND r.committed_transaction_id = j.created_transaction_id " + + "WHERE r.request_id = ?", + committed.requestId()) + .get("confirmation_request_id", UUID.class)) + .isEqualTo(witness.requestId()); + assertThat( + c.setup() + .fetch( + "SELECT request_id, observed_at FROM subscription_first_invoice_expired_before_post " + + "WHERE request_id = ?", + witness.requestId()) + .intoMaps()) + .isEqualTo(witnessImage); + assertThat( + c.setup() + .fetch( + "SELECT * FROM subscription_first_invoice_command_claims WHERE request_id = ?", + witness.requestId()) + .intoMaps()) + .isEqualTo(claimImage); + var settlement = + one( + c, + "SELECT w.phase, s.status, s.current_receipt_request_id, r.released_at, " + + "r.terminal_resolution_id = t.resolution_id AS exact_release " + + "FROM subscription s JOIN subscription_provisioning_work w USING (subscription_id) " + + "JOIN subscription_instrument_reservations r ON r.subscription_id = s.subscription_id " + + "JOIN subscription_provider_terminal_resolutions t ON t.resolution_id = s.terminal_resolution_id " + + "WHERE s.subscription_id = ?", + f.creation().subscriptionId()); + assertThat(settlement.get("phase", String.class)).isEqualTo("CANCELED"); + assertThat(settlement.get("status", String.class)).isEqualTo("canceled"); + assertThat(settlement.get("current_receipt_request_id", UUID.class)) + .isEqualTo(committed.requestId()); + assertThat(settlement.get("released_at")).isNotNull(); + assertThat(settlement.get("exact_release", Boolean.class)).isTrue(); + assertThat(f.terminalInvoiceTransport().readPaths()) + .containsExactly( + "/v1/invoices/in_" + f.creation().subscriptionId().toString().replace("-", ""), + "/v1/payment_intents/pi_" + f.creation().subscriptionId().toString().replace("-", "")); + assertThat(f.terminalInvoiceTransport().confirmations()).isZero(); + assertThat(f.terminalInvoiceTransport().reads()).isEqualTo(2); + int subscriptionReads = f.transport().reads; + assertThat( + f.service() + .reconcileUnpaidFirstInvoiceCancellation( + committed.requestId(), f.creation().requestId(), version, f.providerId())) + .isEqualTo(committed); + assertThat(f.transport().reads).isEqualTo(subscriptionReads); + assertThat(f.terminalInvoiceTransport().reads()).isEqualTo(2); + assertThat(count(c, "subscription_provider_terminal_resolutions")).isOne(); + } + + @Test + void nonExactTerminalInvoiceOrIntentEvidenceRetainsHoldAndNeverPosts() { + for (String failure : List.of("nonvoid-invoice", "live-intent", "wrong-intent", "received")) { + Context c = context("latest"); + Fixture f = fixture(c); + var checkout = + CanonicalHostingSubscriptionTestFixture.prepareFirstInvoice( + invoiceCheckoutDirectory, + c.source(), + c.dsl(), + c.tx(), + f.creation(), + f.instrument(), + f.providerId(), + f.clock(), + f.owner()); + var witness = + checkout.claimExpiredBeforePost(CanonicalHostingSubscriptionTestFixture.BILLING_PASSWORD); + assertThat(witness.requestId()).isNotNull(); + long version = + in( + c, + () -> + checkout + .payments() + .ownerRowVersion( + f.creation().subscriptionId(), checkout.invoice().ownerAccountId())); + UUID cancellationId = UUID.randomUUID(); + f.transport().json = response(f, "canceled"); + switch (failure) { + case "nonvoid-invoice" -> f.terminalInvoiceTransport().terminalInvoiceStatus("open"); + case "live-intent" -> + f.terminalInvoiceTransport().terminalIntentStatus("requires_confirmation"); + case "wrong-intent" -> + f.terminalInvoiceTransport().terminalIntentId("pi_wrong_controlled_binding"); + case "received" -> f.terminalInvoiceTransport().terminalAmounts(0, 0, 1); + default -> throw new AssertionError("Unexpected terminal evidence case: " + failure); + } + + assertThat( + f.service() + .reconcileUnpaidFirstInvoiceCancellation( + cancellationId, f.creation().requestId(), version, f.providerId()) + .outcome()) + .isEqualTo(Outcome.RECONCILING); + assertThat(count(c, "subscription_lifecycle_operations")).isZero(); + assertThat(count(c, "subscription_provider_terminal_resolutions")).isZero(); + assertThat(count(c, "subscription_first_invoice_completions")).isZero(); + assertThat( + one( + c, + "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", + f.creation().requestId()) + .get("released_at")) + .isNull(); + int expectedReads = failure.equals("wrong-intent") ? 2 : 1; + assertThat(f.terminalInvoiceTransport().reads()).isEqualTo(expectedReads); + assertThat(f.terminalInvoiceTransport().confirmations()).isZero(); + var expectedPaths = + new ArrayList<>( + List.of( + "/v1/invoices/in_" + f.creation().subscriptionId().toString().replace("-", ""))); + if (failure.equals("wrong-intent")) + expectedPaths.add( + "/v1/payment_intents/pi_" + f.creation().subscriptionId().toString().replace("-", "")); + assertThat(f.terminalInvoiceTransport().readPaths()).containsExactlyElementsOf(expectedPaths); + } + } + + @Test + void expiredCancellationCaptureKeepsExactInvoiceReservationHeld() { + Context c = context("latest"); + Fixture f = fixture(c); + var checkout = + CanonicalHostingSubscriptionTestFixture.prepareFirstInvoice( + invoiceCheckoutDirectory, + c.source(), + c.dsl(), + c.tx(), + f.creation(), + f.instrument(), + f.providerId(), + f.clock(), + f.owner()); + var witness = + checkout.claimExpiredBeforePost(CanonicalHostingSubscriptionTestFixture.BILLING_PASSWORD); + assertThat(witness.requestId()).isNotNull(); + long version = + in( + c, + () -> + checkout + .payments() + .ownerRowVersion( + f.creation().subscriptionId(), checkout.invoice().ownerAccountId())); + f.transport().json = response(f, "canceled"); + f.terminalInvoiceTransport().duringRead(() -> f.clock().advance(Duration.ofSeconds(11))); + + assertThat( + f.service() + .reconcileUnpaidFirstInvoiceCancellation( + UUID.randomUUID(), f.creation().requestId(), version, f.providerId()) + .outcome()) + .isEqualTo(Outcome.RECONCILING); + assertThat(count(c, "subscription_lifecycle_operations")).isZero(); + assertThat(count(c, "subscription_provider_terminal_resolutions")).isZero(); + assertThat( + one( + c, + "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", + f.creation().requestId()) + .get("released_at")) + .isNull(); + assertThat(f.terminalInvoiceTransport().confirmations()).isZero(); + } + + @ParameterizedTest + @ValueSource(longs = {-1, 0}) + void exactSignedPaymentWithoutConsentWhileCheckoutAwaitsPaymentRequiresReconciliation( + long secondsFromCapture) throws Exception { + Context c = context("latest"); + Fixture f = fixture(c); + var checkout = + CanonicalHostingSubscriptionTestFixture.prepareFirstInvoice( + invoiceCheckoutDirectory, + c.source(), + c.dsl(), + c.tx(), + f.creation(), + f.instrument(), + f.providerId(), + f.clock(), + f.owner()); + var owner = + new net.firedevops.firemud.accountservice.service.session + .AccountHostingFirstInvoicePaymentService( + mock( + net.firedevops.firemud.accountservice.service.session.AccountControlUiActorService + .class), + mock( + net.firedevops.firemud.accountservice.service.session + .AccountRecentReauthenticationService.class), + checkout.payments(), + new StripeEventInboxRepository(c.dsl()), + checkout.provider(), + checkout.verifier(), + f.service(), + new DataSourceTransactionManager(c.source())); + var before = firstInvoiceImage(c); + var capturedAt = + one( + c, + "SELECT captured_at FROM subscription_first_invoices WHERE subscription_id = ?", + checkout.invoice().subscriptionId()) + .get("captured_at", java.time.OffsetDateTime.class) + .toInstant(); + var signed = checkout.signedSuccessAt(capturedAt.plusSeconds(secondsFromCapture)); + assertThat(owner.completeSigned(signed.payload(), signed.signature()).state()) + .isEqualTo("RECONCILING"); + assertThat(owner.completeSigned(signed.payload(), signed.signature()).state()) + .isEqualTo("RECONCILING"); + assertThat(firstInvoiceImage(c)).isEqualTo(before); + assertThat(count(c, "subscription_first_invoice_confirmations")).isZero(); + assertThat(count(c, "subscription_first_invoice_completions")).isZero(); + assertThat(count(c, "stripe_event_inbox")).isOne(); + assertThat( + one( + c, + "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", + f.creation().requestId()) + .get("released_at")) + .isNull(); + + // Keep the same verified original event and commit consent strictly after its creation. + var verified = checkout.verifier().verify(signed.payload(), signed.signature()); + f.clock() + .advanceToAtLeast( + Instant.ofEpochSecond(verified.eventCreatedAtEpochSeconds()).plusSeconds(2)); + var providerReads = checkout.providerReads(); + var dispatch = + checkout.prepareConfirmationDispatch( + CanonicalHostingSubscriptionTestFixture.BILLING_PASSWORD); + var consent = + one( + c, + "SELECT consented_at FROM subscription_first_invoice_confirmations" + + " WHERE subscription_id = ?", + checkout.invoice().subscriptionId()) + .get("consented_at", java.time.OffsetDateTime.class); + assertThat(consent).isNotNull(); + assertThat(consent.toInstant().getEpochSecond()) + .isGreaterThan(verified.eventCreatedAtEpochSeconds()); + assertThat(checkout.confirmations()).isZero(); + assertThat(checkout.providerReads()).isEqualTo(providerReads); + var imageWithConsent = firstInvoiceImage(c); + + assertThat(owner.completeSigned(signed.payload(), signed.signature()).state()) + .isEqualTo("RECONCILING"); + assertThat(firstInvoiceImage(c)).isEqualTo(imageWithConsent); + assertThat(count(c, "subscription_first_invoice_confirmations")).isOne(); + assertThat(count(c, "subscription_first_invoice_completions")).isZero(); + assertThat(count(c, "stripe_event_inbox")).isOne(); + assertThat( + one( + c, + "SELECT processing_status FROM stripe_event_inbox WHERE provider_event_id = ?", + verified.providerEventId()) + .get("processing_status", String.class)) + .isEqualTo("PENDING"); + assertThat(checkout.confirmations()).isZero(); + assertThat(checkout.providerReads()).isEqualTo(providerReads); + f.transport().json = response(f, "canceled"); + assertThat( + f.service() + .reconcileUnpaidFirstInvoiceCancellation( + UUID.randomUUID(), + f.creation().requestId(), + dispatch.expectedRowVersion(), + f.providerId()) + .outcome()) + .isEqualTo(Outcome.RECONCILING); + assertThat(firstInvoiceImage(c)).isEqualTo(imageWithConsent); + assertThat(count(c, "subscription_lifecycle_operations")).isZero(); + assertThat(count(c, "subscription_provider_terminal_resolutions")).isZero(); + } + + @Test + void firstInvoiceCaptureWaitsForExactSignedIntakeBeforeItsMappingExists() throws Exception { + Context c = context("latest"); + var signer = prepareFirstInvoice(fixture(c)); + Fixture f = fixture(c); + String intentSuffix = f.creation().subscriptionId().toString().replace("-", ""); + var signed = + signer.signWebhookPayload( + signer + .signedSuccess() + .payload() + .replace(signer.invoice().paymentIntentId().substring(3), intentSuffix) + .replace(signer.invoice().providerCustomerId(), f.creation().providerCustomerId()) + .replace( + signer.invoice().providerPaymentMethodId(), + f.instrument().providerPaymentMethodId())); + var verified = signer.verifier().verify(signed.payload(), signed.signature()); + try (var workers = Executors.newVirtualThreadPerTaskExecutor()) { + var capture = + in( + c, + () -> { + assertThat( + one( + c, + "SELECT count(*) FROM subscription_first_invoices" + + " WHERE subscription_id = ?", + f.creation().subscriptionId()) + .get(0, Long.class)) + .isZero(); + new StripeEventInboxRepository(c.dsl()).retainOrReplay(verified); + int intakePid = + c.dsl().fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class); + var pendingCapture = workers.submit(() -> prepareFirstInvoice(f)); + awaitFirstInvoiceIntentBlockedBy(c, intakePid); + return pendingCapture; + }); + var retained = capture.get(5, TimeUnit.SECONDS); + assertThat(retained.invoice().paymentIntentId()).isEqualTo("pi_" + intentSuffix); + assertThat(retained.confirmations()).isZero(); + } + + f.transport().json = response(f, "canceled"); + long capturedVersion = + c.intents().findCurrentByTenant(f.creation().tenantId()).orElseThrow().rowVersion(); + assertThat( + f.service() + .reconcileUnpaidFirstInvoiceCancellation( + UUID.randomUUID(), f.creation().requestId(), capturedVersion, f.providerId()) .outcome()) - .isEqualTo(Outcome.COMMITTED); - assertThat(f.service().readCurrent(f.creation().tenantId()).tenantBillingSequence()).isOne(); + .isEqualTo(Outcome.RECONCILING); + assertThat(count(c, "subscription_provider_terminal_resolutions")).isZero(); + assertThat(count(c, "subscription_first_invoice_success_evidence")).isZero(); + assertThat(count(c, "stripe_event_inbox")).isOne(); + assertThat( + one( + c, + "SELECT released_at FROM subscription_instrument_reservations" + + " WHERE request_id = ?", + f.creation().requestId()) + .get("released_at")) + .isNull(); + assertThat(f.terminalInvoiceTransport().confirmations()).isZero(); } @Test - void databaseGuardRejectsUnauditedOwnerUpdateDuringSdkTransport() { - Context c = context("1030"); + void verifiedPaidInboxEventRetainedDuringProviderReadWinsBeforeCancellationApply() + throws Exception { + Context c = context("latest"); Fixture f = fixture(c); - var claim = claim(f); - // The actual database refuses an unaudited transfer. Preserve that guard rather than - // manufacturing an owner change that this source boundary cannot legitimately produce. - f.transport().duringRead = - () -> - c.tx() - .executeWithoutResult(s -> - c.dsl() - .execute( - "UPDATE account_tenant_billing_owners SET owner_version = owner_version + 1, owner_generation = ? WHERE tenant_uuid = ?", - UUID.randomUUID(), - f.creation().tenantId())); - UUID reconciliationRequest = UUID.randomUUID(); - assertSqlState( - "23514", - () -> - f.service() - .reconcile( - reconciliationRequest, - f.creation().requestId(), - 2, - f.providerId(), - claim.attemptId())); - assertThat(count(c, "subscription_lifecycle_receipts")).isZero(); - assertThat(count(c, "subscription_provider_history")).isZero(); - assertThat(count(c, "account_authority_outbox_events")).isZero(); + var checkout = prepareFirstInvoice(f); + var witness = + checkout.claimExpiredBeforePost(CanonicalHostingSubscriptionTestFixture.BILLING_PASSWORD); + assertThat(witness.requestId()).isNotNull(); + long version = + in( + c, + () -> + checkout + .payments() + .ownerRowVersion( + f.creation().subscriptionId(), checkout.invoice().ownerAccountId())); + var signed = checkout.signedSuccess(); + var verified = checkout.verifier().verify(signed.payload(), signed.signature()); + f.transport().json = response(f, "canceled"); + var providerRead = new CountDownLatch(1); + var continueProviderRead = new CountDownLatch(1); + f.terminalInvoiceTransport() + .duringRead(() -> { + providerRead.countDown(); + await(continueProviderRead); + }); + + UUID cancellationId = UUID.randomUUID(); + try (var workers = Executors.newVirtualThreadPerTaskExecutor()) { + var cancellation = + workers.submit(() -> + f.service() + .reconcileUnpaidFirstInvoiceCancellation( + cancellationId, f.creation().requestId(), version, f.providerId())); + try { + await(providerRead); + in( + c, + () -> { + int intakePid = c.dsl().fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class); + // The inbox insert's trigger holds the matching intent lock until commit. + var retained = new StripeEventInboxRepository(c.dsl()).retainOrReplay(verified); + assertThat(count(c, "stripe_event_inbox")).isZero(); + continueProviderRead.countDown(); + awaitFirstInvoiceIntentBlockedBy(c, intakePid); + return retained; + }); + } finally { + continueProviderRead.countDown(); + } + assertThat(cancellation.get(5, TimeUnit.SECONDS).outcome()).isEqualTo(Outcome.RECONCILING); + } assertThat( one( c, - "SELECT state FROM subscription_lifecycle_operations WHERE request_id = ?", - reconciliationRequest) - .get("state", String.class)) - .isEqualTo("PENDING"); + "SELECT count(*) FROM subscription_lifecycle_receipts WHERE request_id = ?", + cancellationId) + .get(0, Long.class)) + .isZero(); + assertThat(count(c, "subscription_lifecycle_operations")).isZero(); + assertThat(count(c, "subscription_provider_terminal_resolutions")).isZero(); + assertThat(count(c, "subscription_first_invoice_success_evidence")).isZero(); assertThat( one( c, - "SELECT lifecycle_inflight_request_id FROM subscription WHERE subscription_id = ?", - f.creation().subscriptionId()) - .get("lifecycle_inflight_request_id", UUID.class)) - .isEqualTo(reconciliationRequest); + "SELECT processing_status FROM stripe_event_inbox WHERE provider_event_id = ?", + verified.providerEventId()) + .get("processing_status", String.class)) + .isEqualTo("PENDING"); assertThat( one( c, - "SELECT current_receipt_request_id FROM subscription WHERE subscription_id = ?", - f.creation().subscriptionId()) - .get("current_receipt_request_id", UUID.class)) + "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", + f.creation().requestId()) + .get("released_at")) .isNull(); + assertThat(f.terminalInvoiceTransport().readPaths()) + .containsExactly( + "/v1/invoices/in_" + f.creation().subscriptionId().toString().replace("-", ""), + "/v1/payment_intents/pi_" + f.creation().subscriptionId().toString().replace("-", "")); + assertThat(f.terminalInvoiceTransport().confirmations()).isZero(); + } + + private static void awaitFirstInvoiceIntentBlockedBy(Context c, int intakePid) { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + do { + if (Boolean.TRUE.equals( + one( + c, + "SELECT EXISTS (SELECT 1 FROM pg_locks WHERE locktype = 'advisory' " + + "AND NOT granted AND ? = ANY(pg_blocking_pids(pid)))", + intakePid) + .get(0, Boolean.class))) { + return; + } + try { + Thread.sleep(10); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new AssertionError( + "Interrupted while observing the first-invoice intent wait", interrupted); + } + } while (System.nanoTime() < deadline); + throw new AssertionError( + "The first-invoice operation did not wait on the signed intake intent lock"); + } + + private CanonicalHostingSubscriptionTestFixture.FirstInvoiceCheckout prepareFirstInvoice( + Fixture f) { + Context c = f.context(); + return CanonicalHostingSubscriptionTestFixture.prepareFirstInvoice( + invoiceCheckoutDirectory, + c.source(), + c.dsl(), + c.tx(), + f.creation(), + f.instrument(), + f.providerId(), + f.clock(), + f.owner()); + } + + @Test + void claimedFirstInvoiceCannotReleaseThroughUnpaidCancellation() { + Context c = context("latest"); + Fixture f = fixture(c); + var checkout = + CanonicalHostingSubscriptionTestFixture.prepareFirstInvoice( + invoiceCheckoutDirectory, + c.source(), + c.dsl(), + c.tx(), + f.creation(), + f.instrument(), + f.providerId(), + f.clock(), + f.owner()); + var claimed = checkout.authorize(CanonicalHostingSubscriptionTestFixture.BILLING_PASSWORD); + assertThat(count(c, "subscription_first_invoice_command_claims")).isOne(); + assertThat(count(c, "subscription_first_invoice_success_evidence")).isZero(); + f.transport().json = response(f, "canceled"); + assertThatThrownBy(() -> + f.service() + .reconcileUnpaidFirstInvoiceCancellation( + UUID.randomUUID(), + f.creation().requestId(), + claimed.expectedRowVersion(), + f.providerId())) + .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class) + .hasMessageContaining("unclaimed unpaid"); + assertThat(f.transport().reads).isZero(); + assertThat(count(c, "subscription_provider_terminal_resolutions")).isZero(); assertThat( one( c, - "SELECT owner_version FROM account_tenant_billing_owners WHERE tenant_uuid = ?", - f.creation().tenantId()) - .get("owner_version", Long.class)) - .isEqualTo(f.creation().owner().version()); - assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) - .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", + f.creation().requestId()) + .get("released_at")) + .isNull(); } - @Test - void realInitialCanceledEvidenceRetiresOnlyItsHoldAndCommittedReceiptCannotBeDetached() { - Context c = context("1030"); + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void lateSignedPaymentAfterUnpaidCancellationRetainsOneOperatorConflict(boolean noSendWitness) + throws Exception { + Context c = context("latest"); Fixture f = fixture(c); + var checkout = + CanonicalHostingSubscriptionTestFixture.prepareFirstInvoice( + invoiceCheckoutDirectory, + c.source(), + c.dsl(), + c.tx(), + f.creation(), + f.instrument(), + f.providerId(), + f.clock(), + f.owner()); + UUID confirmationRequestId; + long expectedRowVersion; + if (noSendWitness) { + var witness = + checkout.claimExpiredBeforePost(CanonicalHostingSubscriptionTestFixture.BILLING_PASSWORD); + confirmationRequestId = witness.requestId(); + expectedRowVersion = + in( + c, + () -> + checkout + .payments() + .ownerRowVersion( + checkout.invoice().subscriptionId(), + checkout.invoice().ownerAccountId())); + } else { + var dispatch = + checkout.prepareConfirmationDispatch( + CanonicalHostingSubscriptionTestFixture.BILLING_PASSWORD); + confirmationRequestId = dispatch.requestId(); + expectedRowVersion = dispatch.expectedRowVersion(); + } + UUID cancellationId = UUID.randomUUID(); f.transport().json = response(f, "canceled"); - var claim = claim(f); assertThat( + f.service() + .reconcileUnpaidFirstInvoiceCancellation( + cancellationId, f.creation().requestId(), expectedRowVersion, f.providerId()) + .outcome()) + .isEqualTo(Outcome.COMMITTED); + List canceledImage = firstInvoiceImage(c); + int providerReads = f.transport().reads; + long canceledVersion = + c.intents().findCurrentByTenant(f.creation().tenantId()).orElseThrow().rowVersion(); + assertThatThrownBy(() -> f.service() .reconcile( UUID.randomUUID(), f.creation().requestId(), - 2, + canceledVersion, f.providerId(), - claim.attemptId()) + null)) + .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class) + .hasMessage( + "Ordinary lifecycle cannot replace the retained unpaid first-invoice cancellation"); + assertThat(f.transport().reads).isEqualTo(providerReads); + assertThat(firstInvoiceImage(c)).isEqualTo(canceledImage); + assertThat( + f.service() + .reconcileUnpaidFirstInvoiceCancellation( + cancellationId, f.creation().requestId(), expectedRowVersion, f.providerId()) .outcome()) .isEqualTo(Outcome.COMMITTED); - assertThat(f.service().readCurrent(f.creation().tenantId()).gameplayAvailable()).isFalse(); - assertThat(count(c, "subscription_provider_terminal_resolutions")).isOne(); + assertThat(f.transport().reads).isEqualTo(providerReads); + assertThat(firstInvoiceImage(c)).isEqualTo(canceledImage); + + checkout.status("succeeded"); + if (!noSendWitness) { + var delayed = checkout.signedSuccess(); + var delayedEvent = checkout.verifier().verify(delayed.payload(), delayed.signature()); + in(c, () -> new StripeEventInboxRepository(c.dsl()).retainOrReplay(delayedEvent)); + var staleObservation = checkout.provider().observe(checkout.invoice()); + // Freeze the application read and let PostgreSQL cross its exact observation deadline. + // Keep the preceding cancellation and consent on their original monotonic clock. + var observationDeadline = staleObservation.readStartedAt().plusSeconds(20); + one( + c, + "SELECT pg_sleep(GREATEST(0, EXTRACT(EPOCH FROM (?::timestamptz - clock_timestamp()))))", + observationDeadline.atOffset(ZoneOffset.UTC)); + assertSqlState( + "23514", + "Late first-invoice payment observation expired before conflict insertion", + () -> + in(c, () -> checkout.payments().retainSignedOutcome(delayedEvent, staleObservation))); + assertThat(count(c, "subscription_first_invoice_late_paid_conflicts")).isZero(); + } + + f.clock().advanceToAtLeast(checkout.invoice().expiresAt().plusSeconds(1)); + var delivery = checkout.signedSuccess(); + var signed = + checkout.signWebhookPayload(delivery.payload().replace("evt_", "evt_late_success_")); + var owner = + new net.firedevops.firemud.accountservice.service.session + .AccountHostingFirstInvoicePaymentService( + mock( + net.firedevops.firemud.accountservice.service.session.AccountControlUiActorService + .class), + mock( + net.firedevops.firemud.accountservice.service.session + .AccountRecentReauthenticationService.class), + checkout.payments(), + new StripeEventInboxRepository(c.dsl()), + checkout.provider(), + checkout.verifier(), + f.service(), + new DataSourceTransactionManager(c.source())); + var verified = checkout.verifier().verify(signed.payload(), signed.signature()); + in(c, () -> new StripeEventInboxRepository(c.dsl()).retainOrReplay(verified)); + var equivalent = checkout.signWebhookPayload(" \n" + signed.payload() + "\n "); + var conflict = owner.completeSigned(equivalent.payload(), equivalent.signature()); + assertThat(conflict.state()).isEqualTo("OPERATOR_RECONCILIATION_REQUIRED"); + assertThat(conflict.requestId()).isEqualTo(confirmationRequestId); + assertThat(count(c, "subscription_first_invoice_late_paid_conflicts")).isOne(); + var paidObservation = checkout.provider().observe(checkout.invoice()); + assertThatThrownBy( + () -> in(c, () -> checkout.payments().retainSignedSuccess(verified, paidObservation))) + .isInstanceOf(IllegalStateException.class); + assertSqlState( + "23514", + () -> + c.setup() + .execute( + "INSERT INTO subscription_first_invoice_success_evidence " + + "(request_id, subscription_id, provider_event_id, event_payload_digest, " + + "tuple_digest, observed_at) VALUES (?, ?, ?, ?, ?, ?::timestamptz)", + confirmationRequestId, + checkout.invoice().subscriptionId(), + verified.providerEventId(), + verified.payloadSha256(), + checkout.invoice().digest(), + java.time.OffsetDateTime.ofInstant(f.clock().instant(), ZoneOffset.UTC))); + assertThat(firstInvoiceImage(c)).isEqualTo(canceledImage); + + var distinctSuccess = + checkout.signWebhookPayload(signed.payload().replace("evt_", "evt_second_success_")); + assertThat(owner.completeSigned(distinctSuccess.payload(), distinctSuccess.signature())) + .isEqualTo(conflict); + assertThat(count(c, "subscription_first_invoice_late_paid_conflicts")).isOne(); assertThat( - one( - c, - "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", - f.creation().requestId()) - .get("released_at")) - .isNotNull(); + c.setup() + .fetchSingle( + "SELECT provider_event_id FROM subscription_first_invoice_late_paid_conflicts") + .get(0, String.class)) + .isEqualTo(verified.providerEventId()); + assertThat(firstInvoiceImage(c)).isEqualTo(canceledImage); + + var consent = + c.setup() + .fetchSingle( + "SELECT consented_at FROM subscription_first_invoice_confirmations WHERE request_id = ?", + confirmationRequestId) + .get(0, java.time.OffsetDateTime.class); + var earlyReplay = + checkout.signWebhookPayload( + signed + .payload() + .replace("evt_", "evt_early_replay_") + .replace( + "\"created\":" + verified.eventCreatedAtEpochSeconds() + ",", + "\"created\":" + (consent.toEpochSecond() - 1) + ",")); + var early = checkout.verifier().verify(earlyReplay.payload(), earlyReplay.signature()); + assertThat(early.eventCreatedAtEpochSeconds()).isLessThan(consent.toEpochSecond()); + in(c, () -> new StripeEventInboxRepository(c.dsl()).retainOrReplay(early)); assertSqlState( "23514", () -> c.setup() .execute( - "UPDATE subscription SET current_receipt_request_id = NULL, row_version = row_version + 1 WHERE subscription_id = ?", - f.creation().subscriptionId())); - assertThat(f.service().readCurrent(f.creation().tenantId()).subscriptionStatus()) - .isEqualTo(Status.CANCELED); + "INSERT INTO subscription_first_invoice_late_paid_event_replays " + + "(provider_event_id, subscription_id, event_payload_digest) VALUES (?, ?, ?)", + early.providerEventId(), + checkout.invoice().subscriptionId(), + early.payloadSha256())); + assertThat(count(c, "subscription_first_invoice_late_paid_event_replays")).isOne(); + + checkout.status("requires_confirmation"); + int providerReadsBeforeReplay = checkout.providerReads(); + assertThat(owner.completeSigned(distinctSuccess.payload(), distinctSuccess.signature())) + .isEqualTo(conflict); + assertThat(count(c, "subscription_first_invoice_late_paid_event_replays")).isOne(); + assertThat(owner.completeSigned(signed.payload(), signed.signature())).isEqualTo(conflict); + assertThat(owner.completeSigned(equivalent.payload(), equivalent.signature())) + .isEqualTo(conflict); + assertThat(checkout.providerReads()).isEqualTo(providerReadsBeforeReplay); + assertThat( + c.setup() + .fetchSingle( + "SELECT event_payload_digest FROM subscription_first_invoice_late_paid_conflicts") + .get(0, String.class)) + .isEqualTo(verified.payloadSha256()); + var unrelated = + checkout.signWebhookPayload( + signed + .payload() + .replace("evt_", "evt_unrelated_") + .replace("payment_intent.succeeded", "invoice.paid")); + assertThat(owner.completeSigned(unrelated.payload(), unrelated.signature()).state()) + .isEqualTo("IGNORED"); + checkout.status("succeeded"); + int providerReadsBeforeWrongMethod = checkout.providerReads(); + var wrongMethod = + checkout.signWebhookPayload( + signed + .payload() + .replace("evt_", "evt_wrongmethod_") + .replace(checkout.invoice().providerPaymentMethodId(), "pm_other")); + assertThatThrownBy(() -> owner.completeSigned(wrongMethod.payload(), wrongMethod.signature())) + .isInstanceOf(IllegalStateException.class); + assertThat(checkout.providerReads()).isEqualTo(providerReadsBeforeWrongMethod); + assertThat(firstInvoiceImage(c)).isEqualTo(canceledImage); + assertThat(count(c, "subscription_first_invoice_late_paid_conflicts")).isOne(); + assertThat(count(c, "subscription_first_invoice_success_evidence")).isZero(); + assertThat(count(c, "subscription_first_invoice_completions")).isZero(); + assertThat(f.service().readCurrent(f.creation().tenantId()).gameplayAvailable()).isFalse(); + } + + @Test + void unavailableReservedInstrumentRefusesFirstInvoiceCommandWithoutClaimOrProviderPost() + throws Exception { + Context c = context("latest"); + Fixture f = fixture(c); + var checkout = + CanonicalHostingSubscriptionTestFixture.prepareFirstInvoice( + invoiceCheckoutDirectory, + c.source(), + c.dsl(), + c.tx(), + f.creation(), + f.instrument(), + f.providerId(), + f.clock(), + f.owner()); + var dispatch = + checkout.prepareConfirmationDispatch( + CanonicalHostingSubscriptionTestFixture.BILLING_PASSWORD); + var instrument = f.instrument(); + in( + c, + () -> + new AccountPaymentInstrumentRepository(c.dsl()) + .recordAvailability( + new AccountPaymentInstrumentRepository.AvailabilityObservation( + UUID.randomUUID(), + instrument.instrumentUuid(), + instrument.accountUuid(), + instrument.rowVersion(), + AccountPaymentInstrumentRecord.State.UNAVAILABLE, + instrument.display(), + "sha256:" + "e".repeat(64)))); + + assertThatThrownBy(() -> + checkout + .provider() + .confirm( + dispatch, + () -> + in( + c, + () -> + checkout + .payments() + .claimCommand(dispatch, checkout.invoice().ownerAccountId())))) + .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class); + assertThat(checkout.confirmations()).isZero(); + assertThat(count(c, "subscription_first_invoice_command_claims")).isZero(); + } + + @Test + void paidFirstInvoiceWithCanceledProviderKeepsCustodyAndRecordsOperatorWork() { + Context c = context("latest"); + Fixture f = fixture(c); + var checkout = + CanonicalHostingSubscriptionTestFixture.prepareFirstInvoice( + invoiceCheckoutDirectory, + c.source(), + c.dsl(), + c.tx(), + f.creation(), + f.instrument(), + f.providerId(), + f.clock(), + f.owner()); + var paid = + checkout.authorizeAndRetainSuccess( + CanonicalHostingSubscriptionTestFixture.BILLING_PASSWORD); + f.transport().json = response(f, "canceled"); + + var result = + f.service() + .reconcile( + paid.lifecycleRequestId(), + f.creation().requestId(), + paid.expectedRowVersion(), + f.providerId(), + null); + + assertThat(result.outcome()).isEqualTo(Outcome.TERMINAL_FAILURE); + assertThat( + one( + c, + "SELECT reason FROM subscription_lifecycle_operator_outbox WHERE request_id = ?", + paid.lifecycleRequestId()) + .get("reason", String.class)) + .isEqualTo("PAID_FIRST_INVOICE_PROVIDER_CANCELED"); + var held = + one( + c, + "SELECT s.status, w.phase, r.released_at FROM subscription s " + + "JOIN subscription_provisioning_work w USING (subscription_id) " + + "JOIN subscription_instrument_reservations r USING (subscription_id) " + + "WHERE s.subscription_id = ?", + paid.invoice().subscriptionId()); + assertThat(held.get("status", String.class)).isEqualTo("provisioning"); + assertThat(held.get("phase", String.class)).isEqualTo("AWAITING_PAYMENT"); + assertThat(held.get("released_at")).isNull(); + assertThat(count(c, "subscription_lifecycle_receipts")).isZero(); + assertThat(count(c, "subscription_first_invoice_completions")).isZero(); + assertThat(count(c, "subscription_first_invoice_success_evidence")).isOne(); } @Test void freshReadsBeyondObservationAgePreserveCommittedReceiptAndAuthorityUntilRealPeriodEnd() { for (String status : List.of("active", "trialing")) { - Context c = context("1030"); + Context c = context("latest"); Fixture f = fixture(c); - f.transport().json = response(f, status); activate(f); + long checkpoints = 1; + if ("trialing".equals(status)) { + f.transport().json = response(f, status); + refresh(f); + checkpoints = 2; + } var receipt = one( c, - "SELECT row_to_json(r)::text AS value, xmin::text AS xmin FROM subscription_lifecycle_receipts r"); + "SELECT row_to_json(r)::text AS value, xmin::text AS xmin FROM subscription_lifecycle_receipts r WHERE request_id = (SELECT current_receipt_request_id FROM subscription)"); var authority = one( c, "SELECT row_to_json(a)::text AS value, xmin::text AS xmin FROM account_tenant_authority_source_records a"); Instant periodEnd = Instant.ofEpochSecond(f.creation().createdAt().getEpochSecond() + 3600); assertThat( - one(c, "SELECT valid_until FROM subscription_lifecycle_receipts") + one( + c, + "SELECT valid_until FROM subscription_lifecycle_receipts WHERE request_id = (SELECT current_receipt_request_id FROM subscription)") .get(0, java.time.OffsetDateTime.class) .toInstant()) .isEqualTo(periodEnd); @@ -691,21 +2860,22 @@ void freshReadsBeyondObservationAgePreserveCommittedReceiptAndAuthorityUntilReal var current = f.service().readCurrent(f.creation().tenantId()); assertThat(current.gameplayAvailable()).isTrue(); assertThat(current.validUntil()).isEqualTo(f.clock().instant().plusSeconds(15)); - assertThat(current.tenantBillingSequence()).isOne(); - assertThat(current.tenantAuthorityEvent().tenantAuthorityGeneration()).isEqualTo(2); + assertThat(current.tenantBillingSequence()).isEqualTo(checkpoints); + assertThat(current.tenantAuthorityEvent().tenantAuthorityGeneration()) + .isEqualTo(checkpoints + 1); assertThat(f.transport().reads).isEqualTo(reads + laterRead); assertThat( one( c, - "SELECT row_to_json(r)::text AS value, xmin::text AS xmin FROM subscription_lifecycle_receipts r")) + "SELECT row_to_json(r)::text AS value, xmin::text AS xmin FROM subscription_lifecycle_receipts r WHERE request_id = (SELECT current_receipt_request_id FROM subscription)")) .isEqualTo(receipt); assertThat( one( c, "SELECT row_to_json(a)::text AS value, xmin::text AS xmin FROM account_tenant_authority_source_records a")) .isEqualTo(authority); - assertThat(count(c, "account_tenant_entitlement_outbox_events")).isOne(); - assertThat(count(c, "account_authority_outbox_events")).isOne(); + assertThat(count(c, "account_tenant_entitlement_outbox_events")).isEqualTo(checkpoints); + assertThat(count(c, "account_authority_outbox_events")).isEqualTo(checkpoints); } f.clock().advance(Duration.between(f.clock().instant(), periodEnd)); int beforeExpiredRead = f.transport().reads; @@ -717,28 +2887,32 @@ void freshReadsBeyondObservationAgePreserveCommittedReceiptAndAuthorityUntilReal .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class) .hasMessageContaining("current receipt is expired"); assertThat(f.transport().reads).isEqualTo(beforeExpiredRead); - assertThat(count(c, "subscription_lifecycle_receipts")).isOne(); + assertThat(count(c, "subscription_lifecycle_receipts")).isEqualTo(checkpoints); } } @Test void canceledReceiptsReturnFreshNegativeProjectionAfterOriginalObservationAgeWithoutMutation() { for (boolean providerCanceled : new boolean[] {true, false}) { - Context c = context("1030"); + Context c = context("latest"); Fixture f = fixture(c); - f.transport().json = + String canceledFacts = providerCanceled ? response(f, "canceled") : response(f, "active") .replace( "\"cancel_at\":null", "\"cancel_at\":" + f.clock().instant().getEpochSecond()); - String originalFacts = f.transport().json; + f.transport().json = providerCanceled ? canceledFacts : response(f, "active"); activate(f); + f.transport().json = canceledFacts; + if (!providerCanceled) refresh(f); + long expectedSequence = providerCanceled ? 1L : 2L; var receipt = one( c, - "SELECT row_to_json(r)::text AS value, xmin::text AS xmin FROM subscription_lifecycle_receipts r"); + "SELECT row_to_json(r)::text AS value, xmin::text AS xmin FROM subscription_lifecycle_receipts r WHERE entitlement_version = ?", + expectedSequence); var authority = one( c, @@ -752,7 +2926,7 @@ void canceledReceiptsReturnFreshNegativeProjectionAfterOriginalObservationAgeWit assertThat(canceled.allowNewGameplayBindings()).isFalse(); assertThat(canceled.allowNewInstanceStarts()).isFalse(); assertThat(canceled.validUntil()).isEqualTo(f.clock().instant().plusSeconds(15)); - assertThat(canceled.tenantBillingSequence()).isOne(); + assertThat(canceled.tenantBillingSequence()).isEqualTo(expectedSequence); } // An aged terminal receipt is not permission to turn unknown or changed facts into denial. f.transport().duringRead = () -> f.clock().advance(Duration.ofSeconds(15)); @@ -763,21 +2937,22 @@ void canceledReceiptsReturnFreshNegativeProjectionAfterOriginalObservationAgeWit assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) .isInstanceOf( AccountHostingSubscriptionLifecycleService.EntitlementUnavailableException.class); - f.transport().json = originalFacts; + f.transport().json = canceledFacts; assertThat(f.service().readCurrent(f.creation().tenantId()).gameplayAvailable()).isFalse(); assertThat( one( c, - "SELECT row_to_json(r)::text AS value, xmin::text AS xmin FROM subscription_lifecycle_receipts r")) + "SELECT row_to_json(r)::text AS value, xmin::text AS xmin FROM subscription_lifecycle_receipts r WHERE entitlement_version = ?", + expectedSequence)) .isEqualTo(receipt); assertThat( one( c, "SELECT row_to_json(a)::text AS value, xmin::text AS xmin FROM account_tenant_authority_source_records a")) .isEqualTo(authority); - assertThat(count(c, "account_tenant_entitlement_outbox_events")).isOne(); - assertThat(count(c, "account_authority_outbox_events")).isOne(); - assertThat(count(c, "subscription_lifecycle_receipts")).isOne(); + assertThat(count(c, "account_tenant_entitlement_outbox_events")).isEqualTo(expectedSequence); + assertThat(count(c, "account_authority_outbox_events")).isEqualTo(expectedSequence); + assertThat(count(c, "subscription_lifecycle_receipts")).isEqualTo(expectedSequence); assertThat(count(c, "subscription_provider_terminal_resolutions")) .isEqualTo(providerCanceled ? 1 : 0); } @@ -785,7 +2960,7 @@ void canceledReceiptsReturnFreshNegativeProjectionAfterOriginalObservationAgeWit @Test void inFlightAndStaleObservationOrChangedSdkFactsNeverRefreshAnOldPositiveSnapshot() { - Context c = context("1030"); + Context c = context("latest"); Fixture f = fixture(c); activate(f); var fence = in(c, () -> f.owner().prepareCurrentRead(f.creation().tenantId())); @@ -827,7 +3002,7 @@ void inFlightAndStaleObservationOrChangedSdkFactsNeverRefreshAnOldPositiveSnapsh @Test void unchangedInvalidEvidenceExhaustsFrozenStallBudgetOnceAndNeverReleasesBillingWork() { - Context c = context("1030"); + Context c = context("latest"); Fixture f = fixture(c); var claim = claim(f); UUID request = UUID.randomUUID(); @@ -863,7 +3038,7 @@ void unchangedInvalidEvidenceExhaustsFrozenStallBudgetOnceAndNeverReleasesBillin @Test void firstPastDueObservationWithoutRetainedRecoveryOriginStaysUnresolvedAndHoldsReservation() { - Context c = context("1030"); + Context c = context("latest"); Fixture f = fixture(c); activate(f); var receipt = @@ -939,7 +3114,7 @@ void firstPastDueObservationWithoutRetainedRecoveryOriginStaysUnresolvedAndHolds @Test void effectiveCancellationAdvancesMonotonicCutoffWithoutPrematureReservationRelease() { - Context c = context("1030"); + Context c = context("latest"); Fixture f = fixture(c); activate(f); Instant cancellation = @@ -1103,11 +3278,97 @@ void populatedV1029UpgradePreservesIntentQuoteRowAndFlywayHistoryWithoutSynthesi c.setup().fetch("SELECT * FROM flyway_schema_history ORDER BY installed_rank").intoMaps(); assertThat(afterHistory).hasSize(history.size() + 1); assertThat(afterHistory.subList(0, history.size())).isEqualTo(history); + var v1030Subscription = + one( + c, + "SELECT row_to_json(s)::text AS value, xmin::text AS xmin FROM subscription s WHERE subscription_id = ?", + f.creation().subscriptionId()); + configuration(c).target("1041").load().migrate(); + assertThat( + one( + c, + "SELECT row_to_json(s)::text AS value, xmin::text AS xmin FROM subscription s WHERE subscription_id = ?", + f.creation().subscriptionId())) + .isEqualTo(v1030Subscription); + assertThat( + one( + c, + "SELECT row_to_json(o)::text AS value, xmin::text AS xmin FROM subscription_create_operations o WHERE request_id = ?", + f.creation().requestId())) + .isEqualTo(intent); + var currentHistory = + c.setup().fetch("SELECT * FROM flyway_schema_history ORDER BY installed_rank").intoMaps(); + assertThat(currentHistory.subList(0, afterHistory.size())).isEqualTo(afterHistory); + assertThat(count(c, "subscription_first_invoices")).isZero(); + assertThat(count(c, "subscription_first_invoice_completions")).isZero(); assertThat(count(c, "subscription_lifecycle_receipts")).isZero(); assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); } + private AccountHostingFirstInvoicePaymentRepository.ConfirmationDispatch paidClaim(Fixture f) { + var checkout = + CanonicalHostingSubscriptionTestFixture.prepareFirstInvoice( + invoiceCheckoutDirectory, + f.context().source(), + f.context().dsl(), + f.context().tx(), + f.creation(), + f.instrument(), + f.providerId(), + f.clock(), + f.owner()); + var authorized = + checkout.authorizeAndRetainSuccess( + CanonicalHostingSubscriptionTestFixture.BILLING_PASSWORD); + assertThat(checkout.confirmations()).isOne(); + assertThat(count(f.context(), "subscription_first_invoice_completions")).isZero(); + return authorized; + } + + private AccountHostingFirstInvoicePaymentRepository.ConfirmationDispatch paidClaimAt1046( + Fixture f) throws StripeException { + var checkout = + CanonicalHostingSubscriptionTestFixture.prepareFirstInvoice( + invoiceCheckoutDirectory, + f.context().source(), + f.context().dsl(), + f.context().tx(), + f.creation(), + f.instrument(), + f.providerId(), + f.clock(), + f.owner()); + var authorized = checkout.authorize(CanonicalHostingSubscriptionTestFixture.BILLING_PASSWORD); + assertThat(checkout.confirmations()).isOne(); + var signed = checkout.signedSuccess(); + var verified = checkout.verifier().verify(signed.payload(), signed.signature()); + var observation = checkout.provider().observe(checkout.invoice()); + // The pre-V1046.3 frontier has no late-payment conflict table. Retain its verified success + // evidence directly so this historical proof does not invoke the later conflict lookup. + in( + f.context(), + () -> { + new StripeEventInboxRepository(f.context().dsl()).retainOrReplay(verified); + f.context() + .dsl() + .execute( + "INSERT INTO subscription_first_invoice_success_evidence " + + "(request_id, subscription_id, provider_event_id, event_payload_digest, tuple_digest, observed_at) " + + "VALUES (?, ?, ?, ?, ?, ?::timestamptz)", + authorized.requestId(), + checkout.invoice().subscriptionId(), + verified.providerEventId(), + verified.payloadSha256(), + checkout.invoice().digest(), + java.time.OffsetDateTime.ofInstant( + observation.observedAt(), java.time.ZoneOffset.UTC)); + return Boolean.TRUE; + }); + assertThat(count(f.context(), "subscription_first_invoice_completions")).isZero(); + return authorized; + } + private static AccountHostingSubscriptionLifecycleRepository.ProvisioningClaim claim(Fixture f) { return Objects.requireNonNull( f.service().claimProvisioning(f.creation().requestId(), 1, UUID.randomUUID()).claim()); @@ -1486,7 +3747,7 @@ private static boolean attemptResolution( } private static FailedResolution failedResolution() { - Context c = context("1036"); + Context c = context("latest"); Fixture f = fixture(c); var claim = claim(f); UUID failed = UUID.randomUUID(); @@ -1587,20 +3848,63 @@ private static List resolutionImage(Context c) { return List.copyOf(image); } + private static List firstInvoiceImage(Context c) { + List image = new ArrayList<>(resolutionImage(c)); + for (String table : + List.of( + "subscription_provisioning_work", + "subscription_provisioning_attempts", + "subscription_first_invoices", + "subscription_first_invoice_confirmations", + "subscription_first_invoice_dispatches", + "subscription_first_invoice_authorizations", + "subscription_first_invoice_command_claims", + "subscription_first_invoice_success_evidence", + "subscription_first_invoice_completions", + "account_tenant_entitlement_outbox_streams", + "account_authority_outbox_streams", + "account_authority_outbox_events")) { + image.add( + one( + c, + "SELECT coalesce(jsonb_agg(to_jsonb(value) ORDER BY to_jsonb(value)::text)::text, '[]') FROM " + + table + + " value") + .get(0, String.class)); + } + return List.copyOf(image); + } + /** Controlled authorization callback only; no genuine actor/primary-authentication claim. */ private record FailedResolution( Fixture fixture, Request request, String failureImage, long auditRowsBefore) {} - private static void activate(Fixture f) { - var claim = claim(f); + private void activate(Fixture f) { + // Terminal initial provider evidence may release a hold without authorizing a payment. + boolean terminal = f.transport().json.contains("\"status\":\"canceled\""); + if (terminal) { + var claim = claim(f); + assertThat( + f.service() + .reconcile( + UUID.randomUUID(), + f.creation().requestId(), + claim.subscriptionRowVersion(), + f.providerId(), + claim.attemptId()) + .outcome()) + .isEqualTo(Outcome.COMMITTED); + return; + } + var payment = paidClaim(f); assertThat( f.service() .reconcile( - UUID.randomUUID(), + payment.lifecycleRequestId(), f.creation().requestId(), - claim.subscriptionRowVersion(), + payment.expectedRowVersion(), f.providerId(), - claim.attemptId()) + null) .outcome()) .isEqualTo(Outcome.COMMITTED); } @@ -1623,12 +3927,8 @@ private static void refresh(Fixture f) { private static Fixture fixture(Context c) { long row = ROWS.incrementAndGet(); UUID account = - one( - c, - "INSERT INTO accounts(username,email,password_hash) VALUES (?, ?, 'controlled-hash') RETURNING account_uuid", - "hosting-" + row, - "hosting-" + row + "@example.test") - .get("account_uuid", UUID.class); + CanonicalHostingSubscriptionTestFixture.createBillingAccount(c.dsl(), c.tx()) + .getAccountUuid(); UUID tenant = UUID.randomUUID(); UUID createRequest = UUID.randomUUID(); UUID createOperation = UUID.randomUUID(); @@ -1736,12 +4036,32 @@ private static Fixture fixture(Context c) { clock, Duration.ofMillis(250), Duration.ofSeconds(1)); + var terminalInvoiceTransport = + new ControlledFirstInvoiceTransport(creation, instrument, "sub_" + row, true); + var terminalInvoiceClient = + new net.firedevops.firemud.accountservice.client.StripeHostingFirstInvoicePaymentClient( + new com.stripe.StripeClient(terminalInvoiceTransport), + clock, + Duration.ofMillis(250), + Duration.ofSeconds(1)); var service = new AccountHostingSubscriptionLifecycleService( - repository, observer, new DataSourceTransactionManager(c.source())); + repository, + observer, + new DataSourceTransactionManager(c.source()), + terminalInvoiceClient); Fixture fixture = new Fixture( - c, creation, instrument, "sub_" + row, clock, transport, repository, observer, service); + c, + creation, + instrument, + "sub_" + row, + clock, + transport, + terminalInvoiceTransport, + repository, + observer, + service); transport.json = response(fixture, "active"); return fixture; } @@ -1802,6 +4122,7 @@ private static String response(Fixture f, String status) { f.creation().planQuote().providerPriceId()); } + // Runtime fixtures use the latest schema; upgrade witnesses pin their historical targets. private static Context context(String target) { String schema = "hosting_lifecycle_" + UUID.randomUUID().toString().replace("-", ""); var source = @@ -1856,11 +4177,18 @@ private static void await(CountDownLatch latch) { } private static void assertSqlState(String state, Runnable body) { + assertSqlState(state, null, body); + } + + private static void assertSqlState(String state, String diagnostic, Runnable body) { assertThatThrownBy(body::run) .satisfies(failure -> { for (Throwable cause = failure; cause != null; cause = cause.getCause()) { if (cause instanceof SQLException sql) { assertThat(sql.getSQLState()).isEqualTo(state); + if (diagnostic != null) { + assertThat(sql.getMessage()).contains(diagnostic); + } return; } } @@ -1883,37 +4211,11 @@ private record Fixture( String providerId, MutableClock clock, ControlledTransport transport, + ControlledFirstInvoiceTransport terminalInvoiceTransport, AccountHostingSubscriptionLifecycleRepository owner, StripeHostingSubscriptionObserver observer, AccountHostingSubscriptionLifecycleService service) {} - private static final class MutableClock extends Clock { - private Instant current; - - MutableClock(Instant current) { - this.current = current; - } - - void advance(Duration amount) { - current = current.plus(amount); - } - - @Override - public ZoneId getZone() { - return ZoneOffset.UTC; - } - - @Override - public Clock withZone(ZoneId zone) { - return this; - } - - @Override - public Instant instant() { - return current; - } - } - private static final class ControlledTransport implements StripeResponseGetter { private String json; private StripeException failure; diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java index 86f8655cbd..925d5014a2 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java @@ -6,6 +6,7 @@ import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.nio.file.Path; import java.sql.SQLException; import java.time.Duration; import java.time.Instant; @@ -46,6 +47,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInfo; import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.NullSource; @@ -59,6 +61,8 @@ @SuppressWarnings("resource") @TestInstance(TestInstance.Lifecycle.PER_METHOD) class AccountRepositoryIntegrationTest { + @TempDir Path invoiceCheckoutDirectory; + private static final UUID REALM_ID = UUID.fromString("4c4b57d8-e3a2-48fe-9977-e7df0fdce901"); private static final String MIGRATION_LOCATION = "classpath:db/migration"; private static final String MIGRATION_PROOF_ONLY_TAG = "migration-proof-only"; @@ -515,20 +519,10 @@ void auditAttemptTimesUseUtcLocalDateTimeUnderNonUtcDatabaseSession() { @Test void canonicalSubscriptionOriginalBindingLocksRequiredOwnerChainThroughCommit() throws Exception { var fixture = CanonicalHostingSubscriptionTestFixture.create(dataSource); - var claim = - fixture - .service() - .claimProvisioning(fixture.creation().requestId(), 1, UUID.randomUUID()) - .claim(); assertThat( fixture - .service() - .reconcile( - UUID.randomUUID(), - fixture.creation().requestId(), - claim.subscriptionRowVersion(), - fixture.providerId(), - claim.attemptId()) + .withCheckoutDirectory(invoiceCheckoutDirectory) + .completeFirstInvoice() .outcome()) .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Outcome.COMMITTED); var receipt = fixture.service().readCurrent(fixture.tenantId()); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java index d29ac7b743..8239a7f1f5 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java @@ -95,10 +95,12 @@ void freshInstallAppliesEveryForwardMigrationThroughV98() { context .dsl() .resultQuery( - "SELECT count(*) FROM flyway_schema_history " - + "WHERE version::numeric BETWEEN 74 AND 98 AND success") - .fetchOne(0, Long.class)) - .isEqualTo(25L); + "SELECT version FROM flyway_schema_history WHERE success " + + "AND version ~ '^(7[4-9]|8[0-9]|9[0-8])$' ORDER BY installed_rank") + .fetch() + .getValues(0, String.class)) + .containsExactlyElementsOf( + java.util.stream.IntStream.rangeClosed(74, 98).mapToObj(String::valueOf).toList()); for (String relation : new String[] { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionPostgresIntegrationTest.java index bc58778d4f..c96c1acd90 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionPostgresIntegrationTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertThrows; +import java.nio.file.Path; import java.sql.SQLException; import java.util.Map; import java.util.Objects; @@ -13,7 +14,6 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; -import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Outcome; import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceKind; import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceSelection; @@ -23,6 +23,7 @@ import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -35,6 +36,8 @@ */ @Testcontainers(disabledWithoutDocker = true) class AccountTenantAuthoritySourceSelectionPostgresIntegrationTest { + @TempDir Path invoiceCheckoutDirectory; + @Container private static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>(TestContainerImages.postgres()); @@ -251,7 +254,7 @@ private static void assertSqlState23514(Runnable operation) { throw new AssertionError("Expected PostgreSQL guard refusal", failure); } - private static Context context() { + private Context context() { String schema = "source_selection_" + UUID.randomUUID().toString().replace("-", ""); var source = new DriverManagerDataSource( @@ -279,13 +282,14 @@ private static Context context() { var demos = new AccountDemoTenantEntitlementRepository( f.dsl(), identities, generations, billing, events); - return new Context(f, events, demos); + return new Context(f, events, demos, invoiceCheckoutDirectory); } private record Context( CanonicalHostingSubscriptionTestFixture.Fixture fixture, AccountTenantAuthorityEventRepository events, - AccountDemoTenantEntitlementRepository demos) { + AccountDemoTenantEntitlementRepository demos, + Path invoiceCheckoutDirectory) { private SourceSelection select() { return Objects.requireNonNull( fixture @@ -322,24 +326,10 @@ private DemoTenantEntitlementSnapshot provisionDemo( } private UUID activatePaid() { - var claim = - fixture - .service() - .claimProvisioning(fixture.creation().requestId(), 1L, UUID.randomUUID()) - .claim(); - UUID requestId = UUID.randomUUID(); - assertThat( - fixture - .service() - .reconcile( - requestId, - fixture.creation().requestId(), - claim.subscriptionRowVersion(), - fixture.providerId(), - claim.attemptId()) - .outcome()) - .isEqualTo(Outcome.COMMITTED); - return requestId; + return fixture + .withCheckoutDirectory(invoiceCheckoutDirectory) + .completeFirstInvoice() + .requestId(); } } } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityIncrementalConservationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityIncrementalConservationPostgresIntegrationTest.java new file mode 100644 index 0000000000..5e1f2d2a79 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityIncrementalConservationPostgresIntegrationTest.java @@ -0,0 +1,785 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static integration.net.firedevops.firemud.accountservice.repository.AccountTenantCapacityMigrationPostgresIntegrationTest.capacityFreshnessTableImages; +import static integration.net.firedevops.firemud.accountservice.repository.AccountTenantCapacityMigrationPostgresIntegrationTest.capacityTableImages; +import static integration.net.firedevops.firemud.accountservice.repository.AccountTenantCapacityMigrationPostgresIntegrationTest.configureFlyway; +import static integration.net.firedevops.firemud.accountservice.repository.AccountTenantCapacityMigrationPostgresIntegrationTest.hex; +import static integration.net.firedevops.firemud.accountservice.repository.AccountTenantCapacityMigrationPostgresIntegrationTest.populateCapacity; +import static integration.net.firedevops.firemud.accountservice.repository.AccountTenantCapacityMigrationPostgresIntegrationTest.sqlState; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import integration.net.firedevops.firemud.accountservice.repository.AccountTenantCapacityMigrationPostgresIntegrationTest.CapacityFixture; +import java.util.List; +import java.util.Locale; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +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.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; + +/** Physical forward upgrade and unchanged application-style usage/reservation composition. */ +class AccountTenantCapacityIncrementalConservationPostgresIntegrationTest { + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + + @BeforeAll + static void start() { + POSTGRES.start(); + } + + @AfterAll + static void stop() { + POSTGRES.stop(); + } + + @Test + void emptyAndPopulated1043UpgradePreservesSourceRowsAndHistoryAndSeedsExactConservation() { + for (boolean populated : List.of(false, true)) { + try (Database database = database("1043")) { + DSLContext dsl = database.dsl(); + if (populated) { + CapacityFixture capacity = populateCapacity(dsl, database.transaction()); + addFinalizedHistory(database, capacity, 16); + database + .transaction() + .executeWithoutResult(status -> { + CapacityFixture released = insertReservation(dsl, capacity, 2); + changeUsage(dsl, capacity, 2, 0); + settle(dsl, released, "RELEASED"); + changeUsage(dsl, capacity, -2, 0); + CapacityFixture quarantined = insertReservation(dsl, capacity, 4); + changeUsage(dsl, capacity, 4, 0); + quarantine(dsl, quarantined); + insertReservation(dsl, capacity, 0); + }); + } + List rows = capacityImage(dsl); + List history = historyImages(dsl); + List triggers = triggerImages(dsl); + + var flyway = configureFlyway(database.data(), database.schema(), "1044"); + flyway.migrate(); + + assertThat(capacityImage(dsl)).isEqualTo(rows); + assertThat(historyImages(dsl)).isEqualTo(history); + assertThat(triggerImages(dsl)).containsAll(triggers); + assertThat(flyway.validateWithResult().validationSuccessful).isTrue(); + assertThat(flyway.getConfiguration().isOutOfOrder()).isFalse(); + assertThat(flyway.getConfiguration().isValidateOnMigrate()).isTrue(); + assertThat(dsl.fetchCount(DSL.table("account_tenant_capacity_conservation"))) + .isEqualTo(populated ? 2 : 0); + assertConserved(dsl); + assertBoundedFunctions(dsl); + } + } + } + + @Test + void forwardUpgradeOrdersReservationDeltasBeforeImmediateChecksWithoutChangingDeferral() { + try (Database database = database("1046.9")) { + DSLContext dsl = database.dsl(); + CapacityFixture capacity = populateCapacity(dsl, database.transaction()); + List capacityBefore = capacityImage(dsl); + List conservationBefore = conservationImages(dsl); + List triggersBefore = triggerImages(dsl); + List historyBefore = historyImages(dsl); + + var flyway = configureFlyway(database.data(), database.schema(), "1046.9.0.1"); + assertThat(flyway.migrate().migrationsExecuted).isEqualTo(1); + assertThat(flyway.validateWithResult().validationSuccessful).isTrue(); + assertThat(capacityImage(dsl)).isEqualTo(capacityBefore); + assertThat(conservationImages(dsl)).isEqualTo(conservationBefore); + assertThat(historyImages(dsl)).startsWith(historyBefore.toArray(String[]::new)); + assertThat(triggerImages(dsl)) + .containsExactlyInAnyOrderElementsOf( + triggersBefore.stream() + .map(definition -> + definition.replace( + "account_tenant_capacity_reservation_conservation_", + "account_tenant_capacity_reservation_aggregate_")) + .toList()); + + database + .transaction() + .executeWithoutResult(status -> { + dsl.execute( + "SET CONSTRAINTS account_tenant_capacity_reservation_complete_insert, " + + "account_tenant_capacity_reservation_complete_update IMMEDIATE"); + changeUsage(dsl, capacity, 2, 0); + CapacityFixture held = insertReservation(dsl, capacity, 2); + assertConserved(dsl); + changeUsage(dsl, capacity, -2, 2); + settle(dsl, held, "FINALIZED"); + assertConserved(dsl); + }); + assertConserved(dsl); + } + } + + @Test + void lockedUpgradeRefusesHeldOrUsedDriftWithoutRepairingRowsOrHistory() { + for (String column : List.of("held_units", "used_units")) { + try (Database database = database("1043")) { + DSLContext dsl = database.dsl(); + CapacityFixture capacity = populateCapacity(dsl, database.transaction()); + // Deliberately corrupt only the disposable predecessor fixture. The upgrade must not + // silently trust usage, repair history, or bless a guessed conservation baseline. + database + .transaction() + .executeWithoutResult(status -> { + dsl.execute( + "ALTER TABLE account_tenant_capacity_usage DISABLE TRIGGER account_tenant_capacity_usage_complete"); + dsl.execute( + "UPDATE account_tenant_capacity_usage SET " + + column + + " = " + + column + + " + 1, usage_revision = usage_revision + 1 WHERE tenant_uuid = ? AND owner_service = 'game-session-service'", + capacity.tenantUuid()); + dsl.execute( + "ALTER TABLE account_tenant_capacity_usage ENABLE TRIGGER account_tenant_capacity_usage_complete"); + }); + List rows = capacityImage(dsl); + List history = historyImages(dsl); + assertThatThrownBy( + () -> configureFlyway(database.data(), database.schema(), "1044").migrate()) + .satisfies(failure -> assertThat(sqlState(failure)).isEqualTo("23514")) + .hasStackTraceContaining( + "Capacity conservation upgrade refuses inconsistent durable reservation inventory"); + assertThat(capacityImage(dsl)).isEqualTo(rows); + assertThat(historyImages(dsl)).isEqualTo(history); + assertThat( + dsl.fetchSingle("SELECT to_regclass('account_tenant_capacity_conservation')") + .get(0)) + .isNull(); + assertThat(function(dsl, "account_tenant_capacity_exact_usage")) + .contains("sum(capacity_delta)"); + assertThat( + configureFlyway(database.data(), database.schema(), "1043") + .validateWithResult() + .validationSuccessful) + .isTrue(); + } + } + } + + @Test + void freshBootstrapAndAllExistingTransitionKindsConserveWithoutApplicationChanges() { + try (Database database = database("1044")) { + DSLContext dsl = database.dsl(); + // Real existing bootstrap trigger nesting creates two zero aggregates before reservation. + CapacityFixture capacity = populateCapacity(dsl, database.transaction()); + database + .transaction() + .executeWithoutResult(status -> { + CapacityFixture finalized = insertReservation(dsl, capacity, 2); + changeUsage(dsl, capacity, 2, 0); + settle(dsl, finalized, "FINALIZED"); + changeUsage(dsl, capacity, -2, 2); + CapacityFixture released = insertReservation(dsl, capacity, 4); + changeUsage(dsl, capacity, 4, 0); + settle(dsl, released, "RELEASED"); + changeUsage(dsl, capacity, -4, 0); + settle(dsl, insertReservation(dsl, capacity, 0), "FINALIZED"); + settle(dsl, insertReservation(dsl, capacity, 0), "RELEASED"); + quarantine(dsl, insertReservation(dsl, capacity, 0)); + CapacityFixture quarantined = insertReservation(dsl, capacity, 5); + changeUsage(dsl, capacity, 5, 0); + quarantine(dsl, quarantined); + }); + assertConserved(dsl); + assertUsage(dsl, capacity, 8, 2); + + List aggregate = conservationImages(dsl); + database + .transaction() + .executeWithoutResult(status -> { + dsl.execute( + "UPDATE account_tenant_capacity_reservations SET recovery_owner = ?, " + + "recovery_claim_fence = 1, recovery_claim_expires_at = CURRENT_TIMESTAMP + INTERVAL '1 minute', " + + "execution_status = 'NOT_EXECUTED_AFTER_AUTHORIZATION', owner_readback = ?, owner_readback_digest = ? " + + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?", + UUID.randomUUID(), + new byte[] {1}, + hex('5'), + capacity.tenantUuid(), + capacity.requestId(), + capacity.admissionId()); + UUID rearmedAttempt = UUID.randomUUID(); + String rearmedDigest = hex('6'); + byte[] rearmedPayload = new byte[] {2}; + insertOriginDecision( + dsl, + capacity.tenantUuid(), + capacity.requestId(), + capacity.admissionId(), + 2, + rearmedAttempt, + rearmedDigest, + rearmedPayload); + dsl.execute( + "INSERT INTO account_tenant_capacity_attempt_history " + + "(tenant_uuid, request_id, admission_id, admission_attempt_id, capacity_rearm_fence, mutation_digest, canonical_payload, owner_readback) " + + "SELECT tenant_uuid, request_id, admission_id, admission_attempt_id, capacity_rearm_fence, mutation_digest, canonical_payload, owner_readback " + + "FROM account_tenant_capacity_reservations WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?", + capacity.tenantUuid(), + capacity.requestId(), + capacity.admissionId()); + dsl.execute( + "UPDATE account_tenant_capacity_reservations SET admission_attempt_id = ?, " + + "capacity_rearm_fence = capacity_rearm_fence + 1, reservation_fence = reservation_fence + 1, " + + "mutation_digest = ?, canonical_payload = ?, execution_status = 'OWNER_EXECUTION_PENDING', " + + "owner_readback = NULL, owner_readback_digest = NULL WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?", + rearmedAttempt, + rearmedDigest, + rearmedPayload, + capacity.tenantUuid(), + capacity.requestId(), + capacity.admissionId()); + }); + assertThat(conservationImages(dsl)).isEqualTo(aggregate); + assertUsage(dsl, capacity, 8, 2); + assertConserved(dsl); + } + } + + @Test + void forgedUsageAndEveryDirectAggregateMutationRefuseAndRollbackIsAtomic() { + try (Database database = database("1044")) { + DSLContext dsl = database.dsl(); + CapacityFixture capacity = populateCapacity(dsl, database.transaction()); + List rows = capacityImage(dsl); + List aggregate = conservationImages(dsl); + for (String statement : + List.of( + "UPDATE account_tenant_capacity_conservation SET held_units = held_units + 1 WHERE tenant_uuid = ?", + "UPDATE account_tenant_capacity_conservation SET held_units = held_units WHERE tenant_uuid = ?", + "DELETE FROM account_tenant_capacity_conservation WHERE tenant_uuid = ?", + "INSERT INTO account_tenant_capacity_conservation VALUES (?, 'game-session-service', 0, 0)")) { + assertThatThrownBy(() -> + database + .transaction() + .executeWithoutResult(status -> dsl.execute(statement, capacity.tenantUuid()))) + .satisfies(failure -> assertThat(sqlState(failure)).isEqualTo("23514")); + } + assertThatThrownBy(() -> + database + .transaction() + .executeWithoutResult( + status -> dsl.execute("TRUNCATE account_tenant_capacity_conservation"))) + .satisfies(failure -> assertThat(sqlState(failure)).isEqualTo("23514")); + assertThatThrownBy(() -> + database + .transaction() + .executeWithoutResult(status -> changeUsage(dsl, capacity, 1, 0))) + .satisfies( + AccountTenantCapacityIncrementalConservationPostgresIntegrationTest + ::assertConservationRefusal); + assertThatThrownBy(() -> + database + .transaction() + .executeWithoutResult(status -> insertReservation(dsl, capacity, 1))) + .satisfies( + AccountTenantCapacityIncrementalConservationPostgresIntegrationTest + ::assertConservationRefusal); + assertThatThrownBy(() -> + database + .transaction() + .executeWithoutResult(status -> settle(dsl, capacity, "FINALIZED"))) + .satisfies( + AccountTenantCapacityIncrementalConservationPostgresIntegrationTest + ::assertConservationRefusal); + assertThatThrownBy(() -> + database + .transaction() + .executeWithoutResult(status -> { + changeUsage(dsl, capacity, 1, 0); + insertReservation(dsl, capacity, 1); + dsl.execute("SET CONSTRAINTS ALL IMMEDIATE"); + throw new IllegalStateException("deliberate owner rollback"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessage("deliberate owner rollback"); + assertThat(capacityImage(dsl)).isEqualTo(rows); + assertThat(conservationImages(dsl)).isEqualTo(aggregate); + assertConserved(dsl); + } + } + + @Test + void concurrentReservationsSerializeAndAnUnbalancedWriterCannotPoisonConservation() + throws Exception { + try (Database database = database("1044"); + var workers = Executors.newFixedThreadPool(2)) { + CapacityFixture capacity = populateCapacity(database.dsl(), database.transaction()); + runContendedReservationPhase(database, capacity, workers, 2, true); + assertUsage(database.dsl(), capacity, 6, 0); + assertConserved(database.dsl()); + + runContendedReservationPhase(database, capacity, workers, 2, false); + assertUsage(database.dsl(), capacity, 7, 0); + assertConserved(database.dsl()); + } + } + + @Test + void finalizedHistoryIsNotReadByNewHoldsFinalizationOrMetadataChecks() { + try (Database database = database("1044")) { + DSLContext dsl = database.dsl(); + CapacityFixture capacity = populateCapacity(dsl, database.transaction()); + addFinalizedHistory(database, capacity, 4096); + dsl.execute("VACUUM (ANALYZE) account_tenant_capacity_reservations"); + assertIndexOnlyHistoryDetected(database, capacity); + assertBoundedFunctions(dsl); + database + .transaction() + .executeWithoutResult(status -> { + long before = reservationRowsRead(dsl); + changeUsage(dsl, capacity, 1, 0); + CapacityFixture next = insertReservation(dsl, capacity, 1); + dsl.execute("SET CONSTRAINTS ALL IMMEDIATE"); + assertThat(reservationRowsRead(dsl) - before).isLessThanOrEqualTo(8L); + // Restore deferred scheduling so the unchanged application may write usage first. + dsl.execute("SET CONSTRAINTS ALL DEFERRED"); + before = reservationRowsRead(dsl); + changeUsage(dsl, capacity, -1, 1); + settle(dsl, next, "FINALIZED"); + dsl.execute("SET CONSTRAINTS ALL IMMEDIATE"); + assertThat(reservationRowsRead(dsl) - before).isLessThanOrEqualTo(8L); + }); + List aggregate = conservationImages(dsl); + database + .transaction() + .executeWithoutResult(status -> { + long before = reservationRowsRead(dsl); + changeUsage(dsl, capacity, 1, 0); + dsl.execute( + "UPDATE account_tenant_capacity_reservations SET recovery_owner = ?, recovery_claim_fence = 1, " + + "recovery_claim_expires_at = CURRENT_TIMESTAMP + INTERVAL '1 minute' " + + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?", + UUID.randomUUID(), + capacity.tenantUuid(), + capacity.requestId(), + capacity.admissionId()); + dsl.execute( + "SET CONSTRAINTS account_tenant_capacity_reservation_complete_update IMMEDIATE"); + changeUsage(dsl, capacity, -1, 0); + dsl.execute("SET CONSTRAINTS ALL IMMEDIATE"); + assertThat(reservationRowsRead(dsl) - before).isLessThanOrEqualTo(8L); + }); + assertThat(conservationImages(dsl)).isEqualTo(aggregate); + assertUsage(dsl, capacity, 3, 4097); + assertConserved(dsl); + } + } + + private static void addFinalizedHistory(Database database, CapacityFixture capacity, int count) { + DSLContext dsl = database.dsl(); + database + .transaction() + .executeWithoutResult(status -> { + changeUsage(dsl, capacity, count, 0); + for (int index = 0; index < count; index++) { + UUID requestId = UUID.randomUUID(); + UUID admissionId = UUID.randomUUID(); + UUID attemptId = UUID.randomUUID(); + String mutationDigest = hex('9'); + byte[] canonicalPayload = new byte[] {9}; + insertOriginDecision( + dsl, + capacity.tenantUuid(), + requestId, + admissionId, + 1, + attemptId, + mutationDigest, + canonicalPayload); + dsl.execute( + "INSERT INTO account_tenant_capacity_reservations " + + "(tenant_uuid, request_id, admission_id, reservation_id, owner_service, caller_workload, admission_attempt_id, " + + "capacity_rearm_fence, reservation_fence, mutation_digest, canonical_payload, evaluation_identity, capacity_delta, " + + "expires_at, state, execution_status, reconcile_deadline) " + + "VALUES (?, ?, ?, ?, 'game-session-service', ?, ?, 1, 1, ?, ?, ?, 1, " + + "CURRENT_TIMESTAMP + INTERVAL '5 minutes', 'RESERVED', 'OWNER_EXECUTION_PENDING', " + + "CURRENT_TIMESTAMP + INTERVAL '10 minutes')", + capacity.tenantUuid(), + requestId, + admissionId, + UUID.randomUUID(), + capacity.callerWorkload(), + attemptId, + mutationDigest, + canonicalPayload, + capacity.evaluationIdentity()); + } + changeUsage(dsl, capacity, -count, count); + assertThat( + dsl.execute( + "UPDATE account_tenant_capacity_reservations SET state = 'FINALIZED', execution_status = 'COMMITTED', " + + "recovery_owner = ?, recovery_claim_fence = 1, recovery_claim_expires_at = CURRENT_TIMESTAMP + INTERVAL '1 minute', " + + "owner_readback = ?, owner_readback_digest = ? WHERE tenant_uuid = ? AND mutation_digest = ? AND state = 'RESERVED'", + UUID.randomUUID(), + new byte[] {9}, + hex('9'), + capacity.tenantUuid(), + hex('9'))) + .isEqualTo(count); + }); + } + + private static CapacityFixture insertReservation( + DSLContext dsl, CapacityFixture capacity, long delta) { + UUID request = UUID.randomUUID(), admission = UUID.randomUUID(); + UUID attempt = UUID.randomUUID(); + String mutationDigest = hex('4'); + byte[] canonicalPayload = new byte[] {4}; + insertOriginDecision( + dsl, + capacity.tenantUuid(), + request, + admission, + 1, + attempt, + mutationDigest, + canonicalPayload); + dsl.execute( + "INSERT INTO account_tenant_capacity_reservations " + + "(tenant_uuid, request_id, admission_id, reservation_id, owner_service, caller_workload, admission_attempt_id, " + + "capacity_rearm_fence, reservation_fence, mutation_digest, canonical_payload, evaluation_identity, capacity_delta, " + + "expires_at, state, execution_status, reconcile_deadline) " + + "VALUES (?, ?, ?, ?, 'game-session-service', ?, ?, 1, 1, ?, ?, ?, ?, CURRENT_TIMESTAMP + INTERVAL '5 minutes', " + + "'RESERVED', 'OWNER_EXECUTION_PENDING', CURRENT_TIMESTAMP - INTERVAL '1 second')", + capacity.tenantUuid(), + request, + admission, + UUID.randomUUID(), + capacity.callerWorkload(), + attempt, + mutationDigest, + canonicalPayload, + capacity.evaluationIdentity(), + delta); + return new CapacityFixture( + capacity.tenantUuid(), + request, + admission, + capacity.evaluationIdentity(), + capacity.callerWorkload()); + } + + private static void insertOriginDecision( + DSLContext dsl, + UUID tenantUuid, + UUID requestId, + UUID admissionId, + long rearmFence, + UUID attemptId, + String mutationDigest, + byte[] canonicalPayload) { + dsl.execute( + "INSERT INTO account_capacity_origin_decisions " + + "(tenant_uuid, request_id, admission_id, capacity_rearm_fence, admission_attempt_id, " + + "mutation_digest, canonical_payload, decision, decision_id) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, 'ACCEPTED', ?)", + tenantUuid, + requestId, + admissionId, + rearmFence, + attemptId, + mutationDigest, + canonicalPayload, + UUID.randomUUID()); + } + + private static void settle(DSLContext dsl, CapacityFixture capacity, String state) { + dsl.execute( + "UPDATE account_tenant_capacity_reservations SET state = ?, execution_status = ?, " + + "recovery_owner = ?, recovery_claim_fence = 1, recovery_claim_expires_at = CURRENT_TIMESTAMP + INTERVAL '1 minute', " + + "reservation_fence = reservation_fence + ?, owner_readback = ?, owner_readback_digest = ? " + + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?", + state, + state.equals("FINALIZED") ? "COMMITTED" : "NOT_EXECUTED_AFTER_AUTHORIZATION", + UUID.randomUUID(), + state.equals("RELEASED") ? 1 : 0, + new byte[] {5}, + hex('5'), + capacity.tenantUuid(), + capacity.requestId(), + capacity.admissionId()); + } + + private static void quarantine(DSLContext dsl, CapacityFixture capacity) { + dsl.execute( + "UPDATE account_tenant_capacity_reservations SET state = 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION', " + + "recovery_owner = ?, recovery_claim_fence = 1, recovery_claim_expires_at = CURRENT_TIMESTAMP + INTERVAL '1 minute', " + + "recovery_escalated_at = CURRENT_TIMESTAMP, next_reconcile_at = NULL " + + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?", + UUID.randomUUID(), + capacity.tenantUuid(), + capacity.requestId(), + capacity.admissionId()); + } + + private static void changeUsage(DSLContext dsl, CapacityFixture capacity, long held, long used) { + assertThat( + dsl.execute( + "UPDATE account_tenant_capacity_usage SET held_units = held_units + ?, used_units = used_units + ?, " + + "usage_revision = usage_revision + 1 WHERE tenant_uuid = ? AND owner_service = 'game-session-service'", + held, + used, + capacity.tenantUuid())) + .isEqualTo(1); + } + + private static void assertUsage(DSLContext dsl, CapacityFixture capacity, long held, long used) { + var usage = + dsl.fetchSingle( + "SELECT held_units, used_units FROM account_tenant_capacity_usage " + + "WHERE tenant_uuid = ? AND owner_service = 'game-session-service'", + capacity.tenantUuid()); + assertThat(usage.get("held_units", Long.class)).isEqualTo(held); + assertThat(usage.get("used_units", Long.class)).isEqualTo(used); + } + + private static void assertConserved(DSLContext dsl) { + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM account_tenant_capacity_usage usage " + + "FULL JOIN account_tenant_capacity_conservation conserved USING (tenant_uuid, owner_service) " + + "FULL JOIN (SELECT tenant_uuid, owner_service, COALESCE(sum(capacity_delta) FILTER " + + "(WHERE state IN ('RESERVED', 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION')), 0) AS held_units, " + + "COALESCE(sum(capacity_delta) FILTER (WHERE state = 'FINALIZED'), 0) AS used_units " + + "FROM account_tenant_capacity_reservations GROUP BY tenant_uuid, owner_service) inventory USING (tenant_uuid, owner_service) " + + "WHERE usage.tenant_uuid IS NULL OR conserved.tenant_uuid IS NULL " + + "OR usage.held_units IS DISTINCT FROM conserved.held_units OR usage.used_units IS DISTINCT FROM conserved.used_units " + + "OR usage.held_units IS DISTINCT FROM COALESCE(inventory.held_units, 0) " + + "OR usage.used_units IS DISTINCT FROM COALESCE(inventory.used_units, 0)") + .get(0, Integer.class)) + .isZero(); + } + + private static void assertConservationRefusal(Throwable failure) { + assertThat(sqlState(failure)).isEqualTo("23514"); + assertThat(failure) + .hasStackTraceContaining( + "Capacity usage differs from its protected reservation conservation"); + } + + private static void assertBoundedFunctions(DSLContext dsl) { + assertThat(function(dsl, "account_tenant_capacity_exact_usage")) + .contains("account_tenant_capacity_conservation") + .doesNotContain("account_tenant_capacity_reservations", "sum("); + assertThat(function(dsl, "account_tenant_capacity_conservation_delta")) + .doesNotContain("FROM account_tenant_capacity_reservations", "sum("); + String updateTrigger = + Objects.requireNonNull( + dsl.fetchSingle( + "SELECT pg_get_triggerdef(oid) FROM pg_trigger " + + "WHERE tgrelid = 'account_tenant_capacity_reservations'::regclass " + + "AND tgname = 'account_tenant_capacity_reservation_conservation_update'") + .get(0, String.class)); + assertThat( + updateTrigger + .toLowerCase(Locale.ROOT) + .replace("::text", "") + .replace("(", "") + .replace(")", "")) + .contains("old.state is distinct from new.state"); + } + + private static String function(DSLContext dsl, String name) { + return Objects.requireNonNull( + dsl.fetchSingle("SELECT pg_get_functiondef(?::regprocedure)", name + "()") + .get(0, String.class)); + } + + private static void assertIndexOnlyHistoryDetected(Database database, CapacityFixture capacity) { + DSLContext dsl = database.dsl(); + database + .transaction() + .executeWithoutResult(status -> { + dsl.execute("SET LOCAL enable_seqscan = off"); + dsl.execute("SET LOCAL enable_bitmapscan = off"); + dsl.execute("SET LOCAL max_parallel_workers_per_gather = 0"); + long before = reservationRowsRead(dsl); + List plan = + dsl.fetch( + "EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF) SELECT count(request_id) " + + "FROM account_tenant_capacity_reservations WHERE tenant_uuid = ?", + capacity.tenantUuid()) + .getValues(0, String.class); + assertThat(plan).anyMatch(line -> line.contains("Index Only Scan")); + assertThat(plan).anyMatch(line -> line.trim().equals("Heap Fetches: 0")); + assertThat(reservationRowsRead(dsl) - before) + .as("the bounded-work oracle must detect the index-only history scan") + .isGreaterThanOrEqualTo(4096L); + }); + } + + private static long reservationRowsRead(DSLContext dsl) { + return Objects.requireNonNull( + dsl.fetchSingle( + "SELECT seq_tup_read + idx_tup_fetch + " + + "(SELECT COALESCE(SUM(pg_stat_get_xact_tuples_returned(indexrelid)), 0) " + + "FROM pg_index WHERE indrelid = stats.relid) " + + "FROM pg_stat_xact_user_tables stats " + + "WHERE relid = 'account_tenant_capacity_reservations'::regclass") + .get(0, Long.class)); + } + + private static List conservationImages(DSLContext dsl) { + return dsl.fetch( + "SELECT (to_jsonb(row_data) || jsonb_build_object('_original_xmin', row_data.xmin::text))::text AS image " + + "FROM account_tenant_capacity_conservation row_data ORDER BY tenant_uuid, owner_service") + .getValues("image", String.class); + } + + private static List historyImages(DSLContext dsl) { + return dsl.fetch( + "SELECT (to_jsonb(history) || jsonb_build_object('_original_xmin', history.xmin::text))::text AS image " + + "FROM flyway_schema_history history WHERE version IS DISTINCT FROM '1044' ORDER BY installed_rank") + .getValues("image", String.class); + } + + private static List triggerImages(DSLContext dsl) { + return dsl.fetch( + "SELECT pg_get_triggerdef(oid) AS definition FROM pg_trigger WHERE NOT tgisinternal " + + "AND tgrelid IN ('account_tenant_capacity_usage'::regclass, 'account_tenant_capacity_reservations'::regclass) ORDER BY tgname") + .getValues("definition", String.class); + } + + private static void runContendedReservationPhase( + Database database, + CapacityFixture capacity, + ExecutorService workers, + int contenderAmount, + boolean balanced) + throws Exception { + CountDownLatch firstHoldsUsage = new CountDownLatch(1); + CountDownLatch releaseFirst = new CountDownLatch(1); + CountDownLatch contenderConnected = new CountDownLatch(1); + var firstPid = new AtomicInteger(); + var contenderPid = new AtomicInteger(); + DSLContext dsl = database.dsl(); + var first = + workers.submit(() -> + database + .transaction() + .executeWithoutResult(status -> { + firstPid.set(backendPid(dsl)); + changeUsage(dsl, capacity, 1, 0); + insertReservation(dsl, capacity, 1); + firstHoldsUsage.countDown(); + await(releaseFirst); + })); + try { + await(firstHoldsUsage); + Runnable contend = + () -> + database + .transaction() + .executeWithoutResult(status -> { + contenderPid.set(backendPid(dsl)); + contenderConnected.countDown(); + if (balanced) { + changeUsage(dsl, capacity, contenderAmount, 0); + } + insertReservation(dsl, capacity, contenderAmount); + dsl.execute("SET CONSTRAINTS ALL IMMEDIATE"); + }); + var second = + workers.submit(() -> { + if (balanced) { + contend.run(); + } else { + assertThatThrownBy(contend::run) + .satisfies( + AccountTenantCapacityIncrementalConservationPostgresIntegrationTest + ::assertConservationRefusal); + } + }); + try { + await(contenderConnected); + assertThat(contenderPid.get()).isNotEqualTo(firstPid.get()); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (!blocks(dsl, firstPid.get(), contenderPid.get()) && System.nanoTime() < deadline) { + if (second.isDone()) { + break; + } + Thread.sleep(20); + } + assertThat(blocks(dsl, firstPid.get(), contenderPid.get())) + .as("the second PostgreSQL transaction is blocked by the first") + .isTrue(); + } finally { + releaseFirst.countDown(); + } + first.get(30, TimeUnit.SECONDS); + second.get(30, TimeUnit.SECONDS); + } finally { + releaseFirst.countDown(); + } + } + + private static int backendPid(DSLContext dsl) { + return Objects.requireNonNull(dsl.fetchOne("SELECT pg_backend_pid()")).get(0, Integer.class); + } + + private static boolean blocks(DSLContext dsl, int holder, int contender) { + return Boolean.TRUE.equals( + Objects.requireNonNull( + dsl.fetchOne("SELECT ? = ANY(pg_blocking_pids(?))", holder, contender)) + .get(0, Boolean.class)); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) + throw new IllegalStateException("Capacity race did not start"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + } + + private static Database database(String target) { + String schema = "capacity_incremental_" + UUID.randomUUID().toString().replace("-", ""); + new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema); + var data = POSTGRES.dataSource(schema); + configureFlyway(data, schema, target).migrate(); + return new Database( + schema, + data, + DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES), + new TransactionTemplate(new DataSourceTransactionManager(data))); + } + + private static List capacityImage(DSLContext dsl) { + return dsl.fetchSingle("SELECT to_regclass('account_capacity_origin_decisions') IS NOT NULL") + .get(0, Boolean.class) + ? capacityFreshnessTableImages(dsl) + : capacityTableImages(dsl); + } + + private record Database( + String schema, javax.sql.DataSource data, DSLContext dsl, TransactionTemplate transaction) + implements AutoCloseable { + @Override + public void close() { + new JdbcTemplate(POSTGRES.dataSource()).execute("DROP SCHEMA " + schema + " CASCADE"); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java index 2517468270..de2e7c177a 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java @@ -5,9 +5,12 @@ import integration.net.firedevops.firemud.accountservice.AccountTenantCreatorBootstrapIntegrationFixture; import java.nio.charset.StandardCharsets; +import java.sql.SQLException; import java.time.Instant; import java.time.temporal.ChronoUnit; +import java.util.ArrayList; import java.util.List; +import java.util.Locale; import java.util.Objects; import java.util.UUID; import javax.sql.DataSource; @@ -21,6 +24,8 @@ import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.configuration.FluentConfiguration; +import org.jooq.DSLContext; +import org.jooq.Record; import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.AfterAll; @@ -609,6 +614,166 @@ void refusalBudgetRunsAfterIdentityArbitrationAndCountsTheInsertedLastSlot() thr } } + @Test + void paidCutoffUpgradePreservesRetainedEvaluationAndMakesFreshCutoffImmutable() { + String schema = "capacity_paid_cutoff_" + UUID.randomUUID().toString().replace("-", ""); + new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema); + var data = POSTGRES.dataSource(schema); + try { + configureFlyway(data, schema, "1046.9.0.6").migrate(); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); + var transaction = new TransactionTemplate(new DataSourceTransactionManager(data)); + var tenant = source(); + transaction.executeWithoutResult(status -> + new FreshTenantIdentityAssociationRepository(dsl, "prod").importVerified(tenant)); + + String legacyEvaluation = digest('a'); + String freshEvaluation = digest('b'); + String caller = "spiffe://firemud/ns/prod/sa/game-session-service"; + Instant evaluatedAt = Instant.parse("2026-11-02T00:00:00Z"); + var databaseExpiry = AccountTenantCapacityRepository.at(evaluatedAt.plusSeconds(30)); + var originalCutoff = + AccountTenantCapacityRepository.at(evaluatedAt.plusSeconds(43).plusNanos(123_456_000)); + dsl.execute( + "INSERT INTO account_tenant_capacity_evaluations (evaluation_identity, snapshot_identity," + + " tenant_uuid, caller_workload, owner_service, canonical_evidence, evaluated_at," + + " expires_at) VALUES (?, ?, ?, ?, 'game-session-service', ?, ?::timestamptz," + + " ?::timestamptz)", + legacyEvaluation, + digest('c'), + tenant.canonicalTenantId(), + caller, + new byte[] {10, 0, 12}, + AccountTenantCapacityRepository.at(evaluatedAt), + databaseExpiry); + String legacyRowSql = + "SELECT ((to_jsonb(evaluation) - 'original_paid_cutoff')" + + " || jsonb_build_object('_original_xmin', evaluation.xmin::text))::text" + + " FROM account_tenant_capacity_evaluations evaluation WHERE evaluation_identity = ?"; + String priorHistorySql = + "SELECT (to_jsonb(history)" + + " || jsonb_build_object('_original_xmin', history.xmin::text))::text AS image" + + " FROM flyway_schema_history history WHERE version IS DISTINCT FROM '1046.9.0.7'" + + " ORDER BY installed_rank"; + var legacyRow = dsl.fetchSingle(legacyRowSql, legacyEvaluation).get(0, String.class); + var priorHistory = dsl.fetch(priorHistorySql).getValues("image", String.class); + assertThat(priorHistory).isNotEmpty(); + + var successor = configureFlyway(data, schema, "1046.9.0.7"); + assertThat(successor.migrate().migrationsExecuted).isEqualTo(1); + assertThat(successor.validateWithResult().validationSuccessful).isTrue(); + assertThat(dsl.fetch(priorHistorySql).getValues("image", String.class)) + .isEqualTo(priorHistory); + assertThat(dsl.fetchSingle(legacyRowSql, legacyEvaluation).get(0, String.class)) + .isEqualTo(legacyRow); + + String cutoffSql = + "SELECT original_paid_cutoff FROM account_tenant_capacity_evaluations" + + " WHERE evaluation_identity = ?"; + assertThat(dsl.fetchSingle(cutoffSql, legacyEvaluation).get(0)).isNull(); + + assertThat( + dsl.execute( + "INSERT INTO account_tenant_capacity_evaluations (evaluation_identity," + + " snapshot_identity, tenant_uuid, caller_workload, owner_service," + + " canonical_evidence, evaluated_at, expires_at, original_paid_cutoff)" + + " VALUES (?, ?, ?, ?, 'game-session-service', ?, ?::timestamptz," + + " ?::timestamptz, ?::timestamptz)", + freshEvaluation, + digest('d'), + tenant.canonicalTenantId(), + caller, + new byte[] {13, 0, 14}, + AccountTenantCapacityRepository.at(evaluatedAt), + databaseExpiry, + originalCutoff)) + .isEqualTo(1); + assertThat( + AccountTenantCapacityRepository.time( + dsl.fetchSingle(cutoffSql, freshEvaluation), "original_paid_cutoff")) + .isEqualTo(originalCutoff.toInstant()); + + assertThatThrownBy(() -> + dsl.execute( + "UPDATE account_tenant_capacity_evaluations SET original_paid_cutoff =" + + " ?::timestamptz WHERE evaluation_identity = ?", + originalCutoff.plusSeconds(1), + freshEvaluation)) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> { + assertThat(failure.sqlState()).isEqualTo("23514"); + assertThat(failure) + .hasMessageContaining( + "Capacity evaluation and historical attempt evidence is immutable"); + }); + assertThat( + AccountTenantCapacityRepository.time( + dsl.fetchSingle(cutoffSql, freshEvaluation), "original_paid_cutoff")) + .isEqualTo(originalCutoff.toInstant()); + } finally { + new JdbcTemplate(POSTGRES.dataSource()).execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + + @Test + void freshAndPopulated1040Through1041UpgradesPreserveRowsHistoryAndScopeReservationChecks() { + verify1040Upgrade(false); + verify1040Upgrade(true); + } + + private static void verify1040Upgrade(boolean populated) { + String schema = "capacity_trigger_" + UUID.randomUUID().toString().replace("-", ""); + new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema); + var data = POSTGRES.dataSource(schema); + try { + configureFlyway(data, schema, "1040").migrate(); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); + var transaction = new TransactionTemplate(new DataSourceTransactionManager(data)); + CapacityFixture capacity = populated ? populateCapacity(dsl, transaction) : null; + PredecessorImage before1041 = predecessorImage(dsl); + configureFlyway(data, schema, "1041").migrate(); + assertThat(migrationHistoryImage(dsl)) + .startsWith(before1041.migrationHistoryImage().toArray(String[]::new)); + assertThat(capacityTableImages(dsl)).isEqualTo(before1041.tableImages()); + List after1041Triggers = otherCapacityTriggerImages(dsl); + assertThat(after1041Triggers).containsAll(before1041.otherTriggerImages()); + assertThat(after1041Triggers).hasSize(before1041.otherTriggerImages().size() + 1); + assertThat(after1041Triggers) + .anyMatch(image -> image.contains(":account_capacity_origin_reservation_guard:")); + assertThat(exactUsageFunctionImage(dsl)).isEqualTo(before1041.exactUsageFunctionImage()); + assertThat(migrationChecksum(dsl)).isEqualTo(before1041.migrationChecksum()); + assertThat( + dsl.fetch( + "SELECT version FROM flyway_schema_history WHERE success AND version IN ('1040', '1041') ORDER BY installed_rank") + .getValues("version", String.class)) + .containsExactly("1040", "1041"); + PredecessorImage before = predecessorImage(dsl); + + configureFlyway(data, schema, "1042").migrate(); + + assertThat(migrationHistoryImage(dsl)).isEqualTo(before.migrationHistoryImage()); + assertThat(migrationChecksum(dsl)).isEqualTo(before.migrationChecksum()); + assertThat(capacityTableImages(dsl)).isEqualTo(before.tableImages()); + assertThat(otherCapacityTriggerImages(dsl)).isEqualTo(before.otherTriggerImages()); + assertThat(exactUsageFunctionImage(dsl)).isEqualTo(before.exactUsageFunctionImage()); + assertThat( + dsl.fetch( + "SELECT version FROM flyway_schema_history WHERE success AND version IN ('1040', '1041', '1042') ORDER BY installed_rank") + .getValues("version", String.class)) + .containsExactly("1040", "1041", "1042"); + assertThat(configureFlyway(data, schema, "1042").validateWithResult().validationSuccessful) + .isTrue(); + assertReservationConstraintTriggers(dsl); + + if (populated) { + assertCapacityTriggerBehavior(dsl, transaction, Objects.requireNonNull(capacity)); + } + } finally { + new JdbcTemplate(POSTGRES.dataSource()).execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + @Test void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { String schema = "capacity_refusal_slots_" + UUID.randomUUID().toString().replace("-", ""); @@ -1387,6 +1552,470 @@ private record AcceptedCapacityAttempt( private record RefusalSlot(UUID tenantUuid, long slot, UUID decisionId) {} + static Flyway configureFlyway(javax.sql.DataSource data, String schema, String target) { + return Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .placeholders(java.util.Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target(target) + .load(); + } + + private static PredecessorImage predecessorImage(DSLContext dsl) { + return new PredecessorImage( + migrationHistoryImage(dsl), + migrationChecksum(dsl), + capacityTableImages(dsl), + otherCapacityTriggerImages(dsl), + exactUsageFunctionImage(dsl)); + } + + private static List migrationHistoryImage(DSLContext dsl) { + return List.copyOf( + dsl.fetch( + "SELECT (to_jsonb(history) || jsonb_build_object('_original_xmin', history.xmin::text))::text AS history_image " + + "FROM flyway_schema_history history WHERE version IS DISTINCT FROM '1042' ORDER BY installed_rank") + .getValues("history_image", String.class)); + } + + private static Integer migrationChecksum(DSLContext dsl) { + return Objects.requireNonNull( + dsl.fetchSingle("SELECT checksum FROM flyway_schema_history WHERE version = '1040'") + .get(0, Integer.class)); + } + + static List capacityTableImages(DSLContext dsl) { + List images = new ArrayList<>(); + for (String table : + List.of( + "accounts", + "account_canonical_tenant_identity_claims", + "account_fresh_tenant_identity_associations", + "account_tenant_creation_bootstrap_operations", + "account_tenant_capacity_usage", + "account_tenant_capacity_evaluations", + "account_tenant_capacity_reservations", + "account_tenant_capacity_attempt_history", + "account_tenant_capacity_recovery_evidence")) { + appendCapacityTableImage(dsl, table, images); + } + return List.copyOf(images); + } + + static List capacityFreshnessTableImages(DSLContext dsl) { + List images = new ArrayList<>(capacityTableImages(dsl)); + appendCapacityTableImage(dsl, "account_capacity_origin_decisions", images); + return List.copyOf(images); + } + + private static void appendCapacityTableImage(DSLContext dsl, String table, List images) { + images.add(table); + images.addAll( + dsl.fetch( + "SELECT (to_jsonb(row_data) || jsonb_build_object('_original_xmin', row_data.xmin::text))::text AS row_image " + + "FROM " + + table + + " row_data ORDER BY row_image") + .getValues("row_image", String.class)); + } + + private static List otherCapacityTriggerImages(DSLContext dsl) { + return List.copyOf( + dsl.fetch( + "SELECT relation.relname || ':' || t.tgname || ':' || t.tgenabled::text || ':' " + + "|| t.tgdeferrable::text || ':' || t.tginitdeferred::text || ':' " + + "|| pg_get_triggerdef(t.oid) AS trigger_image " + + "FROM pg_trigger t JOIN pg_class relation ON relation.oid = t.tgrelid " + + "JOIN pg_namespace namespace ON namespace.oid = relation.relnamespace " + + "WHERE namespace.nspname = current_schema() AND NOT t.tgisinternal " + + "AND relation.relname IN ('account_tenant_capacity_usage', " + + "'account_tenant_capacity_evaluations', 'account_tenant_capacity_reservations', " + + "'account_tenant_capacity_attempt_history', 'account_tenant_capacity_recovery_evidence') " + + "AND t.tgname NOT LIKE 'account_tenant_capacity_reservation_complete%' " + + "ORDER BY relation.relname, t.tgname") + .getValues("trigger_image", String.class)); + } + + private static String exactUsageFunctionImage(DSLContext dsl) { + return Objects.requireNonNull( + dsl.fetchSingle( + "SELECT pg_get_functiondef('account_tenant_capacity_exact_usage()'::regprocedure)") + .get(0, String.class)); + } + + private static void assertReservationConstraintTriggers(DSLContext dsl) { + assertReservationConstraintTrigger( + dsl, "account_tenant_capacity_reservation_complete_insert", "after insert", null); + assertReservationConstraintTrigger( + dsl, + "account_tenant_capacity_reservation_complete_update", + "after update", + "old.state is distinct from new.state"); + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM pg_trigger WHERE tgrelid = " + + "'account_tenant_capacity_reservations'::regclass " + + "AND NOT tgisinternal AND tgname LIKE " + + "'account_tenant_capacity_reservation_complete%'") + .get(0, Integer.class)) + .isEqualTo(2); + } + + private static void assertReservationConstraintTrigger( + DSLContext dsl, String name, String event, String condition) { + Record trigger = + Objects.requireNonNull( + dsl.fetchSingle( + "SELECT tgdeferrable, tginitdeferred, pg_get_triggerdef(oid) AS definition " + + "FROM pg_trigger WHERE tgrelid = 'account_tenant_capacity_reservations'::regclass " + + "AND NOT tgisinternal AND tgname = ?", + name)); + assertThat(trigger.get("tgdeferrable", Boolean.class)).isTrue(); + assertThat(trigger.get("tginitdeferred", Boolean.class)).isTrue(); + String definition = trigger.get("definition", String.class).toLowerCase(Locale.ROOT); + assertThat(definition).contains(event); + assertThat(definition).contains("execute function account_tenant_capacity_exact_usage()"); + if (condition != null) { + assertThat(definition.replace("::text", "").replace("(", "").replace(")", "")) + .contains(condition); + } + } + + static CapacityFixture populateCapacity(DSLContext dsl, TransactionTemplate transaction) { + UUID accountUuid = + Objects.requireNonNull( + transaction.execute(status -> + dsl.fetchSingle( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) " + + "RETURNING account_uuid", + "capacity-" + UUID.randomUUID(), + "capacity-" + UUID.randomUUID() + "@example.test", + "test-password") + .get(0, UUID.class))); + FreshTenantCreationEvidence tenant = source(); + UUID bootstrapRequest = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + UUID admissionId = UUID.randomUUID(); + String evaluationIdentity = digest('a'); + String callerWorkload = "spiffe://firemud.test/account/game-session-service"; + + transaction.executeWithoutResult(status -> { + new FreshTenantIdentityAssociationRepository(dsl, "prod").importVerified(tenant); + UUID attemptId = UUID.randomUUID(); + String mutationDigest = hex('c'); + byte[] canonicalPayload = new byte[] {8}; + insertOriginDecisionIfPresent( + dsl, + tenant.canonicalTenantId(), + requestId, + admissionId, + 1, + attemptId, + mutationDigest, + canonicalPayload); + dsl.execute( + "INSERT INTO account_tenant_creation_bootstrap_operations " + + "(request_id, schema_version, initiating_account_uuid, tenant_uuid, " + + "creation_request_id, creation_operation_id, account_authorization_operation_id, " + + "account_authorization_digest, creator_evidence_digest, creator_evidence_payload, " + + "source_snapshot_payload, source_snapshot_digest, request_payload, request_digest, " + + "baseline_membership_version, baseline_membership_authority_generation, " + + "baseline_event_sequence, status) " + + "VALUES (?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 1, 0, 'IN_PROGRESS')", + bootstrapRequest, + accountUuid, + tenant.canonicalTenantId(), + tenant.creationRequestId(), + tenant.operationId(), + bootstrapRequest, + digest('d'), + tenant.evidenceDigest(), + new byte[] {1}, + new byte[] {2}, + digest('e'), + new byte[] {3}, + digest('f')); + dsl.execute( + "UPDATE account_tenant_creation_bootstrap_operations SET " + + "membership_id = 1, membership_version = 2, membership_authority_generation = 1, " + + "membership_lifecycle_state = 'ACTIVE', gameplay_admission_allowed = FALSE, " + + "membership_roles_payload = convert_to('[\"tenantAdmin\"]', 'UTF8'), " + + "event_stream_key = ?, event_request_id = ?, event_sequence = 1, event_id = ?, " + + "event_digest = ?, caller_bound_authority_invalidated = FALSE, event_payload = ?, " + + "audit_event_id = ?, audit_event_type = 'ACCOUNT_TENANT_CREATOR_BOOTSTRAPPED', " + + "audit_occurred_at = CURRENT_TIMESTAMP, audit_payload_digest = ?, audit_payload = ?, " + + "result_payload = ?, result_digest = ?, status = 'COMMITTED' WHERE request_id = ?", + "account:auth-authority:v1:membership/" + accountUuid + "/" + tenant.canonicalTenantId(), + bootstrapRequest.toString(), + "capacity-bootstrap-" + bootstrapRequest, + digest('1'), + new byte[] {4}, + UUID.randomUUID(), + digest('2'), + new byte[] {5}, + new byte[] {6}, + digest('3'), + bootstrapRequest); + + dsl.execute( + "INSERT INTO account_tenant_capacity_evaluations " + + "(evaluation_identity, snapshot_identity, tenant_uuid, caller_workload, " + + "owner_service, canonical_evidence, evaluated_at, expires_at) " + + "VALUES (?, ?, ?, ?, 'game-session-service', ?, CURRENT_TIMESTAMP, " + + "CURRENT_TIMESTAMP + INTERVAL '5 minutes')", + evaluationIdentity, + digest('b'), + tenant.canonicalTenantId(), + callerWorkload, + new byte[] {7}); + dsl.execute( + "INSERT INTO account_tenant_capacity_reservations " + + "(tenant_uuid, request_id, admission_id, reservation_id, owner_service, " + + "caller_workload, admission_attempt_id, capacity_rearm_fence, reservation_fence, " + + "mutation_digest, canonical_payload, evaluation_identity, capacity_delta, expires_at, " + + "state, execution_status, reconcile_deadline) " + + "VALUES (?, ?, ?, ?, 'game-session-service', ?, ?, 1, 1, ?, ?, ?, 3, " + + "CURRENT_TIMESTAMP + INTERVAL '5 minutes', 'RESERVED', " + + "'OWNER_EXECUTION_PENDING', CURRENT_TIMESTAMP + INTERVAL '10 minutes')", + tenant.canonicalTenantId(), + requestId, + admissionId, + UUID.randomUUID(), + callerWorkload, + attemptId, + mutationDigest, + canonicalPayload, + evaluationIdentity); + dsl.execute( + "UPDATE account_tenant_capacity_usage SET held_units = 3, usage_revision = 2 " + + "WHERE tenant_uuid = ? AND owner_service = 'game-session-service'", + tenant.canonicalTenantId()); + }); + return new CapacityFixture( + tenant.canonicalTenantId(), requestId, admissionId, evaluationIdentity, callerWorkload); + } + + private static void assertCapacityTriggerBehavior( + DSLContext dsl, TransactionTemplate transaction, CapacityFixture capacity) { + List before = capacityTableImages(dsl); + + assertThatThrownBy(() -> + transaction.executeWithoutResult(status -> + dsl.execute( + "UPDATE account_tenant_capacity_reservations SET " + + "capacity_delta = capacity_delta + 1 " + + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?", + capacity.tenantUuid(), + capacity.requestId(), + capacity.admissionId()))) + .satisfies(failure -> assertThat(sqlState(failure)).isEqualTo("23514")); + + assertReservationInsertMismatchRefused(dsl, transaction, capacity); + assertReservationStateChangeMismatchRefused(dsl, transaction, capacity); + assertUsageWriteMismatchRefused(dsl, transaction, capacity); + assertThat(capacityTableImages(dsl)).isEqualTo(before); + + transaction.executeWithoutResult(status -> { + dsl.execute( + "UPDATE account_tenant_capacity_usage SET held_units = held_units + 1, " + + "usage_revision = usage_revision + 1 " + + "WHERE tenant_uuid = ? AND owner_service = 'game-session-service'", + capacity.tenantUuid()); + dsl.execute( + "UPDATE account_tenant_capacity_reservations SET recovery_owner = ?, " + + "recovery_claim_fence = recovery_claim_fence + 1, " + + "recovery_claim_expires_at = CURRENT_TIMESTAMP + INTERVAL '1 minute' " + + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?", + UUID.randomUUID(), + capacity.tenantUuid(), + capacity.requestId(), + capacity.admissionId()); + dsl.execute("SET CONSTRAINTS account_tenant_capacity_reservation_complete_update IMMEDIATE"); + dsl.execute( + "UPDATE account_tenant_capacity_usage SET held_units = held_units - 1, " + + "usage_revision = usage_revision + 1 " + + "WHERE tenant_uuid = ? AND owner_service = 'game-session-service'", + capacity.tenantUuid()); + }); + Record reservation = + Objects.requireNonNull( + dsl.fetchSingle( + "SELECT state, recovery_claim_fence FROM account_tenant_capacity_reservations " + + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?", + capacity.tenantUuid(), + capacity.requestId(), + capacity.admissionId())); + assertThat(reservation.get("state", String.class)).isEqualTo("RESERVED"); + assertThat(reservation.get("recovery_claim_fence", Long.class)).isEqualTo(1L); + Record usage = + Objects.requireNonNull( + dsl.fetchSingle( + "SELECT held_units, used_units FROM account_tenant_capacity_usage " + + "WHERE tenant_uuid = ? AND owner_service = 'game-session-service'", + capacity.tenantUuid())); + assertThat(usage.get("held_units", Long.class)).isEqualTo(3L); + assertThat(usage.get("used_units", Long.class)).isZero(); + } + + private static void assertReservationInsertMismatchRefused( + DSLContext dsl, TransactionTemplate transaction, CapacityFixture capacity) { + transaction.executeWithoutResult(status -> { + UUID requestId = UUID.randomUUID(); + UUID admissionId = UUID.randomUUID(); + UUID attemptId = UUID.randomUUID(); + String mutationDigest = hex('4'); + byte[] canonicalPayload = new byte[] {9}; + insertOriginDecisionIfPresent( + dsl, + capacity.tenantUuid(), + requestId, + admissionId, + 1, + attemptId, + mutationDigest, + canonicalPayload); + dsl.execute( + "UPDATE account_tenant_capacity_usage SET held_units = held_units + 1, " + + "usage_revision = usage_revision + 1 " + + "WHERE tenant_uuid = ? AND owner_service = 'game-session-service'", + capacity.tenantUuid()); + dsl.execute( + "INSERT INTO account_tenant_capacity_reservations " + + "(tenant_uuid, request_id, admission_id, reservation_id, owner_service, " + + "caller_workload, admission_attempt_id, capacity_rearm_fence, " + + "reservation_fence, mutation_digest, canonical_payload, evaluation_identity, " + + "capacity_delta, expires_at, state, execution_status, reconcile_deadline) " + + "VALUES (?, ?, ?, ?, 'game-session-service', ?, ?, 1, 1, ?, ?, ?, 0, " + + "CURRENT_TIMESTAMP + INTERVAL '5 minutes', 'RESERVED', " + + "'OWNER_EXECUTION_PENDING', CURRENT_TIMESTAMP + INTERVAL '10 minutes')", + capacity.tenantUuid(), + requestId, + admissionId, + UUID.randomUUID(), + capacity.callerWorkload(), + attemptId, + mutationDigest, + canonicalPayload, + capacity.evaluationIdentity()); + status.setRollbackOnly(); + assertThatThrownBy(() -> + dsl.execute( + "SET CONSTRAINTS account_tenant_capacity_reservation_complete_insert IMMEDIATE")) + .satisfies(AccountTenantCapacityMigrationPostgresIntegrationTest::assertInventoryRefusal); + }); + } + + private static void insertOriginDecisionIfPresent( + DSLContext dsl, + UUID tenantUuid, + UUID requestId, + UUID admissionId, + long rearmFence, + UUID attemptId, + String mutationDigest, + byte[] canonicalPayload) { + if (dsl.fetchSingle("SELECT to_regclass('account_capacity_origin_decisions') IS NOT NULL") + .get(0, Boolean.class)) { + dsl.execute( + "INSERT INTO account_capacity_origin_decisions " + + "(tenant_uuid, request_id, admission_id, capacity_rearm_fence, admission_attempt_id, " + + "mutation_digest, canonical_payload, decision, decision_id) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, 'ACCEPTED', ?)", + tenantUuid, + requestId, + admissionId, + rearmFence, + attemptId, + mutationDigest, + canonicalPayload, + UUID.randomUUID()); + } + } + + private static void assertReservationStateChangeMismatchRefused( + DSLContext dsl, TransactionTemplate transaction, CapacityFixture capacity) { + transaction.executeWithoutResult(status -> { + dsl.execute( + "UPDATE account_tenant_capacity_usage SET held_units = held_units + 1, " + + "usage_revision = usage_revision + 1 " + + "WHERE tenant_uuid = ? AND owner_service = 'game-session-service'", + capacity.tenantUuid()); + dsl.execute( + "UPDATE account_tenant_capacity_reservations SET state = 'RELEASED', " + + "execution_status = 'NOT_EXECUTED_AFTER_AUTHORIZATION', " + + "recovery_owner = ?, recovery_claim_fence = 1, " + + "recovery_claim_expires_at = CURRENT_TIMESTAMP + INTERVAL '1 minute', " + + "reservation_fence = reservation_fence + 1, owner_readback = ?, " + + "owner_readback_digest = ? " + + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?", + UUID.randomUUID(), + new byte[] {10}, + hex('5'), + capacity.tenantUuid(), + capacity.requestId(), + capacity.admissionId()); + status.setRollbackOnly(); + assertThatThrownBy(() -> + dsl.execute( + "SET CONSTRAINTS account_tenant_capacity_reservation_complete_update IMMEDIATE")) + .satisfies(AccountTenantCapacityMigrationPostgresIntegrationTest::assertInventoryRefusal); + }); + } + + private static void assertUsageWriteMismatchRefused( + DSLContext dsl, TransactionTemplate transaction, CapacityFixture capacity) { + assertThatThrownBy(() -> + transaction.executeWithoutResult(status -> { + dsl.execute( + "UPDATE account_tenant_capacity_usage SET used_units = used_units + 1, " + + "usage_revision = usage_revision + 1 " + + "WHERE tenant_uuid = ? AND owner_service = 'game-session-service'", + capacity.tenantUuid()); + dsl.execute("SET CONSTRAINTS account_tenant_capacity_usage_complete IMMEDIATE"); + })) + .satisfies(AccountTenantCapacityMigrationPostgresIntegrationTest::assertInventoryRefusal); + } + + private static void assertInventoryRefusal(Throwable failure) { + assertThat(sqlState(failure)).isEqualTo("23514"); + assertThat(failure) + .hasStackTraceContaining( + "Capacity usage differs from its complete durable reservation inventory"); + } + + static String sqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sqlException) { + return sqlException.getSQLState(); + } + } + return null; + } + + private static String digest(char digit) { + return "sha256:" + String.valueOf(digit).repeat(64); + } + + static String hex(char digit) { + return String.valueOf(digit).repeat(64); + } + + private record PredecessorImage( + List migrationHistoryImage, + Integer migrationChecksum, + List tableImages, + List otherTriggerImages, + String exactUsageFunctionImage) {} + + record CapacityFixture( + UUID tenantUuid, + UUID requestId, + UUID admissionId, + String evaluationIdentity, + String callerWorkload) {} + private static Account creator() { String suffix = UUID.randomUUID().toString().replace("-", ""); var account = new Account(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityWriteFreshnessPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityWriteFreshnessPostgresIntegrationTest.java new file mode 100644 index 0000000000..daa4b87f22 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityWriteFreshnessPostgresIntegrationTest.java @@ -0,0 +1,529 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static integration.net.firedevops.firemud.accountservice.repository.AccountTenantCapacityMigrationPostgresIntegrationTest.capacityFreshnessTableImages; +import static integration.net.firedevops.firemud.accountservice.repository.AccountTenantCapacityMigrationPostgresIntegrationTest.capacityTableImages; +import static integration.net.firedevops.firemud.accountservice.repository.AccountTenantCapacityMigrationPostgresIntegrationTest.configureFlyway; +import static integration.net.firedevops.firemud.accountservice.repository.AccountTenantCapacityMigrationPostgresIntegrationTest.hex; +import static integration.net.firedevops.firemud.accountservice.repository.AccountTenantCapacityMigrationPostgresIntegrationTest.populateCapacity; +import static integration.net.firedevops.firemud.accountservice.repository.AccountTenantCapacityMigrationPostgresIntegrationTest.sqlState; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import integration.net.firedevops.firemud.accountservice.repository.AccountTenantCapacityMigrationPostgresIntegrationTest.CapacityFixture; +import java.util.List; +import java.util.UUID; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.postgresql.util.PSQLException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Additive write-time freshness, without revalidating or rewriting retained historical attempts. + */ +class AccountTenantCapacityWriteFreshnessPostgresIntegrationTest { + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + + @BeforeAll + static void start() { + POSTGRES.start(); + } + + @AfterAll + static void stop() { + POSTGRES.stop(); + } + + @Test + void freshAndPopulatedUpgradePreservesPriorRowsHistoryAndGuardDefinitions() { + for (boolean populated : List.of(false, true)) { + try (var database = database()) { + if (populated) { + var capacity = populateCapacity(database.dsl(), database.write()); + // The predecessor accepted an already-expired original. Preserve it byte-for-byte; + // installing the correction must never erase its historical result or release its hold. + addExpiredEvaluation(database, capacity); + database + .write() + .executeWithoutResult(ignored -> { + insertExpiredReservation(database.dsl(), capacity); + incrementUsage(database.dsl(), capacity); + }); + } + var rows = capacityImage(database.dsl()); + var history = history(database.dsl()); + var guards = guards(database.dsl()); + + configureFlyway(database.data(), database.schema(), "1046.5").migrate(); + + assertThat(capacityImage(database.dsl())).isEqualTo(rows); + List upgradedHistory = history(database.dsl()); + assertThat(upgradedHistory.subList(0, history.size())).containsExactlyElementsOf(history); + assertThat(upgradedHistory).hasSizeGreaterThan(history.size()); + assertThat(guards(database.dsl())).containsAll(guards); + assertThat( + configureFlyway(database.data(), database.schema(), "1046.5") + .validateWithResult() + .validationSuccessful) + .isTrue(); + if (populated) { + // Same-attempt diagnostic/recovery writes are not new authorization, even when expired. + database + .write() + .executeWithoutResult(ignored -> + database + .dsl() + .execute( + "UPDATE account_tenant_capacity_reservations SET next_reconcile_at = clock_timestamp() " + + "WHERE evaluation_identity = ?", + expiredEvaluation())); + } + } + } + } + + @Test + void expiredOriginalAndRearmWritesRollbackTheirUsageAndHistoryAtCommit() { + try (var database = database()) { + var capacity = populateCapacity(database.dsl(), database.write()); + addExpiredEvaluation(database, capacity); + configureFlyway(database.data(), database.schema(), "1046.5").migrate(); + var before = capacityFreshnessTableImages(database.dsl()); + + assertThatThrownBy(() -> + database + .write() + .executeWithoutResult(ignored -> { + incrementUsage(database.dsl(), capacity); + insertExpiredReservation(database.dsl(), capacity); + })) + .satisfies(failure -> assertThat(sqlState(failure)).isEqualTo("23514")) + .hasStackTraceContaining("stale at the reservation write boundary"); + assertThat(capacityFreshnessTableImages(database.dsl())).isEqualTo(before); + + database + .write() + .executeWithoutResult(ignored -> + database + .dsl() + .execute( + "UPDATE account_tenant_capacity_reservations SET recovery_owner = ?, recovery_claim_fence = 1, " + + "recovery_claim_expires_at = clock_timestamp() + INTERVAL '1 minute', " + + "execution_status = 'NOT_EXECUTED_AFTER_AUTHORIZATION', owner_readback = ?, owner_readback_digest = ? " + + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?", + UUID.randomUUID(), + new byte[] {1}, + hex('5'), + capacity.tenantUuid(), + capacity.requestId(), + capacity.admissionId())); + var terminal = capacityFreshnessTableImages(database.dsl()); + assertThatThrownBy(() -> + database + .write() + .executeWithoutResult(ignored -> { + database + .dsl() + .execute( + "INSERT INTO account_tenant_capacity_attempt_history " + + "(tenant_uuid, request_id, admission_id, admission_attempt_id, capacity_rearm_fence, mutation_digest, canonical_payload, owner_readback) " + + "SELECT tenant_uuid, request_id, admission_id, admission_attempt_id, capacity_rearm_fence, mutation_digest, canonical_payload, owner_readback " + + "FROM account_tenant_capacity_reservations WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?", + capacity.tenantUuid(), + capacity.requestId(), + capacity.admissionId()); + UUID nextAttemptId = UUID.randomUUID(); + String nextMutationDigest = hex('6'); + byte[] nextCanonicalPayload = new byte[] {2}; + insertOriginDecision( + database.dsl(), + capacity.tenantUuid(), + capacity.requestId(), + capacity.admissionId(), + 2, + nextAttemptId, + nextMutationDigest, + nextCanonicalPayload); + database + .dsl() + .execute( + "UPDATE account_tenant_capacity_reservations SET admission_attempt_id = ?, " + + "capacity_rearm_fence = capacity_rearm_fence + 1, reservation_fence = reservation_fence + 1, " + + "mutation_digest = ?, canonical_payload = ?, evaluation_identity = ?, expires_at = clock_timestamp() - INTERVAL '1 minute', " + + "execution_status = 'OWNER_EXECUTION_PENDING', owner_readback = NULL, owner_readback_digest = NULL " + + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?", + nextAttemptId, + nextMutationDigest, + nextCanonicalPayload, + expiredEvaluation(), + capacity.tenantUuid(), + capacity.requestId(), + capacity.admissionId()); + })) + .satisfies(failure -> assertThat(sqlState(failure)).isEqualTo("23514")) + .hasStackTraceContaining("stale at the reservation write boundary"); + assertThat(capacityFreshnessTableImages(database.dsl())).isEqualTo(terminal); + } + } + + @Test + void originalAndRearmRequireBothEvaluationAndReservationToBeLive() { + for (boolean expiredEval : List.of(true, false)) { + for (boolean expiredReservation : List.of(true, false)) { + if (expiredEval == expiredReservation) continue; + try (var database = database()) { + var capacity = populateCapacity(database.dsl(), database.write()); + addExpiredEvaluation(database, capacity); + configureFlyway(database.data(), database.schema(), "1046.5").migrate(); + String evaluationIdentity = + expiredEval ? expiredEvaluation() : capacity.evaluationIdentity(); + var before = capacityFreshnessTableImages(database.dsl()); + assertThatThrownBy(() -> + database + .write() + .executeWithoutResult(ignored -> { + incrementUsage(database.dsl(), capacity); + insertReservationAttempt( + database.dsl(), capacity, evaluationIdentity, expiredReservation); + })) + .satisfies(failure -> assertThat(sqlState(failure)).isEqualTo("23514")) + .hasStackTraceContaining("stale at the reservation write boundary"); + assertThat(capacityFreshnessTableImages(database.dsl())).isEqualTo(before); + + database + .write() + .executeWithoutResult(ignored -> { + database + .dsl() + .execute( + "UPDATE account_tenant_capacity_reservations SET recovery_owner = ?, recovery_claim_fence = 1, " + + "recovery_claim_expires_at = clock_timestamp() + INTERVAL '1 minute', " + + "execution_status = 'NOT_EXECUTED_AFTER_AUTHORIZATION', owner_readback = ?, owner_readback_digest = ? " + + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?", + UUID.randomUUID(), + new byte[] {1}, + hex('5'), + capacity.tenantUuid(), + capacity.requestId(), + capacity.admissionId()); + database + .dsl() + .execute( + "INSERT INTO account_tenant_capacity_attempt_history " + + "(tenant_uuid, request_id, admission_id, admission_attempt_id, capacity_rearm_fence, mutation_digest, canonical_payload, owner_readback) " + + "SELECT tenant_uuid, request_id, admission_id, admission_attempt_id, capacity_rearm_fence, mutation_digest, canonical_payload, owner_readback " + + "FROM account_tenant_capacity_reservations WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?", + capacity.tenantUuid(), + capacity.requestId(), + capacity.admissionId()); + }); + var terminal = capacityFreshnessTableImages(database.dsl()); + assertThatThrownBy(() -> + database + .write() + .executeWithoutResult(ignored -> { + UUID nextAttemptId = UUID.randomUUID(); + String nextMutationDigest = hex('6'); + byte[] nextCanonicalPayload = new byte[] {2}; + insertOriginDecision( + database.dsl(), + capacity.tenantUuid(), + capacity.requestId(), + capacity.admissionId(), + 2, + nextAttemptId, + nextMutationDigest, + nextCanonicalPayload); + database + .dsl() + .execute( + "UPDATE account_tenant_capacity_reservations SET admission_attempt_id = ?, " + + "capacity_rearm_fence = capacity_rearm_fence + 1, reservation_fence = reservation_fence + 1, " + + "mutation_digest = ?, canonical_payload = ?, evaluation_identity = ?, expires_at = " + + "CASE WHEN ? THEN clock_timestamp() - INTERVAL '1 minute' ELSE clock_timestamp() + INTERVAL '1 minute' END, " + + "execution_status = 'OWNER_EXECUTION_PENDING', owner_readback = NULL, owner_readback_digest = NULL " + + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?", + nextAttemptId, + nextMutationDigest, + nextCanonicalPayload, + evaluationIdentity, + expiredReservation, + capacity.tenantUuid(), + capacity.requestId(), + capacity.admissionId()); + })) + .satisfies(failure -> assertThat(sqlState(failure)).isEqualTo("23514")) + .hasStackTraceContaining("stale at the reservation write boundary"); + assertThat(capacityFreshnessTableImages(database.dsl())).isEqualTo(terminal); + } + } + } + } + + @Test + void deferredFreshnessConstraintHasStructuredIdentityAndRollsBackTheWholeWrite() { + try (var database = database()) { + var capacity = populateCapacity(database.dsl(), database.write()); + addExpiredEvaluation(database, capacity); + configureFlyway(database.data(), database.schema(), "1046.5").migrate(); + var before = capacityFreshnessTableImages(database.dsl()); + + assertThatThrownBy(() -> + database + .write() + .executeWithoutResult(ignored -> { + incrementUsage(database.dsl(), capacity); + insertExpiredReservation(database.dsl(), capacity); + })) + .satisfies(failure -> { + PSQLException postgresFailure = postgresFailure(failure); + assertThat(postgresFailure.getSQLState()).isEqualTo("23514"); + assertThat(postgresFailure.getServerErrorMessage().getConstraint()) + .isEqualTo("account_tenant_capacity_attempt_freshness"); + }); + assertThat(capacityFreshnessTableImages(database.dsl())).isEqualTo(before); + } + } + + @Test + void expiryAfterInsertionStillRollsBackTheHoldUsingCommitTimeRatherThanTransactionStart() { + try (var database = database()) { + var capacity = populateCapacity(database.dsl(), database.write()); + configureFlyway(database.data(), database.schema(), "1046.5").migrate(); + var before = capacityFreshnessTableImages(database.dsl()); + assertThatThrownBy(() -> + database + .write() + .executeWithoutResult(ignored -> { + UUID requestId = UUID.randomUUID(); + UUID admissionId = UUID.randomUUID(); + UUID reservationId = UUID.randomUUID(); + UUID attemptId = UUID.randomUUID(); + String mutationDigest = hex('6'); + byte[] canonicalPayload = + database + .dsl() + .fetchSingle( + "SELECT canonical_evidence FROM account_tenant_capacity_evaluations WHERE evaluation_identity = ?", + capacity.evaluationIdentity()) + .get("canonical_evidence", byte[].class); + database + .dsl() + .execute( + "INSERT INTO account_tenant_capacity_evaluations " + + "(evaluation_identity, snapshot_identity, tenant_uuid, caller_workload, owner_service, canonical_evidence, evaluated_at, expires_at) " + + "SELECT ?, snapshot_identity, tenant_uuid, caller_workload, owner_service, canonical_evidence, " + + "clock_timestamp(), clock_timestamp() + INTERVAL '5 seconds' " + + "FROM account_tenant_capacity_evaluations WHERE evaluation_identity = ?", + expiredEvaluation(), + capacity.evaluationIdentity()); + insertOriginDecision( + database.dsl(), + capacity.tenantUuid(), + requestId, + admissionId, + 1, + attemptId, + mutationDigest, + canonicalPayload); + database + .dsl() + .execute( + "INSERT INTO account_tenant_capacity_reservations " + + "(tenant_uuid, request_id, admission_id, reservation_id, owner_service, caller_workload, admission_attempt_id, " + + "capacity_rearm_fence, reservation_fence, mutation_digest, canonical_payload, evaluation_identity, capacity_delta, " + + "expires_at, reconcile_deadline, state, execution_status) " + + "SELECT tenant_uuid, ?, ?, ?, owner_service, caller_workload, ?, 1, 1, ?, canonical_evidence, evaluation_identity, 1, " + + "expires_at, expires_at + INTERVAL '1 minute', 'RESERVED', 'OWNER_EXECUTION_PENDING' " + + "FROM account_tenant_capacity_evaluations WHERE evaluation_identity = ?", + requestId, + admissionId, + reservationId, + attemptId, + mutationDigest, + expiredEvaluation()); + assertThat( + database + .dsl() + .fetchSingle( + "SELECT clock_timestamp() < expires_at " + + "FROM account_tenant_capacity_evaluations WHERE evaluation_identity = ?", + expiredEvaluation()) + .get(0, Boolean.class)) + .as("the reservation insert completed before PostgreSQL's expiry deadline") + .isTrue(); + incrementUsage(database.dsl(), capacity); + database + .dsl() + .fetchSingle( + "SELECT pg_sleep(GREATEST(0, extract(epoch FROM (expires_at - clock_timestamp())))) " + + "FROM account_tenant_capacity_evaluations WHERE evaluation_identity = ?", + expiredEvaluation()); + })) + .satisfies(failure -> assertThat(sqlState(failure)).isEqualTo("23514")) + .hasStackTraceContaining("stale at the reservation write boundary"); + assertThat(capacityFreshnessTableImages(database.dsl())).isEqualTo(before); + } + } + + private static void addExpiredEvaluation(Database database, CapacityFixture capacity) { + database + .write() + .executeWithoutResult(ignored -> + database + .dsl() + .execute( + "INSERT INTO account_tenant_capacity_evaluations " + + "(evaluation_identity, snapshot_identity, tenant_uuid, caller_workload, owner_service, canonical_evidence, evaluated_at, expires_at) " + + "SELECT ?, snapshot_identity, tenant_uuid, caller_workload, owner_service, canonical_evidence, " + + "clock_timestamp() - INTERVAL '2 minutes', clock_timestamp() - INTERVAL '1 minute' " + + "FROM account_tenant_capacity_evaluations WHERE evaluation_identity = ?", + expiredEvaluation(), + capacity.evaluationIdentity())); + } + + private static void insertExpiredReservation(DSLContext dsl, CapacityFixture capacity) { + insertReservationAttempt(dsl, capacity, expiredEvaluation(), true); + } + + private static void insertReservationAttempt( + DSLContext dsl, + CapacityFixture capacity, + String evaluationIdentity, + boolean expiredReservation) { + var source = + dsl.fetchSingle( + "SELECT mutation_digest, canonical_payload FROM account_tenant_capacity_reservations " + + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?", + capacity.tenantUuid(), + capacity.requestId(), + capacity.admissionId()); + UUID requestId = UUID.randomUUID(); + UUID admissionId = UUID.randomUUID(); + UUID attemptId = UUID.randomUUID(); + String mutationDigest = source.get("mutation_digest", String.class); + byte[] canonicalPayload = source.get("canonical_payload", byte[].class); + insertOriginDecision( + dsl, + capacity.tenantUuid(), + requestId, + admissionId, + 1, + attemptId, + mutationDigest, + canonicalPayload); + dsl.execute( + "INSERT INTO account_tenant_capacity_reservations " + + "(tenant_uuid, request_id, admission_id, reservation_id, owner_service, caller_workload, admission_attempt_id, " + + "capacity_rearm_fence, reservation_fence, mutation_digest, canonical_payload, evaluation_identity, capacity_delta, " + + "expires_at, reconcile_deadline, state, execution_status) " + + "SELECT tenant_uuid, ?, ?, ?, owner_service, caller_workload, ?, 1, 1, ?, ?, ?, 1, " + + "CASE WHEN ? THEN clock_timestamp() - INTERVAL '1 minute' ELSE clock_timestamp() + INTERVAL '1 minute' END, " + + "reconcile_deadline, 'RESERVED', 'OWNER_EXECUTION_PENDING' " + + "FROM account_tenant_capacity_reservations WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?", + requestId, + admissionId, + UUID.randomUUID(), + attemptId, + mutationDigest, + canonicalPayload, + evaluationIdentity, + expiredReservation, + capacity.tenantUuid(), + capacity.requestId(), + capacity.admissionId()); + } + + private static List capacityImage(DSLContext dsl) { + return dsl.fetchSingle("SELECT to_regclass('account_capacity_origin_decisions') IS NOT NULL") + .get(0, Boolean.class) + ? capacityFreshnessTableImages(dsl) + : capacityTableImages(dsl); + } + + private static void insertOriginDecision( + DSLContext dsl, + UUID tenantUuid, + UUID requestId, + UUID admissionId, + long rearmFence, + UUID attemptId, + String mutationDigest, + byte[] canonicalPayload) { + dsl.execute( + "INSERT INTO account_capacity_origin_decisions " + + "(tenant_uuid, request_id, admission_id, capacity_rearm_fence, admission_attempt_id, " + + "mutation_digest, canonical_payload, decision, decision_id) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, 'ACCEPTED', ?)", + tenantUuid, + requestId, + admissionId, + rearmFence, + attemptId, + mutationDigest, + canonicalPayload, + UUID.randomUUID()); + } + + private static void incrementUsage(DSLContext dsl, CapacityFixture capacity) { + dsl.execute( + "UPDATE account_tenant_capacity_usage SET held_units = held_units + 1, " + + "usage_revision = usage_revision + 1 WHERE tenant_uuid = ? AND owner_service = 'game-session-service'", + capacity.tenantUuid()); + } + + private static PSQLException postgresFailure(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof PSQLException postgresFailure) return postgresFailure; + } + throw new AssertionError("Expected PostgreSQL diagnostic", failure); + } + + private static String expiredEvaluation() { + return "sha256:" + hex('e'); + } + + private static List history(DSLContext dsl) { + return dsl.fetch( + "SELECT to_jsonb(h)::text FROM flyway_schema_history h ORDER BY installed_rank") + .getValues(0, String.class); + } + + private static List guards(DSLContext dsl) { + return dsl.fetch( + "SELECT pg_get_triggerdef(t.oid) FROM pg_trigger t " + + "JOIN pg_class relation ON relation.oid = t.tgrelid " + + "JOIN pg_namespace namespace ON namespace.oid = relation.relnamespace " + + "WHERE namespace.nspname = current_schema() AND NOT t.tgisinternal " + + "ORDER BY relation.relname, t.tgname") + .getValues(0, String.class); + } + + private static Database database() { + String schema = "capacity_freshness_" + UUID.randomUUID().toString().replace("-", ""); + new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema); + var data = POSTGRES.dataSource(schema); + configureFlyway(data, schema, "1045").migrate(); + return new Database( + schema, + data, + DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES), + new TransactionTemplate(new DataSourceTransactionManager(data))); + } + + private record Database( + String schema, javax.sql.DataSource data, DSLContext dsl, TransactionTemplate write) + implements AutoCloseable { + @Override + public void close() { + new JdbcTemplate(POSTGRES.dataSource()).execute("DROP SCHEMA " + schema + " CASCADE"); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java index c673017952..ee40c14153 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java @@ -1,6 +1,10 @@ package integration.net.firedevops.firemud.accountservice.repository; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import com.stripe.exception.StripeException; import com.stripe.model.StripeObject; @@ -9,43 +13,83 @@ import com.stripe.net.BaseAddress; import com.stripe.net.RequestOptions; import com.stripe.net.StripeResponseGetter; +import de.mkammerer.argon2.Argon2Factory; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.time.Clock; import java.time.Duration; import java.time.Instant; +import java.time.OffsetDateTime; import java.time.ZoneId; import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.UUID; import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Consumer; import java.util.function.Supplier; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.client.StripeHostingFirstInvoicePaymentClient; import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.client.StripeHostingWebhookVerifier; import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; +import net.firedevops.firemud.accountservice.mapper.AccountMapper; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; import net.firedevops.firemud.accountservice.repository.AccountBillingCustomerRecord; import net.firedevops.firemud.accountservice.repository.AccountBillingCustomerRepository; +import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingFirstInvoicePayment; +import net.firedevops.firemud.accountservice.repository.AccountHostingFirstInvoicePaymentRepository; import net.firedevops.firemud.accountservice.repository.AccountHostingPlanCatalog; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy.RecoveryTiming; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReconciliationLimits; import net.firedevops.firemud.accountservice.repository.AccountInitialTenantBillingOwnerRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPaymentInstrumentRecord; import net.firedevops.firemud.accountservice.repository.AccountPaymentInstrumentRecord.DisplayMetadata; import net.firedevops.firemud.accountservice.repository.AccountPaymentInstrumentRecord.State; import net.firedevops.firemud.accountservice.repository.AccountPaymentInstrumentRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest; import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.OwnerFence; import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.ProducerEvidence; import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreationRecord; import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository; import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.StripeEventInboxRepository; import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionLifecycleService; +import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiActorService; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiKeyring; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiResponseCryptography; +import net.firedevops.firemud.accountservice.service.session.AccountHostingFirstInvoicePaymentService; +import net.firedevops.firemud.accountservice.service.session.AccountRecentReauthenticationEvidence; +import net.firedevops.firemud.accountservice.service.session.AccountRecentReauthenticationPolicy; +import net.firedevops.firemud.accountservice.service.session.AccountRecentReauthenticationPolicyRepository; +import net.firedevops.firemud.accountservice.service.session.AccountRecentReauthenticationRepository; +import net.firedevops.firemud.accountservice.service.session.AccountRecentReauthenticationService; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; @@ -53,6 +97,7 @@ import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; +import org.mapstruct.factory.Mappers; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; @@ -67,20 +112,29 @@ */ public final class CanonicalHostingSubscriptionTestFixture { private static final String DIGEST = "sha256:" + "a".repeat(64); + public static final String BILLING_PASSWORD = "test-only-hosting-first-invoice-password"; + private static final String WEBHOOK_SECRET = "whsec_test_only_hosting_first_invoice"; private static final AtomicLong GAME_ROWS = new AtomicLong(20_000); private CanonicalHostingSubscriptionTestFixture() {} public static Fixture create(DataSource source) { - return createInternal(source, null); + return createInternal(source, null, "prod"); + } + + /** Uses the caller's explicit workload namespace without changing controlled source custody. */ + public static Fixture create(DataSource source, String namespace) { + return createInternal(source, null, namespace); } /** Reuses the exact persisted Account of a genuine actor/authentication composition. */ public static Fixture create(DataSource source, Account account) { - return createInternal(source, Objects.requireNonNull(account, "persisted Account required")); + return createInternal( + source, Objects.requireNonNull(account, "persisted Account required"), "prod"); } - private static Fixture createInternal(DataSource source, Account existingAccount) { + private static Fixture createInternal( + DataSource source, Account existingAccount, String namespace) { Objects.requireNonNull(source, "migrated Account datasource is required"); JdbcTemplate jdbc = new JdbcTemplate(source); DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); @@ -95,18 +149,13 @@ private static Fixture createInternal(DataSource source, Account existingAccount new AccountSubscriptionIntentRepository(dsl, catalog); long row = GAME_ROWS.incrementAndGet(); + Account account = + existingAccount == null ? createBillingAccount(dsl, transaction) : existingAccount; var accountRow = - existingAccount == null - ? dsl.fetchOne( - "INSERT INTO accounts (username, email, password_hash) " - + "VALUES (?, ?, 'controlled-hash') RETURNING id, account_uuid", - "hosting-fixture-" + row, - "hosting-fixture-" + row + "@example.test") - : dsl.fetchOne( - "SELECT id, account_uuid FROM accounts WHERE id = ? AND account_uuid = ?", - Objects.requireNonNull(existingAccount.getId(), "persisted Account ID required"), - Objects.requireNonNull( - existingAccount.getAccountUuid(), "persisted Account UUID required")); + dsl.fetchOne( + "SELECT id, account_uuid FROM accounts WHERE id = ? AND account_uuid = ?", + Objects.requireNonNull(account.getId(), "persisted Account ID required"), + Objects.requireNonNull(account.getAccountUuid(), "persisted Account UUID required")); Objects.requireNonNull(accountRow, "Exact persisted Account row required"); long accountId = accountRow.get("id", Long.class); UUID accountUuid = accountRow.get("account_uuid", UUID.class); @@ -117,11 +166,11 @@ private static Fixture createInternal(DataSource source, Account existingAccount String tenantKey = "hosting-fixture-game-" + row; String tenantRequestDigest = GameTenantCreationDigest.requestDigest( - "prod", tenantCreateRequest, tenantKey, "Controlled hosting", "Storage only"); + namespace, tenantCreateRequest, tenantKey, "Controlled hosting", "Storage only"); var tenantSource = new FreshTenantCreationEvidence( 1, - "prod", + namespace, tenantCreateRequest, tenantCreateOperation, tenantRequestDigest, @@ -130,7 +179,7 @@ private static Fixture createInternal(DataSource source, Account existingAccount tenantKey, "NEW_GAME_ROW", GameTenantCreationDigest.evidenceDigest( - "prod", + namespace, tenantCreateRequest, tenantCreateOperation, tenantRequestDigest, @@ -141,7 +190,7 @@ private static Fixture createInternal(DataSource source, Account existingAccount in( transaction, () -> { - new FreshTenantIdentityAssociationRepository(dsl, "prod").importVerified(tenantSource); + new FreshTenantIdentityAssociationRepository(dsl, namespace).importVerified(tenantSource); return new AccountAuthorityGenerationRepository(dsl).initializeTenantIfAbsent(tenantId); }); @@ -219,27 +268,36 @@ private static Fixture createInternal(DataSource source, Account existingAccount MutableClock clock = new MutableClock(creation.createdAt().plusSeconds(1)); ControlledStripeTransport transport = new ControlledStripeTransport(); + var limits = + new ReconciliationLimits( + 4, 3, Duration.ofSeconds(10), Duration.ofSeconds(1), Duration.ofHours(1)); + var policy = + new AccountHostingSubscriptionLifecyclePolicy( + Duration.ofSeconds(15), + new RecoveryTiming(Duration.ofSeconds(60), Duration.ofSeconds(120))); var lifecycleRepository = new AccountHostingSubscriptionLifecycleRepository( - dsl, - intents, - clock, - new ReconciliationLimits( - 4, 3, Duration.ofSeconds(10), Duration.ofSeconds(1), Duration.ofHours(1)), - new AccountHostingSubscriptionLifecyclePolicy( - Duration.ofSeconds(15), - new RecoveryTiming(Duration.ofSeconds(60), Duration.ofSeconds(120))), - "prod", - false); + dsl, intents, clock, limits, policy, namespace, false); var observer = new StripeHostingSubscriptionObserver( new com.stripe.StripeClient(transport), clock, Duration.ofMillis(250), Duration.ofSeconds(1)); + var terminalInvoiceTransport = + new ControlledFirstInvoiceTransport(creation, instrument, "sub_" + row, true); + var terminalInvoiceClient = + new StripeHostingFirstInvoicePaymentClient( + new com.stripe.StripeClient(terminalInvoiceTransport), + clock, + Duration.ofMillis(250), + Duration.ofSeconds(1)); var service = new AccountHostingSubscriptionLifecycleService( - lifecycleRepository, observer, new DataSourceTransactionManager(source)); + lifecycleRepository, + observer, + new DataSourceTransactionManager(source), + terminalInvoiceClient); Fixture fixture = new Fixture( jdbc, @@ -254,13 +312,697 @@ private static Fixture createInternal(DataSource source, Account existingAccount "sub_" + row, clock, transport, + terminalInvoiceTransport, service, lifecycleRepository, - observer); + observer, + source); fixture.providerStatus("active"); return fixture; } + /** Separate factory for protected HTTPS owner tests that supply their own genuine actor. */ + public static Fixture createAwaitingPayment( + DataSource source, Account account, Path checkoutDirectory) { + var fixture = create(source, account); + fixture.withCheckoutDirectory(checkoutDirectory).awaitFirstInvoice(); + fixture.providerStatus("incomplete"); + return fixture; + } + + /** Fresh Account insert through the real identity/authority owner, with a real test password. */ + public static Account createBillingAccount(DSLContext dsl, TransactionTemplate transaction) { + var generations = new AccountAuthorityGenerationRepository(dsl); + var outbox = new AccountAuthorityOutboxRepository(dsl); + var accounts = + new AccountRepository( + dsl, new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox)); + var account = new Account(); + String suffix = UUID.randomUUID().toString(); + account.setUsername("hosting-fi-" + suffix); + account.setEmail(suffix + "@example.test"); + char[] password = BILLING_PASSWORD.toCharArray(); + var argon = Argon2Factory.create(); + try { + account.setPasswordHash(argon.hash(2, 4096, 1, password)); + } finally { + argon.wipeArray(password); + } + account.setRole("player"); + account.setLoginAuthModes("PASSWORD"); + account.setLifecycleState(AccountLifecycleState.ACTIVE); + return in(transaction, () -> accounts.save(account)); + } + + /** Actual dispatch/capture owner. Commercial/security policy rows are explicit test inputs. */ + public static FirstInvoiceCheckout prepareFirstInvoice( + Path checkoutDirectory, + DataSource source, + DSLContext dsl, + TransactionTemplate transaction, + AccountSubscriptionCreationRecord creation, + AccountPaymentInstrumentRecord instrument, + String providerId, + MutableClock clock, + AccountHostingSubscriptionLifecycleRepository lifecycle) { + Objects.requireNonNull(checkoutDirectory, "test-owned checkout directory required"); + in( + transaction, + () -> { + dsl.execute( + "INSERT INTO account_billing_reauthentication_policy_values (policy_scope, policy_version, recent_age_seconds, max_clock_skew_seconds) VALUES ('PLATFORM',1,300,30),('DEPLOYMENT',1,300,30) ON CONFLICT DO NOTHING"); + dsl.execute( + "INSERT INTO account_billing_reauthentication_policy_current (policy_scope, policy_version) VALUES ('PLATFORM',1),('DEPLOYMENT',1) ON CONFLICT DO NOTHING"); + dsl.execute( + "INSERT INTO account_hosting_billing_policy_values (provider_price_id, policy_version, quantity, amount, currency) VALUES (?,1,1,2400,'usd') ON CONFLICT DO NOTHING", + creation.planQuote().providerPriceId()); + dsl.execute( + "INSERT INTO account_hosting_billing_policy_current (provider_price_id, policy_version) VALUES (?,1) ON CONFLICT DO NOTHING", + creation.planQuote().providerPriceId()); + return true; + }); + var claim = + in(transaction, () -> lifecycle.claim(creation.requestId(), 1, UUID.randomUUID()).claim()); + clock.advanceToAtLeast(claim.claimedAt()); + var prepared = + in(transaction, () -> lifecycle.prepareProviderDispatch(claim, UUID.randomUUID())); + var dispatch = in(transaction, () -> lifecycle.readProviderDispatch(prepared)); + var transport = new ControlledFirstInvoiceTransport(creation, instrument, providerId); + var provider = + new StripeHostingFirstInvoicePaymentClient( + new com.stripe.StripeClient(transport), + clock, + Duration.ofMillis(250), + Duration.ofSeconds(1)); + var payments = + new AccountHostingFirstInvoicePaymentRepository( + dsl, + new AccountSubscriptionIntentRepository(dsl, new AccountHostingPlanCatalog(List.of())), + clock); + try { + var observed = provider.capture(dispatch, providerId); + var invoice = + in(transaction, () -> payments.retainAwaitingPayment(dispatch, providerId, observed)); + return new FirstInvoiceCheckout( + checkoutDirectory, + source, + dsl, + transaction, + clock, + payments, + provider, + transport, + invoice); + } catch (StripeException failure) { + throw new IllegalStateException("Controlled existing-invoice capture failed", failure); + } + } + + /** + * Real payment/reauth owners with test-only policy, keys, primary password and signed transport. + */ + public static final class FirstInvoiceCheckout { + private final DSLContext dsl; + private final TransactionTemplate transaction; + private final Clock clock; + private final AccountHostingFirstInvoicePaymentRepository payments; + private final StripeHostingFirstInvoicePaymentClient provider; + private final ControlledFirstInvoiceTransport transport; + private final AccountHostingFirstInvoicePayment invoice; + private final StripeHostingWebhookVerifier verifier; + private final AccountRecentReauthenticationService reauthentication; + private final AccountRepository accounts; + + private FirstInvoiceCheckout( + Path checkoutDirectory, + DataSource source, + DSLContext dsl, + TransactionTemplate transaction, + Clock clock, + AccountHostingFirstInvoicePaymentRepository payments, + StripeHostingFirstInvoicePaymentClient provider, + ControlledFirstInvoiceTransport transport, + AccountHostingFirstInvoicePayment invoice) { + this.dsl = dsl; + this.transaction = transaction; + this.clock = clock; + this.payments = payments; + this.provider = provider; + this.transport = transport; + this.invoice = invoice; + verifier = new StripeHostingWebhookVerifier(WEBHOOK_SECRET, clock); + var manager = new DataSourceTransactionManager(source); + var generations = new AccountAuthorityGenerationRepository(dsl); + var outbox = new AccountAuthorityOutboxRepository(dsl); + var sources = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); + accounts = new AccountRepository(dsl, sources); + var primary = + new AccountServiceImpl( + accounts, + generations, + sources, + outbox, + mock(AccountPasswordResetOperationRepository.class), + mock(AccountLogoutAllOperationRepository.class), + mock(AccountSecurityStateOperationRepository.class), + mock(AccountPasswordResetDraftSourceChangeRepository.class), + mock(AccountAuditOutboxRepository.class), + mock(AccountJoinOperationRepository.class), + new AccountEmailLoginChallengeRepository(dsl), + null, + null, + Mappers.getMapper(AccountMapper.class), + null, + null, + null, + mock(RetainedSubscriptionEvidenceRepository.class), + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + manager); + try { + Path custody = Files.createTempDirectory(checkoutDirectory, "hosting-first-invoice-"); + for (String purpose : List.of("encryption", "request-mac")) { + byte[] bytes = new byte[32]; + Arrays.fill(bytes, (byte) (purpose.equals("encryption") ? 11 : 29)); + Files.createDirectories(custody.resolve(purpose)); + Files.writeString( + custody.resolve(purpose).resolve("keyring"), + "firemud-account-response-envelope-keyring-v1\nactive test1 " + + Base64.getUrlEncoder().withoutPadding().encodeToString(bytes) + + "\n"); + } + reauthentication = + new AccountRecentReauthenticationService( + primary, + accounts, + generations, + new AccountRecentReauthenticationRepository(dsl), + new AccountRecentReauthenticationPolicyRepository(dsl), + manager, + clock, + new AccountControlUiResponseCryptography( + new AccountControlUiKeyring(custody), clock)); + } catch (IOException failure) { + // JUnit owns the containing directory even when checkout construction does not finish. + throw new IllegalStateException("Test-only custody setup failed", failure); + } + } + + public AccountHostingFirstInvoicePayment invoice() { + return invoice; + } + + public AccountHostingFirstInvoicePaymentRepository payments() { + return payments; + } + + public StripeHostingFirstInvoicePaymentClient provider() { + return provider; + } + + public StripeHostingWebhookVerifier verifier() { + return verifier; + } + + public void status(String status) { + transport.status = status; + } + + public int confirmations() { + return transport.confirmations; + } + + public int providerReads() { + return transport.reads(); + } + + public void loseNextConfirmationResponse() { + transport.loseNextConfirmationResponse = true; + } + + public String lastConfirmationIdempotencyKey() { + return transport.lastConfirmationIdempotencyKey; + } + + public AccountHostingFirstInvoicePaymentRepository.ConfirmationDispatch + authorizeAndRetainSuccess(String password) { + authorize(password); + return retainSignedSuccess(); + } + + public AccountHostingFirstInvoicePaymentRepository.ConfirmationDispatch authorize( + String password) { + var dispatch = prepareConfirmationDispatch(password); + try { + assertThat( + provider + .confirm( + dispatch, + () -> + in( + transaction, + () -> payments.claimCommand(dispatch, invoice.ownerAccountId()))) + .status()) + .isEqualTo("succeeded"); + assertThat(transport.confirmations).isOne(); + assertThat(transport.lastConfirmationIdempotencyKey) + .isEqualTo(dispatch.providerIdempotencyId().toString()); + return dispatch; + } catch (StripeException failure) { + throw new IllegalStateException("Controlled confirmation failed", failure); + } + } + + public AccountHostingFirstInvoicePaymentRepository.ConfirmationDispatch + prepareConfirmationDispatch(String password) { + return prepareConfirmationDispatch(password, () -> {}); + } + + /** Produces the actual committed claim and V1046.4 no-send witness without issuing a POST. */ + public StripeHostingFirstInvoicePaymentClient.ExpiredBeforePost claimExpiredBeforePost( + String password) { + return claimExpiredBeforePost(password, observation -> {}); + } + + public StripeHostingFirstInvoicePaymentClient.ExpiredBeforePost claimExpiredBeforePost( + String password, + Consumer beforeRetention) { + if (!(clock instanceof MutableClock mutableClock)) + throw new IllegalStateException("Mutable test clock required"); + Instant originalClock = clock.instant(); + // The fixture's 300-second age less 30 seconds of skew leaves five real seconds to claim. + Instant databaseNow = + dsl.fetchSingle("SELECT clock_timestamp()").get(0, OffsetDateTime.class).toInstant(); + mutableClock.advance(Duration.between(originalClock, databaseNow.minusSeconds(265))); + var dispatch = prepareConfirmationDispatch(password); + StripeHostingFirstInvoicePaymentClient.ExpiredBeforePost observation; + try { + provider.confirm( + dispatch, + () -> { + var claim = + in(transaction, () -> payments.claimCommand(dispatch, invoice.ownerAccountId())); + if (claim == null) throw new IllegalStateException("Exact command claim required"); + mutableClock.advanceToAtLeast(dispatch.validUntil()); + return claim; + }); + throw new IllegalStateException("The controlled confirm unexpectedly reached Stripe"); + } catch (StripeHostingFirstInvoicePaymentClient.ExpiredBeforePost noSend) { + observation = noSend; + } catch (StripeException failure) { + throw new IllegalStateException( + "Controlled expiry-before-post observation failed", failure); + } + beforeRetention.accept(observation); + // PostgreSQL must independently see expiry before it can retain the no-send witness. + dsl.execute( + "SELECT pg_sleep_until(?::timestamptz)", + OffsetDateTime.ofInstant(observation.observedAt(), ZoneOffset.UTC)); + mutableClock.advanceToAtLeast(originalClock); + in( + transaction, + () -> { + payments.retainExpiredBeforePost(observation); + return true; + }); + return observation; + } + + public AccountHostingFirstInvoicePaymentRepository.ConfirmationDispatch + prepareConfirmationDispatch(String password, Runnable beforeConsent) { + UUID requestId = UUID.randomUUID(); + Account account = + in( + transaction, + () -> accounts.findByAccountUuidForUpdate(invoice.ownerAccountId()).orElseThrow()); + long expectedRowVersion = + in( + transaction, + () -> payments.ownerRowVersion(invoice.subscriptionId(), invoice.ownerAccountId())); + String controlledBearer = "controlled-first-invoice-owner"; + var actor = mock(AccountControlUiActorService.AccountAuthenticatedActor.class); + when(actor.accountId()).thenReturn(invoice.ownerAccountId()); + var actors = mock(AccountControlUiActorService.class); + when(actors.withCurrentAccount(eq(controlledBearer), any())) + .thenAnswer(call -> { + java.util.function.Function + action = call.getArgument(1); + return in(transaction, () -> action.apply(actor)); + }); + // Only the checkout's real owner entry issues and binds a fresh billing proof. The + // unrelated lifecycle collaborator is unused; consent/dispatch remain controlled below. + var owner = + new AccountHostingFirstInvoicePaymentService( + actors, + reauthentication, + payments, + new StripeEventInboxRepository(dsl), + provider, + verifier, + mock(AccountHostingSubscriptionLifecycleService.class), + Objects.requireNonNull(transaction.getTransactionManager())); + UUID evidenceId = + owner.reauthenticate( + controlledBearer, + invoice.subscriptionId(), + UUID.randomUUID(), + requestId, + requestId, + expectedRowVersion, + 0L, + invoice.digest(), + invoice.expiresAt(), + AccountRecentReauthenticationEvidence.BillingAuthorizationPurpose + .INITIAL_CONFIRMATION, + account.getEmail(), + password); + beforeConsent.run(); + var prepared = + in( + transaction, + () -> { + var evidence = + reauthentication.requireCurrentBillingEvidenceLocked( + evidenceId, invoice.ownerAccountId(), requestId); + reauthentication.validateAndConsumeLocked( + evidence, + invoice.ownerAccountId(), + AccountRecentReauthenticationPolicy.BILLING_PURPOSE, + requestId); + return payments.prepareConfirmation( + invoice.ownerAccountId(), + requestId, + invoice.subscriptionId(), + expectedRowVersion, + invoice.digest(), + evidence); + }); + return in(transaction, () -> payments.readDispatch(prepared, invoice.ownerAccountId())); + } + + /** + * Signed success and independent paid readback may arrive after consumed authorization expires. + */ + public AccountHostingFirstInvoicePaymentRepository.ConfirmationDispatch retainSignedSuccess() { + try { + var signed = signedSuccess(); + var verified = verifier.verify(signed.payload(), signed.signature()); + in(transaction, () -> new StripeEventInboxRepository(dsl).retainOrReplay(verified)); + var readback = provider.observe(invoice); + return in(transaction, () -> payments.retainSignedSuccess(verified, readback)); + } catch (StripeException failure) { + throw new IllegalStateException("Controlled signed checkout failed", failure); + } + } + + public SignedSuccess signedSuccess() { + return signedSuccessAt(clock.instant()); + } + + public SignedSuccess signedSuccessAt(Instant createdAt) { + String payload = + "{\"id\":\"evt_" + + invoice.paymentIntentId().substring(3) + + "\",\"object\":\"event\",\"type\":\"payment_intent.succeeded\",\"created\":" + + createdAt.getEpochSecond() + + ",\"livemode\":false,\"data\":{\"object\":" + + transport.intent("succeeded") + + "}}"; + return signWebhookPayload(payload); + } + + public SignedSuccess signWebhookPayload(String payload) { + String timestamp = Long.toString(clock.instant().getEpochSecond()); + try { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(WEBHOOK_SECRET.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); + return new SignedSuccess( + payload, + "t=" + + timestamp + + ",v1=" + + HexFormat.of() + .formatHex( + mac.doFinal((timestamp + "." + payload).getBytes(StandardCharsets.UTF_8)))); + } catch (java.security.GeneralSecurityException failure) { + throw new IllegalStateException(failure); + } + } + } + + public record SignedSuccess(String payload, String signature) {} + + public static final class ControlledFirstInvoiceTransport implements StripeResponseGetter { + private final AccountSubscriptionCreationRecord creation; + private final AccountPaymentInstrumentRecord instrument; + private final String providerId, invoiceId, intentId; + private final boolean terminalReadOnly; + private String status = "requires_confirmation"; + private String terminalInvoiceStatus = "void"; + private String terminalIntentStatus = "canceled"; + private String terminalDirectIntentId; + private boolean terminalIntentUnassigned; + private long terminalAmountPaid; + private long terminalAmountRemaining; + private long terminalAmountReceived; + private int reads; + private final List readPaths = new java.util.ArrayList<>(); + private Runnable duringRead; + private int confirmations; + private String confirmationStatus = "succeeded"; + private boolean loseNextConfirmationResponse; + private String lastConfirmationIdempotencyKey; + + private ControlledFirstInvoiceTransport( + AccountSubscriptionCreationRecord creation, + AccountPaymentInstrumentRecord instrument, + String providerId) { + this(creation, instrument, providerId, false); + } + + public ControlledFirstInvoiceTransport( + AccountSubscriptionCreationRecord creation, + AccountPaymentInstrumentRecord instrument, + String providerId, + boolean terminalReadOnly) { + this.creation = creation; + this.instrument = instrument; + this.providerId = providerId; + this.terminalReadOnly = terminalReadOnly; + String suffix = creation.subscriptionId().toString().replace("-", ""); + invoiceId = "in_" + suffix; + intentId = "pi_" + suffix; + terminalDirectIntentId = intentId; + } + + public int reads() { + return reads; + } + + public int confirmations() { + return confirmations; + } + + public List readPaths() { + return List.copyOf(readPaths); + } + + public void terminalInvoiceStatus(String value) { + terminalInvoiceStatus = Objects.requireNonNull(value); + } + + public void terminalIntentStatus(String value) { + terminalIntentStatus = Objects.requireNonNull(value); + } + + public void terminalIntentId(String value) { + terminalDirectIntentId = Objects.requireNonNull(value); + } + + public void terminalIntentUnassigned(boolean value) { + terminalIntentUnassigned = value; + } + + public void terminalAmounts(long paid, long remaining, long received) { + terminalAmountPaid = paid; + terminalAmountRemaining = remaining; + terminalAmountReceived = received; + } + + public void duringRead(Runnable action) { + if (duringRead != null) throw new IllegalStateException("A provider-read action is pending"); + duringRead = Objects.requireNonNull(action); + } + + @Override + @SuppressWarnings("unchecked") + public T request( + BaseAddress address, + RequestMethod method, + String path, + Map params, + Type type, + RequestOptions options, + ApiMode mode) + throws StripeException { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + String json; + if (method == RequestMethod.GET) { + reads++; + readPaths.add(path); + } + if (terminalReadOnly) { + Runnable action = duringRead; + duringRead = null; + if (action != null) action.run(); + if (path.equals("/v1/invoices/" + invoiceId)) { + assertThat(method).isEqualTo(RequestMethod.GET); + json = terminalInvoice(); + } else if (path.equals("/v1/payment_intents/" + intentId)) { + assertThat(method).isEqualTo(RequestMethod.GET); + json = terminalIntent(terminalDirectIntentId); + } else { + throw new AssertionError("Unexpected terminal-evidence Stripe call: " + path); + } + } else if (path.equals("/v1/subscriptions/" + providerId)) { + assertThat(method).isEqualTo(RequestMethod.GET); + json = + "{\"id\":\"" + + providerId + + "\",\"object\":\"subscription\",\"customer\":\"" + + creation.providerCustomerId() + + "\",\"default_payment_method\":\"" + + instrument.providerPaymentMethodId() + + "\",\"livemode\":false,\"status\":\"incomplete\",\"created\":" + + creation.createdAt().getEpochSecond() + + ",\"latest_invoice\":\"" + + invoiceId + + "\",\"metadata\":{\"firemud_operation_id\":\"" + + creation.subscriptionProvisioningRequestId() + + "\",\"firemud_subscription_id\":\"" + + creation.subscriptionId() + + "\"}}"; + } else if (path.equals("/v1/invoices/" + invoiceId)) { + assertThat(method).isEqualTo(RequestMethod.GET); + boolean paid = "succeeded".equals(status); + json = + "{\"id\":\"" + + invoiceId + + "\",\"object\":\"invoice\",\"customer\":\"" + + creation.providerCustomerId() + + "\",\"livemode\":false,\"billing_reason\":\"subscription_create\",\"status\":\"" + + (paid ? "paid" : "open") + + "\",\"amount_due\":2400,\"total\":2400,\"starting_balance\":0,\"amount_paid\":" + + (paid ? 2400 : 0) + + ",\"amount_remaining\":" + + (paid ? 0 : 2400) + + ",\"currency\":\"usd\",\"parent\":{\"subscription_details\":{\"subscription\":\"" + + providerId + + "\"}},\"lines\":{\"has_more\":false,\"data\":[{\"object\":\"line_item\",\"amount\":2400,\"currency\":\"usd\",\"quantity\":" + + creation.planQuote().providerQuantity() + + ",\"pricing\":{\"type\":\"price_details\",\"price_details\":{\"price\":\"" + + creation.planQuote().providerPriceId() + + "\"}}}]},\"payments\":{\"object\":\"list\",\"has_more\":false,\"data\":[{\"object\":\"invoice_payment\",\"payment\":{\"type\":\"payment_intent\",\"payment_intent\":" + + intent(status) + + "}}]}}"; + } else if (path.equals("/v1/payment_intents/" + intentId)) { + assertThat(method).isEqualTo(RequestMethod.GET); + json = intent(status); + } else if (path.equals("/v1/payment_intents/" + intentId + "/confirm")) { + assertThat(method).isEqualTo(RequestMethod.POST); + assertThat(options.getIdempotencyKey()).isNotBlank(); + lastConfirmationIdempotencyKey = options.getIdempotencyKey(); + assertThat(params) + .containsEntry("payment_method", instrument.providerPaymentMethodId()) + .containsEntry("use_stripe_sdk", true); + assertThat(++confirmations).isOne(); + status = confirmationStatus; + if (loseNextConfirmationResponse) { + loseNextConfirmationResponse = false; + throw new com.stripe.exception.ApiConnectionException( + "Controlled accepted confirmation response was lost"); + } + json = intent(status); + } else { + throw new AssertionError("Unexpected controlled Stripe call: " + path); + } + return (T) com.stripe.net.ApiResource.GSON.fromJson(json, type); + } + + private String terminalInvoice() { + return "{\"id\":\"" + + invoiceId + + "\",\"object\":\"invoice\",\"customer\":\"" + + creation.providerCustomerId() + + "\",\"livemode\":false,\"billing_reason\":\"subscription_create\",\"status\":\"" + + terminalInvoiceStatus + + "\",\"amount_due\":2400,\"total\":2400,\"starting_balance\":0,\"amount_paid\":" + + terminalAmountPaid + + ",\"amount_remaining\":" + + terminalAmountRemaining + + ",\"currency\":\"usd\",\"parent\":{\"subscription_details\":{\"subscription\":\"" + + providerId + + "\"}},\"lines\":{\"has_more\":false,\"data\":[{\"object\":\"line_item\",\"amount\":2400,\"currency\":\"usd\",\"quantity\":" + + creation.planQuote().providerQuantity() + + ",\"pricing\":{\"type\":\"price_details\",\"price_details\":{\"price\":\"" + + creation.planQuote().providerPriceId() + + "\"}}}]},\"payments\":{\"object\":\"list\",\"has_more\":false,\"data\":[{\"object\":\"invoice_payment\",\"payment\":{\"type\":\"payment_intent\",\"payment_intent\":" + + terminalIntent(intentId) + + "}}]}}"; + } + + private String terminalIntent(String id) { + return "{\"id\":\"" + + id + + "\",\"object\":\"payment_intent\",\"customer\":\"" + + creation.providerCustomerId() + + "\",\"payment_method\":" + + (terminalIntentUnassigned ? "null" : "\"" + instrument.providerPaymentMethodId() + "\"") + + ",\"livemode\":false,\"confirmation_method\":\"automatic\",\"status\":\"" + + terminalIntentStatus + + "\",\"amount\":2400,\"amount_received\":" + + terminalAmountReceived + + ",\"currency\":\"usd\"}"; + } + + private String intent(String state) { + return "{\"id\":\"" + + intentId + + "\",\"object\":\"payment_intent\",\"customer\":\"" + + creation.providerCustomerId() + + "\",\"payment_method\":\"" + + instrument.providerPaymentMethodId() + + "\",\"livemode\":false,\"confirmation_method\":\"automatic\",\"status\":\"" + + state + + "\",\"amount\":2400,\"amount_received\":" + + (state.equals("succeeded") ? 2400 : 0) + + ",\"currency\":\"usd\"" + + (state.equals("requires_action") + ? ",\"client_secret\":\"" + intentId + "_secret_testOnly\"" + : "") + + "}"; + } + + @Override + public InputStream requestStream( + BaseAddress address, + RequestMethod method, + String path, + Map params, + RequestOptions options, + ApiMode mode) { + throw new AssertionError("No streaming provider calls"); + } + } + private static T in(TransactionTemplate transaction, Supplier body) { return Objects.requireNonNull(transaction.execute(status -> body.get())); } @@ -278,9 +1020,13 @@ public static final class Fixture { private final String providerId; private final MutableClock clock; private final ControlledStripeTransport transport; + private final ControlledFirstInvoiceTransport terminalInvoiceTransport; private final AccountHostingSubscriptionLifecycleService service; private final AccountHostingSubscriptionLifecycleRepository lifecycleRepository; private final StripeHostingSubscriptionObserver observer; + private final DataSource source; + private FirstInvoiceCheckout checkout; + private Path checkoutDirectory; private Fixture( JdbcTemplate jdbc, @@ -295,9 +1041,11 @@ private Fixture( String providerId, MutableClock clock, ControlledStripeTransport transport, + ControlledFirstInvoiceTransport terminalInvoiceTransport, AccountHostingSubscriptionLifecycleService service, AccountHostingSubscriptionLifecycleRepository lifecycleRepository, - StripeHostingSubscriptionObserver observer) { + StripeHostingSubscriptionObserver observer, + DataSource source) { this.jdbc = jdbc; this.dsl = dsl; this.transaction = transaction; @@ -310,9 +1058,11 @@ private Fixture( this.providerId = providerId; this.clock = clock; this.transport = transport; + this.terminalInvoiceTransport = terminalInvoiceTransport; this.service = service; this.lifecycleRepository = lifecycleRepository; this.observer = observer; + this.source = source; } @SuppressFBWarnings( @@ -375,6 +1125,10 @@ public ControlledStripeTransport transport() { return transport; } + public ControlledFirstInvoiceTransport terminalInvoiceTransport() { + return terminalInvoiceTransport; + } + public AccountHostingSubscriptionLifecycleService service() { return service; } @@ -388,6 +1142,112 @@ public StripeHostingSubscriptionObserver observer() { return observer; } + /** Uses a JUnit-owned directory for both successful and partially constructed checkouts. */ + public Fixture withCheckoutDirectory(Path directory) { + Objects.requireNonNull(directory, "test-owned checkout directory required"); + if (checkoutDirectory != null && !checkoutDirectory.equals(directory)) { + throw new IllegalStateException("Cannot replace the checkout directory"); + } + checkoutDirectory = directory; + return this; + } + + /** Retains the actual existing invoice without granting payment or hosting authority. */ + public FirstInvoiceCheckout awaitFirstInvoice() { + if (checkout == null) + checkout = + prepareFirstInvoice( + Objects.requireNonNull(checkoutDirectory, "test-owned checkout directory required"), + source, + dsl, + transaction, + creation, + instrument, + providerId, + clock, + lifecycleRepository); + return checkout; + } + + public AccountHostingFirstInvoicePayment firstInvoice() { + return awaitFirstInvoice().invoice(); + } + + public AccountHostingFirstInvoicePaymentRepository firstInvoiceRepository() { + return awaitFirstInvoice().payments(); + } + + public StripeHostingFirstInvoicePaymentClient firstInvoiceProvider() { + return awaitFirstInvoice().provider(); + } + + public StripeHostingWebhookVerifier webhookVerifier() { + return awaitFirstInvoice().verifier(); + } + + public void firstInvoiceStatus(String status) { + awaitFirstInvoice().status(status); + } + + public void firstInvoiceConfirmationStatus(String status) { + awaitFirstInvoice().transport.confirmationStatus = status; + } + + public int firstInvoiceConfirmations() { + return awaitFirstInvoice().confirmations(); + } + + public void loseNextFirstInvoiceConfirmationResponse() { + awaitFirstInvoice().loseNextConfirmationResponse(); + } + + public String lastFirstInvoiceConfirmationIdempotencyKey() { + return awaitFirstInvoice().lastConfirmationIdempotencyKey(); + } + + public String signedSuccessPayload() { + return signedSuccess().payload(); + } + + public String signedSuccessHeader() { + return signedSuccess().signature(); + } + + public SignedSuccess signedSuccess() { + return awaitFirstInvoice().signedSuccess(); + } + + /** Genuine password reauthentication and signed completion over controlled provider inputs. */ + public AccountHostingSubscriptionLifecycleRepository.TransitionResult completeFirstInvoice() { + return completeFirstInvoice(BILLING_PASSWORD); + } + + public AccountHostingSubscriptionLifecycleRepository.TransitionResult completeFirstInvoice( + String password) { + var authorized = awaitFirstInvoice().authorizeAndRetainSuccess(password); + providerStatus("active"); + var committed = + service.reconcile( + authorized.lifecycleRequestId(), + creation.requestId(), + authorized.expectedRowVersion(), + providerId, + null); + assertThat(committed.outcome()) + .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Outcome.COMMITTED); + assertThat(service.readCurrent(tenantId).receiptRequestId()) + .isEqualTo(authorized.lifecycleRequestId()); + assertThat( + in( + transaction, + () -> + checkout + .payments() + .completed(creation.subscriptionId(), authorized.lifecycleRequestId()))) + .isTrue(); + return committed; + } + public void providerStatus(String status) { transport.json = response(this, status); } @@ -396,7 +1256,7 @@ public void providerStatus(String status) { public static final class MutableClock extends Clock { private volatile Instant current; - private MutableClock(Instant current) { + public MutableClock(Instant current) { this.current = current; } @@ -404,6 +1264,10 @@ public void advance(Duration duration) { current = current.plus(duration); } + public void advanceToAtLeast(Instant instant) { + if (instant.isAfter(current)) current = instant; + } + @Override public ZoneId getZone() { return ZoneOffset.UTC; diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java index 5963fa19a1..247d924fe4 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java @@ -9,7 +9,9 @@ import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture; import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.time.Duration; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; @@ -46,6 +48,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronization; @@ -57,6 +60,8 @@ * real Stripe, World hold, protected admission transport, custody or runtime activation is proved. */ class AccountPaidCanonicalFirstJoinPostgresIntegrationTest { + @TempDir Path invoiceCheckoutDirectory; + private static final String PREFIX = "paid_first_join_"; private static final String CALLER = "controlled-paid-join-caller"; private static final AccountPostgresIntegrationFixture POSTGRES = @@ -89,8 +94,10 @@ void paidJoinCommitsOnePlayerEventAuditAndReceiptThenExactlyReplaysWithoutProvid Context c = context(false); int reads = c.hosting.transport().reads(); var first = c.commit(c.observed); + var committedAuditRows = c.auditRows(); var replay = c.commit(c.observed); assertThat(replay).isEqualTo(first); + assertThat(c.auditRows()).isEqualTo(committedAuditRows); assertThat(c.hosting.transport().reads()).isEqualTo(reads); assertThat(c.scope.accountId()).isNotEqualTo(c.hosting.accountUuid()); var retained = @@ -104,7 +111,7 @@ void paidJoinCommitsOnePlayerEventAuditAndReceiptThenExactlyReplaysWithoutProvid .containsKey(c.hosting.tenantId().toString()); assertThat(c.count("account_tenant_membership")).isEqualTo(1); assertThat(c.count("account_tenant_membership_role_snapshots")).isEqualTo(1); - assertThat(c.count("account_audit_outbox")).isEqualTo(1); + c.assertCommittedAudit(first); assertThat(c.operation().status()).isEqualTo("COMMITTED"); assertThat(c.operation().terminalProof()).isEqualTo(first); } @@ -125,7 +132,7 @@ void providerFactsChangedBeforeCommitRollbackAllStagedWritesThenSameOriginalCanR var committed = c.commit(recovered); assertThat(committed.entitlementVersion()).isEqualTo(original.entitlementVersion()); assertThat(c.count("account_tenant_membership")).isEqualTo(1); - assertThat(c.count("account_audit_outbox")).isEqualTo(1); + c.assertCommittedAudit(committed); } @Test @@ -190,7 +197,10 @@ private Context context(boolean wrongPolicy) { .locations("classpath:db/migration") .load() .migrate(); - return new Context(CanonicalHostingSubscriptionTestFixture.create(source), wrongPolicy); + return new Context( + CanonicalHostingSubscriptionTestFixture.create(source), + wrongPolicy, + invoiceCheckoutDirectory); } private static final class Context { @@ -204,23 +214,15 @@ private static final class Context { private final String requestId = UUID.randomUUID().toString(); private final ReadFence fence; private final StripeHostingSubscriptionObserver.Result observed; + private final List> paidAuditRows; - private Context(CanonicalHostingSubscriptionTestFixture.Fixture hosting, boolean wrongPolicy) { + private Context( + CanonicalHostingSubscriptionTestFixture.Fixture hosting, + boolean wrongPolicy, + Path invoiceCheckoutDirectory) { this.hosting = hosting; - var claim = - hosting - .service() - .claimProvisioning(hosting.creation().requestId(), 1, UUID.randomUUID()) - .claim(); var committed = - hosting - .service() - .reconcile( - UUID.randomUUID(), - hosting.creation().requestId(), - claim.subscriptionRowVersion(), - hosting.providerId(), - claim.attemptId()); + hosting.withCheckoutDirectory(invoiceCheckoutDirectory).completeFirstInvoice(); assertThat(committed.outcome()) .isEqualTo( net.firedevops.firemud.accountservice.repository @@ -331,6 +333,8 @@ private Context(CanonicalHostingSubscriptionTestFixture.Fixture hosting, boolean receipt.allowPublicJoin(), receipt.entitlementVersion() + (wrongPolicy ? 1 : 0)); }); + paidAuditRows = auditRows(); + assertThat(paidAuditRows).isNotEmpty(); } private AccountJoinOperationRepository.CanonicalJoinTerminalProof commit( @@ -374,12 +378,47 @@ private int count(String table) { return hosting.dsl().fetchCount(DSL.table(table)); } + private List> auditRows() { + return hosting + .dsl() + .fetch( + "SELECT audit_event_id, row_to_json(audit)::text AS row_image, xmin::text AS row_xmin " + + "FROM account_audit_outbox audit ORDER BY audit_event_id") + .intoMaps(); + } + + private void assertCommittedAudit( + AccountJoinOperationRepository.CanonicalJoinTerminalProof proof) { + assertThat( + hosting + .dsl() + .fetch( + "SELECT audit_event_id, row_to_json(audit)::text AS row_image, xmin::text AS row_xmin " + + "FROM account_audit_outbox audit WHERE audit_event_id <> ? ORDER BY audit_event_id", + proof.auditEventId()) + .intoMaps()) + .isEqualTo(paidAuditRows); + var joined = + Objects.requireNonNull( + hosting + .transaction() + .execute(status -> + new AccountAuditOutboxRepository(hosting.dsl()) + .findCanonicalTenantEnvelopeForUpdate(proof.auditEventId()) + .orElseThrow())); + assertThat(joined.auditEventId()).isEqualTo(proof.auditEventId()); + assertThat(joined.eventType()).isEqualTo("ACCOUNT_JOINED_PUBLIC_PRODUCTION"); + assertThat(joined.tenantUuid()).isEqualTo(scope.tenantId()); + assertThat(joined.payloadDigest()).isEqualTo(proof.auditPayloadDigest()); + assertThat(joined.occurredAt()).isEqualTo(proof.auditOccurredAt()); + } + private void assertRolledBack( AccountJoinOperationRepository.CanonicalJoinOperationEvidence original) { assertThat(operation()).isEqualTo(original); assertThat(count("account_tenant_membership")).isZero(); assertThat(count("account_tenant_membership_role_snapshots")).isZero(); - assertThat(count("account_audit_outbox")).isZero(); + assertThat(auditRows()).isEqualTo(paidAuditRows); var checkpoint = hosting.transaction().execute(status -> outbox.readCheckpoint(stream())); assertThat(checkpoint).isEmpty(); var pair = diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java index 51795ff946..b5fc58e926 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java @@ -17,6 +17,7 @@ import java.sql.Connection; import java.sql.SQLException; import java.time.Clock; +import java.time.Duration; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneId; @@ -30,6 +31,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; 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.StripeHostingSubscriptionObserver; @@ -56,6 +58,7 @@ 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.AccountTenantCapacityRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.CapacityException; import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; @@ -72,6 +75,7 @@ import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner.AuthenticatedSignerCorrespondence; import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Evidence; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; @@ -124,7 +128,6 @@ class AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest { private static final String ISSUER = "firemud-account-service"; private static final String PEER = "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service"; - private static final Instant NOW = Instant.parse("2026-11-02T00:00:00Z"); private static final AccountPostgresIntegrationFixture POSTGRES = new AccountPostgresIntegrationFixture(); @TempDir Path certificateDirectory; @@ -191,7 +194,7 @@ void controlledOwnerReceiverAndGameSessionClientComposeWithoutGrantingAdmission( when(target.ownerProofDigest()) .thenReturn((String) sources.get("gameSessionOwnerProofDigest")); var claims = mock(ContextClaims.class); - when(claims.expiresAtMillis()).thenReturn(NOW.plusSeconds(120).toEpochMilli()); + when(claims.expiresAtMillis()).thenReturn(f.baseTime.plusSeconds(120).toEpochMilli()); var context = mock(FirstPartyConnectContext.class); when(context.hasCompleteRoutingScope()).thenReturn(true); when(context.claims()).thenReturn(claims); @@ -210,9 +213,9 @@ void controlledOwnerReceiverAndGameSessionClientComposeWithoutGrantingAdmission( UUID.fromString((String) sources.get("callerTokenJti")), controlledTokenDigest(), GameSessionAccountDelegationProfile.PROFILE, - NOW.minusSeconds(10).getEpochSecond(), - NOW.minusSeconds(10).getEpochSecond(), - NOW.plusSeconds(120).getEpochSecond(), + f.baseTime.minusSeconds(10).getEpochSecond(), + f.baseTime.minusSeconds(10).getEpochSecond(), + f.baseTime.plusSeconds(120).getEpochSecond(), "1", "1", ByteString.EMPTY, @@ -234,10 +237,18 @@ void controlledOwnerReceiverAndGameSessionClientComposeWithoutGrantingAdmission( pki.clientProperties(certificateDirectory, pki.identity("client")), new GrpcChannelFactory(), NAMESPACE, - Clock.fixed(NOW, ZoneOffset.UTC))) { + Clock.fixed(expected.evaluatedAt(), ZoneOffset.UTC))) { client.init(); var received = client.read(context, request.requestId(), login, () -> true); - assertThat(received.canonicalBytes()).isEqualTo(expected.canonicalBytes()); + assertThat(received.fields().get("snapshotIdentity")) + .isEqualTo(expected.fields().get("snapshotIdentity")); + assertThat( + f.dsl + .fetchSingle( + "SELECT canonical_evidence FROM account_tenant_capacity_evaluations WHERE evaluation_identity = ?", + received.fields().get("evaluationIdentity")) + .get(0, byte[].class)) + .containsExactly(received.canonicalBytes()); assertThat(received.membershipSource().membershipExists()).isEqualTo(joined); assertThat(received.membershipSource().gameplayAdmissionAllowed()).isEqualTo(joined); assertThat(new String(received.canonicalBytes(), StandardCharsets.UTF_8)) @@ -289,7 +300,7 @@ void tenantOperationDemoCapturesCurrentSourceOnActualWritableSerializableConnect mock(AccountHostingSubscriptionLifecycleService.class), f.demos, new DataSourceTransactionManager(f.dataSource), - Clock.fixed(NOW, ZoneOffset.UTC), + Clock.fixed(f.baseTime, ZoneOffset.UTC), NAMESPACE); var request = new AccountTenantOperationEntitlementOwner.Request( @@ -332,6 +343,136 @@ void actualAbsenceBaselineReturnsNonadmittingPlayerEvidenceWithoutCreatingMember assertThat(value.membershipSource().sourceEvidence()).isNotEmpty(); } + @Test + void postCommitClockQueryIsCancelledAndReleasesItsConnection() { + var clockReads = new AtomicInteger(); + var blockedBackend = new AtomicInteger(); + Fixture f = + fixture( + false, + Clock.systemUTC(), + new org.jooq.impl.DefaultExecuteListener() { + @Override + public void renderEnd(org.jooq.ExecuteContext context) { + if (!"SELECT clock_timestamp() AS observed_at".equals(context.sql()) + || clockReads.incrementAndGet() != 2) return; + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + try (var statement = context.connection().createStatement(); + var result = statement.executeQuery("SELECT pg_backend_pid()")) { + assertThat(result.next()).isTrue(); + blockedBackend.set(result.getInt(1)); + } catch (SQLException failure) { + throw new IllegalStateException(failure); + } + context.sql("SELECT clock_timestamp() AS observed_at FROM pg_sleep(15)"); + } + }); + long started = System.nanoTime(); + assertThatThrownBy(() -> f.owner.evaluate(f.request(), CONTROLLED_COMPACT_TOKEN)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .rootCause() + .isInstanceOfSatisfying( + SQLException.class, failure -> assertThat(failure.getSQLState()).isEqualTo("57014")); + assertThat(Duration.ofNanos(System.nanoTime() - started)).isLessThan(Duration.ofSeconds(10)); + assertThat(blockedBackend.get()).isPositive(); + org.awaitility.Awaitility.await("PostgreSQL backend released") + .atMost(Duration.ofSeconds(3)) + .until(() -> + !f.dsl.fetchExists( + DSL.selectOne().from("pg_stat_activity").where("pid = ?", blockedBackend.get()))); + assertThat(f.dsl.fetchCount(DSL.table("account_tenant_capacity_evaluations"))).isOne(); + } + + @Test + void paidDeadlinePreservesOnlyTheEarlierBoundAgainstActualPostgresTime() { + Fixture f = fixture(false); + f.transaction.executeWithoutResult(status -> { + Instant stamp = databaseNow(f.dsl); + Instant cutoff = stamp.plusSeconds(20); + assertThat( + AccountPlayerAdmissionEntitlementOwner.conservativePaidReceiptDeadline( + cutoff, stamp, stamp.plusSeconds(5))) + .isEqualTo(stamp.plusSeconds(15)); + assertThat( + AccountPlayerAdmissionEntitlementOwner.conservativePaidReceiptDeadline( + cutoff, stamp, stamp.minusSeconds(5))) + .isEqualTo(cutoff); + assertThatThrownBy(() -> + AccountPlayerAdmissionEntitlementOwner.conservativePaidReceiptDeadline( + cutoff, stamp, cutoff)) + .isInstanceOf(AccountPlayerAdmissionEntitlementOwner.SourceUnavailableException.class); + assertThatThrownBy(() -> + AccountPlayerAdmissionEntitlementOwner.conservativePaidReceiptDeadline( + stamp, stamp, stamp.minusSeconds(5))) + .isInstanceOf(AccountPlayerAdmissionEntitlementOwner.SourceUnavailableException.class); + }); + } + + @Test + void capacityEvaluationUsesDatabaseTimeWhenApplicationClockLeadsDatabaseTime() { + MutableClock aheadOfDatabase = new MutableClock(Instant.EPOCH, ZoneOffset.UTC); + Fixture f = fixture(false, aheadOfDatabase); + Instant databaseBeforeEvaluation = databaseNow(f.dsl); + aheadOfDatabase.setInstant(databaseBeforeEvaluation.plusSeconds(5)); + var value = f.owner.evaluate(f.request(), CONTROLLED_COMPACT_TOKEN); + Instant databaseAfterEvaluation = databaseNow(f.dsl); + assertThat(aheadOfDatabase.instant()).isAfter(databaseAfterEvaluation); + assertThat(value.evaluatedAt()).isAfterOrEqualTo(databaseBeforeEvaluation); + assertThat(value.evaluatedAt()).isBeforeOrEqualTo(databaseAfterEvaluation); + + var target = (Map) value.fields().get("target"); + var sourceReferences = (Map) value.fields().get("sourceReferences"); + assertThat(target.get("evaluatedAt")).isEqualTo(f.scope.evaluatedAt()); + assertThat(target.get("connectScopeExpiresAt")).isEqualTo(f.scope.connectScopeExpiresAt()); + assertThat(sourceReferences.get("scopeDigest")).isEqualTo(AccountJoinDigest.scopeV2(f.scope)); + + var retained = + f.dsl.fetchOne( + "SELECT canonical_evidence, evaluated_at, expires_at " + + "FROM account_tenant_capacity_evaluations WHERE evaluation_identity = ?", + value.fields().get("evaluationIdentity")); + assertThat(retained).isNotNull(); + assertThat(retained.get("canonical_evidence", byte[].class)) + .containsExactly(value.canonicalBytes()); + assertThat(AccountTenantCapacityRepository.time(retained, "evaluated_at")) + .isEqualTo(value.evaluatedAt()); + assertThat(AccountTenantCapacityRepository.time(retained, "expires_at")) + .isEqualTo( + value.validUntil().isBefore(value.evaluatedAt().plusSeconds(15)) + ? value.validUntil() + : value.evaluatedAt().plusSeconds(15)); + + var capacity = new AccountTenantCapacityRepository(f.dsl); + f.transaction.executeWithoutResult(status -> capacity.requireFresh(Evidence.player(value))); + } + + @Test + void capacityEvaluationUsesDatabaseTimeWhenApplicationClockTrailsDatabaseTime() { + MutableClock behindDatabase = new MutableClock(Instant.EPOCH, ZoneOffset.UTC); + Fixture f = fixture(false, behindDatabase); + Instant databaseBeforeEvaluation = databaseNow(f.dsl); + behindDatabase.setInstant(databaseBeforeEvaluation.plusSeconds(-5)); + var value = f.owner.evaluate(f.request(), CONTROLLED_COMPACT_TOKEN); + Instant databaseAfterEvaluation = databaseNow(f.dsl); + assertThat(behindDatabase.instant()).isBefore(databaseBeforeEvaluation); + assertThat(value.evaluatedAt()).isAfterOrEqualTo(databaseBeforeEvaluation); + assertThat(value.evaluatedAt()).isBeforeOrEqualTo(databaseAfterEvaluation); + + var retained = + f.dsl.fetchOne( + "SELECT canonical_evidence, evaluated_at, expires_at " + + "FROM account_tenant_capacity_evaluations WHERE evaluation_identity = ?", + value.fields().get("evaluationIdentity")); + assertThat(retained).isNotNull(); + assertThat(retained.get("canonical_evidence", byte[].class)) + .containsExactly(value.canonicalBytes()); + assertThat(AccountTenantCapacityRepository.time(retained, "evaluated_at")) + .isEqualTo(value.evaluatedAt()); + + var capacity = new AccountTenantCapacityRepository(f.dsl); + f.transaction.executeWithoutResult(status -> capacity.requireFresh(Evidence.player(value))); + } + @Test void actualFirstJoinRetainsItsPositiveMembershipAndExactScopeBinding() { Fixture f = fixture(true); @@ -713,6 +854,22 @@ private Fixture fixture(boolean join) { } private Fixture fixture(boolean join, boolean initializeCapacity) { + return fixture(join, null, new org.jooq.impl.DefaultExecuteListener(), initializeCapacity); + } + + private Fixture fixture(boolean join, Clock applicationClock) { + return fixture(join, applicationClock, new org.jooq.impl.DefaultExecuteListener(), false); + } + + private Fixture fixture(boolean join, Clock applicationClock, org.jooq.ExecuteListener listener) { + return fixture(join, applicationClock, listener, false); + } + + private Fixture fixture( + boolean join, + Clock applicationClock, + org.jooq.ExecuteListener listener, + boolean initializeCapacity) { String schema = SCHEMA_PREFIX + UUID.randomUUID().toString().replace("-", ""); schemas.add(schema); DriverManagerDataSource dataSource = POSTGRES.dataSource(schema); @@ -724,7 +881,14 @@ private Fixture fixture(boolean join, boolean initializeCapacity) { .locations("classpath:db/migration") .load() .migrate(); - return new Fixture(dataSource, join, initializeCapacity); + DSLContext setupDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + Instant baseTime = databaseNow(setupDsl).truncatedTo(java.time.temporal.ChronoUnit.MILLIS); + return new Fixture(dataSource, join, baseTime, applicationClock, listener, initializeCapacity); + } + + private static Instant databaseNow(DSLContext dsl) { + return AccountTenantCapacityRepository.time( + dsl.fetchSingle("SELECT clock_timestamp() AS observed_at"), "observed_at"); } /** Controlled protected-client double: no physical GS/World source provenance is claimed. */ @@ -812,23 +976,30 @@ private static void controlledTarget(CanonicalGameplayAdmissionDecisionReadClien private static final class Fixture { private final DriverManagerDataSource dataSource; private final DSLContext dsl; - private final Instant now; private final MutableClock clock; private final TransactionTemplate transaction; private final AccountRepository accounts; private final AccountTenantMembershipRepository memberships; private final AccountDemoTenantEntitlementRepository demos; private final Account account; + private final Instant baseTime; private final UUID tenantId = UUID.randomUUID(); private final CanonicalJoinScopeV2 scope; private final AccountPlayerAdmissionEntitlementOwner owner; private final AccountTenantCapacityOwner capacityOwner; - private Fixture(DriverManagerDataSource dataSource, boolean join, boolean initializeCapacity) { + private Fixture( + DriverManagerDataSource dataSource, + boolean join, + Instant baseTime, + Clock applicationClock, + org.jooq.ExecuteListener listener, + boolean initializeCapacity) { this.dataSource = dataSource; - now = initializeCapacity ? Instant.now().truncatedTo(ChronoUnit.MICROS) : NOW; - clock = new MutableClock(now, ZoneOffset.UTC); + this.baseTime = baseTime; + clock = new MutableClock(baseTime, ZoneOffset.UTC); dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + dsl.configuration().set(new org.jooq.impl.DefaultExecuteListenerProvider(listener)); var transactions = new DataSourceTransactionManager(dataSource); transaction = new TransactionTemplate(transactions); accounts = new AccountRepository(dsl); @@ -915,8 +1086,8 @@ private Fixture(DriverManagerDataSource dataSource, boolean join, boolean initia UUID.randomUUID(), 7, 3, - now.minusSeconds(20).toString(), - now.plusSeconds(120).toString()); + baseTime.minusSeconds(20).toString(), + baseTime.plusSeconds(120).toString()); String joinRequestId = UUID.randomUUID().toString(); String callerBinding = "controlled-join-caller"; transaction.execute(status -> { @@ -984,9 +1155,9 @@ private Fixture(DriverManagerDataSource dataSource, boolean join, boolean initia mock(AccountGameplayCredentialRequestBinding.class), "a".repeat(64), UUID.randomUUID(), - now.minusSeconds(10).getEpochSecond(), - now.minusSeconds(10).getEpochSecond(), - now.plusSeconds(120).getEpochSecond()); + baseTime.minusSeconds(10).getEpochSecond(), + baseTime.minusSeconds(10).getEpochSecond(), + baseTime.plusSeconds(120).getEpochSecond()); var candidate = mock(CommittedCandidateVerificationData.class); when(candidate.identity()).thenReturn(identity); when(candidate.authoritySnapshot()) @@ -1035,7 +1206,7 @@ private Fixture(DriverManagerDataSource dataSource, boolean join, boolean initia tenantEvents, targets, transactions, - clock, + applicationClock == null ? clock : applicationClock, NAMESPACE); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerPostgresIntegrationTest.java index adfdf376d3..916c565ff1 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerPostgresIntegrationTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture; +import java.nio.file.Path; import java.util.List; import java.util.Map; import java.util.UUID; @@ -23,6 +24,7 @@ import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -37,6 +39,8 @@ */ @Testcontainers(disabledWithoutDocker = true) class AccountTenantOperationEntitlementOwnerPostgresIntegrationTest { + @TempDir Path invoiceCheckoutDirectory; + private static final String WORLD = "spiffe://firemud/ns/prod/sa/world-management-service"; @Container @@ -94,16 +98,7 @@ void reusedAccountFixtureKeepsConfirmedCustomerAndObservationHistoryUnchanged() void paidUsesActualReceiptSdkAndAuthorityCheckpointWithFreshEvaluationOfSameSnapshot() { Context c = context(); var f = c.fixture(); - var claim = - f.service().claimProvisioning(f.creation().requestId(), 1, UUID.randomUUID()).claim(); - var committed = - f.service() - .reconcile( - UUID.randomUUID(), - f.creation().requestId(), - claim.subscriptionRowVersion(), - f.providerId(), - claim.attemptId()); + var committed = f.withCheckoutDirectory(invoiceCheckoutDirectory).completeFirstInvoice(); assertThat(committed.outcome()).isEqualTo(Outcome.COMMITTED); int beforeReads = f.transport().reads(); UUID requestId = UUID.randomUUID(); @@ -154,16 +149,7 @@ void paidUsesActualReceiptSdkAndAuthorityCheckpointWithFreshEvaluationOfSameSnap void captureRunsInsideFinalWritableTransactionAndFailureRollsBackCapturedSql() { Context c = context(); var f = c.fixture(); - var claim = - f.service().claimProvisioning(f.creation().requestId(), 1, UUID.randomUUID()).claim(); - var committed = - f.service() - .reconcile( - UUID.randomUUID(), - f.creation().requestId(), - claim.subscriptionRowVersion(), - f.providerId(), - claim.attemptId()); + var committed = f.withCheckoutDirectory(invoiceCheckoutDirectory).completeFirstInvoice(); assertThat(committed.outcome()).isEqualTo(Outcome.COMMITTED); String marker = "capture_marker_" + UUID.randomUUID().toString().replace("-", ""); AtomicInteger captures = new AtomicInteger(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java index 4fdb8ddc3b..d6dc363b85 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java @@ -2,7 +2,10 @@ 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.mock; +import static org.mockito.Mockito.when; import de.mkammerer.argon2.Argon2Factory; import java.io.IOException; @@ -136,6 +139,61 @@ void postgresMicrosecondTimestampReadbackPreservesOriginalAndExactReplay() { assertThat(replay.issuedAt()).isEqualTo(persistedInstant); } + @Test + void typedBillingBindingRoundTripsJavaFractionGroupsThroughPostgres() { + Context c = context(); + installBillingPolicy(c); + Account account = c.account("PASSWORD"); + var actors = controlledBillingActors(c, account); + for (Instant expiry : + List.of( + Instant.parse("2026-11-01T01:02:03.123400Z"), + Instant.parse("2026-11-01T01:02:03.100000Z"))) { + UUID requestId = UUID.randomUUID(); + UUID authorizationId = UUID.randomUUID(); + var binding = + new AccountRecentReauthenticationEvidence.BillingContext( + account.getAccountUuid(), + UUID.randomUUID(), + UUID.randomUUID(), + "sha256:" + "d".repeat(64), + 3L, + expiry, + authorizationId, + 0L, + AccountRecentReauthenticationEvidence.BillingAuthorizationPurpose.PRE_ROW_RENEWAL); + var request = + new AccountRecentReauthenticationService.Request( + requestId, + account.getAccountUuid(), + AccountRecentReauthenticationPolicy.BILLING_PURPOSE, + authorizationId, + binding, + account.getEmail(), + PASSWORD); + + var fenceCallbacks = new ArrayList(); + var original = + c.service.reauthenticateAndBindBilling( + request, actors, "controlled-bearer", e -> fenceCallbacks.add(e.evidenceId())); + Record row = c.evidenceRow(original.evidenceId()); + var replay = + c.service.reauthenticateAndBindBilling( + request, actors, "controlled-bearer", e -> fenceCallbacks.add(e.evidenceId())); + assertThat(fenceCallbacks).containsExactly(original.evidenceId(), original.evidenceId()); + + assertThat(original.billingContext()).isEqualTo(binding); + assertThat( + row.get("billing_context_invoice_expires_at", java.time.OffsetDateTime.class) + .toInstant()) + .isEqualTo(expiry); + assertThat(row.get("billing_context_digest", String.class)).isEqualTo(binding.digest()); + assertThat(row.get("request_digest", String.class)).isEqualTo(original.requestDigest()); + assertThat(replay.evidenceId()).isEqualTo(original.evidenceId()); + assertThat(replay.billingContext()).isEqualTo(binding); + } + } + @Test void nonV4RequestAndCreationIdsAreAcceptedForPersistedAccountIdentity() { Context c = context(); @@ -809,8 +867,10 @@ void forwardSourceOrderingMigrationSeedsOnlyCurrentPointersAndPreservesRetainedB Account account = c.account("PASSWORD"); UUID evidenceId = insertEvidenceWithoutMac(c, account, UUID.randomUUID(), UUID.randomUUID()); var evidence = readHistoricalEvidence(c, evidenceId); - c.consume( - evidence, account.getAccountUuid(), evidence.purpose(), evidence.creationOperationId()); + // This predecessor schema has the original consumption contract, without billing columns. + c.tx(() -> + new AccountRecentReauthenticationRepository(c.dsl) + .insertConsumption(evidence, c.clock.instant())); Record originalEvidence = c.evidenceRow(evidence.evidenceId()); Record originalConsumption = Objects.requireNonNull( @@ -840,7 +900,7 @@ void forwardSourceOrderingMigrationSeedsOnlyCurrentPointersAndPreservesRetainedB c.migrateToLatest(); - assertThat(c.evidenceRow(evidence.evidenceId())).isEqualTo(originalEvidence); + assertHistoricalEvidence(c, evidence.evidenceId(), originalEvidence); assertThat( Objects.requireNonNull( c.dsl.fetchOne( @@ -1156,7 +1216,7 @@ void migrationPreservesHistoricalEvidenceWithoutGrantingReplayOrAllowingBackfill .migrate(); assertThat(c.count("SELECT count(*) FROM account_recent_reauthentication_replay_failures")) .isZero(); - assertThat(c.evidenceRow(evidenceId)).isEqualTo(original); + assertHistoricalEvidence(c, evidenceId, original); assertThatThrownBy( () -> c.service.reauthenticate(c.request(account, requestId, operationId, PASSWORD))) .isInstanceOf(IllegalStateException.class); @@ -1172,13 +1232,93 @@ void migrationPreservesHistoricalEvidenceWithoutGrantingReplayOrAllowingBackfill operationId, "a".repeat(64)))) .isInstanceOf(DataAccessException.class); - assertThat(c.evidenceRow(evidenceId)).isEqualTo(original); + assertHistoricalEvidence(c, evidenceId, original); assertThat(c.count("SELECT count(*) FROM account_recent_reauthentication_evidence")) .isEqualTo(1); assertThat(c.count("SELECT count(*) FROM account_recent_reauthentication_replay_credentials")) .isZero(); } + @Test + void firstInvoiceFenceMigrationPreservesUnboundBillingEvidenceWithoutAuthorizingIt() { + Context c = contextAtVersion(true, MigrationVersion.fromVersion("1042")); + installBillingPolicy(c); + Account account = c.account("PASSWORD"); + UUID requestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String purpose = AccountRecentReauthenticationPolicy.BILLING_PURPOSE; + UUID evidenceId = + c.tx(() -> { + UUID id = insertEvidenceWithoutMac(c, account, requestId, operationId, purpose); + c.dsl.execute( + "INSERT INTO account_recent_reauthentication_replay_credentials" + + " (evidence_id, request_id, account_uuid, purpose, creation_operation_id, key_id, credential_mac)" + + " VALUES (?, ?, ?, ?, ?, 'mac1', ?)", + id, + requestId, + account.getAccountUuid(), + purpose, + operationId, + "a".repeat(64)); + return id; + }); + Record original = c.evidenceRow(evidenceId); + String xmin = c.evidenceXmin(evidenceId); + String credentialRead = + "SELECT to_jsonb(credential)::text AS image" + + " FROM account_recent_reauthentication_replay_credentials credential" + + " WHERE evidence_id = ?"; + String replayCredential = + c.dsl.fetchSingle(credentialRead, evidenceId).get("image", String.class); + assertThat(replayCredential).isNotNull(); + c.migrateToLatest(); + assertThat(c.dsl.fetchSingle(credentialRead, evidenceId).get("image", String.class)) + .isEqualTo(replayCredential); + assertHistoricalEvidence(c, evidenceId, original); + var repository = new AccountRecentReauthenticationRepository(c.dsl); + var retained = c.tx(() -> repository.findByRequest(requestId).orElseThrow()); + assertThat(retained.evidenceId()).isEqualTo(evidenceId); + assertThat(retained.billingContext()).isNull(); + + var binding = + new AccountRecentReauthenticationEvidence.BillingContext( + account.getAccountUuid(), + UUID.randomUUID(), + operationId, + "sha256:" + "d".repeat(64), + 1L, + BASE.plusSeconds(60), + operationId, + 0L, + AccountRecentReauthenticationEvidence.BillingAuthorizationPurpose.INITIAL_CONFIRMATION); + var changed = + new AccountRecentReauthenticationService.Request( + requestId, + account.getAccountUuid(), + purpose, + operationId, + binding, + account.getEmail(), + PASSWORD); + var actors = controlledBillingActors(c, account); + assertThatThrownBy(() -> + c.service.reauthenticateAndBindBilling( + changed, + actors, + "controlled-bearer", + ignored -> { + throw new AssertionError("Changed legacy binding must not reach invoice fence"); + })) + .isInstanceOf(AccountRecentReauthenticationService.IdempotencyConflictException.class); + assertHistoricalEvidence(c, evidenceId, original); + assertThat(c.evidenceXmin(evidenceId)).isEqualTo(xmin); + assertThat(c.count("SELECT count(*) FROM account_recent_reauthentication_evidence")).isOne(); + assertThat(c.count("SELECT count(*) FROM account_recent_reauthentication_consumptions")) + .isZero(); + assertThat(c.count("SELECT count(*) FROM subscription_first_invoice_operation_fences")) + .isZero(); + } + @Test void forwardBudgetMigrationPreservesPreviouslyCommittedProofAndStartsWithNoFailures() { Context c = contextAtVersion(true, MigrationVersion.fromVersion("1018.1")); @@ -1209,7 +1349,7 @@ void forwardBudgetMigrationPreservesPreviouslyCommittedProofAndStartsWithNoFailu .locations("classpath:db/migration") .load() .migrate(); - assertThat(c.evidenceRow(evidenceId)).isEqualTo(original); + assertHistoricalEvidence(c, evidenceId, original); assertThat(c.dsl.fetchOne("SELECT * FROM account_recent_reauthentication_replay_credentials")) .isEqualTo(proof); assertThat(c.count("SELECT count(*) FROM account_recent_reauthentication_replay_failures")) @@ -1219,7 +1359,7 @@ void forwardBudgetMigrationPreservesPreviouslyCommittedProofAndStartsWithNoFailu .isInstanceOf(AuthenticationException.class); assertThat(c.count("SELECT count(*) FROM account_recent_reauthentication_replay_failures")) .isEqualTo(1L); - assertThat(c.evidenceRow(evidenceId)).isEqualTo(original); + assertHistoricalEvidence(c, evidenceId, original); assertThat(c.dsl.fetchOne("SELECT * FROM account_recent_reauthentication_replay_credentials")) .isEqualTo(proof); } @@ -1898,16 +2038,60 @@ private static AccountRecentReauthenticationEvidence readHistoricalEvidence( row.get("issued_at", java.time.OffsetDateTime.class).toInstant()); } + private static AccountControlUiActorService controlledBillingActors(Context c, Account account) { + var actor = mock(AccountControlUiActorService.AccountAuthenticatedActor.class); + when(actor.accountId()).thenReturn(account.getAccountUuid()); + var actors = mock(AccountControlUiActorService.class); + when(actors.withCurrentAccount(eq("controlled-bearer"), any())) + .thenAnswer(call -> { + java.util.function.Function + action = call.getArgument(1); + return c.tx(() -> action.apply(actor)); + }); + return actors; + } + + private static void installBillingPolicy(Context c) { + c.tx(() -> { + c.dsl.execute( + "INSERT INTO account_billing_reauthentication_policy_values " + + "(policy_scope, policy_version, recent_age_seconds, max_clock_skew_seconds) " + + "VALUES ('PLATFORM', 1, 300, 30), ('DEPLOYMENT', 1, 300, 30)"); + return c.dsl.execute( + "INSERT INTO account_billing_reauthentication_policy_current " + + "(policy_scope, policy_version) VALUES ('PLATFORM', 1), ('DEPLOYMENT', 1)"); + }); + } + + private static void assertHistoricalEvidence(Context c, UUID id, Record original) { + Record retained = c.evidenceRow(id); + assertThat(retained.into(original.fields())).isEqualTo(original); + assertThat( + Arrays.stream(retained.fields()) + .map(field -> field.getName()) + .filter(name -> name.startsWith("billing_context_")) + .toList()) + .hasSize(9) + .allMatch(name -> retained.get(name) == null); + } + /** Controlled pre-migration evidence fixture using actual Account and policy source guards. */ private static UUID insertEvidenceWithoutMac( Context c, Account account, UUID requestId, UUID operationId) { + return insertEvidenceWithoutMac( + c, account, requestId, operationId, AccountRecentReauthenticationPolicy.PURPOSE); + } + + private static UUID insertEvidenceWithoutMac( + Context c, Account account, UUID requestId, UUID operationId, String purpose) { UUID evidenceId = UUID.randomUUID(); String payload = "account-recent-reauthentication-request/v1\nrequestId=" + requestId + "\naccountId=" + account.getAccountUuid() - + "\npurpose=SELF_SERVICE_GAME_CREATION" + + "\npurpose=" + + purpose + "\ncreationOperationId=" + operationId + "\n"; @@ -1923,6 +2107,7 @@ private static UUID insertEvidenceWithoutMac( } var policy = AccountRecentReauthenticationPolicy.resolve( + purpose, new AccountRecentReauthenticationPolicy.PlatformValue(1, 300, 30), new AccountRecentReauthenticationPolicy.DeploymentValue(1, 300, 30)); c.tx(() -> { @@ -1934,10 +2119,11 @@ private static UUID insertEvidenceWithoutMac( + " identity_provenance, account_uuid_source_numeric_id, account_lifecycle_state, account_authority_generation," + " account_authority_source_version, issuance_fence, issuance_fence_source_version, platform_policy_version," + " deployment_policy_version, effective_policy_version, recent_age_seconds, max_clock_skew_seconds, issued_at)" - + " VALUES (?, ?, ?, 'SELF_SERVICE_GAME_CREATION', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 1, ?, 300, 30, ?::timestamptz)", + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 1, ?, 300, 30, ?::timestamptz)", evidenceId, requestId, account.getAccountUuid(), + purpose, operationId, bytes, digest, @@ -2050,6 +2236,14 @@ Record evidenceRow(UUID evidenceId) { evidenceId)); } + String evidenceXmin(UUID evidenceId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT xmin::text FROM account_recent_reauthentication_evidence WHERE evidence_id = ?", + evidenceId)) + .get(0, String.class); + } + long count(String query, Object... parameters) { return Objects.requireNonNull(dsl.fetchOne(query, parameters)).get(0, Long.class); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java index a4fd16104a..082121f922 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java @@ -639,8 +639,15 @@ void boundedIndeterminateCapacityRecoveryQuarantinesTheOriginalCompleteHold() { } @Test - void firstRecoveryAfterDeadlineFinalizesAnExactPositiveOnce() { - var f = capacityPersistenceFixture(true); + void firstRecoveryAfterDeadlineFinalizesPositiveAndQuarantinesOtherOutcomes() + throws InterruptedException { + var outcomes = List.of("negative", "indeterminate", "malformed", "unavailable", "late"); + var fixtures = capacityPersistenceFixturesPastRecoveryDeadline(1 + outcomes.size()); + assertExactPositiveAfterDeadline(fixtures.getFirst()); + assertOtherOutcomesAfterDeadline(outcomes, fixtures.subList(1, fixtures.size())); + } + + private static void assertExactPositiveAfterDeadline(CapacityPersistenceFixture f) { assertThat(Instant.now()).isAfter(f.initial.expiresAt().plusSeconds(60)); var calls = new java.util.concurrent.atomic.AtomicInteger(); var recovery = @@ -685,11 +692,11 @@ void firstRecoveryAfterDeadlineFinalizesAnExactPositiveOnce() { .isEqualTo(1); } - @Test - void firstLateNegativeMalformedUnavailableAndOverBudgetReadsQuarantineWithoutReleasing() { - for (String outcome : - List.of("negative", "indeterminate", "malformed", "unavailable", "late")) { - var f = capacityPersistenceFixture(true); + private static void assertOtherOutcomesAfterDeadline( + List outcomes, List fixtures) { + for (int index = 0; index < outcomes.size(); index++) { + String outcome = outcomes.get(index); + var f = fixtures.get(index); assertThat(Instant.now()).isAfter(f.initial.expiresAt().plusSeconds(60)); var now = new java.util.concurrent.atomic.AtomicReference<>(Instant.now()); var recoveryClock = @@ -778,12 +785,55 @@ public Instant instant() { } } - /** Genuine same-transaction fresh creation; controlled entitlement and owner execution source. */ - private static CapacityPersistenceFixture capacityPersistenceFixture() { - return capacityPersistenceFixture(false); + /** Age committed fresh attempts without changing evidence, immutable rows or database time. */ + private static List capacityPersistenceFixturesPastRecoveryDeadline( + int count) throws InterruptedException { + var fixtures = new ArrayList(); + var retained = new ArrayList(); + // Create all cases before waiting, so all six cases share one real aging window. + for (int index = 0; index < count; index++) { + var fixture = capacityPersistenceFixture(); + fixtures.add(fixture); + retained.add(capacityReservationImage(fixture)); + } + long started = System.nanoTime(); + for (int index = 0; index < fixtures.size(); index++) { + var fixture = fixtures.get(index); + var poll = + fixture.context.deadlinePoll.resultQuery( + "SELECT clock_timestamp() > reconcile_deadline AS expired" + + " FROM account_tenant_capacity_reservations WHERE reservation_id = ?", + fixture.initial.reservationId()); + poll.queryTimeout(3); + while (!Boolean.TRUE.equals(poll.fetchSingle().get("expired", Boolean.class)) + || !Instant.now().isAfter(fixture.initial.expiresAt().plusSeconds(60))) { + assertThat(System.nanoTime() - started) + .as( + "Fresh reservation must age past its persisted recovery deadline within two minutes") + .isLessThan(TimeUnit.MINUTES.toNanos(2)); + Thread.sleep(250); + } + assertThat(capacityReservationImage(fixture)).isEqualTo(retained.get(index)); + assertThat( + fixture.context.dsl.fetchCount( + DSL.table("account_tenant_capacity_recovery_evidence"))) + .isZero(); + } + return fixtures; } - private static CapacityPersistenceFixture capacityPersistenceFixture(boolean expired) { + private static String capacityReservationImage(CapacityPersistenceFixture fixture) { + return fixture + .context + .dsl + .fetchSingle( + "SELECT jsonb_build_object('row', to_jsonb(reservation), 'xmin', reservation.xmin::text)::text AS image FROM account_tenant_capacity_reservations reservation WHERE reservation_id = ?", + fixture.initial.reservationId()) + .get("image", String.class); + } + + /** Genuine same-transaction fresh creation; controlled entitlement and owner execution source. */ + private static CapacityPersistenceFixture capacityPersistenceFixture() { StorageContext c = storageContext(); var fixture = storageFixture(c); var assembled = assembleStoredOwner(c, fixture, new AccountAuditOutboxRepository(c.dsl)); @@ -796,53 +846,52 @@ private static CapacityPersistenceFixture capacityPersistenceFixture(boolean exp var base = net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture.worldRequest( 17L); - // A retained historical reservation is inserted through the same controlled source fixture. - // No live producer accepts stale evidence, and no immutable row or database clock is changed. - var now = - java.time.Instant.now() - .minusSeconds(expired ? 120 : 0) - .truncatedTo(java.time.temporal.ChronoUnit.MICROS); - String json = - new String(base.evidence().canonicalBytes(), java.nio.charset.StandardCharsets.UTF_8) - .replace(base.identity().tenantId().toString(), tenant.toString()) - .replace( - net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture.NOW - .toString(), - now.toString()); - var evidence = - net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Evidence.parse( - json.getBytes(java.nio.charset.StandardCharsets.UTF_8), - net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Owner - .WORLD_MANAGEMENT); - var context = - (net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.WorldContext) - base.context(); - var request = - new net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request( - new net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Identity( - tenant, base.identity().requestId(), base.identity().admissionId()), - base.admissionAttemptId(), - base.capacityRearmFence(), - base.targetNamespace(), - new net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission - .WorldContext( - tenant, - context.operationId(), - context.lifecycleId(), - context.gameInstanceId(), - context.ownerId(), - context.ownerFence()), - base.operation(), - base.priorShape(), - base.requestedShape(), - evidence, - base.capacityDelta(), - null) - .withDigest(); var repository = new net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository(c.dsl); var initial = c.transaction.execute(status -> { + var now = + net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository + .databaseNow(c.dsl); + String json = + new String(base.evidence().canonicalBytes(), java.nio.charset.StandardCharsets.UTF_8) + .replace(base.identity().tenantId().toString(), tenant.toString()) + .replace( + net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture + .NOW + .toString(), + now.toString()); + var evidence = + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Evidence.parse( + json.getBytes(java.nio.charset.StandardCharsets.UTF_8), + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Owner + .WORLD_MANAGEMENT); + var context = + (net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.WorldContext) + base.context(); + var request = + new net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request( + new net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission + .Identity( + tenant, base.identity().requestId(), base.identity().admissionId()), + base.admissionAttemptId(), + base.capacityRearmFence(), + base.targetNamespace(), + new net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission + .WorldContext( + tenant, + context.operationId(), + context.lifecycleId(), + context.gameInstanceId(), + context.ownerId(), + context.ownerFence()), + base.operation(), + base.priorShape(), + base.requestedShape(), + evidence, + base.capacityDelta(), + null) + .withDigest(); // Controlled fixture evidence deliberately bypasses the absent World producer. // Production // has no route to perform this insertion and World admission remains unavailable. @@ -858,12 +907,11 @@ private static CapacityPersistenceFixture capacityPersistenceFixture(boolean exp evidence.evaluatedAt()), net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.at( evidence.expiresAt())); - return repository - .createIfQuotaAvailable( - request, - evidence.expiresAt(), - Clock.fixed(evidence.evaluatedAt(), ZoneOffset.UTC)) - .orElseThrow(() -> new AssertionError("Controlled fixture must have capacity")); + var reservation = + repository + .createIfQuotaAvailable(request, repository.usage(request), evidence.expiresAt()) + .orElseThrow(); + return Map.entry(request, reservation); }); var owner = new net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner( @@ -881,7 +929,8 @@ private static CapacityPersistenceFixture capacityPersistenceFixture(boolean exp c.manager, java.time.Clock.systemUTC(), "prod"); - return new CapacityPersistenceFixture(c, request, repository, owner, initial); + return new CapacityPersistenceFixture( + c, initial.getKey(), repository, owner, initial.getValue()); } private static net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker @@ -1764,6 +1813,15 @@ private static StorageContext storageContext(int recentAgeSeconds, int maxClockS .load() .migrate(); DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + var pollSource = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + pollSource.setSchema(schema); + var pollProperties = new java.util.Properties(); + pollProperties.setProperty("connectTimeout", "5"); + pollProperties.setProperty("socketTimeout", "5"); + pollSource.setConnectionProperties(pollProperties); + DSLContext deadlinePoll = DSL.using(pollSource, SQLDialect.POSTGRES); var manager = new DataSourceTransactionManager(source); var transaction = new TransactionTemplate(manager); transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); @@ -1828,7 +1886,7 @@ private static StorageContext storageContext(int recentAgeSeconds, int maxClockS manager, Clock.systemUTC(), reauthenticationCryptography(Clock.systemUTC())); - return new StorageContext(dsl, accounts, evidence, service, transaction, manager); + return new StorageContext(dsl, deadlinePoll, accounts, evidence, service, transaction, manager); } private static AccountControlUiResponseCryptography reauthenticationCryptography(Clock clock) { @@ -1867,6 +1925,7 @@ private record StorageFixture( private record StorageContext( DSLContext dsl, + DSLContext deadlinePoll, AccountRepository accounts, AccountRecentReauthenticationRepository evidenceRepository, AccountRecentReauthenticationService service, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeFirstInvoiceHttpClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeFirstInvoiceHttpClientTest.java new file mode 100644 index 0000000000..f5cf28966d --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeFirstInvoiceHttpClientTest.java @@ -0,0 +1,152 @@ +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.junit.jupiter.api.Assertions.assertTimeoutPreemptively; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.stripe.exception.ApiConnectionException; +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.List; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.Flow; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; + +class StripeFirstInvoiceHttpClientTest { + @Test + void cancelsASlowlyStreamingStripeBodyWithoutAnotherRequest() throws Exception { + var streaming = new CountDownLatch(5); + try (var server = new ServerSocket(); + var serverExecutor = Executors.newSingleThreadExecutor(); + var transport = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(1)).build()) { + server.bind(new InetSocketAddress("127.0.0.1", 0)); + server.setSoTimeout(5_000); + var peerClosed = + serverExecutor.submit(() -> { + try (var peer = server.accept()) { + peer.setSoTimeout(5_000); + var inbound = + new BufferedReader( + new InputStreamReader(peer.getInputStream(), StandardCharsets.US_ASCII)); + assertThat(inbound.readLine()).startsWith("GET /v1/invoices/in_exact HTTP/"); + String header; + do { + header = inbound.readLine(); + assertThat(header) + .as("request headers terminate before the body fixture") + .isNotNull(); + } while (!header.isEmpty()); + var outbound = peer.getOutputStream(); + outbound.write( + ("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n" + + "Transfer-Encoding: chunked\r\n\r\n" + + "8\r\n{\"held\":\r\n") + .getBytes(StandardCharsets.US_ASCII)); + outbound.flush(); + // Keep making progress with valid JSON whitespace chunks. The provider deadline, + // rather than an idle socket, must end this otherwise-live response body. + long fixtureDeadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(4); + try { + byte[] chunk = "1\r\n \r\n".getBytes(StandardCharsets.US_ASCII); + while (System.nanoTime() < fixtureDeadline) { + outbound.write(chunk); + outbound.flush(); + Thread.sleep(20); + } + return false; + } catch (java.io.IOException resetAfterBodyChunk) { + return true; + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + return false; + } + } + }); + var client = new StripeFirstInvoiceHttpClient(Duration.ofSeconds(1), Duration.ofSeconds(2)); + var observedTransport = mock(HttpClient.class); + when(observedTransport.sendAsync( + any(HttpRequest.class), + org.mockito.ArgumentMatchers.>any())) + .thenAnswer(invocation -> { + HttpRequest request = invocation.getArgument(0); + HttpResponse.BodyHandler handler = invocation.getArgument(1); + return transport.sendAsync( + request, response -> observeBodyChunks(handler.apply(response), streaming)); + }); + ReflectionTestUtils.setField(client, "transport", observedTransport); + var stripe = + com.stripe.StripeClient.builder() + .setApiKey("sk_test_controlled") + .setApiBase("http://127.0.0.1:" + server.getLocalPort()) + .setMaxNetworkRetries(0) + .setHttpClient(client) + .build(); + assertTimeoutPreemptively( + Duration.ofSeconds(5), + () -> + assertThatThrownBy(() -> stripe.invoices().retrieve("in_exact")) + .isInstanceOf(ApiConnectionException.class) + .hasMessageContaining("First-invoice provider response deadline expired") + .hasCauseInstanceOf(TimeoutException.class)); + assertThat(streaming.await(1, TimeUnit.SECONDS)) + .as("the client continued receiving small chunks without an idle gap") + .isTrue(); + assertThat(peerClosed.get(5, TimeUnit.SECONDS)) + .as("the real client closed the peer connection after receiving body bytes") + .isTrue(); + verify(observedTransport) + .sendAsync( + any(HttpRequest.class), + org.mockito.ArgumentMatchers.>any()); + } + } + + private static HttpResponse.BodySubscriber observeBodyChunks( + HttpResponse.BodySubscriber delegate, CountDownLatch observed) { + return new HttpResponse.BodySubscriber<>() { + @Override + public CompletionStage getBody() { + return delegate.getBody(); + } + + @Override + public void onSubscribe(Flow.Subscription subscription) { + delegate.onSubscribe(subscription); + } + + @Override + public void onNext(List chunks) { + boolean receivedBytes = chunks.stream().anyMatch(ByteBuffer::hasRemaining); + delegate.onNext(chunks); + if (receivedBytes) observed.countDown(); + } + + @Override + public void onError(Throwable failure) { + delegate.onError(failure); + } + + @Override + public void onComplete() { + delegate.onComplete(); + } + }; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingFirstInvoicePaymentClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingFirstInvoicePaymentClientTest.java new file mode 100644 index 0000000000..0888038532 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingFirstInvoicePaymentClientTest.java @@ -0,0 +1,816 @@ +package net.firedevops.firemud.accountservice.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.stripe.model.StripeObject; +import com.stripe.net.ApiMode; +import com.stripe.net.ApiResource.RequestMethod; +import com.stripe.net.BaseAddress; +import com.stripe.net.RequestOptions; +import com.stripe.net.StripeResponseGetter; +import java.io.InputStream; +import java.lang.reflect.Type; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.repository.AccountHostingFirstInvoicePayment; +import net.firedevops.firemud.accountservice.repository.AccountHostingFirstInvoicePaymentRepository.CommandClaim; +import net.firedevops.firemud.accountservice.repository.AccountHostingFirstInvoicePaymentRepository.ConfirmationDispatch; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProviderDispatch; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Actual SDK parsing and confirmation through controlled transport, not a live Stripe charge. */ +class StripeHostingFirstInvoicePaymentClientTest { + private static final Instant NOW = Instant.parse("2026-11-07T00:00:00Z"); + private static final UUID KEY = UUID.randomUUID(); + private static final AccountHostingFirstInvoicePayment INVOICE = + new AccountHostingFirstInvoicePayment( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + 1, + "sub_exact", + "cus_exact", + "pm_exact", + "in_exact", + "pi_exact", + 2400, + "usd", + "sha256:" + "a".repeat(64), + "price_exact", + 1, + 1, + "sha256:" + "b".repeat(64), + false, + NOW.minusSeconds(1), + NOW.plusSeconds(1000)); + + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + @Test + void exactExistingIntentIsConfirmedOnlyAfterReadWithRetainedKeyAndSelectedMethod() + throws Exception { + var transport = + new Transport( + invoice("requires_confirmation"), + intent("requires_confirmation"), + intent("requires_action")); + var response = + client(transport).confirm(dispatch(), StripeHostingFirstInvoicePaymentClientTest::claim); + assertThat(response.status()).isEqualTo("requires_action"); + assertThat(response.clientSecret()).isEqualTo("pi_exact_secret_controlled"); + assertThat(response.toString()).doesNotContain("secret_controlled"); + assertThat(transport.paths) + .containsExactly( + "/v1/invoices/in_exact", + "/v1/payment_intents/pi_exact", + "/v1/payment_intents/pi_exact/confirm"); + assertThat(transport.methods) + .containsExactly(RequestMethod.GET, RequestMethod.GET, RequestMethod.POST); + assertThat(transport.methods.stream().filter(RequestMethod.GET::equals).count()).isEqualTo(2); + assertThat(transport.params.get(2)) + .containsEntry("payment_method", "pm_exact") + .containsEntry("use_stripe_sdk", true); + assertThat(transport.options.get(2).getIdempotencyKey()).isEqualTo(KEY.toString()); + assertThat(transport.options) + .allSatisfy(options -> assertThat(options.getMaxNetworkRetries()).isZero()); + } + + @Test + void actionResponseArrivingAtConsentExpiryDoesNotReturnHandoff() { + var clock = mock(Clock.class); + when(clock.instant()).thenReturn(NOW); + var transport = + new Transport( + invoice("requires_confirmation"), + intent("requires_confirmation"), + intent("requires_action")); + transport.afterProviderResponse = () -> when(clock.instant()).thenReturn(NOW.plusSeconds(120)); + + assertThatThrownBy(() -> + client(transport, clock) + .confirm(dispatch(), StripeHostingFirstInvoicePaymentClientTest::claim)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Exact existing first-invoice provider binding refused"); + assertThat(transport.methods) + .containsExactly(RequestMethod.GET, RequestMethod.GET, RequestMethod.POST); + assertThat(transport.methods.stream().filter(RequestMethod.POST::equals).count()).isOne(); + } + + @Test + void checkoutCaptureQualifiesUnassignedIntentAndRefusesMissingStatus() throws Exception { + var dispatch = mock(ProviderDispatch.class); + when(dispatch.readyForProviderIo()).thenReturn(true); + when(dispatch.expectedBinding("sub_exact")) + .thenReturn( + new StripeHostingSubscriptionObserver.ExpectedBinding( + "sub_exact", + INVOICE.subscriptionId(), + "cus_exact", + "pm_exact", + "price_exact", + 1, + StripeHostingSubscriptionObserver.OperationType.SUBSCRIPTION_PROVISIONING, + INVOICE.creationRequestId(), + false)); + String subscription = + """ + {"object":"subscription","id":"sub_exact","customer":"cus_exact", + "default_payment_method":"pm_exact","livemode":false,"status":"incomplete", + "latest_invoice":"in_exact","created":CREATED_EPOCH,"metadata":{"firemud_operation_id":"CREATION_REQUEST", + "firemud_subscription_id":"SUBSCRIPTION_ID"}} + """ + .replace("CREATED_EPOCH", Long.toString(NOW.getEpochSecond())) + .replace("CREATION_REQUEST", INVOICE.creationRequestId().toString()) + .replace("SUBSCRIPTION_ID", INVOICE.subscriptionId().toString()); + var transport = new Transport(subscription, unassigned(invoice("requires_payment_method"))); + var observation = client(transport).capture(dispatch, "sub_exact"); + assertThat(observation.paymentIntentId()).isEqualTo("pi_exact"); + assertThat(observation.providerPaymentMethodId()).isEqualTo("pm_exact"); + assertThat(transport.methods).containsExactly(RequestMethod.GET, RequestMethod.GET); + assertThat(transport.methods.stream().filter(RequestMethod.GET::equals).count()).isEqualTo(2); + + var wrongDefault = new Transport(subscription.replace("pm_exact", "pm_other")); + assertThatThrownBy(() -> client(wrongDefault).capture(dispatch, "sub_exact")) + .isInstanceOf(IllegalStateException.class); + assertThat(wrongDefault.methods).containsExactly(RequestMethod.GET); + + String incompleteIntent = + invoice("requires_confirmation").replace(",\"status\":\"requires_confirmation\"", ""); + var missingStatus = new Transport(subscription, incompleteIntent); + assertThatThrownBy(() -> client(missingStatus).capture(dispatch, "sub_exact")) + .isExactlyInstanceOf(StripeHostingFirstInvoicePaymentClient.ProviderEvidenceRefused.class); + assertThat(missingStatus.methods).containsExactly(RequestMethod.GET, RequestMethod.GET); + } + + @Test + void exactUnassignedUnpaidIntentUsesReservedMethodAndOriginalOneShotConfirmation() + throws Exception { + String unpaidInvoice = unassigned(invoice("requires_payment_method")); + String unpaidIntent = unassigned(intent("requires_payment_method")); + var transport = new Transport(unpaidInvoice, unpaidIntent, intent("requires_action")); + var dispatch = dispatch(); + var provider = client(transport); + assertThat( + provider.confirm(dispatch, StripeHostingFirstInvoicePaymentClientTest::claim).status()) + .isEqualTo("requires_action"); + assertThat(transport.methods) + .containsExactly(RequestMethod.GET, RequestMethod.GET, RequestMethod.POST); + assertThat(transport.params.get(2)).containsEntry("payment_method", "pm_exact"); + assertThat(transport.options.get(2).getIdempotencyKey()).isEqualTo(KEY.toString()); + } + + @Test + void unassignedObservationDoesNotReplaceTheDurableOneShotClaim() throws Exception { + var transport = + new Transport( + unassigned(invoice("requires_payment_method")), + unassigned(intent("requires_payment_method"))); + assertThat(client(transport).confirm(dispatch(), () -> null).status()) + .isEqualTo("AUTHORIZED_NOT_CONFIRMED"); + assertThat(transport.methods).containsExactly(RequestMethod.GET, RequestMethod.GET); + assertThat(transport.methods.stream().filter(RequestMethod.GET::equals).count()).isEqualTo(2); + } + + @ParameterizedTest + @ValueSource(strings = {"requires_confirmation", "requires_action", "processing", "succeeded"}) + void absentMethodInOtherProviderStatesIsNotPreConfirmationEvidence(String status) { + var transport = new Transport(unassigned(invoice(status))); + assertThatThrownBy(() -> + client(transport) + .confirm( + dispatch(), + () -> { + throw new AssertionError("Unqualified intent cannot claim a command"); + })) + .isInstanceOf(IllegalStateException.class); + assertThat(transport.methods).containsExactly(RequestMethod.GET); + assertThat(transport.methods.stream().filter(RequestMethod.GET::equals).count()).isOne(); + } + + @Test + void missingMethodRequiresZeroReceivedNoChargeAndConsistentOriginalReads() { + String unpaidInvoice = unassigned(invoice("requires_payment_method")); + String unpaid = unassigned(intent("requires_payment_method")); + for (String conflicting : + List.of( + unpaid.replace("\"amount_received\":0", "\"amount_received\":1"), + unpaid.replace( + "\"object\":\"payment_intent\"", + "\"latest_charge\":\"ch_prior\",\"object\":\"payment_intent\""), + unpaid.replace("\"pi_exact\"", "\"pi_other\""), + unpaid.replace("\"cus_exact\"", "\"cus_other\""), + intent("requires_payment_method"), + intent("requires_payment_method").replace("pm_exact", "pm_conflict"))) { + var transport = new Transport(unpaidInvoice, conflicting); + assertThatThrownBy(() -> + client(transport) + .confirm( + dispatch(), + () -> { + throw new AssertionError("Contradictory intent cannot claim a command"); + })) + .isInstanceOf(IllegalStateException.class); + assertThat(transport.methods).containsExactly(RequestMethod.GET, RequestMethod.GET); + } + } + + @Test + void missingMethodNeverQualifiesOrdinaryReadOrAlreadyClaimedConfirmation() { + String unpaidInvoice = unassigned(invoice("requires_payment_method")); + var readTransport = new Transport(unpaidInvoice); + assertThatThrownBy(() -> client(readTransport).observe(INVOICE)) + .isInstanceOf(IllegalStateException.class); + var recoveryTransport = new Transport(unpaidInvoice); + var recovery = dispatch(); + when(recovery.initialCommandAvailable()).thenReturn(false); + assertThatThrownBy(() -> + client(recoveryTransport) + .confirm( + recovery, + () -> { + throw new AssertionError("Recovery cannot claim"); + })) + .isInstanceOf(IllegalStateException.class); + assertThat(readTransport.methods).containsExactly(RequestMethod.GET); + assertThat(recoveryTransport.methods).containsExactly(RequestMethod.GET); + } + + @Test + void providerConfirmationResponseStillRequiresExactReservedMethod() { + var transport = + new Transport( + unassigned(invoice("requires_payment_method")), + unassigned(intent("requires_payment_method")), + unassigned(intent("requires_action"))); + assertThatThrownBy(() -> + client(transport) + .confirm(dispatch(), StripeHostingFirstInvoicePaymentClientTest::claim)) + .isInstanceOf(IllegalStateException.class); + assertThat(transport.methods) + .containsExactly(RequestMethod.GET, RequestMethod.GET, RequestMethod.POST); + } + + @ParameterizedTest + @ValueSource(strings = {"requires_action", "processing", "succeeded"}) + void recoveryOfAlreadyDispatchedIntentNeverConfirmsOrCreatesAnother(String status) + throws Exception { + var transport = new Transport(invoice(status), intent(status)); + var spent = dispatch(); + when(spent.initialCommandAvailable()).thenReturn(false); + when(spent.takeInitialCommandPermission()).thenReturn(false); + var handoff = + client(transport) + .confirm( + spent, + () -> { + throw new AssertionError("Post-claim recovery cannot claim a command"); + }); + assertThat(transport.methods).containsExactly(RequestMethod.GET, RequestMethod.GET); + assertThat(transport.methods.stream().filter(RequestMethod.GET::equals).count()).isEqualTo(2); + assertThat(handoff.status()).isEqualTo(status); + assertThat(handoff.clientSecret()) + .isEqualTo("requires_action".equals(status) ? "pi_exact_secret_controlled" : null); + } + + @ParameterizedTest + @ValueSource( + strings = {"pm_other", "cus_other", "eur", "manual", "in_other", "sub_other", "price_other"}) + void mismatchedProviderTupleCannotReachConfirmation(String replacement) { + String response = invoice("requires_confirmation"); + String needle = + switch (replacement) { + case "pm_other" -> "pm_exact"; + case "cus_other" -> "cus_exact"; + case "eur" -> "usd"; + case "manual" -> "automatic"; + case "in_other" -> "in_exact"; + case "price_other" -> "price_exact"; + default -> "sub_exact"; + }; + var transport = new Transport(response.replace(needle, replacement)); + assertThatThrownBy(() -> + client(transport) + .confirm(dispatch(), StripeHostingFirstInvoicePaymentClientTest::claim)) + .isInstanceOf(IllegalStateException.class); + assertThat(transport.methods).containsExactly(RequestMethod.GET); + } + + @Test + void lostResponseOrOwnerRetryCannotDispatchASecondConfirmation() throws Exception { + var transport = + new Transport(invoice("requires_confirmation"), intent("requires_confirmation")); + var original = dispatch(); + when(original.takeInitialCommandPermission()).thenReturn(false); + assertThat( + client(transport) + .confirm(original, StripeHostingFirstInvoicePaymentClientTest::claim) + .status()) + .isEqualTo("AUTHORIZED_NOT_CONFIRMED"); + assertThat(transport.methods).containsExactly(RequestMethod.GET, RequestMethod.GET); + } + + @Test + void lostConfirmationResponseRecoversExistingActionWithoutRepeatingProviderPost() + throws Exception { + var transport = + new Transport( + invoice("requires_confirmation"), + intent("requires_confirmation"), + "lost-response", + invoice("requires_action"), + intent("requires_action")); + transport.loseConfirmationResponse = true; + var original = dispatch(); + when(original.takeInitialCommandPermission()).thenReturn(true, false); + var provider = client(transport); + assertThatThrownBy( + () -> provider.confirm(original, StripeHostingFirstInvoicePaymentClientTest::claim)) + .isInstanceOf(com.stripe.exception.ApiConnectionException.class); + assertThat( + provider + .confirm( + original, + () -> { + throw new AssertionError("Retry of lost response cannot claim again"); + }) + .status()) + .isEqualTo("requires_action"); + assertThat(transport.methods.stream().filter(RequestMethod.POST::equals).count()).isOne(); + assertThat(transport.paths) + .allMatch(path -> !path.contains("checkout") && !path.endsWith("/payment_intents")); + } + + @Test + void changedSeparatelyRetrievedIntentCannotBeConfirmedAfterExactInvoiceRead() { + var transport = + new Transport( + invoice("requires_confirmation"), + intent("requires_confirmation").replace("\"amount\":2400", "\"amount\":2500")); + assertThatThrownBy(() -> + client(transport) + .confirm(dispatch(), StripeHostingFirstInvoicePaymentClientTest::claim)) + .isInstanceOf(IllegalStateException.class); + assertThat(transport.methods).containsExactly(RequestMethod.GET, RequestMethod.GET); + } + + @ParameterizedTest + @ValueSource(strings = {"requires_action", "processing", "succeeded"}) + void advancedExpandedIntentCannotClaimAnInitialCommandFromAnOlderDirectRead(String status) { + var transport = new Transport(invoice(status), intent("requires_confirmation")); + var dispatch = dispatch(); + + assertThatThrownBy(() -> + client(transport) + .confirm( + dispatch, + () -> { + throw new AssertionError( + "Contradictory reads must not reach the command claim"); + })) + .isInstanceOf(IllegalStateException.class); + verify(dispatch, never()).takeInitialCommandPermission(); + assertThat(transport.methods).containsExactly(RequestMethod.GET, RequestMethod.GET); + } + + @Test + void directProcessingReadCanRecoverWithoutClaimAfterAnEligibleExpandedRead() throws Exception { + var transport = new Transport(invoice("requires_confirmation"), intent("processing")); + var dispatch = dispatch(); + var handoff = + client(transport) + .confirm( + dispatch, + () -> { + throw new AssertionError( + "Read-only provider recovery must not reach the command claim"); + }); + assertThat(handoff.status()).isEqualTo("processing"); + verify(dispatch, never()).takeInitialCommandPermission(); + assertThat(transport.methods).containsExactly(RequestMethod.GET, RequestMethod.GET); + } + + @Test + void insufficientAuthorizationWindowAfterProviderReadsLeavesCommandUnclaimed() { + var transport = + new Transport(invoice("requires_confirmation"), intent("requires_confirmation")); + var dispatch = dispatch(); + when(dispatch.validUntil()).thenReturn(NOW.plusSeconds(1)); + assertThatThrownBy(() -> + client(transport) + .confirm( + dispatch, + () -> { + throw new AssertionError("Expired dispatch budget reached the claim"); + })) + .isInstanceOf(IllegalStateException.class); + assertThat(transport.methods).containsExactly(RequestMethod.GET, RequestMethod.GET); + } + + @Test + void expiryAfterClaimBeforePostKeepsOriginalCommandHeldAcrossRetries() throws Exception { + var transport = + new Transport( + invoice("requires_confirmation"), + intent("requires_confirmation"), + invoice("requires_confirmation"), + intent("requires_confirmation")); + var clock = mock(Clock.class); + when(clock.instant()).thenReturn(NOW); + var provider = client(transport, clock); + var original = dispatch(); + when(original.requestId()).thenReturn(UUID.randomUUID()); + Instant expiredAt = original.validUntil().plusSeconds(1); + var originalClaim = claim(); + var held = new AtomicBoolean(); + Supplier claimCommand = + () -> { + if (!held.compareAndSet(false, true)) return null; + when(clock.instant()).thenReturn(expiredAt); + return originalClaim; + }; + + assertThatThrownBy(() -> provider.confirm(original, claimCommand)) + .hasMessage("Exact existing first-invoice provider binding refused") + .isInstanceOfSatisfying( + StripeHostingFirstInvoicePaymentClient.ExpiredBeforePost.class, + observation -> { + assertThat(observation.requestId()).isEqualTo(original.requestId()); + assertThat(observation.observedAt()).isEqualTo(expiredAt); + }); + verify(originalClaim).takePermission(original); + assertThat(transport.methods).containsExactly(RequestMethod.GET, RequestMethod.GET); + + assertThatThrownBy(() -> provider.confirm(original, claimCommand)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Committed current billing-owner consent required"); + assertThat(transport.methods).containsExactly(RequestMethod.GET, RequestMethod.GET); + + // Fresh consent keeps the original invoice and provider key, and cannot reclaim its command. + var renewed = dispatch(); + when(renewed.validUntil()).thenReturn(NOW.plusSeconds(240)); + var handoff = provider.confirm(renewed, claimCommand); + assertThat(handoff.status()).isEqualTo("AUTHORIZED_NOT_CONFIRMED"); + assertThat(handoff.clientSecret()).isNull(); + assertThat(transport.methods) + .containsExactly( + RequestMethod.GET, RequestMethod.GET, RequestMethod.GET, RequestMethod.GET); + } + + @Test + void expiryAfterDispatchDoesNotPermitAnotherCommandOrClientSecretDisclosure() { + var transport = new Transport(); + var original = dispatch(); + when(original.validUntil()).thenReturn(NOW); + when(original.takeInitialCommandPermission()).thenReturn(false); + assertThatThrownBy(() -> + client(transport).confirm(original, StripeHostingFirstInvoicePaymentClientTest::claim)) + .isInstanceOf(IllegalStateException.class); + assertThat(transport.methods).isEmpty(); + } + + @Test + void creditBalancePartialPaymentAndAmountChangesRefuseRatherThanFallback() { + for (String response : + List.of( + invoice("succeeded").replace("\"amount_received\":2400", "\"amount_received\":2300"), + invoice("requires_confirmation").replace("\"amount_due\":2400", "\"amount_due\":2300"), + invoice("requires_confirmation") + .replace("\"lines\":{\"has_more\":false", "\"lines\":{\"has_more\":true"), + invoice("requires_confirmation") + .replace( + "\"payments\":{\"object\":\"list\",\"has_more\":false", + "\"payments\":{\"object\":\"list\",\"has_more\":true"), + invoice("requires_confirmation") + .replace("\"starting_balance\":0", "\"starting_balance\":100"), + invoice("requires_confirmation").replace("\"total\":2400", "\"total\":2500"), + invoice("requires_confirmation").replace("\"quantity\":1", "\"quantity\":2"), + invoice("requires_confirmation") + .replace("\"amount_remaining\":2400", "\"amount_remaining\":2300"))) { + var transport = new Transport(response); + assertThatThrownBy(() -> client(transport).observe(INVOICE)) + .isInstanceOf(IllegalStateException.class); + assertThat(transport.methods).containsExactly(RequestMethod.GET); + } + } + + @Test + void terminalUnpaidObservationRequiresVoidedOriginalAndSeparatelyRetrievedCanceledIntent() + throws Exception { + var transport = new Transport(terminalInvoice(), intent("canceled")); + var evidence = client(transport).observeTerminalUnpaid(INVOICE, false); + + assertThat(evidence.invoiceId()).isEqualTo("in_exact"); + assertThat(evidence.paymentIntentId()).isEqualTo("pi_exact"); + assertThat(evidence.tupleDigest()).isEqualTo(INVOICE.digest()); + assertThat(evidence.readStartedAt()).isEqualTo(NOW); + assertThat(evidence.observedAt()).isEqualTo(NOW); + assertThat(transport.paths) + .containsExactly("/v1/invoices/in_exact", "/v1/payment_intents/pi_exact"); + assertThat(transport.methods).containsExactly(RequestMethod.GET, RequestMethod.GET); + assertThat(transport.params.getFirst()) + .containsEntry("expand", List.of("payments.data.payment.payment_intent")); + assertThat(transport.options) + .allSatisfy(options -> assertThat(options.getMaxNetworkRetries()).isZero()); + } + + @Test + void terminalUnpaidObservationAcceptsMatchingCanceledUnassignedIntentWithoutCharge() + throws Exception { + var transport = new Transport(unassigned(terminalInvoice()), unassigned(intent("canceled"))); + + var evidence = client(transport).observeTerminalUnpaid(INVOICE, true); + + assertThat(evidence.intentMethodUnassigned()).isTrue(); + assertThat(evidence.tupleDigest()).isEqualTo(INVOICE.digest()); + assertThat(transport.paths) + .containsExactly("/v1/invoices/in_exact", "/v1/payment_intents/pi_exact"); + assertThat(transport.methods).containsExactly(RequestMethod.GET, RequestMethod.GET); + } + + @Test + void terminalUnpaidObservationRefusesConflictingMethodOrChargeOnUnassignedIntent() { + String unassignedInvoice = unassigned(terminalInvoice()); + String unassignedIntent = unassigned(intent("canceled")); + String chargedIntent = + unassignedIntent.replace( + "\"payment_method\":null", "\"payment_method\":null,\"latest_charge\":\"ch_prior\""); + var transports = + List.of( + new Transport(unassignedInvoice, intent("canceled")), + new Transport(terminalInvoice(), unassignedIntent), + new Transport(unassignedInvoice, chargedIntent), + new Transport( + unassignedInvoice.replace(unassignedIntent, chargedIntent), unassignedIntent)); + for (var transport : transports) { + assertThatThrownBy(() -> client(transport).observeTerminalUnpaid(INVOICE, true)) + .isInstanceOf(IllegalStateException.class); + assertThat(transport.methods).allMatch(method -> method == RequestMethod.GET); + } + } + + @Test + void terminalUnpaidObservationRemainsAvailableAfterOriginalCheckoutExpiry() throws Exception { + var expired = + new AccountHostingFirstInvoicePayment( + INVOICE.subscriptionId(), + INVOICE.creationRequestId(), + INVOICE.tenantId(), + INVOICE.ownerAccountId(), + INVOICE.paymentInstrumentId(), + INVOICE.instrumentVersion(), + INVOICE.providerSubscriptionId(), + INVOICE.providerCustomerId(), + INVOICE.providerPaymentMethodId(), + INVOICE.invoiceId(), + INVOICE.paymentIntentId(), + INVOICE.amount(), + INVOICE.currency(), + INVOICE.quoteDigest(), + INVOICE.providerPriceId(), + INVOICE.providerQuantity(), + INVOICE.billingPolicyVersion(), + INVOICE.billingPolicyDigest(), + INVOICE.livemode(), + NOW.minusSeconds(200), + NOW.minusSeconds(100)); + var transport = new Transport(terminalInvoice(), intent("canceled")); + + assertThat(client(transport).observeTerminalUnpaid(expired, false).observedAt()).isEqualTo(NOW); + assertThat(transport.methods).containsExactly(RequestMethod.GET, RequestMethod.GET); + } + + @Test + void terminalUnpaidObservationRefusesPaidAmbiguousOrMismatchedProviderEvidence() { + for (String response : + List.of( + terminalInvoice().replace("\"status\":\"void\"", "\"status\":\"paid\""), + terminalInvoice().replace("\"amount_paid\":0", "\"amount_paid\":1"), + terminalInvoice().replace("\"amount_remaining\":0", "\"amount_remaining\":1"), + terminalInvoice() + .replace("\"lines\":{\"has_more\":false", "\"lines\":{\"has_more\":true"), + terminalInvoice() + .replace( + "\"payments\":{\"object\":\"list\",\"has_more\":false", + "\"payments\":{\"object\":\"list\",\"has_more\":true"), + terminalInvoice().replace("\"price\":\"price_exact\"", "\"price\":\"price_other\""), + terminalInvoice().replace("\"id\":\"pi_exact\"", "\"id\":\"pi_other\""))) { + var transport = new Transport(response, intent("canceled")); + assertThatThrownBy(() -> client(transport).observeTerminalUnpaid(INVOICE, false)) + .isInstanceOf(IllegalStateException.class); + assertThat(transport.methods).containsExactly(RequestMethod.GET); + } + + for (String response : + List.of( + intent("canceled") + .replace("\"payment_method\":\"pm_exact\"", "\"payment_method\":\"pm_other\""), + intent("canceled").replace("\"customer\":\"cus_exact\"", "\"customer\":\"cus_other\""), + intent("canceled").replace("\"amount\":2400", "\"amount\":2500"), + intent("canceled").replace("\"amount_received\":0", "\"amount_received\":1"), + intent("canceled").replace("\"status\":\"canceled\"", "\"status\":\"succeeded\""))) { + var transport = new Transport(terminalInvoice(), response); + assertThatThrownBy(() -> client(transport).observeTerminalUnpaid(INVOICE, false)) + .isInstanceOf(IllegalStateException.class); + assertThat(transport.methods).containsExactly(RequestMethod.GET, RequestMethod.GET); + } + } + + @Test + void forgedUncommittedDispatchAndAmbientSqlRefuseBeforeProviderIo() { + var transport = new Transport(); + assertThatThrownBy(() -> + client(transport) + .confirm( + mock(ConfirmationDispatch.class), + StripeHostingFirstInvoicePaymentClientTest::claim)) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client(transport).observe(INVOICE)) + .isInstanceOf(IllegalStateException.class); + assertThat(transport.paths).isEmpty(); + } + + private static net.firedevops.firemud.accountservice.repository + .AccountHostingFirstInvoicePaymentRepository.CommandClaim + claim() { + var claim = + mock( + net.firedevops.firemud.accountservice.repository + .AccountHostingFirstInvoicePaymentRepository.CommandClaim.class); + when(claim.takePermission(org.mockito.ArgumentMatchers.any())).thenReturn(true, false); + return claim; + } + + private static ConfirmationDispatch dispatch() { + var dispatch = mock(ConfirmationDispatch.class); + when(dispatch.invoice()).thenReturn(INVOICE); + when(dispatch.independentlyRead()).thenReturn(true); + when(dispatch.initialCommandAvailable()).thenReturn(true); + when(dispatch.takeInitialCommandPermission()).thenReturn(true); + when(dispatch.providerIdempotencyId()).thenReturn(KEY); + when(dispatch.validUntil()).thenReturn(NOW.plusSeconds(120)); + return dispatch; + } + + @Test + void freshAuthorizationCanRecoverBeforeClaimButCannotResendAnAmbiguousClaim() throws Exception { + var transport = + new Transport( + invoice("requires_confirmation"), + intent("requires_confirmation"), + intent("requires_action"), + invoice("requires_confirmation"), + intent("requires_confirmation")); + var provider = client(transport); + var claimed = new java.util.concurrent.atomic.AtomicBoolean(); + // A new authorization is still the same original invoice and provider idempotency identity. + assertThat( + provider + .confirm(dispatch(), () -> claimed.compareAndSet(false, true) ? claim() : null) + .status()) + .isEqualTo("requires_action"); + assertThat( + provider + .confirm(dispatch(), () -> claimed.compareAndSet(false, true) ? claim() : null) + .status()) + .isEqualTo("AUTHORIZED_NOT_CONFIRMED"); + assertThat(transport.methods.stream().filter(RequestMethod.POST::equals).count()).isOne(); + assertThat(transport.options.get(2).getIdempotencyKey()).isEqualTo(KEY.toString()); + } + + @Test + void failedOrUncertainDurableClaimNeverSendsProviderCommand() { + var transport = + new Transport(invoice("requires_confirmation"), intent("requires_confirmation")); + assertThatThrownBy(() -> + client(transport) + .confirm( + dispatch(), + () -> { + throw new IllegalStateException("claim commit unknown"); + })) + .hasMessageContaining("claim commit unknown"); + assertThat(transport.methods).containsExactly(RequestMethod.GET, RequestMethod.GET); + } + + private static StripeHostingFirstInvoicePaymentClient client(Transport transport) { + return client(transport, Clock.fixed(NOW, ZoneOffset.UTC)); + } + + private static StripeHostingFirstInvoicePaymentClient client(Transport transport, Clock clock) { + return new StripeHostingFirstInvoicePaymentClient( + new com.stripe.StripeClient(transport), + clock, + Duration.ofMillis(250), + Duration.ofSeconds(1)); + } + + private static String unassigned(String response) { + return response.replace("\"payment_method\":\"pm_exact\"", "\"payment_method\":null"); + } + + private static String intent(String status) { + return "{\"object\":\"payment_intent\",\"id\":\"pi_exact\",\"customer\":\"cus_exact\",\"payment_method\":\"pm_exact\"," + + "\"amount\":2400,\"amount_received\":" + + ("succeeded".equals(status) ? 2400 : 0) + + ",\"currency\":\"usd\",\"livemode\":false," + + "\"confirmation_method\":\"automatic\",\"client_secret\":\"pi_exact_secret_controlled\",\"status\":\"" + + status + + "\"}"; + } + + private static String invoice(String status) { + boolean paid = "succeeded".equals(status); + return "{\"object\":\"invoice\",\"id\":\"in_exact\",\"customer\":\"cus_exact\",\"livemode\":false,\"billing_reason\":\"subscription_create\"," + + "\"parent\":{\"type\":\"subscription_details\",\"subscription_details\":{\"subscription\":\"sub_exact\"}},\"total\":2400,\"starting_balance\":0,\"amount_due\":2400,\"amount_paid\":" + + (paid ? 2400 : 0) + + ",\"amount_remaining\":" + + (paid ? 0 : 2400) + + ",\"currency\":\"usd\",\"status\":\"" + + (paid ? "paid" : "open") + + "\",\"lines\":{\"has_more\":false,\"data\":[{\"object\":\"line_item\",\"amount\":2400,\"currency\":\"usd\",\"quantity\":1,\"pricing\":{\"type\":\"price_details\",\"price_details\":{\"price\":\"price_exact\"}}}]},\"payments\":{\"object\":\"list\",\"has_more\":false,\"data\":[{\"object\":\"invoice_payment\",\"id\":\"inpay_exact\"," + + "\"payment\":{\"type\":\"payment_intent\",\"payment_intent\":" + + intent(status) + + "}}]}}"; + } + + private static String terminalInvoice() { + return invoice("canceled") + .replace("\"amount_remaining\":2400", "\"amount_remaining\":0") + .replace("\"status\":\"open\"", "\"status\":\"void\""); + } + + private static final class Transport implements StripeResponseGetter { + private final List responses; + private boolean loseConfirmationResponse; + private Runnable afterProviderResponse = () -> {}; + private final List paths = new ArrayList<>(); + private final List methods = new ArrayList<>(); + private final List> params = new ArrayList<>(); + private final List options = new ArrayList<>(); + + private Transport(String... responses) { + this.responses = List.of(responses); + } + + @Override + @SuppressWarnings("unchecked") + public T request( + BaseAddress base, + RequestMethod method, + String path, + Map parameters, + Type type, + RequestOptions requestOptions, + ApiMode mode) + throws com.stripe.exception.StripeException { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + int index = paths.size(); + paths.add(path); + methods.add(method); + params.add(parameters == null ? Map.of() : Map.copyOf(parameters)); + options.add(requestOptions); + if (loseConfirmationResponse && method == RequestMethod.POST) { + loseConfirmationResponse = false; + throw new com.stripe.exception.ApiConnectionException( + "Controlled lost confirmation response"); + } + T response = (T) com.stripe.net.ApiResource.GSON.fromJson(responses.get(index), type); + if (method == RequestMethod.POST) afterProviderResponse.run(); + return response; + } + + @Override + public InputStream requestStream( + BaseAddress base, + RequestMethod method, + String path, + Map params, + RequestOptions options, + ApiMode mode) { + throw new AssertionError("Streaming is unsupported"); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingBillingPolicyRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingBillingPolicyRepositoryTest.java new file mode 100644 index 0000000000..95d10c0809 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingBillingPolicyRepositoryTest.java @@ -0,0 +1,50 @@ +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 net.firedevops.firemud.accountservice.repository.AccountHostingBillingPolicyRepository.Policy; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountHostingBillingPolicyRepositoryTest { + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + @Test + void policyDigestBindsExactPriceVersionQuantityAmountAndCurrency() { + var initial = new Policy("price_exact", 1, 1, 2400, "usd"); + for (var changed : + java.util.List.of( + new Policy("price_other", 1, 1, 2400, "usd"), + new Policy("price_exact", 2, 1, 2400, "usd"), + new Policy("price_exact", 1, 2, 2400, "usd"), + new Policy("price_exact", 1, 1, 2500, "usd"), + new Policy("price_exact", 1, 1, 2400, "eur"))) { + assertThat(changed.digest()).isNotEqualTo(initial.digest()); + } + } + + @Test + void absentCurrentPolicyRefusesWithoutInventingPriceBalanceTaxOrCurrencyDefault() { + var dsl = mock(DSLContext.class); + var policies = new AccountHostingBillingPolicyRepository(dsl); + var quote = new AccountHostingPlanQuote("hosting", "price_exact", 1, 10, 1, 100); + assertThatThrownBy(() -> policies.requireCurrent(quote)) + .hasMessageContaining("owner transaction"); + verifyNoInteractions(dsl); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> policies.requireCurrent(quote)) + .hasMessageContaining("policy unavailable"); + assertThatThrownBy(() -> new Policy("price_exact", 1, 1, 0, "usd")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Policy("price_exact", 1, 1, 2400, null)) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingFirstInvoicePaymentRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingFirstInvoicePaymentRepositoryTest.java new file mode 100644 index 0000000000..00b1f429df --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingFirstInvoicePaymentRepositoryTest.java @@ -0,0 +1,552 @@ +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.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.time.Clock; +import java.time.Instant; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.service.session.AccountRecentReauthenticationEvidence; +import net.firedevops.firemud.accountservice.service.session.AccountRecentReauthenticationPolicy; +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 AccountHostingFirstInvoicePaymentRepositoryTest { + private final DSLContext dsl = mock(DSLContext.class); + private final AccountHostingFirstInvoicePaymentRepository payments = + new AccountHostingFirstInvoicePaymentRepository( + dsl, mock(AccountSubscriptionIntentRepository.class), Clock.systemUTC()); + + @AfterEach + void clearTransactions() { + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } + + @Test + void immutableDigestBindsExistingProviderInvoiceIntentInstrumentPolicyAndExpiry() { + var invoice = invoice("in_exact", "pi_exact", 2400, "usd"); + assertThat(invoice.digest()).isEqualTo(invoice("in_exact", "pi_exact", 2400, "usd").digest()); + assertThat(invoice.digest()) + .isNotEqualTo(invoice("in_other", "pi_exact", 2400, "usd").digest()); + assertThat(invoice.digest()) + .isNotEqualTo(invoice("in_exact", "pi_other", 2400, "usd").digest()); + assertThat(invoice.digest()) + .isNotEqualTo(invoice("in_exact", "pi_exact", 2500, "usd").digest()); + assertThat(invoice.digest()) + .isNotEqualTo(invoice("in_exact", "pi_exact", 2400, "eur").digest()); + assertThat(invoice.digest()) + .isNotEqualTo( + invoice( + "in_exact", + "pi_exact", + 2400, + "usd", + UUID.randomUUID(), + invoice.billingPolicyDigest(), + invoice.expiresAt()) + .digest()) + .isNotEqualTo( + invoice( + "in_exact", + "pi_exact", + 2400, + "usd", + invoice.paymentInstrumentId(), + "sha256:" + "c".repeat(64), + invoice.expiresAt()) + .digest()) + .isNotEqualTo( + invoice( + "in_exact", + "pi_exact", + 2400, + "usd", + invoice.paymentInstrumentId(), + invoice.billingPolicyDigest(), + invoice.expiresAt().minusSeconds(1)) + .digest()); + } + + @Test + void invoiceDigestUsesPostgresTimestampPrecision() { + var invoice = invoice("in_exact", "pi_exact", 2400, "usd"); + var subMicrosecond = + invoice( + invoice.invoiceId(), + invoice.paymentIntentId(), + invoice.amount(), + invoice.currency(), + invoice.paymentInstrumentId(), + invoice.billingPolicyDigest(), + invoice.capturedAt().plusNanos(900), + invoice.expiresAt().plusNanos(900)); + assertThat(subMicrosecond).isEqualTo(invoice); + assertThat(subMicrosecond.digest()).isEqualTo(invoice.digest()); + assertThatThrownBy(() -> + invoice( + invoice.invoiceId(), + invoice.paymentIntentId(), + invoice.amount(), + invoice.currency(), + invoice.paymentInstrumentId(), + invoice.billingPolicyDigest(), + invoice.capturedAt(), + invoice.capturedAt().plusNanos(900))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void missingAndReadonlyTransactionsCannotReadOrMutateCheckout() { + for (boolean readOnly : new boolean[] {false, true}) { + TransactionSynchronizationManager.setActualTransactionActive(readOnly); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(readOnly); + assertThatThrownBy(() -> payments.find(UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> payments.retainAwaitingPayment(null, null, null)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> payments.retainSignedSuccess(null, null)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> payments.readDispatch(null, null)) + .isInstanceOf(IllegalStateException.class); + } + verifyNoInteractions(dsl); + } + + @Test + void onlyExactCurrentAwaitingPaymentSourcePermitsCommandPreparationOrSecretReadback() { + TransactionSynchronizationManager.setActualTransactionActive(true); + var invoice = invoice("in_exact", "pi_exact", 2400, "usd"); + Record row = mock(Record.class); + when(dsl.fetchOne( + AccountHostingFirstInvoicePaymentRepository.AWAITING_PAYMENT_SQL, + invoice.subscriptionId(), + invoice.creationRequestId())) + .thenReturn(row); + when(row.get("status", String.class)).thenReturn("provisioning"); + when(row.get("phase", String.class)).thenReturn("AWAITING_PAYMENT"); + when(row.get("row_version", Long.class)).thenReturn(3L); + when(row.get("provider_subscription_id", String.class)).thenReturn("sub_exact"); + payments.requireAwaitingPayment(invoice, 3); + for (String status : new String[] {"active", "trialing", "canceled"}) { + when(row.get("status", String.class)).thenReturn(status); + assertThatThrownBy(() -> payments.requireAwaitingPayment(invoice, 3)) + .isInstanceOf(IllegalStateException.class); + } + when(row.get("status", String.class)).thenReturn("provisioning"); + when(row.get("phase", String.class)).thenReturn("CONFIRMED"); + assertThatThrownBy(() -> payments.requireAwaitingPayment(invoice, 3)) + .isInstanceOf(IllegalStateException.class); + when(row.get("phase", String.class)).thenReturn("AWAITING_PAYMENT"); + assertThatThrownBy(() -> payments.requireAwaitingPayment(invoice, 4)) + .isInstanceOf(IllegalStateException.class); + when(row.get("provider_subscription_id", String.class)).thenReturn("sub_replacement"); + assertThatThrownBy(() -> payments.requireAwaitingPayment(invoice, 3)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void commercialZeroNegativeAmbiguousCurrencyAndNewProviderIdentifiersAreNotAccepted() { + assertThatThrownBy(() -> invoice("in_exact", "pi_exact", 0, "usd")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> invoice("in_exact", "pi_exact", -1, "usd")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> invoice("in_exact", "pi_exact", 2400, "USD")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> invoice("in_exact", "cs_newCheckout", 2400, "usd")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void freshConsentRecoversCrashBeforeCommandClaimAndKeepsEveryOriginalIdentity() { + var f = new RenewalFixture(); + var prepared = f.renew(); + assertThat(prepared.requestId()).isEqualTo(f.originalId); + assertThat(prepared.providerIdempotencyId()).isEqualTo(f.providerId); + assertThat(prepared.lifecycleRequestId()).isEqualTo(f.lifecycleId); + assertThat(prepared.invoice()).isEqualTo(f.invoice); + assertThat(prepared.authorizationVersion()).isEqualTo(2); + var dispatch = f.repository.readDispatch(prepared, f.invoice.ownerAccountId()); + assertThat(dispatch.takeInitialCommandPermission()).isTrue(); + var claim = f.repository.claimCommand(dispatch, f.invoice.ownerAccountId()); + assertThat(claim).isNotNull(); + assertThat(claim.takePermission(prepared)).isFalse(); + assertThat(claim.takePermission(dispatch)).isTrue(); + assertThat(claim.takePermission(dispatch)).isFalse(); + assertThat(f.repository.claimCommand(dispatch, f.invoice.ownerAccountId())).isNull(); + } + + @Test + void exactRenewalReplayIsReadOnlyAndChangedEvidenceOrVersionCannotRearmIt() { + var f = new RenewalFixture(); + f.renew(); + assertThat(f.renew().takeInitialCommandPermission()).isFalse(); + when(f.evidence.evidenceId()).thenReturn(UUID.randomUUID()); + assertThatThrownBy(f::renew).isInstanceOf(IllegalStateException.class); + when(f.evidence.evidenceId()).thenReturn(f.evidenceId); + assertThatThrownBy(() -> + f.repository.renewAuthorization( + f.invoice.ownerAccountId(), + f.originalId, + f.authorizationId, + f.invoice.subscriptionId(), + 3, + 2, + f.invoice.digest(), + f.evidence)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void changedConsentOriginalIdentityOrWrongPurposeCannotRenew() { + var f = new RenewalFixture(); + assertThatThrownBy(() -> + f.repository.renewAuthorization( + f.invoice.ownerAccountId(), + UUID.randomUUID(), + f.authorizationId, + f.invoice.subscriptionId(), + 3, + 1, + f.invoice.digest(), + f.evidence)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> + f.repository.renewAuthorization( + f.invoice.ownerAccountId(), + f.originalId, + f.authorizationId, + f.invoice.subscriptionId(), + 3, + 1, + "sha256:" + "c".repeat(64), + f.evidence)) + .isInstanceOf(IllegalStateException.class); + when(f.evidence.purpose()).thenReturn(AccountRecentReauthenticationPolicy.PURPOSE); + assertThatThrownBy(f::renew).isInstanceOf(IllegalStateException.class); + when(f.evidence.purpose()).thenReturn(AccountRecentReauthenticationPolicy.BILLING_PURPOSE); + when(f.evidence.creationOperationId()).thenReturn(f.originalId); + assertThatThrownBy(f::renew).isInstanceOf(IllegalStateException.class); + when(f.evidence.creationOperationId()).thenReturn(f.authorizationId); + when(f.evidence.accountId()).thenReturn(UUID.randomUUID()); + assertThatThrownBy(f::renew).isInstanceOf(IllegalStateException.class); + assertThat(f.authorizations).isEmpty(); + } + + @Test + void exactExpiryStaleRowAndLosingAuthorizationFenceRefuse() { + var f = new RenewalFixture(); + when(f.evidence.issuedAt()).thenReturn(RenewalFixture.NOW.minusSeconds(115)); + assertThatThrownBy(f::renew).isInstanceOf(IllegalStateException.class); + when(f.evidence.issuedAt()).thenReturn(RenewalFixture.NOW); + f.currentRowVersion = 4; + assertThatThrownBy(f::renew).isInstanceOf(IllegalStateException.class); + f.currentRowVersion = 3; + f.latestVersion = 2; + assertThatThrownBy(f::renew).isInstanceOf(IllegalStateException.class); + assertThat(f.authorizations).isEmpty(); + } + + @Test + void laterRenewalCannotRepeatAnAlreadyClaimedOrAmbiguousCommand() { + var f = new RenewalFixture(); + f.commandClaimed = true; + var dispatch = f.repository.readDispatch(f.renew(), f.invoice.ownerAccountId()); + assertThat(f.repository.claimCommand(dispatch, f.invoice.ownerAccountId())).isNull(); + f.latestVersion = 3; + assertThatThrownBy(() -> f.repository.readDispatch(dispatch, f.invoice.ownerAccountId())) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> f.repository.claimCommand(dispatch, f.invoice.ownerAccountId())) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void authorizationAndOriginalInvoiceExactDeadlinesCannotBeExtendedByRenewal() { + var f = new RenewalFixture(); + var prepared = f.renew(); + when(f.clock.instant()).thenReturn(RenewalFixture.NOW.plusSeconds(115)); + assertThatThrownBy(() -> f.repository.readDispatch(prepared, f.invoice.ownerAccountId())) + .isInstanceOf(IllegalStateException.class); + when(f.clock.instant()).thenReturn(f.invoice.expiresAt()); + when(f.evidence.issuedAt()).thenReturn(f.invoice.expiresAt()); + assertThatThrownBy(f::renew).isInstanceOf(IllegalStateException.class); + } + + /** Controlled SQL results exercise the owner methods, not physical PostgreSQL constraints. */ + private static final class RenewalFixture { + static final Instant NOW = Instant.parse("2026-11-07T00:00:00Z"); + final UUID originalId = UUID.randomUUID(), + authorizationId = UUID.randomUUID(), + evidenceId = UUID.randomUUID(), + providerId = UUID.randomUUID(), + lifecycleId = UUID.randomUUID(); + final DSLContext dsl = mock(DSLContext.class); + final Clock clock = mock(Clock.class); + final AccountSubscriptionIntentRepository intents = + mock(AccountSubscriptionIntentRepository.class); + final AccountRecentReauthenticationEvidence evidence = + mock(AccountRecentReauthenticationEvidence.class); + final Map authorizations = new HashMap<>(); + final AccountHostingFirstInvoicePayment invoice; + final AccountHostingFirstInvoicePaymentRepository repository; + long latestVersion = 1; + long currentRowVersion = 3; + boolean commandClaimed; + + RenewalFixture() { + TransactionSynchronizationManager.setActualTransactionActive(true); + var policy = + new AccountHostingBillingPolicyRepository.Policy("price_exact", 1, 1, 2400, "usd"); + var base = invoice("in_exact", "pi_exact", 2400, "usd"); + invoice = + new AccountHostingFirstInvoicePayment( + base.subscriptionId(), + base.creationRequestId(), + base.tenantId(), + base.ownerAccountId(), + base.paymentInstrumentId(), + base.instrumentVersion(), + base.providerSubscriptionId(), + base.providerCustomerId(), + base.providerPaymentMethodId(), + base.invoiceId(), + base.paymentIntentId(), + base.amount(), + base.currency(), + base.quoteDigest(), + base.providerPriceId(), + base.providerQuantity(), + base.billingPolicyVersion(), + policy.digest(), + false, + base.capturedAt(), + base.expiresAt()); + repository = spy(new AccountHostingFirstInvoicePaymentRepository(dsl, intents, clock)); + when(clock.instant()).thenReturn(NOW); + doReturn(invoice) + .when(repository) + .requireOwner(invoice.subscriptionId(), invoice.ownerAccountId()); + var creation = mock(AccountSubscriptionCreationRecord.class); + var quote = mock(AccountHostingPlanQuote.class); + when(quote.providerPriceId()).thenReturn("price_exact"); + when(quote.providerQuantity()).thenReturn(1L); + when(quote.digest()).thenReturn(invoice.quoteDigest()); + when(creation.planQuote()).thenReturn(quote); + when(intents.findCreation(invoice.creationRequestId())).thenReturn(Optional.of(creation)); + when(evidence.accountId()).thenReturn(invoice.ownerAccountId()); + when(evidence.evidenceId()).thenReturn(evidenceId); + when(evidence.purpose()).thenReturn(AccountRecentReauthenticationPolicy.BILLING_PURPOSE); + when(evidence.creationOperationId()).thenReturn(authorizationId); + when(evidence.billingContext()) + .thenReturn( + new AccountRecentReauthenticationEvidence.BillingContext( + invoice.ownerAccountId(), + invoice.subscriptionId(), + originalId, + invoice.digest(), + 3L, + invoice.expiresAt(), + authorizationId, + 1L, + AccountRecentReauthenticationEvidence.BillingAuthorizationPurpose + .FOLLOWUP_RENEWAL)); + when(evidence.issuedAt()).thenReturn(NOW); + when(evidence.recentAgeSeconds()).thenReturn(120L); + when(evidence.maxClockSkewSeconds()).thenReturn(5L); + Record original = + row( + Map.of( + "request_id", + originalId, + "subscription_id", + invoice.subscriptionId(), + "account_uuid", + invoice.ownerAccountId(), + "tuple_digest", + invoice.digest(), + "expected_row_version", + 3L, + "provider_idempotency_id", + providerId, + "lifecycle_request_id", + lifecycleId)); + Record commercial = + row( + Map.of( + "provider_price_id", + "price_exact", + "policy_version", + 1L, + "quantity", + 1L, + "amount", + 2400L, + "currency", + "usd")); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenAnswer(call -> { + String sql = call.getArgument(0); + Object[] values = (Object[]) call.getRawArguments()[1]; + if (sql.equals(AccountHostingFirstInvoicePaymentRepository.AWAITING_PAYMENT_SQL)) { + return row( + Map.of( + "status", + "provisioning", + "phase", + "AWAITING_PAYMENT", + "row_version", + currentRowVersion, + "provider_subscription_id", + invoice.providerSubscriptionId())); + } + if (sql.contains("account_hosting_billing_policy_current")) return commercial; + if (sql.contains("FROM subscription_first_invoice_confirmations")) return original; + if (sql.contains("subscription_first_invoice_operation_fences")) return null; + if (sql.contains("COALESCE(MAX")) return row(Map.of("version", latestVersion)); + if (sql.contains("FROM subscription_first_invoice_authorizations")) + return authorizations.get(values[0]); + throw new AssertionError(sql); + }); + Record transaction = row(Map.of("id", 100L)); + when(dsl.fetchOne("SELECT txid_current() AS id")).thenReturn(transaction); + doAnswer( + call -> { + String sql = call.getArgument(0); + Object[] values = (Object[]) call.getRawArguments()[1]; + if (sql.startsWith("INSERT INTO subscription_first_invoice_authorizations")) { + authorizations.put( + (UUID) values[0], + row( + Map.of( + "authorization_request_id", + values[0], + "request_id", + values[1], + "subscription_id", + values[2], + "authorization_version", + values[3], + "reauthentication_evidence_id", + values[4], + "consented_at", + values[5], + "valid_until", + values[6], + "created_transaction_id", + 99L))); + latestVersion = (Long) values[3]; + return 1; + } + if (sql.startsWith("INSERT INTO subscription_first_invoice_command_claims")) { + assertThat(values[0]).isEqualTo(originalId); + if (commandClaimed) return 0; + commandClaimed = true; + return 1; + } + throw new AssertionError(sql); + }) + .when(dsl) + .execute(anyString(), any(Object[].class)); + } + + AccountHostingFirstInvoicePaymentRepository.ConfirmationDispatch renew() { + return repository.renewAuthorization( + invoice.ownerAccountId(), + originalId, + authorizationId, + invoice.subscriptionId(), + 3, + 1, + invoice.digest(), + evidence); + } + + @SuppressWarnings("unchecked") + private static Record row(Map values) { + Record row = mock(Record.class); + when(row.get(anyString(), any(Class.class))) + .thenAnswer(call -> values.get(call.getArgument(0))); + when(row.get(anyString())).thenAnswer(call -> values.get(call.getArgument(0))); + return row; + } + } + + private static AccountHostingFirstInvoicePayment invoice( + String invoice, String intent, long amount, String currency) { + return invoice( + invoice, + intent, + amount, + currency, + UUID.fromString("d4bc0143-4bf9-48ac-86a7-88f422146cfa"), + "sha256:" + "b".repeat(64), + Instant.parse("2026-11-07T23:00:00Z")); + } + + private static AccountHostingFirstInvoicePayment invoice( + String invoice, + String intent, + long amount, + String currency, + UUID instrument, + String billingPolicyDigest, + Instant expiresAt) { + return invoice( + invoice, + intent, + amount, + currency, + instrument, + billingPolicyDigest, + Instant.parse("2026-11-07T00:00:00Z"), + expiresAt); + } + + private static AccountHostingFirstInvoicePayment invoice( + String invoice, + String intent, + long amount, + String currency, + UUID instrument, + String billingPolicyDigest, + Instant capturedAt, + Instant expiresAt) { + UUID id = UUID.fromString("d4bc0143-4bf9-48ac-86a7-88f422146cfa"); + return new AccountHostingFirstInvoicePayment( + id, + id, + id, + id, + instrument, + 1, + "sub_exact", + "cus_exact", + "pm_exact", + invoice, + intent, + amount, + currency, + "sha256:" + "a".repeat(64), + "price_exact", + 1, + 1, + billingPolicyDigest, + false, + capturedAt, + expiresAt); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java index 156223618e..6c1d599a3a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java @@ -2,6 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -21,6 +22,7 @@ import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReconciliationLimits; import org.jooq.DSLContext; import org.jooq.Record; +import org.jooq.ResultQuery; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -51,6 +53,54 @@ void clearTransactionState() { TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); } + @Test + void retainedPositiveInspectionRequiresBoundedReadOnlyTransactionBeforeSql() { + assertThatThrownBy(() -> repository.requireNoRetainedPositiveCompletionGaps(0)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> repository.requireNoRetainedPositiveCompletionGaps(6)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> repository.requireNoRetainedPositiveCompletionGaps(1)) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> repository.requireNoRetainedPositiveCompletionGaps(1)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(dsl); + } + + @Test + @SuppressWarnings("unchecked") + void retainedPositiveInspectionOnlyAcceptsExplicitClearSnapshot() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + ResultQuery query = mock(ResultQuery.class); + Record result = mock(Record.class); + when(dsl.resultQuery(anyString())).thenReturn(query); + when(query.fetchOne()).thenReturn(result); + when(result.get("unresolved", Boolean.class)).thenReturn(true, null, false); + assertThatThrownBy(() -> repository.requireNoRetainedPositiveCompletionGaps(2)) + .hasMessageContaining("HOSTING_ACTIVATION_UNAVAILABLE"); + assertThatThrownBy(() -> repository.requireNoRetainedPositiveCompletionGaps(2)) + .hasMessageContaining("HOSTING_ACTIVATION_UNAVAILABLE"); + repository.requireNoRetainedPositiveCompletionGaps(2); + verify(query, org.mockito.Mockito.times(3)).queryTimeout(2); + when(query.fetchOne()).thenReturn(null); + assertThatThrownBy(() -> repository.requireNoRetainedPositiveCompletionGaps(2)) + .isInstanceOf(NullPointerException.class); + } + + @Test + @SuppressWarnings("unchecked") + void retainedPositiveInspectionPropagatesDatabaseFailure() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + ResultQuery query = mock(ResultQuery.class); + when(dsl.resultQuery(anyString())).thenReturn(query); + when(query.fetchOne()).thenThrow(new org.jooq.exception.DataAccessException("timeout")); + assertThatThrownBy(() -> repository.requireNoRetainedPositiveCompletionGaps(1)) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + verify(query).queryTimeout(1); + } + @Test void recoveryOriginIsOnlyRetainedEpisodeHistoryAndMissingHistoryStaysUnresolved() { assertThat(AccountHostingSubscriptionLifecycleRepository.retainedPastDueOrigin(null)).isNull(); 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 index 97f7d4208a..fbacae8df9 100644 --- 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 @@ -52,6 +52,8 @@ void clearTransaction() { @Test void lifecycleEmitsExactBillingIdentityConsumedByCanonicalTenantCodec() throws Exception { + UUID subscriptionId = UUID.fromString("55555555-5555-4555-8555-555555555555"); + UUID paidReceiptId = UUID.fromString("66666666-6666-4666-8666-666666666666"); DSLContext dsl = mock(DSLContext.class); AccountSubscriptionIntentRepository intents = mock(AccountSubscriptionIntentRepository.class); Record operation = mock(Record.class); @@ -59,7 +61,7 @@ void lifecycleEmitsExactBillingIdentityConsumedByCanonicalTenantCodec() throws E 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("reserved_row_version", Long.class)).thenReturn(6L); 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)) @@ -74,6 +76,15 @@ void lifecycleEmitsExactBillingIdentityConsumedByCanonicalTenantCodec() throws E .thenReturn(NOW.plusSeconds(10).atOffset(ZoneOffset.UTC)); Record links = mock(Record.class); when(links.get("lifecycle_inflight_request_id", UUID.class)).thenReturn(REQUEST_ID); + when(links.get("current_receipt_request_id", UUID.class)).thenReturn(paidReceiptId); + Record paidReceipt = mock(Record.class); + when(paidReceipt.get("request_id", UUID.class)).thenReturn(paidReceiptId); + when(paidReceipt.get("subscription_id", UUID.class)).thenReturn(subscriptionId); + when(paidReceipt.get("subscription_row_version", Long.class)).thenReturn(5L); + when(paidReceipt.get("status", String.class)).thenReturn("active"); + when(paidReceipt.get("provider_subscription_id", String.class)).thenReturn("sub_exact"); + Record paidCompletion = mock(Record.class); + when(paidCompletion.get("subscription_id", UUID.class)).thenReturn(subscriptionId); Record sourceHead = mock(Record.class); when(sourceHead.get("current_generation", Long.class)).thenReturn(4L); when(sourceHead.get("current_source_version", Long.class)).thenReturn(4L); @@ -89,6 +100,15 @@ void lifecycleEmitsExactBillingIdentityConsumedByCanonicalTenantCodec() throws E if (sql.contains("FROM subscription_lifecycle_attempts")) { return attempt; } + if (sql.equals( + "SELECT subscription_id FROM subscription_first_invoice_completions WHERE subscription_id = ?")) { + assertThat((Object[]) invocation.getRawArguments()[1]).containsExactly(subscriptionId); + return paidCompletion; + } + if (sql.equals("SELECT * FROM subscription_lifecycle_receipts WHERE request_id = ?")) { + assertThat((Object[]) invocation.getRawArguments()[1]).containsExactly(paidReceiptId); + return paidReceipt; + } if (sql.contains("FROM subscription WHERE")) { return links; } @@ -112,7 +132,6 @@ void lifecycleEmitsExactBillingIdentityConsumedByCanonicalTenantCodec() throws E 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 = @@ -145,18 +164,37 @@ void lifecycleEmitsExactBillingIdentityConsumedByCanonicalTenantCodec() throws E ATTEMPT_ID, "cus_exact", CREATION_ID, - 1L, - "pending", - null, + 6L, + "active", + "sub_exact", null, null, null); when(intents.findCreation(CREATION_ID)).thenReturn(Optional.of(original)); - when(intents.lockForLifecycle(CREATION_ID, 1L)).thenReturn(current); + when(intents.lockForLifecycle(CREATION_ID, 6L)).thenReturn(current); + var history = + new AccountSubscriptionProviderHistoryRecord( + "sub_exact", + subscriptionId, + "SUBSCRIPTION_PROVISIONING", + CREATION_ID, + original.subscriptionProvisioningRequestId(), + "canonical", + NOW.minusSeconds(60), + REQUEST_DIGEST, + NOW.minusSeconds(60)); + when(intents.lookupProviderId("sub_exact")) + .thenReturn( + new AccountSubscriptionIntentRepository.ProviderLookup( + AccountSubscriptionIntentRepository.MappingDisposition.CURRENT_MAPPING, + Optional.of(history), + Optional.empty())); 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. + // Reconcile an already-paid active subscription with exact retained mapping/completion. + // Storage/provider inputs are controlled and execution stops before the receipt insert; + // this proves real event encoding, not initial-payment qualification or a durable commit. ObservedSubscription observed = mock(ObservedSubscription.class, Answers.RETURNS_DEEP_STUBS); when(observed.providerSubscriptionId()).thenReturn("sub_exact"); when(observed.providerCustomerId()).thenReturn("cus_exact"); 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 index bd960d17b8..a6ab0e3206 100644 --- 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 @@ -321,6 +321,35 @@ void clearContexts() { TransactionSynchronizationManager.clear(); } + @Test + void scopeIssuedWhenApplicationLeadsRetainsDatabaseTime() { + Fixture f = new Fixture(300000L); + Instant databaseTime = + Instant.now().minusSeconds(1).truncatedTo(java.time.temporal.ChronoUnit.MICROS); + org.mockito.Mockito.doReturn(databaseTime).when(f.scopes).canonicalIssuanceTime(); + + var result = f.owner.listRealmScopes(f.token, "tenant", "world").getFirst(); + + assertThat(result.scope().evaluatedAt()).isEqualTo(databaseTime.toString()); + assertThat(f.retained.get()).isEqualTo(result.scope()); + } + + @Test + void scopeExpiresAtDatabasePublicationSampleEvenWhenApplicationClockIsEarlier() { + Fixture f = new Fixture(300000L); + Instant databaseTime = + Instant.now().minusSeconds(1).truncatedTo(java.time.temporal.ChronoUnit.MICROS); + org.mockito.Mockito.doReturn(databaseTime) + .doAnswer(invocation -> Instant.parse(f.retained.get().connectScopeExpiresAt())) + .when(f.scopes) + .canonicalIssuanceTime(); + + assertThatThrownBy(() -> f.owner.listRealmScopes(f.token, "tenant", "world")) + .isInstanceOf(AuthenticationException.class) + .hasMessageContaining("Canonical scope expired before publication"); + assertThat(f.retained.get()).isNotNull(); + } + @Test void genuineAbsenceAndClosedEnrollmentStillProduceOnlyACanonicalPublicSelectorScope() { Fixture f = new Fixture(300000L); @@ -352,7 +381,7 @@ void genuineAbsenceAndClosedEnrollmentStillProduceOnlyACanonicalPublicSelectorSc 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.transactions.commits).isEqualTo(3); assertThat(f.registryChecks.get()).isEqualTo(3); verify(f.scopes).insertCanonical(PRIVATE_ACCOUNT, scope, f.provenance()); verify(f.memberships, never()).createFreshMembershipForJoin(any(), any()); @@ -849,6 +878,11 @@ private Fixture(long bootstrapLifetime) { }) .when(scopes) .insertCanonical(anyLong(), any(), any()); + when(scopes.canonicalIssuanceTime()) + .thenAnswer(invocation -> { + assertInsideSql(); + return Instant.now().truncatedTo(java.time.temporal.ChronoUnit.MICROS); + }); when(scopes.findCanonical(any())) .thenAnswer(invocation -> { assertInsideSql(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java index 67211fd1e7..ae12399dc5 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java @@ -4,12 +4,19 @@ 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.verifyNoMoreInteractions; import static org.mockito.Mockito.when; +import com.stripe.exception.StripeException; import java.util.UUID; +import net.firedevops.firemud.accountservice.client.StripeHostingFirstInvoicePaymentClient; import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionProvisioner; +import net.firedevops.firemud.accountservice.repository.AccountHostingFirstInvoicePayment; +import net.firedevops.firemud.accountservice.repository.AccountHostingFirstInvoicePaymentRepository; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Disposition; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProviderDispatch; @@ -29,12 +36,14 @@ class AccountHostingSubscriptionProvisioningServiceTest { mock(AccountHostingSubscriptionLifecycleRepository.class); private final StripeHostingSubscriptionProvisioner provider = mock(StripeHostingSubscriptionProvisioner.class); - private final AccountHostingSubscriptionLifecycleService lifecycle = - mock(AccountHostingSubscriptionLifecycleService.class); + private final StripeHostingFirstInvoicePaymentClient firstInvoiceProvider = + mock(StripeHostingFirstInvoicePaymentClient.class); + private final AccountHostingFirstInvoicePaymentRepository firstInvoices = + mock(AccountHostingFirstInvoicePaymentRepository.class); private final LocalTransactions transactions = new LocalTransactions(); private final AccountHostingSubscriptionProvisioningService service = new AccountHostingSubscriptionProvisioningService( - repository, provider, lifecycle, transactions); + repository, provider, firstInvoiceProvider, firstInvoices, transactions); private final ProvisioningClaim claim = mock(ProvisioningClaim.class); @AfterEach @@ -45,6 +54,68 @@ void clearAmbient() { } } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void concurrentCaptureRecoversOnlyExactRetainedWinner(boolean retainedWinner) throws Exception { + ProviderDispatch dispatch = mock(ProviderDispatch.class); + when(dispatch.claim()).thenReturn(claim); + when(repository.prepareProviderDispatch(any(), any())).thenReturn(dispatch); + when(repository.readProviderDispatch(dispatch)).thenReturn(dispatch); + var located = mock(StripeHostingSubscriptionProvisioner.Located.class); + when(located.providerSubscriptionId()).thenReturn("sub_original"); + when(provider.provision(dispatch)).thenReturn(located); + var observed = mock(StripeHostingFirstInvoicePaymentClient.Observation.class); + when(firstInvoiceProvider.capture(dispatch, "sub_original")).thenReturn(observed); + var failure = new FenceRejectedException("concurrent capture advanced version"); + when(firstInvoices.retainAwaitingPayment(dispatch, "sub_original", observed)) + .thenThrow(failure); + var winner = mock(AccountHostingFirstInvoicePayment.class); + when(firstInvoices.findAwaitingPayment(claim)).thenReturn(null, retainedWinner ? winner : null); + if (retainedWinner) { + assertThat(service.provision(claim, UUID.randomUUID())) + .isEqualTo(new AccountHostingSubscriptionProvisioningService.AwaitingPayment(winner)); + } else { + assertThatThrownBy(() -> service.provision(claim, UUID.randomUUID())).isSameAs(failure); + } + verify(provider).provision(dispatch); + verify(firstInvoiceProvider).capture(dispatch, "sub_original"); + verify(firstInvoices, times(2)).findAwaitingPayment(claim); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void onlyExpectedProviderCaptureRefusalDefersTheOriginalClaim(boolean evidenceRefused) + throws Exception { + var dispatch = mock(ProviderDispatch.class); + when(dispatch.claim()).thenReturn(claim); + when(repository.prepareProviderDispatch(any(), any())).thenReturn(dispatch); + when(repository.readProviderDispatch(dispatch)).thenReturn(dispatch); + var located = mock(StripeHostingSubscriptionProvisioner.Located.class); + when(located.providerSubscriptionId()).thenReturn("sub_original"); + when(provider.provision(dispatch)).thenReturn(located); + var refusal = + evidenceRefused + ? new StripeHostingFirstInvoicePaymentClient.ProviderEvidenceRefused() + : new IllegalStateException("unexpected programming error"); + when(firstInvoiceProvider.capture(dispatch, "sub_original")).thenThrow(refusal); + if (evidenceRefused) { + when(repository.deferUnresolved(claim)).thenReturn(Disposition.WAITING); + assertThat(service.provision(claim, UUID.randomUUID())) + .isEqualTo( + new AccountHostingSubscriptionProvisioningService.Pending( + Disposition.WAITING, + new StripeHostingSubscriptionProvisioner.Pending( + "FIRST_INVOICE_UNRESOLVED", null))); + verify(repository).deferUnresolved(claim); + } else { + assertThatThrownBy(() -> service.provision(claim, UUID.randomUUID())).isSameAs(refusal); + verify(repository, never()).deferUnresolved(any()); + } + verify(provider).provision(dispatch); + verify(firstInvoiceProvider).capture(dispatch, "sub_original"); + verify(firstInvoices, never()).retainAwaitingPayment(any(), any(), any()); + } + @Test void claimCommitAndIndependentReadbackPrecedeProviderAndUnknownOutcomeDefersWithoutLifecycle() { ProviderDispatch prepared = mock(ProviderDispatch.class); @@ -58,14 +129,14 @@ void claimCommitAndIndependentReadbackPrecedeProviderAndUnknownOutcomeDefersWith when(repository.readProviderDispatch(prepared)) .thenAnswer(call -> { assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - assertThat(transactions.commits).isEqualTo(1); + assertThat(transactions.commits).isEqualTo(2); return readback; }); when(provider.provision(readback)) .thenAnswer(call -> { assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - assertThat(transactions.commits).isEqualTo(2); + assertThat(transactions.commits).isEqualTo(3); return new StripeHostingSubscriptionProvisioner.Pending("UNKNOWN", null); }); when(repository.deferUnresolved(claim)) @@ -75,10 +146,12 @@ void claimCommitAndIndependentReadbackPrecedeProviderAndUnknownOutcomeDefersWith }); var result = (AccountHostingSubscriptionProvisioningService.Pending) - service.provision(claim, UUID.randomUUID(), UUID.randomUUID()); + service.provision(claim, UUID.randomUUID()); assertThat(result.disposition()).isEqualTo(Disposition.WAITING); - assertThat(transactions.commits).isEqualTo(3); - verifyNoInteractions(lifecycle); + assertThat(transactions.commits).isEqualTo(4); + verify(firstInvoices).findAwaitingPayment(claim); + verifyNoMoreInteractions(firstInvoices); + verifyNoInteractions(firstInvoiceProvider); } @ParameterizedTest @@ -97,12 +170,14 @@ void expiredAttemptReturnsTypedPendingWithoutStartingLifecycle(String providerRe return Disposition.ATTEMPT_EXPIRED; }); - assertThat(service.provision(claim, UUID.randomUUID(), UUID.randomUUID())) + assertThat(service.provision(claim, UUID.randomUUID())) .isEqualTo( new AccountHostingSubscriptionProvisioningService.Pending( Disposition.ATTEMPT_EXPIRED, providerResult)); - assertThat(transactions.commits).isEqualTo(3); - verifyNoInteractions(lifecycle); + assertThat(transactions.commits).isEqualTo(4); + verify(firstInvoices).findAwaitingPayment(claim); + verifyNoMoreInteractions(firstInvoices); + verifyNoInteractions(firstInvoiceProvider); } @ParameterizedTest @@ -123,28 +198,73 @@ void refusedDispatchCommitsLocalDeferralWithoutCallingProvider(boolean readbackR return Disposition.TERMINAL_FAILURE; }); - assertThat(service.provision(claim, UUID.randomUUID(), UUID.randomUUID())) + assertThat(service.provision(claim, UUID.randomUUID())) .isEqualTo( new AccountHostingSubscriptionProvisioningService.Pending( Disposition.TERMINAL_FAILURE, new StripeHostingSubscriptionProvisioner.Pending("DISPATCH_FENCE_REJECTED", null))); - assertThat(transactions.commits).isEqualTo(readbackRefused ? 2 : 1); + assertThat(transactions.commits).isEqualTo(readbackRefused ? 4 : 3); verify(repository).deferUnresolved(claim); - verifyNoInteractions(provider, lifecycle); + verify(firstInvoices, times(2)).findAwaitingPayment(claim); + verifyNoMoreInteractions(firstInvoices); + verifyNoInteractions(provider, firstInvoiceProvider); } - @Test - void refusedDispatchCannotHideStaleClaimSettlementFailure() { + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void fencedDeferralReturnsInvoiceRetainedByTheSameClaim(boolean captureFailure) throws Exception { + var winner = mock(AccountHostingFirstInvoicePayment.class); + var refusal = new FenceRejectedException("sibling retained invoice before deferral"); + when(repository.deferUnresolved(claim)).thenThrow(refusal); + if (captureFailure) { + var dispatch = mock(ProviderDispatch.class); + var located = mock(StripeHostingSubscriptionProvisioner.Located.class); + when(dispatch.claim()).thenReturn(claim); + when(located.providerSubscriptionId()).thenReturn("sub_original"); + when(repository.prepareProviderDispatch(any(), any())).thenReturn(dispatch); + when(repository.readProviderDispatch(dispatch)).thenReturn(dispatch); + when(provider.provision(dispatch)).thenReturn(located); + when(firstInvoiceProvider.capture(dispatch, "sub_original")) + .thenThrow(mock(StripeException.class)); + when(firstInvoices.findAwaitingPayment(claim)).thenReturn(null, winner); + } else { + when(repository.prepareProviderDispatch(any(), any())) + .thenThrow(new FenceRejectedException("dispatch refused")); + when(firstInvoices.findAwaitingPayment(claim)).thenReturn(null, null, winner); + } + + assertThat(service.provision(claim, UUID.randomUUID())) + .isEqualTo(new AccountHostingSubscriptionProvisioningService.AwaitingPayment(winner)); + verify(repository).deferUnresolved(claim); + verify(firstInvoices, times(captureFailure ? 2 : 3)).findAwaitingPayment(claim); + verify(firstInvoices, never()).retainAwaitingPayment(any(), any(), any()); + if (captureFailure) { + verify(provider).provision(any()); + verify(firstInvoiceProvider).capture(any(), any()); + } else { + verifyNoInteractions(provider, firstInvoiceProvider); + } + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void refusedDispatchCannotHideStaleClaimSettlementFailure(boolean replacementRetained) { + var stale = new FenceRejectedException("stale retained attempt"); when(repository.prepareProviderDispatch(any(), any())) .thenThrow(new FenceRejectedException("dispatch refused")); - when(repository.deferUnresolved(claim)) - .thenThrow(new FenceRejectedException("stale retained attempt")); + when(repository.deferUnresolved(claim)).thenThrow(stale); + if (replacementRetained) { + when(firstInvoices.findAwaitingPayment(claim)) + .thenReturn(null) + .thenReturn(null) + .thenThrow(new FenceRejectedException("invoice belongs to a replacement claim")); + } - assertThatThrownBy(() -> service.provision(claim, UUID.randomUUID(), UUID.randomUUID())) - .isInstanceOf(FenceRejectedException.class) - .hasMessage("stale retained attempt"); - assertThat(transactions.commits).isZero(); - verifyNoInteractions(provider, lifecycle); + assertThatThrownBy(() -> service.provision(claim, UUID.randomUUID())).isSameAs(stale); + assertThat(transactions.commits).isEqualTo(replacementRetained ? 2 : 3); + verify(firstInvoices, times(3)).findAwaitingPayment(claim); + verifyNoMoreInteractions(firstInvoices); + verifyNoInteractions(provider, firstInvoiceProvider); } @Test @@ -153,22 +273,24 @@ void failedIndependentReadbackNeverCallsProvider() { when(repository.prepareProviderDispatch(any(), any())).thenReturn(prepared); when(repository.readProviderDispatch(prepared)) .thenThrow(new IllegalStateException("readback rejected")); - assertThatThrownBy(() -> service.provision(claim, UUID.randomUUID(), UUID.randomUUID())) + assertThatThrownBy(() -> service.provision(claim, UUID.randomUUID())) .hasMessageContaining("readback rejected"); - assertThat(transactions.commits).isEqualTo(1); - verifyNoInteractions(provider, lifecycle); + assertThat(transactions.commits).isEqualTo(2); + verify(firstInvoices).findAwaitingPayment(claim); + verifyNoMoreInteractions(firstInvoices); + verifyNoInteractions(provider, firstInvoiceProvider); } @Test void ambientTransactionAndSynchronizationRefuseBeforeAnyEffects() { TransactionSynchronizationManager.setActualTransactionActive(true); - assertThatThrownBy(() -> service.provision(claim, UUID.randomUUID(), UUID.randomUUID())) + assertThatThrownBy(() -> service.provision(claim, UUID.randomUUID())) .hasMessageContaining("ambient SQL"); TransactionSynchronizationManager.setActualTransactionActive(false); TransactionSynchronizationManager.initSynchronization(); - assertThatThrownBy(() -> service.provision(claim, UUID.randomUUID(), UUID.randomUUID())) + assertThatThrownBy(() -> service.provision(claim, UUID.randomUUID())) .hasMessageContaining("ambient SQL"); - verifyNoInteractions(repository, provider, lifecycle); + verifyNoInteractions(repository, provider, firstInvoiceProvider, firstInvoices); } private static final class LocalTransactions extends AbstractPlatformTransactionManager { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java index e07e7e4e22..dc04a20374 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java @@ -62,6 +62,7 @@ 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.AccountTenantCapacityRepository; import net.firedevops.firemud.accountservice.security.AccountPlayerAdmissionEntitlementWorkloadGuard; import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner; import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner.Request; @@ -114,6 +115,7 @@ class AccountPlayerAdmissionEntitlementOwnerTest { private static final UUID ACCOUNT = UUID.fromString("11111111-1111-4111-8111-111111111111"); private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID BILLING_OWNER = UUID.fromString("00000000-0000-4000-8000-000000000001"); private static final String ISSUER = "firemud-account-service"; private static final String PEER = "spiffe://firemud/ns/prod/sa/game-session-service"; private static final String PREFIX = "account:auth-authority:v1:"; @@ -124,6 +126,7 @@ class AccountPlayerAdmissionEntitlementOwnerTest { void clearTransactionFlags() { TransactionSynchronizationManager.setActualTransactionActive(false); TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(null); } @Test @@ -165,7 +168,8 @@ void missingMembershipRemainsAnExplicitNonadmittingBaselineWithActualCallerAndTa assertThat(binding.get("playableStateScope")).isEqualTo("SHARED"); assertThat(binding.get("characterCreationPolicy")).isEqualTo("PRESEEDED_ONLY"); assertThat(value.toString()).doesNotContain("controlled-token", f.scope.connectScopeId()); - assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "commit"); + assertThat(f.transactions.events) + .containsExactly("begin", "commit", "begin", "commit", "begin", "commit"); verifyNoInteractions(f.hosting, f.observer); } @@ -216,6 +220,142 @@ void existingMembershipCarriesItsIndependentVersionAndPositiveCheckpoint() throw order.verify(f.demos).readCurrent(TENANT); } + @Test + void capacityEvidenceFreshnessUsesDatabaseTimeWhenApplicationClockTrails() throws Exception { + Fixture f = new Fixture(true); + f.time.set(NOW.minusSeconds(1)); + f.databaseTime.set(NOW); + + var value = f.owner.evaluate(f.request, "controlled-token"); + + assertThat(value.evaluatedAt()).isEqualTo(NOW); + assertThat(value.evaluatedAt()).isAfter(f.time.get()); + } + + @Test + void capacityCaptureRejectsConnectScopeExpiredAtDatabaseStamp() throws Exception { + Fixture f = new Fixture(false); + f.databaseTime.set(NOW.plusSeconds(60)); + + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .isInstanceOf(AccountPlayerAdmissionEntitlementOwner.SourceUnavailableException.class) + .hasMessage("ENTITLEMENT_UNAVAILABLE: current player source evidence is unavailable") + .hasNoCause(); + assertThat(f.retainedCapacity).isEmpty(); + assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "rollback"); + } + + @Test + void capacityCaptureRejectsPaidReceiptExpiredAtDatabaseStamp() throws Exception { + Fixture f = new Fixture(true); + when(f.sources.readCurrentSourceSelection(TENANT)) + .thenReturn(new SourceSelection(SourceKind.PAID_HOSTING, f.tenantEvent)); + var fence = mock(ReadFence.class); + var observed = mock(StripeHostingSubscriptionObserver.ObservedSubscription.class); + when(f.hosting.prepareCurrentRead(TENANT)).thenReturn(fence); + when(f.observer.observe(fence.binding())).thenReturn(observed); + var receipt = f.receipt(Status.ACTIVE); + receipt = + new AccountHostingSubscriptionCurrentReceipt( + receipt.current(), + receipt.receiptRequestId(), + receipt.subscriptionStatus(), + receipt.gameplayAvailable(), + receipt.allowPublicJoin(), + receipt.allowNewGameplayBindings(), + receipt.allowNewInstanceStarts(), + receipt.entitlementVersion(), + receipt.tenantBillingSequence(), + receipt.billingEventId(), + receipt.billingEventDigest(), + receipt.tenantAuthorityEvent(), + receipt.rawProviderStatus(), + receipt.currentPeriodStart(), + receipt.currentPeriodEnd(), + receipt.cancelAtPeriodEnd(), + receipt.cancelAt(), + receipt.cutoffAt(), + receipt.evaluatedAt(), + NOW.plusSeconds(1)); + when(f.hosting.readCurrent(fence, observed)).thenReturn(receipt); + f.databaseTime.set(NOW.plusSeconds(1)); + + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .isInstanceOf(AccountPlayerAdmissionEntitlementOwner.SourceUnavailableException.class) + .hasMessage("ENTITLEMENT_UNAVAILABLE: current player source evidence is unavailable") + .hasNoCause(); + assertThat(f.retainedCapacity).isEmpty(); + assertThat(f.transactions.events) + .containsExactly("begin", "commit", "begin", "commit", "begin", "rollback"); + } + + @Test + void paidEvaluationRetainsOriginalAndTranslatedCutoffsWhenDatabaseTrails() throws Exception { + Fixture f = new Fixture(true); + var fence = mock(ReadFence.class); + var observed = mock(StripeHostingSubscriptionObserver.ObservedSubscription.class); + when(f.sources.readCurrentSourceSelection(TENANT)) + .thenReturn(new SourceSelection(SourceKind.PAID_HOSTING, f.tenantEvent)); + when(f.hosting.prepareCurrentRead(TENANT)).thenReturn(fence); + when(f.observer.observe(fence.binding())).thenReturn(observed); + var originalCutoff = NOW.plusSeconds(60).plusNanos(123_789); + var receipt = f.receipt(Status.ACTIVE, originalCutoff); + when(f.hosting.readCurrent(fence, observed)).thenReturn(receipt); + f.time.set(NOW.plusSeconds(12)); + f.databaseTime.set(NOW); + + var value = f.owner.evaluate(f.request, "controlled-token"); + + var sources = (Map) value.fields().get("sourceReferences"); + assertThat(sources.get("paidReceiptValidUntil")) + .isEqualTo(originalCutoff.minusSeconds(12).toString()); + assertThat(value.evaluatedAt()).isEqualTo(NOW); + var evaluation = f.retainedCapacity.get(value.fields().get("evaluationIdentity")); + assertThat(evaluation.get("canonical_evidence", byte[].class)) + .containsExactly(value.canonicalBytes()); + assertThat(evaluation.get("original_paid_cutoff", java.time.OffsetDateTime.class)) + .isEqualTo(NOW.plusSeconds(60).plusNanos(123_000).atOffset(java.time.ZoneOffset.UTC)); + + TransactionSynchronizationManager.setActualTransactionActive(true); + var repository = new AccountTenantCapacityRepository(f.dsl); + repository.retainPlayerEvaluation(value, originalCutoff); + assertThatThrownBy( + () -> repository.retainPlayerEvaluation(value, originalCutoff.plusSeconds(1))) + .isInstanceOf(AccountTenantCapacityRepository.CapacityException.class); + assertThat(f.retainedCapacity).hasSize(1); + } + + @ParameterizedTest + @ValueSource(ints = {1, 2}) + void paidCaptureFailsWhenOriginalAppReceiptExpiresDuringDatabaseRead(int expiringRead) + throws Exception { + Fixture f = new Fixture(true); + var fence = mock(ReadFence.class); + var observed = mock(StripeHostingSubscriptionObserver.ObservedSubscription.class); + when(f.sources.readCurrentSourceSelection(TENANT)) + .thenReturn(new SourceSelection(SourceKind.PAID_HOSTING, f.tenantEvent)); + when(f.hosting.prepareCurrentRead(TENANT)).thenReturn(fence); + when(f.observer.observe(fence.binding())).thenReturn(observed); + var receipt = f.receipt(Status.ACTIVE, NOW.plusSeconds(5)); + when(f.hosting.readCurrent(fence, observed)).thenReturn(receipt); + var dbReads = new java.util.concurrent.atomic.AtomicInteger(); + var stamp = mock(org.jooq.Record.class); + when(stamp.get("observed_at", java.time.OffsetDateTime.class)) + .thenReturn(AccountTenantCapacityRepository.at(NOW)); + when(f.dsl.fetchSingle("SELECT clock_timestamp() AS observed_at")) + .thenAnswer(invocation -> { + if (dbReads.incrementAndGet() == expiringRead) f.time.set(NOW.plusSeconds(5)); + return stamp; + }); + + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .isInstanceOf(AccountPlayerAdmissionEntitlementOwner.SourceUnavailableException.class); + assertThat(dbReads).hasValue(expiringRead); + if (expiringRead == 1) { + assertThat(f.retainedCapacity).isEmpty(); + } + } + @ParameterizedTest @EnumSource(Status.class) void paidReadRunsProviderOutsideSqlThenCapturesCurrentReceiptAndPlayerInFinalTransaction( @@ -233,11 +373,13 @@ void paidReadRunsProviderOutsideSqlThenCapturesCurrentReceiptAndPlayerInFinalTra when(f.observer.observe(fence.binding())) .thenAnswer(invocation -> { assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(f.accountLocks).isEmpty(); return observed; }); when(f.hosting.readCurrent(fence, observed)) .thenAnswer(invocation -> { assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(f.accountLocks).containsExactly(BILLING_OWNER, ACCOUNT); return f.receipt(status); }); var value = f.owner.evaluate(f.request, "controlled-token"); @@ -253,12 +395,15 @@ void paidReadRunsProviderOutsideSqlThenCapturesCurrentReceiptAndPlayerInFinalTra .containsEntry("allowNewGameplayBindings", available && status != Status.GRACE) .containsEntry("allowNewInstanceStarts", available && status != Status.GRACE); assertThat(f.transactions.events) - .containsExactly("begin", "commit", "begin", "commit", "begin", "commit"); - var order = inOrder(f.observer, f.accounts, f.hosting); + .containsExactly( + "begin", "commit", "begin", "commit", "begin", "commit", "begin", "commit"); + var order = inOrder(f.hosting, f.observer, f.accounts, f.issuances, f.memberships); order.verify(f.hosting).prepareCurrentRead(TENANT); order.verify(f.observer).observe(fence.binding()); - order.verify(f.accounts).findByAccountUuidForUpdate(ACCOUNT); order.verify(f.hosting).readCurrent(fence, observed); + order.verify(f.accounts).findByAccountUuidForUpdate(ACCOUNT); + order.verify(f.issuances).readCurrentCommittedCandidateByJti(f.identity.tokenJti()); + order.verify(f.memberships).readCurrent(ACCOUNT, TENANT); } @ParameterizedTest @@ -468,6 +613,18 @@ void anotherAccountsScopeFailsBeforeEntitlementCapture() throws Exception { verifyNoInteractions(f.demos); } + @Test + void callerDeadlineExpiresDuringFinalClockCommit() throws Exception { + Instant callerDeadline = NOW.plusSeconds(30); + Fixture f = new Fixture(false, "SHARED", callerDeadline); + assertThat(callerDeadline).isBefore(Instant.parse(f.scope.connectScopeExpiresAt())); + f.transactions.afterThirdCommit = () -> f.time.set(callerDeadline); + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + assertThat(f.transactions.events) + .containsExactly("begin", "commit", "begin", "commit", "begin", "commit"); + } + @Test void expiredScopeDoesNotReturnCapturedAuthority() throws Exception { Fixture f = new Fixture(false); @@ -935,6 +1092,7 @@ private static void controlledTarget(CanonicalGameplayAdmissionDecisionReadClien private static final class Fixture { private final AccountRepository accounts = mock(AccountRepository.class); + private final DSLContext dsl = mock(DSLContext.class); private final AccountGameplayAdmissionCallerVerifier callers = mock(AccountGameplayAdmissionCallerVerifier.class); private final AccountGameplayDelegationIssuanceRepository issuances = @@ -953,27 +1111,18 @@ private static final class Fixture { private final CanonicalGameplayAdmissionDecisionReadClient targets = mock(CanonicalGameplayAdmissionDecisionReadClient.class); private final RecordingTransactions transactions = new RecordingTransactions(); + private final List accountLocks = new ArrayList<>(); private final Map retainedCapacity = new LinkedHashMap<>(); private boolean refuseCapacityRetention; private boolean missingCapacityRetentionReadback; private final java.util.concurrent.atomic.AtomicReference time = new java.util.concurrent.atomic.AtomicReference<>(NOW); + private final java.util.concurrent.atomic.AtomicReference databaseTime = + new java.util.concurrent.atomic.AtomicReference<>(NOW); private final FreshTenantCreationEvidence source = source(); private final TenantAuthorityEventV1Codec.Event tenantEvent = tenantEvent(source); private final CanonicalJoinScopeV2 scope; - private final AccountGameplayDelegationPendingIdentity identity = - new AccountGameplayDelegationPendingIdentity( - UUID.randomUUID(), - UUID.randomUUID(), - ACCOUNT, - PEER, - UUID.randomUUID(), - mock(AccountGameplayCredentialRequestBinding.class), - HASH, - UUID.randomUUID(), - NOW.minusSeconds(10).getEpochSecond(), - NOW.minusSeconds(10).getEpochSecond(), - NOW.plusSeconds(120).getEpochSecond()); + private final AccountGameplayDelegationPendingIdentity identity; private final DemoTenantEntitlementSnapshot demo = new DemoTenantEntitlementSnapshot( TENANT, @@ -1007,6 +1156,23 @@ private Fixture(boolean exists) throws Exception { } private Fixture(boolean exists, String stateScope) throws Exception { + this(exists, stateScope, NOW.plusSeconds(120)); + } + + private Fixture(boolean exists, String stateScope, Instant callerDeadline) throws Exception { + identity = + new AccountGameplayDelegationPendingIdentity( + UUID.randomUUID(), + UUID.randomUUID(), + ACCOUNT, + PEER, + UUID.randomUUID(), + mock(AccountGameplayCredentialRequestBinding.class), + HASH, + UUID.randomUUID(), + NOW.minusSeconds(10).getEpochSecond(), + NOW.minusSeconds(10).getEpochSecond(), + callerDeadline.getEpochSecond()); scope = new CanonicalJoinScopeV2( "private-bearer-" + UUID.randomUUID(), @@ -1042,7 +1208,6 @@ private Fixture(boolean exists, String stateScope) throws Exception { scope.connectScopeId(), PEER); controlledTarget(targets); - var dsl = mock(DSLContext.class); // Controlled retention content, not physical atomicity or Account source authentication. when(dsl.execute(anyString(), any(Object[].class))) .thenAnswer(invocation -> { @@ -1068,17 +1233,37 @@ private Fixture(boolean exists, String stateScope) throws Exception { .thenReturn((java.time.OffsetDateTime) values[6]); when(row.get("expires_at", java.time.OffsetDateTime.class)) .thenReturn((java.time.OffsetDateTime) values[7]); + when(row.get("original_paid_cutoff", java.time.OffsetDateTime.class)) + .thenReturn((java.time.OffsetDateTime) values[8]); retainedCapacity.put(id, row); return 1; }); when(dsl.fetchOne(anyString(), any(Object[].class))) .thenAnswer(invocation -> { String sql = invocation.getArgument(0, String.class); + if (sql.startsWith("SELECT owner_account_uuid FROM account_tenant_billing_owners ")) { + var owner = mock(org.jooq.Record.class); + when(owner.get("owner_account_uuid", UUID.class)).thenReturn(BILLING_OWNER); + return owner; + } + if (sql.startsWith("SELECT account_uuid FROM accounts WHERE account_uuid = ?")) { + Object[] values = (Object[]) invocation.getRawArguments()[1]; + UUID accountId = (UUID) values[0]; + accountLocks.add(accountId); + var accountLock = mock(org.jooq.Record.class); + when(accountLock.get("account_uuid", UUID.class)).thenReturn(accountId); + return accountLock; + } if (!sql.startsWith("SELECT * FROM account_tenant_capacity_evaluations ")) throw new AssertionError(sql); Object[] values = (Object[]) invocation.getRawArguments()[1]; return retainedCapacity.get((String) values[0]); }); + var evaluationTime = mock(org.jooq.Record.class); + when(evaluationTime.get("observed_at", java.time.OffsetDateTime.class)) + .thenAnswer(invocation -> AccountTenantCapacityRepository.at(databaseTime.get())); + when(dsl.fetchSingle("SELECT clock_timestamp() AS observed_at")) + .thenAnswer(invocation -> evaluationTime); var connection = mock(Connection.class); when(connection.getTransactionIsolation()).thenReturn(Connection.TRANSACTION_SERIALIZABLE); doAnswer( @@ -1172,6 +1357,10 @@ private CanonicalConnectScopeEvidence scopeEvidence(UUID account, String expiry) } private AccountHostingSubscriptionCurrentReceipt receipt(Status status) { + return receipt(status, NOW.plusSeconds(60)); + } + + private AccountHostingSubscriptionCurrentReceipt receipt(Status status, Instant validUntil) { var current = mock(AccountSubscriptionCurrentRecord.class); when(current.tenantId()).thenReturn(TENANT); when(current.subscriptionId()).thenReturn(UUID.randomUUID()); @@ -1198,7 +1387,7 @@ private AccountHostingSubscriptionCurrentReceipt receipt(Status status) { null, null, NOW, - NOW.plusSeconds(60)); + validUntil); } private Snapshot snapshot(boolean exists) { @@ -1342,6 +1531,7 @@ private static final class RecordingTransactions implements PlatformTransactionM private final List events = new ArrayList<>(); private boolean failCommit; private Runnable afterSecondCommit = () -> {}; + private Runnable afterThirdCommit = () -> {}; @Override public TransactionStatus getTransaction( @@ -1356,6 +1546,10 @@ public TransactionStatus getTransaction( } events.add("begin"); TransactionSynchronizationManager.setActualTransactionActive(true); + if (definition != null) { + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + definition.getIsolationLevel()); + } return new SimpleTransactionStatus(); } @@ -1363,7 +1557,9 @@ public TransactionStatus getTransaction( public void commit(TransactionStatus status) { events.add("commit"); TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(null); if (events.size() == 4) afterSecondCommit.run(); + if (events.size() == 6) afterThirdCommit.run(); if (failCommit && events.size() == 4) throw new IllegalStateException("controlled commit failure"); } @@ -1372,6 +1568,7 @@ public void commit(TransactionStatus status) { public void rollback(TransactionStatus status) { events.add("rollback"); TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(null); } } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java index 500b6b195f..79032999e9 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java @@ -8,6 +8,7 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.startsWith; import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; @@ -19,6 +20,7 @@ import java.sql.Connection; import java.sql.SQLException; import java.time.Clock; +import java.time.Instant; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.List; @@ -26,6 +28,7 @@ import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; @@ -48,11 +51,15 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.postgresql.util.PSQLException; +import org.postgresql.util.ServerErrorMessage; 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; +import org.springframework.transaction.support.TransactionSynchronizationUtils; import tools.jackson.databind.json.JsonMapper; /** @@ -79,19 +86,19 @@ void sharedRejectedUsageVectorsReachAccountReservationGuardWithoutWrites() throw .thenReturn(TenantCapacityAdmission.decimal(vector.path("held").asText())); when(usage.get("used_units", Long.class)) .thenReturn(TenantCapacityAdmission.decimal(vector.path("usage").asText())); - when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(usage); var request = CapacityAdmissionTestFixture.worldRequest( TenantCapacityAdmission.decimal(vector.path("capacityDelta").asText())); request.requireCommittable(); + Record databaseTime = mock(Record.class); + when(databaseTime.get("observed_at", java.time.OffsetDateTime.class)) + .thenReturn(request.evidence().evaluatedAt().atOffset(java.time.ZoneOffset.UTC)); + when(dsl.fetchSingle("SELECT clock_timestamp() AS observed_at")).thenReturn(databaseTime); TransactionSynchronizationManager.setActualTransactionActive(true); try { assertThat( new AccountTenantCapacityRepository(dsl) - .createIfQuotaAvailable( - request, - request.evidence().expiresAt(), - Clock.fixed(request.evidence().evaluatedAt(), ZoneOffset.UTC))) + .createIfQuotaAvailable(request, usage, request.evidence().expiresAt())) .as(vector.path("name").asText()) .isEmpty(); verify(dsl, never()).execute(anyString(), any(Object[].class)); @@ -106,21 +113,24 @@ void sharedRejectedUsageVectorsReachAccountReservationGuardWithoutWrites() throw void expiryWhileWaitingForUsageDoesNotReserveCapacity() { var request = CapacityAdmissionTestFixture.playerRequest(); DSLContext dsl = mock(DSLContext.class); - Clock clock = mock(Clock.class); - when(clock.instant()).thenThrow(new AssertionError("read before acquiring usage row")); - when(dsl.fetchOne(anyString(), any(Object[].class))) - .thenAnswer(invocation -> { - org.mockito.Mockito.doReturn(request.evidence().expiresAt()).when(clock).instant(); - return mock(Record.class); - }); + Record usage = mock(Record.class); + Record databaseTime = mock(Record.class); + when(databaseTime.get("observed_at", java.time.OffsetDateTime.class)) + .thenReturn(AccountTenantCapacityRepository.at(request.evidence().expiresAt())); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(usage); + when(dsl.fetchSingle("SELECT clock_timestamp() AS observed_at")).thenReturn(databaseTime); + var repository = new AccountTenantCapacityRepository(dsl); TransactionSynchronizationManager.setActualTransactionActive(true); assertThatThrownBy(() -> - new AccountTenantCapacityRepository(dsl) - .createIfQuotaAvailable(request, request.evidence().expiresAt(), clock)) + repository.createIfQuotaAvailable( + request, repository.usage(request), request.evidence().expiresAt())) .isInstanceOfSatisfying( AccountTenantCapacityRepository.CapacityException.class, failure -> assertThat(failure.code()).isEqualTo(Failure.CAPACITY_ADMISSION_STALE)); + var order = inOrder(dsl); + order.verify(dsl).fetchOne(anyString(), any(Object[].class)); + order.verify(dsl).fetchSingle("SELECT clock_timestamp() AS observed_at"); verify(dsl, never()).execute(anyString(), any(Object[].class)); } @@ -135,6 +145,34 @@ void exactReplayPrecedesFreshnessCurrentSourcesAndUsageEvenAfterOriginalExpiry() verify(f.dsl, never()).execute(anyString(), any(Object[].class)); } + @Test + void onlyTheNamedDeferredFreshnessViolationMapsToStaleAdmission() throws Exception { + for (String constraint : + new String[] {"account_tenant_capacity_attempt_freshness", "unrelated_constraint"}) { + var f = new Fixture(true); + var violation = mock(PSQLException.class); + var diagnostic = mock(ServerErrorMessage.class); + when(violation.getSQLState()).thenReturn("23514"); + when(violation.getServerErrorMessage()).thenReturn(diagnostic); + when(diagnostic.getConstraint()).thenReturn(constraint); + var commitFailure = + new org.springframework.transaction.TransactionSystemException( + "Commit refused", violation); + f.transactions.commitFailure = commitFailure; + + var result = + assertThatThrownBy( + () -> f.owner.commit(f.request, f.request.evidence().callerWorkload())); + if ("account_tenant_capacity_attempt_freshness".equals(constraint)) { + result.isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> assertThat(failure.code()).isEqualTo(Failure.CAPACITY_ADMISSION_STALE)); + } else { + result.isSameAs(commitFailure); + } + } + } + @Test void genericNoAcceptCannotReplayAsQuotaDenial() throws Exception { var f = new Fixture(false); @@ -243,7 +281,7 @@ void durableDenialReplaysWithoutConsultingMutableCapacity(Failure cause) throws when(f.scopes.findCanonicalEvidenceByTokenHash(verifiedScopeTokenHash(f.request))) .thenAnswer(ignored -> { when(f.clock.instant()).thenReturn(f.request.evidence().expiresAt()); - f.databaseExpired = true; + f.databaseNow.set(f.request.evidence().expiresAt()); return Optional.of(scope); }); } @@ -270,7 +308,8 @@ void durableDenialReplaysWithoutConsultingMutableCapacity(Failure cause) throws when(usage.get("held_units", Long.class)).thenReturn(0L); org.mockito.Mockito.clearInvocations(f.dsl, f.accounts, f.memberships, f.issuances, f.scopes); - // Capacity is now available. Exact retries return the original committed denial. + // Capacity is now available and the evidence expired. Replay the committed denial. + f.databaseNow.set(f.request.evidence().expiresAt()); for (int retry = 0; retry < 2; retry++) { assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) .isInstanceOfSatisfying( @@ -288,8 +327,9 @@ void durableDenialReplaysWithoutConsultingMutableCapacity(Failure cause) throws } @Test - void localExpiryWithoutPostgresExpiryDoesNotRetainDenial() throws Exception { - var f = new Fixture(false, qualifiedRequest(true)); + void applicationTimePastEvaluationExpiryDoesNotOverrideFreshPostgresEvaluation() + throws Exception { + var f = new Fixture(false, qualifiedRequest(false)); f.existing = false; f.retained = true; qualifySources(f); @@ -299,15 +339,11 @@ void localExpiryWithoutPostgresExpiryDoesNotRetainDenial() throws Exception { .isInstanceOfSatisfying( AccountTenantCapacityRepository.CapacityException.class, failure -> { - assertThat(failure.code()).isEqualTo(Failure.CAPACITY_ADMISSION_STALE); + assertThat(failure.code()).isEqualTo(Failure.TENANT_BILLING_BLOCKED); assertThat(failure.durableDenialId()).isNull(); }); - verify(f.dsl) - .fetchOne( - eq("SELECT clock_timestamp() >= ?::timestamptz AS expired"), - eq(AccountTenantCapacityRepository.at(f.request.evidence().expiresAt()))); verify(f.dsl, never()).execute(anyString(), any(Object[].class)); - verifyNoInteractions(f.issuances, f.scopes); + verify(f.scopes).findCanonicalEvidenceByTokenHash(verifiedScopeTokenHash(f.request)); } @Test @@ -315,13 +351,14 @@ void notYetValidExactEvaluationDoesNotRetainDenial() throws Exception { var f = new Fixture(false, qualifiedRequest(true)); f.existing = false; f.retained = true; - when(f.clock.instant()).thenReturn(f.request.evidence().evaluatedAt().minusMillis(1)); + qualifySources(f); + f.databaseNow.set(f.request.evidence().evaluatedAt().minusMillis(1)); assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) .hasMessage("CAPACITY_ADMISSION_STALE"); - verify(f.dsl, never()).fetchOne(startsWith("SELECT clock_timestamp()"), any(Object[].class)); + verify(f.dsl).fetchSingle("SELECT clock_timestamp() AS observed_at"); verify(f.dsl, never()).execute(anyString(), any(Object[].class)); - verifyNoInteractions(f.memberships, f.issuances, f.scopes); + verifyNoInteractions(f.issuances, f.scopes); } @Test @@ -340,7 +377,10 @@ void expiryDuringOriginRetentionRollsBackAcceptanceAndRefusal() throws Exception .fetchOne( startsWith("SELECT * FROM account_tenant_capacity_usage "), any(Object[].class)); retainOriginThenAdvanceClock( - f, f.request, quotaFull ? "NO_ACCEPT" : "ACCEPTED", f.request.evidence().expiresAt()); + f, + f.request, + quotaFull ? "NO_ACCEPT" : "ACCEPTED", + () -> f.databaseNow.set(f.request.evidence().expiresAt())); assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) .isInstanceOfSatisfying( @@ -359,10 +399,58 @@ void expiryDuringOriginRetentionRollsBackAcceptanceAndRefusal() throws Exception } } - @Test - void claimExpiryDuringRearmAcceptanceRollsBackBeforeHistoryOrFenceMutation() throws Exception { + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void databaseExpiryBeforeCommitRollsBackNewReservationOrDenial(boolean quotaFull) + throws Exception { var f = new Fixture(false, qualifiedRequest(true)); + f.existing = false; + f.retained = true; + qualifySources(f); + Record usage = mock(Record.class); + when(usage.get("held_units", Long.class)) + .thenReturn(quotaFull ? f.request.evidence().quota() : 0L); + when(usage.get("used_units", Long.class)).thenReturn(0L); + when(usage.get("usage_revision", Long.class)).thenReturn(1L); + org.mockito.Mockito.doReturn(usage) + .when(f.dsl) + .fetchOne(startsWith("SELECT * FROM account_tenant_capacity_usage "), any(Object[].class)); + retainOriginThenAdvanceClock(f, f.request, quotaFull ? "NO_ACCEPT" : "ACCEPTED", () -> {}); + when(f.dsl.execute(startsWith("UPDATE account_tenant_capacity_usage "), any(Object[].class))) + .thenReturn(1); + when(f.dsl.execute( + startsWith("INSERT INTO account_tenant_capacity_reservations "), any(Object[].class))) + .thenAnswer(ignored -> { + f.pendingReservation = true; + return 1; + }); + f.transactions.beforeCommit = () -> f.databaseNow.set(f.request.evidence().expiresAt()); + + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> assertThat(failure.code()).isEqualTo(Failure.CAPACITY_ADMISSION_STALE)); + assertThat(f.transactionEvents).containsExactly("begin", "rollback"); + assertThat(f.originDecision).isNull(); + assertThat(f.pendingOriginDecision).isNull(); + assertThat(f.existing).isFalse(); + verify(f.dsl, times(quotaFull ? 0 : 1)) + .execute( + startsWith("INSERT INTO account_tenant_capacity_reservations "), any(Object[].class)); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void expiryDuringRearmAcceptanceRollsBackBeforeHistoryOrFenceMutation(boolean paidReceiptExpires) + throws Exception { + Instant originalPaidCutoff = CapacityAdmissionTestFixture.NOW.plusSeconds(2); + var f = + new Fixture( + false, + qualifiedRequest( + true, paidReceiptExpires ? originalPaidCutoff.minusMillis(500) : null)); f.retained = true; + if (paidReceiptExpires) f.originalPaidCutoff = originalPaidCutoff; qualifySources(f); var next = new Request( @@ -382,7 +470,7 @@ void claimExpiryDuringRearmAcceptanceRollsBackBeforeHistoryOrFenceMutation() thr java.util.Objects.requireNonNull( f.dsl.fetchOne("SELECT * FROM account_tenant_capacity_reservations ", new Object[0])); UUID claimOwner = UUID.randomUUID(); - var claimExpiry = CapacityAdmissionTestFixture.NOW.plusSeconds(2); + var claimExpiry = paidReceiptExpires ? originalPaidCutoff.plusSeconds(10) : originalPaidCutoff; when(row.get("recovery_owner", UUID.class)).thenReturn(claimOwner); when(row.get("recovery_claim_fence", Long.class)).thenReturn(7L); when(row.get("recovery_claim_expires_at", java.time.OffsetDateTime.class)) @@ -394,16 +482,20 @@ void claimExpiryDuringRearmAcceptanceRollsBackBeforeHistoryOrFenceMutation() thr org.mockito.Mockito.doReturn(mock(Record.class)) .when(f.dsl) .fetchOne(startsWith(usageLock), any(Object[].class)); - retainOriginThenAdvanceClock(f, next, "ACCEPTED", claimExpiry); + retainOriginThenAdvanceClock( + f, next, "ACCEPTED", () -> when(f.clock.instant()).thenReturn(originalPaidCutoff)); var rearm = AccountTenantCapacityOwner.class.getDeclaredMethod( "rearm", Request.class, Request.class, UUID.class, long.class); rearm.setAccessible(true); assertThatThrownBy(() -> rearm.invoke(f.owner, f.request, next, claimOwner, 7L)) .hasCauseInstanceOf(AccountTenantCapacityRepository.CapacityException.class) - .hasRootCauseMessage("IDEMPOTENCY_CONFLICT"); - var lockOrder = org.mockito.Mockito.inOrder(f.dsl); + .hasRootCauseMessage( + paidReceiptExpires ? "ENTITLEMENT_UNAVAILABLE" : "IDEMPOTENCY_CONFLICT"); + var lockOrder = org.mockito.Mockito.inOrder(f.dsl, f.memberships); lockOrder.verify(f.dsl).fetchOne(startsWith(usageLock), any(Object[].class)); + var player = (TenantCapacityAdmission.PlayerContext) next.context(); + lockOrder.verify(f.memberships).readCurrent(player.accountId(), player.tenantId()); lockOrder .verify(f.dsl) .execute(startsWith("INSERT INTO account_capacity_origin_decisions "), any(Object[].class)); @@ -417,8 +509,71 @@ void claimExpiryDuringRearmAcceptanceRollsBackBeforeHistoryOrFenceMutation() thr assertThat(f.pendingOriginDecision).isNull(); } + @Test + void applicationExpiryBeforeCommitRollsBackRearm() throws Exception { + var f = new Fixture(false, qualifiedRequest(true)); + f.retained = true; + var scope = qualifySources(f); + var cutoff = CapacityAdmissionTestFixture.NOW.plusSeconds(2); + when(scope.connectScopeExpiresAt()).thenReturn(cutoff.toString()); + var next = + new Request( + f.request.identity(), + UUID.randomUUID(), + 2, + f.request.targetNamespace(), + f.request.context(), + f.request.operation(), + f.request.priorShape(), + f.request.requestedShape(), + f.request.evidence(), + f.request.capacityDelta(), + null) + .withDigest(); + Record row = + java.util.Objects.requireNonNull( + f.dsl.fetchOne("SELECT * FROM account_tenant_capacity_reservations ", new Object[0])); + UUID claimOwner = UUID.randomUUID(); + when(row.get("recovery_owner", UUID.class)).thenReturn(claimOwner); + when(row.get("recovery_claim_fence", Long.class)).thenReturn(7L); + when(row.get("recovery_claim_expires_at", java.time.OffsetDateTime.class)) + .thenReturn(AccountTenantCapacityRepository.at(cutoff.plusSeconds(10))); + when(row.get("execution_status", String.class)).thenReturn("NOT_EXECUTED_AFTER_AUTHORIZATION"); + when(row.get("owner_readback", byte[].class)).thenReturn(new byte[] {1}); + retainOriginThenAdvanceClock(f, next, "ACCEPTED", () -> {}); + when(f.dsl.execute( + startsWith("INSERT INTO account_tenant_capacity_attempt_history "), + any(Object[].class))) + .thenReturn(1); + when(f.dsl.execute( + startsWith("UPDATE account_tenant_capacity_reservations "), any(Object[].class))) + .thenAnswer(ignored -> { + when(row.get("admission_attempt_id", UUID.class)).thenReturn(next.admissionAttemptId()); + when(row.get("capacity_rearm_fence", Long.class)).thenReturn(next.capacityRearmFence()); + when(row.get("reservation_fence", Long.class)).thenReturn(2L); + when(row.get("mutation_digest", String.class)).thenReturn(next.mutationDigest()); + when(row.get("canonical_payload", byte[].class)) + .thenReturn(CapacityAdmissionDigest.preimage(next)); + return 1; + }); + f.transactions.beforeCommit = () -> when(f.clock.instant()).thenReturn(cutoff); + + var rearm = + AccountTenantCapacityOwner.class.getDeclaredMethod( + "rearm", Request.class, Request.class, UUID.class, long.class); + rearm.setAccessible(true); + assertThatThrownBy(() -> rearm.invoke(f.owner, f.request, next, claimOwner, 7L)) + .hasCauseInstanceOf(AccountTenantCapacityRepository.CapacityException.class) + .hasRootCauseMessage("ENTITLEMENT_UNAVAILABLE"); + assertThat(f.transactionEvents).containsExactly("begin", "rollback"); + assertThat(f.originDecision).isNull(); + assertThat(f.pendingOriginDecision).isNull(); + verify(f.dsl) + .execute(startsWith("UPDATE account_tenant_capacity_reservations "), any(Object[].class)); + } + private static void retainOriginThenAdvanceClock( - Fixture f, Request request, String decision, java.time.Instant afterWrite) { + Fixture f, Request request, String decision, Runnable afterWrite) { Record retained = mock(Record.class); when(retained.get("admission_attempt_id", UUID.class)).thenReturn(request.admissionAttemptId()); when(retained.get("mutation_digest", String.class)).thenReturn(request.mutationDigest()); @@ -432,7 +587,7 @@ private static void retainOriginThenAdvanceClock( startsWith("INSERT INTO account_capacity_origin_decisions "), any(Object[].class))) .thenAnswer(invocation -> { f.pendingOriginDecision = retained; - when(f.clock.instant()).thenReturn(afterWrite); + afterWrite.run(); return 1; }); } @@ -690,9 +845,10 @@ void exactRetainedNonCreatingEvidenceOutsideWindowIsStale() throws Exception { var f = new Fixture(true, CapacityAdmissionTestFixture.playerRequest(false)); f.existing = false; f.retained = true; + qualifySources(f); assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) .hasMessage("CAPACITY_ADMISSION_STALE"); - verifyNoInteractions(f.memberships, f.issuances, f.scopes); + verifyNoInteractions(f.issuances, f.scopes); verify(f.dsl, never()).execute(anyString(), any(Object[].class)); } @@ -705,7 +861,7 @@ void qualifiedNewerBillingCutoffMakesExactRetainedEvaluationStale(boolean expire f.retained = true; if (expired) { when(f.clock.instant()).thenReturn(f.request.evidence().expiresAt()); - f.databaseExpired = true; + f.databaseNow.set(f.request.evidence().expiresAt()); } var current = mock(Snapshot.class); var tuple = mock(AuthorityTuple.class); @@ -828,20 +984,20 @@ void globalAttemptConflictPrecedesFreshOrExpiredNonCreatingEvidence() throws Exc } } - @Test - void expiryDuringSourceQualificationCannotBecomeBillingRefusal() throws Exception { - var f = new Fixture(false, qualifiedRequest(false)); + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void databaseExpiryDuringSourceQualificationCannotBecomeBillingRefusal(boolean paid) + throws Exception { + Instant paidDatabaseCutoff = CapacityAdmissionTestFixture.NOW.plusSeconds(3); + var f = new Fixture(false, qualifiedRequest(false, paid ? paidDatabaseCutoff : null)); f.existing = false; f.retained = true; + if (paid) f.originalPaidCutoff = paidDatabaseCutoff.plusSeconds(5); var scope = qualifySources(f); var scopeTokenHash = verifiedScopeTokenHash(f.request); - var now = - new java.util.concurrent.atomic.AtomicReference<>( - CapacityAdmissionTestFixture.NOW.plusSeconds(1)); - when(f.clock.instant()).thenAnswer(ignored -> now.get()); when(f.scopes.findCanonicalEvidenceByTokenHash(scopeTokenHash)) .thenAnswer(ignored -> { - now.set(f.request.evidence().expiresAt()); + f.databaseNow.set(f.request.evidence().expiresAt()); return Optional.of(scope); }); assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) @@ -854,8 +1010,100 @@ void expiryDuringSourceQualificationCannotBecomeBillingRefusal() throws Exceptio verify(f.dsl, never()).execute(anyString(), any(Object[].class)); } - @SuppressWarnings("unchecked") + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void applicationCutoffDuringSourceQualificationRefusesBeforeFreshCapacityDecision( + boolean paidReceiptExpires) throws Exception { + var expiresAt = CapacityAdmissionTestFixture.NOW.plusSeconds(2); + var f = + new Fixture( + false, qualifiedRequest(true, paidReceiptExpires ? expiresAt.minusMillis(500) : null)); + f.existing = false; + f.retained = true; + var scope = qualifySources(f); + var applicationTime = new AtomicReference<>(expiresAt.minusSeconds(1)); + when(f.clock.instant()).thenAnswer(ignored -> applicationTime.get()); + if (paidReceiptExpires) { + f.originalPaidCutoff = expiresAt; + } else { + when(scope.connectScopeExpiresAt()).thenReturn(expiresAt.toString()); + } + var scopeTokenHash = verifiedScopeTokenHash(f.request); + when(f.scopes.findCanonicalEvidenceByTokenHash(scopeTokenHash)) + .thenAnswer(ignored -> { + applicationTime.set(expiresAt); + return Optional.of(scope); + }); + + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> assertThat(failure.code()).isEqualTo(Failure.ENTITLEMENT_UNAVAILABLE)); + verify(f.scopes).findCanonicalEvidenceByTokenHash(scopeTokenHash); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void applicationCutoffWhileRetainingQuotaDenialRollsBackWithFreshDatabaseClock( + boolean paidReceiptExpires) throws Exception { + var expiresAt = CapacityAdmissionTestFixture.NOW.plusSeconds(2); + var f = + new Fixture( + false, qualifiedRequest(true, paidReceiptExpires ? expiresAt.minusMillis(500) : null)); + f.existing = false; + f.retained = true; + var scope = qualifySources(f); + var applicationTime = new AtomicReference<>(expiresAt.minusSeconds(1)); + when(f.clock.instant()).thenAnswer(ignored -> applicationTime.get()); + if (paidReceiptExpires) { + f.originalPaidCutoff = expiresAt; + } else { + when(scope.connectScopeExpiresAt()).thenReturn(expiresAt.toString()); + } + var usage = mock(Record.class); + when(usage.get("held_units", Long.class)).thenReturn(f.request.evidence().quota()); + when(usage.get("used_units", Long.class)).thenReturn(0L); + org.mockito.Mockito.doReturn(usage) + .when(f.dsl) + .fetchOne(startsWith("SELECT * FROM account_tenant_capacity_usage "), any(Object[].class)); + retainOriginThenAdvanceClock(f, f.request, "NO_ACCEPT", () -> applicationTime.set(expiresAt)); + + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> assertThat(failure.code()).isEqualTo(Failure.ENTITLEMENT_UNAVAILABLE)); + assertThat(f.originDecision).isNull(); + assertThat(f.pendingOriginDecision).isNull(); + } + + @Test + void paidEvaluationWithoutOriginalCutoffAllowsOnlyExactRetainedReplay() throws Exception { + var explicitDatabaseCutoff = CapacityAdmissionTestFixture.NOW.plusSeconds(4); + var f = new Fixture(false, qualifiedRequest(true, explicitDatabaseCutoff)); + f.retained = true; + f.existing = false; + qualifySources(f); + + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> assertThat(failure.code()).isEqualTo(Failure.ENTITLEMENT_UNAVAILABLE)); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + + org.mockito.Mockito.clearInvocations(f.memberships, f.issuances, f.scopes); + f.existing = true; + assertThat(f.owner.commit(f.request, f.request.evidence().callerWorkload()).reservationId()) + .isEqualTo(f.reservation); + verifyNoInteractions(f.memberships, f.issuances, f.scopes); + } + private static Request qualifiedRequest(boolean creating) { + return qualifiedRequest(creating, null); + } + + @SuppressWarnings("unchecked") + private static Request qualifiedRequest(boolean creating, Instant databasePaidCutoff) { var original = CapacityAdmissionTestFixture.playerRequest(); var player = (TenantCapacityAdmission.PlayerContext) original.context(); var target = (Map) original.evidence().fields().get("target"); @@ -867,7 +1115,7 @@ private static Request qualifiedRequest(boolean creating) { "prod", target, CapacityAdmissionTestFixture.NOW); - if (creating) return admitted; + if (creating && databasePaidCutoff == null) return admitted; var fields = admitted.evidence().fields(); var parsed = net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence @@ -888,7 +1136,14 @@ private static Request qualifiedRequest(boolean creating) { "tenantAuthorityGeneration")) { facts.put(key, fields.get(key)); } - facts.put("allowNewGameplayBindings", false); + facts.put("allowNewGameplayBindings", creating); + var sources = + new java.util.LinkedHashMap<>((Map) fields.get("sourceReferences")); + if (databasePaidCutoff != null) { + facts.put("sourceKind", "PAID_HOSTING"); + facts.put("subscriptionStatus", "active"); + sources.put("paidReceiptValidUntil", databasePaidCutoff.toString()); + } var evidence = net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence .fromOwnerEvaluation( @@ -898,7 +1153,7 @@ private static Request qualifiedRequest(boolean creating) { parsed.membershipSource(), target, facts, - (Map) fields.get("sourceReferences"), + sources, CapacityAdmissionTestFixture.NOW); return new Request( admitted.identity(), @@ -976,15 +1231,19 @@ private static final class Fixture { mock(AccountGameplayDelegationIssuanceRepository.class); private final AccountConnectScopeRepository scopes = mock(AccountConnectScopeRepository.class); private final Clock clock = mock(Clock.class); + private final AtomicReference databaseNow = new AtomicReference<>(); private final Request request; private final UUID reservation = UUID.randomUUID(); private final AccountTenantCapacityOwner owner; private boolean existing = true; + private boolean pendingReservation; private boolean retained; - private boolean databaseExpired; + private Instant originalPaidCutoff; private Record originDecision; private Record pendingOriginDecision; + private final ControlledTransactions transactions = new ControlledTransactions(this); + private Fixture(boolean expired) throws Exception { this(expired, CapacityAdmissionTestFixture.playerRequest()); } @@ -1039,14 +1298,17 @@ private Fixture(boolean expired, Request request, String namespace) throws Excep .thenReturn(AccountTenantCapacityRepository.at(evidence.evaluatedAt())); when(evaluation.get("expires_at", java.time.OffsetDateTime.class)) .thenReturn(AccountTenantCapacityRepository.at(evidence.expiresAt())); + when(evaluation.get("original_paid_cutoff", java.time.OffsetDateTime.class)) + .thenAnswer(ignored -> + originalPaidCutoff == null + ? null + : AccountTenantCapacityRepository.at(originalPaidCutoff)); Record databaseObservation = mock(Record.class); - when(databaseObservation.get("expired", Boolean.class)) - .thenAnswer(ignored -> databaseExpired); when(dsl.fetchOne(anyString(), any(Object[].class))) .thenAnswer(invocation -> { String sql = invocation.getArgument(0, String.class); if (sql.startsWith("SELECT * FROM account_tenant_capacity_reservations ")) - return existing ? row : null; + return existing || pendingReservation ? row : null; if (sql.startsWith("SELECT 1 FROM (SELECT tenant_uuid")) return null; if (sql.startsWith("SELECT * FROM account_capacity_origin_decisions ")) return pendingOriginDecision != null ? pendingOriginDecision : originDecision; @@ -1055,19 +1317,28 @@ private Fixture(boolean expired, Request request, String namespace) throws Excep return evaluation; if (sql.startsWith("SELECT * FROM account_tenant_capacity_evaluations ")) return retained ? evaluation : null; - if (sql.startsWith("SELECT clock_timestamp()")) return databaseObservation; + if (sql.startsWith("SELECT * FROM account_tenant_capacity_usage ")) + return mock(Record.class); + if (sql.equals("SELECT clock_timestamp() >= ?::timestamptz AS expired")) { + var bindValues = (Object[]) invocation.getRawArguments()[1]; + var deadline = (java.time.OffsetDateTime) bindValues[0]; + when(databaseObservation.get("expired", Boolean.class)) + .thenReturn(!databaseNow.get().isBefore(deadline.toInstant())); + return databaseObservation; + } throw new AssertionError(sql); }); + Record databaseTime = mock(Record.class); + databaseNow.set( + expired + ? request.evidence().expiresAt() + : request.evidence().evaluatedAt().plusSeconds(1)); + when(databaseTime.get("observed_at", java.time.OffsetDateTime.class)) + .thenAnswer(ignored -> AccountTenantCapacityRepository.at(databaseNow.get())); + when(dsl.fetchSingle("SELECT clock_timestamp() AS observed_at")).thenReturn(databaseTime); owner = new AccountTenantCapacityOwner( - dsl, - accounts, - memberships, - issuances, - scopes, - new ControlledTransactions(this), - clock, - namespace); + dsl, accounts, memberships, issuances, scopes, transactions, clock, namespace); } } @@ -1078,6 +1349,9 @@ private ControlledTransactions(Fixture fixture) { this.fixture = fixture; } + private RuntimeException commitFailure; + private Runnable beforeCommit = () -> {}; + @Override public TransactionStatus getTransaction( @org.jspecify.annotations.Nullable TransactionDefinition definition) { @@ -1091,21 +1365,40 @@ public TransactionStatus getTransaction( fixture.transactionEvents.add("begin"); fixture.pendingOriginDecision = null; TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.initSynchronization(); return new SimpleTransactionStatus(); } @Override public void commit(TransactionStatus status) { - if (fixture.pendingOriginDecision != null) - fixture.originDecision = fixture.pendingOriginDecision; - fixture.pendingOriginDecision = null; - TransactionSynchronizationManager.setActualTransactionActive(false); + try { + beforeCommit.run(); + TransactionSynchronizationUtils.triggerBeforeCommit(false); + if (commitFailure != null) throw commitFailure; + if (fixture.pendingReservation) fixture.existing = true; + if (fixture.pendingOriginDecision != null) { + fixture.originDecision = fixture.pendingOriginDecision; + } + } catch (RuntimeException | Error failure) { + rollback(status); + throw failure; + } finally { + clearTransaction(); + } } @Override public void rollback(TransactionStatus status) { fixture.transactionEvents.add("rollback"); + clearTransaction(); + } + + private void clearTransaction() { fixture.pendingOriginDecision = null; + fixture.pendingReservation = false; + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } TransactionSynchronizationManager.setActualTransactionActive(false); } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 42eff5f790..27fec9a974 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -8,6 +8,8 @@ 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.never; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -555,6 +557,97 @@ void invalidCredentialsDoNotConsultUuidOwnerReadback(OrdinaryIssuance mode) { verifyNoInteractions(sessionService); } + @ParameterizedTest + @CsvSource({"password, true", "123456, false", "wrong, false"}) + void billingVerificationKeepsOnlyAcceptedPasswordWhenChallengeIsReplaced( + String credential, boolean passwordAccepted) { + Account account = ordinaryIssuanceAccount(); + ordinaryIssuanceChallenge(account); + var verification = + service.preverifyBillingPrimaryCredential( + account.getAccountUuid(), account.getEmail(), credential); + + var replacement = ordinaryIssuanceChallenge(account); + replacement.setId(4L); + when(accountEmailLoginChallengeRepository.tryLockAccountChallenge(account.getId())) + .thenReturn(true); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + if (passwordAccepted) { + assertEquals( + account.getAccountUuid(), + service.applyBillingPrimaryVerification(account, verification).accountId()); + } else { + assertThrows( + IllegalStateException.class, + () -> service.applyBillingPrimaryVerification(account, verification)); + } + } finally { + TransactionSynchronizationManager.clear(); + } + + assertEquals(0, replacement.getInvalidAttemptCount()); + verify(accountEmailLoginChallengeRepository, never()) + .delete(org.mockito.ArgumentMatchers.any()); + verify(accountEmailLoginChallengeRepository, never()).save(org.mockito.ArgumentMatchers.any()); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void billingVerificationStillRequiresCurrentPasswordHashAndMode(boolean changedPassword) { + Account account = ordinaryIssuanceAccount(); + ordinaryIssuanceChallenge(account); + var verification = + service.preverifyBillingPrimaryCredential( + account.getAccountUuid(), account.getEmail(), "password"); + Account locked = new Account(); + locked.setId(account.getId()); + locked.setAccountUuid(account.getAccountUuid()); + locked.setAccountUuidSourceNumericId(account.getAccountUuidSourceNumericId()); + locked.setAccountUuidProvenance(account.getAccountUuidProvenance()); + locked.setEmail(account.getEmail()); + locked.setLoginAuthModes(changedPassword ? account.getLoginAuthModes() : "EMAIL_OTP"); + locked.setPasswordHash(changedPassword ? hash("replacement") : account.getPasswordHash()); + ordinaryIssuanceChallenge(account).setId(4L); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThrows( + IllegalStateException.class, + () -> service.applyBillingPrimaryVerification(locked, verification)); + } finally { + TransactionSynchronizationManager.clear(); + } + + verify(accountEmailLoginChallengeRepository, never()).tryLockAccountChallenge(account.getId()); + } + + @Test + void billingVerificationCountsFailedCredentialAgainstUnchangedChallenge() { + Account account = ordinaryIssuanceAccount(); + var challenge = ordinaryIssuanceChallenge(account); + var verification = + service.preverifyBillingPrimaryCredential( + account.getAccountUuid(), account.getEmail(), "wrong"); + when(accountEmailLoginChallengeRepository.tryLockAccountChallenge(account.getId())) + .thenReturn(true); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + var denied = + assertThrows( + AuthenticationException.class, + () -> service.applyBillingPrimaryVerification(account, verification)); + assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, denied.getCode()); + } finally { + TransactionSynchronizationManager.clear(); + } + + assertEquals(1, challenge.getInvalidAttemptCount()); + verify(accountEmailLoginChallengeRepository).save(challenge); + } + private Account ordinaryIssuanceAccount() { Account account = new Account(); account.setId(42L); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java index fd32ed4de5..5861d65181 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java @@ -483,6 +483,30 @@ void accountSourceCallbacksUseExactOriginalInsideTransactionAndProducerLocks() t assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); } + @Test + void billingBearerExpiryAfterBindingRollsBackOwnerTransaction() throws Exception { + var clock = mock(Clock.class); + when(clock.instant()).thenReturn(NOW); + var f = new Fixture(true, clock); + String compact = f.sign(f.claims); + f.owner(compact); + + assertThatThrownBy(() -> + f.actors.withCurrentAccount( + compact, + actor -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + when(clock.instant()).thenReturn(NOW.plusSeconds(300)); + f.actors.requireCurrentOriginalToken(actor); + return null; + })) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Exact current authenticated initial creator required"); + verify(f.transactions).rollback(any()); + verify(f.transactions, never()).commit(any()); + } + @Test void accountOriginalRecoveryRejectsTenantChangedAccountAndExpiredOriginal() throws Exception { Fixture tenant = new Fixture(); @@ -624,6 +648,10 @@ private static final class Fixture { } Fixture(boolean accountOnly, Instant clockNow) { + this(accountOnly, Clock.fixed(clockNow, ZoneOffset.UTC)); + } + + Fixture(boolean accountOnly, Clock clock) { when(snapshot.scopeKind()) .thenReturn( accountOnly @@ -730,14 +758,7 @@ private static final class Fixture { .rollback(any()); actors = new AccountControlUiActorService( - operations, - authority, - signers, - registry, - source, - fences, - transactions, - Clock.fixed(clockNow, ZoneOffset.UTC)); + operations, authority, signers, registry, source, fences, transactions, clock); } void owner(String compact) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoicePaymentServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoicePaymentServiceTest.java new file mode 100644 index 0000000000..b21331fb7a --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoicePaymentServiceTest.java @@ -0,0 +1,383 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +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 java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.accountservice.client.StripeHostingFirstInvoicePaymentClient; +import net.firedevops.firemud.accountservice.client.StripeHostingWebhookVerifier; +import net.firedevops.firemud.accountservice.repository.AccountHostingFirstInvoicePayment; +import net.firedevops.firemud.accountservice.repository.AccountHostingFirstInvoicePaymentRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingFirstInvoicePaymentRepository.ConfirmationDispatch; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionCurrentReceipt; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Outcome; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.TransitionResult; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCurrentRecord; +import net.firedevops.firemud.accountservice.repository.StripeEventInboxRepository; +import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionLifecycleService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountHostingFirstInvoicePaymentServiceTest { + private final AccountControlUiActorService actors = mock(AccountControlUiActorService.class); + private final AccountRecentReauthenticationService reauthentication = + mock(AccountRecentReauthenticationService.class); + private final AccountHostingFirstInvoicePaymentRepository payments = + mock(AccountHostingFirstInvoicePaymentRepository.class); + private final StripeEventInboxRepository inbox = mock(StripeEventInboxRepository.class); + private final StripeHostingFirstInvoicePaymentClient provider = + mock(StripeHostingFirstInvoicePaymentClient.class); + private final StripeHostingWebhookVerifier verifier = mock(StripeHostingWebhookVerifier.class); + private final AccountHostingSubscriptionLifecycleService lifecycle = + mock(AccountHostingSubscriptionLifecycleService.class); + private final AccountHostingFirstInvoicePaymentService service = + new AccountHostingFirstInvoicePaymentService( + actors, + reauthentication, + payments, + inbox, + provider, + verifier, + lifecycle, + new LocalTransactions()); + + @AfterEach + void clearAmbient() { + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) + TransactionSynchronizationManager.clearSynchronization(); + } + + @Test + void + delayedSignedSuccessAfterAuthorizationExpiryOrAuthorityAdvanceIsReadOnlyAndAtomicallyReadBack() + throws Exception { + var candidate = signedCandidate(); + var invoice = candidate.invoice(); + UUID lifecycleRequestId = candidate.lifecycleRequestId(); + long expectedVersion = candidate.expectedRowVersion(); + when(candidate.validUntil()).thenReturn(Instant.EPOCH); + var event = mock(StripeHostingWebhookVerifier.VerifiedEvent.class); + when(verifier.verify("signed", "header")).thenReturn(event); + when(payments.classifySignedEvent(event)) + .thenReturn( + new AccountHostingFirstInvoicePaymentRepository.SignedClassification(candidate, false)); + when(payments.completed(invoice.subscriptionId(), lifecycleRequestId)) + .thenReturn(false, true, true, true); + var observed = mock(StripeHostingFirstInvoicePaymentClient.Observation.class); + when(provider.observe(invoice)) + .thenAnswer(call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return observed; + }); + when(payments.retainSignedOutcome(event, observed)) + .thenReturn( + new AccountHostingFirstInvoicePaymentRepository.SignedOutcome(candidate, false)); + var committed = new TransitionResult(lifecycleRequestId, Outcome.COMMITTED, 5, null); + when(lifecycle.reconcile( + lifecycleRequestId, + invoice.creationRequestId(), + expectedVersion, + invoice.providerSubscriptionId(), + null)) + .thenReturn(committed); + var receipt = mock(AccountHostingSubscriptionCurrentReceipt.class); + var current = mock(AccountSubscriptionCurrentRecord.class); + UUID subscriptionId = invoice.subscriptionId(); + when(current.subscriptionId()).thenReturn(subscriptionId); + when(receipt.current()).thenReturn(current); + when(receipt.receiptRequestId()).thenReturn(UUID.randomUUID()); + when(lifecycle.readCurrent(invoice.tenantId())).thenReturn(receipt); + + assertThatThrownBy(() -> service.completeSigned("signed", "header")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Independent first-invoice authority readback refused"); + assertThat(service.completeSigned("signed", "header")) + .isEqualTo( + new AccountHostingFirstInvoicePaymentService.Completion( + "COMMITTED", candidate.requestId())); + verify(lifecycle, times(1)).readCurrent(invoice.tenantId()); + verify(lifecycle, times(1)) + .reconcile( + lifecycleRequestId, + invoice.creationRequestId(), + expectedVersion, + invoice.providerSubscriptionId(), + null); + verify(provider, times(1)).observe(invoice); + verify(provider, times(0)).confirm(any(), any()); + verify(payments, times(1)).retainSignedOutcome(event, observed); + verifyNoInteractions(actors, reauthentication); + } + + @Test + void paidTerminalReconciliationReturnsOperatorState() throws Exception { + var candidate = signedCandidate(); + var invoice = candidate.invoice(); + UUID lifecycleRequestId = candidate.lifecycleRequestId(); + var event = mock(StripeHostingWebhookVerifier.VerifiedEvent.class); + var observed = mock(StripeHostingFirstInvoicePaymentClient.Observation.class); + when(verifier.verify("signed", "header")).thenReturn(event); + when(payments.classifySignedEvent(event)) + .thenReturn( + new AccountHostingFirstInvoicePaymentRepository.SignedClassification(candidate, false)); + when(provider.observe(invoice)).thenReturn(observed); + when(payments.retainSignedOutcome(event, observed)) + .thenReturn( + new AccountHostingFirstInvoicePaymentRepository.SignedOutcome(candidate, false)); + when(lifecycle.reconcile( + lifecycleRequestId, + invoice.creationRequestId(), + candidate.expectedRowVersion(), + invoice.providerSubscriptionId(), + null)) + .thenReturn(new TransitionResult(lifecycleRequestId, Outcome.TERMINAL_FAILURE, 0, null)); + + assertThat(service.completeSigned("signed", "header")) + .isEqualTo( + new AccountHostingFirstInvoicePaymentService.Completion( + "OPERATOR_RECONCILIATION_REQUIRED", candidate.requestId())); + verify(lifecycle, times(0)).readCurrent(invoice.tenantId()); + } + + @Test + void exactLatePaidConflictReplayNeverReadsProviderOrChangesLifecycle() throws Exception { + var event = mock(StripeHostingWebhookVerifier.VerifiedEvent.class); + UUID requestId = UUID.randomUUID(); + when(verifier.verify("signed", "header")).thenReturn(event); + when(payments.retainedSignedConflictRequestId(event)).thenReturn(requestId); + + assertThat(service.completeSigned("signed", "header")) + .isEqualTo( + new AccountHostingFirstInvoicePaymentService.Completion( + "OPERATOR_RECONCILIATION_REQUIRED", requestId)); + + verify(inbox).retainOrReplay(event); + verify(payments).retainedSignedConflictRequestId(event); + verifyNoInteractions(provider, lifecycle, actors, reauthentication); + } + + @Test + void unrelatedSignedEventIsRetainedWithoutDispatchOrLifecycleWork() throws Exception { + var event = mock(StripeHostingWebhookVerifier.VerifiedEvent.class); + when(verifier.verify("signed", "header")).thenReturn(event); + + when(payments.classifySignedEvent(event)) + .thenReturn( + new AccountHostingFirstInvoicePaymentRepository.SignedClassification(null, false)); + + assertThat(service.completeSigned("signed", "header")) + .isEqualTo(new AccountHostingFirstInvoicePaymentService.Completion("IGNORED", null)); + + verify(inbox).retainOrReplay(event); + verify(payments).classifySignedEvent(event); + verifyNoInteractions(provider, lifecycle, actors, reauthentication); + } + + @Test + void exactPreConsentPaymentRemainsPendingWithoutProviderOrFulfillment() throws Exception { + var event = mock(StripeHostingWebhookVerifier.VerifiedEvent.class); + when(verifier.verify("signed", "header")).thenReturn(event); + when(payments.classifySignedEvent(event)) + .thenReturn( + new AccountHostingFirstInvoicePaymentRepository.SignedClassification(null, true)); + + assertThat(service.completeSigned("signed", "header")) + .isEqualTo(new AccountHostingFirstInvoicePaymentService.Completion("RECONCILING", null)); + + verify(inbox).retainOrReplay(event); + verifyNoInteractions(provider, lifecycle, actors, reauthentication); + } + + @Test + void alreadyCommittedPaymentReplaySurvivesLaterLifecycleAdvanceWithoutNewProviderRead() + throws Exception { + var candidate = signedCandidate(); + var invoice = candidate.invoice(); + UUID lifecycleRequestId = candidate.lifecycleRequestId(); + var event = mock(StripeHostingWebhookVerifier.VerifiedEvent.class); + when(verifier.verify("signed", "header")).thenReturn(event); + when(payments.classifySignedEvent(event)) + .thenReturn( + new AccountHostingFirstInvoicePaymentRepository.SignedClassification(candidate, false)); + when(payments.completed(invoice.subscriptionId(), lifecycleRequestId)).thenReturn(true); + assertThat(service.completeSigned("signed", "header").state()).isEqualTo("COMMITTED"); + verifyNoInteractions(provider, lifecycle, actors, reauthentication); + verify(payments, times(2)).completed(invoice.subscriptionId(), lifecycleRequestId); + } + + @Test + void ambientSqlAndForgedSignatureNeverReachProviderOrCompletion() throws Exception { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> service.completeSigned("forged", "header")) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setActualTransactionActive(false); + when(verifier.verify("forged", "header")) + .thenThrow(new IllegalArgumentException("signature refused")); + assertThatThrownBy(() -> service.completeSigned("forged", "header")) + .hasMessageContaining("signature refused"); + verifyNoInteractions(provider, inbox, payments, lifecycle); + } + + @Test + void renewedProofIsConsumedForItsOwnIdentityAndClaimRechecksCurrentOwnerAfterProviderReads() + throws Exception { + UUID account = UUID.randomUUID(), + original = UUID.randomUUID(), + authorization = UUID.randomUUID(), + subscription = UUID.randomUUID(), + evidenceId = UUID.randomUUID(); + var actor = mock(AccountControlUiActorService.AccountAuthenticatedActor.class); + when(actor.accountId()).thenReturn(account); + when(actors.withCurrentAccount(eq("bearer"), any())) + .thenAnswer(call -> { + java.util.function.Function< + AccountControlUiActorService.AccountAuthenticatedActor, Object> + action = call.getArgument(1); + return action.apply(actor); + }); + var proof = mock(AccountRecentReauthenticationEvidence.class); + when(proof.billingContext()) + .thenReturn(mock(AccountRecentReauthenticationEvidence.BillingContext.class)); + when(reauthentication.requireCurrentBillingEvidenceLocked(evidenceId, account, authorization)) + .thenReturn(proof); + var prepared = mock(ConfirmationDispatch.class); + when(prepared.reauthenticationEvidenceId()).thenReturn(evidenceId); + when(prepared.authorizationRequestId()).thenReturn(authorization); + var dispatch = mock(ConfirmationDispatch.class); + when(dispatch.reauthenticationEvidenceId()).thenReturn(evidenceId); + when(dispatch.authorizationRequestId()).thenReturn(authorization); + when(payments.renewAuthorization( + account, original, authorization, subscription, 3, 1, "tuple", proof)) + .thenReturn(prepared); + when(payments.readDispatch(prepared, account)).thenReturn(dispatch); + when(payments.claimCommand(dispatch, account)).thenReturn(null); + var noHandoff = mock(StripeHostingFirstInvoicePaymentClient.Handoff.class); + when(noHandoff.clientSecret()).thenReturn(null); + when(provider.confirm(eq(dispatch), any())) + .thenAnswer(call -> { + java.util.function.Supplier< + net.firedevops.firemud.accountservice.repository + .AccountHostingFirstInvoicePaymentRepository.CommandClaim> + claim = call.getArgument(1); + assertThat(claim.get()).isNull(); + return noHandoff; + }); + service.renew("bearer", subscription, original, authorization, 3, 1, evidenceId, "tuple"); + verify(reauthentication) + .validateAndConsumeLocked( + proof, account, AccountRecentReauthenticationPolicy.BILLING_PURPOSE, authorization); + verify(reauthentication, times(3)) + .requireCurrentBillingEvidenceLocked(evidenceId, account, authorization); + verify(payments).claimCommand(dispatch, account); + verifyNoInteractions(inbox, lifecycle, verifier); + } + + @Test + void secretHandoffIsBlockedWhenAuthorizationWasSupersededDuringProviderIo() throws Exception { + UUID account = UUID.randomUUID(), + subscription = UUID.randomUUID(), + requestId = UUID.randomUUID(), + evidenceId = UUID.randomUUID(); + var actor = mock(AccountControlUiActorService.AccountAuthenticatedActor.class); + when(actor.accountId()).thenReturn(account); + when(actors.withCurrentAccount(eq("bearer"), any())) + .thenAnswer(call -> { + java.util.function.Function< + AccountControlUiActorService.AccountAuthenticatedActor, Object> + action = call.getArgument(1); + return action.apply(actor); + }); + var proof = mock(AccountRecentReauthenticationEvidence.class); + when(proof.evidenceId()).thenReturn(evidenceId); + when(proof.billingContext()) + .thenReturn(mock(AccountRecentReauthenticationEvidence.BillingContext.class)); + when(reauthentication.requireCurrentBillingEvidenceLocked(evidenceId, account, requestId)) + .thenReturn(proof); + var prepared = mock(ConfirmationDispatch.class); + when(prepared.reauthenticationEvidenceId()).thenReturn(evidenceId); + when(prepared.authorizationRequestId()).thenReturn(requestId); + var dispatch = mock(ConfirmationDispatch.class); + when(dispatch.reauthenticationEvidenceId()).thenReturn(evidenceId); + when(dispatch.authorizationRequestId()).thenReturn(requestId); + when(payments.prepareConfirmation(account, requestId, subscription, 4, "tuple", proof)) + .thenReturn(prepared); + when(payments.readDispatch(prepared, account)).thenReturn(dispatch); + var providerHandoff = mock(StripeHostingFirstInvoicePaymentClient.Handoff.class); + when(providerHandoff.clientSecret()).thenReturn("pi_exact_secret_current"); + when(provider.confirm(eq(dispatch), any())).thenReturn(providerHandoff); + org.mockito.Mockito.doThrow(new IllegalStateException("authorization superseded")) + .when(payments) + .validateHandoffAuthorization(dispatch, account, proof); + + assertThatThrownBy( + () -> service.confirm("bearer", subscription, requestId, 4, evidenceId, "tuple")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("authorization superseded"); + + verify(provider).confirm(eq(dispatch), any()); + verify(providerHandoff).clientSecret(); + verify(payments).validateHandoffAuthorization(dispatch, account, proof); + verify(payments, times(0)).claimCommand(dispatch, account); + } + + private static ConfirmationDispatch signedCandidate() { + var invoice = + new AccountHostingFirstInvoicePayment( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + 1, + "sub_exact", + "cus_exact", + "pm_exact", + "in_exact", + "pi_exact", + 2400, + "usd", + "sha256:" + "a".repeat(64), + "price_exact", + 1, + 1, + "sha256:" + "b".repeat(64), + false, + Instant.parse("2026-11-01T00:00:00Z"), + Instant.parse("2026-11-01T23:00:00Z")); + var candidate = mock(ConfirmationDispatch.class); + when(candidate.invoice()).thenReturn(invoice); + when(candidate.requestId()).thenReturn(UUID.randomUUID()); + when(candidate.lifecycleRequestId()).thenReturn(UUID.randomUUID()); + when(candidate.expectedRowVersion()).thenReturn(3L); + return candidate; + } + + private static final class LocalTransactions extends AbstractPlatformTransactionManager { + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) {} + + @Override + protected void doCommit(DefaultTransactionStatus status) {} + + @Override + protected void doRollback(DefaultTransactionStatus status) {} + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPolicyTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPolicyTest.java index 95877277d2..d06a37f39c 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPolicyTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPolicyTest.java @@ -26,6 +26,20 @@ void explicitPlatformAndDeploymentValuesResolveToExactVersionedEffectivePolicy() assertThat(tightened.effectivePolicyVersion()).isNotEqualTo(baseline.effectivePolicyVersion()); } + @Test + void billingPurposeHasDistinctDigestAndCannotReuseGameCreationPolicyEvidence() { + var platform = new PlatformValue(1L, 300L, 30L); + var deployment = new DeploymentValue(1L, 300L, 30L); + var game = AccountRecentReauthenticationPolicy.resolve(platform, deployment); + var billing = + AccountRecentReauthenticationPolicy.resolve( + AccountRecentReauthenticationPolicy.BILLING_PURPOSE, platform, deployment); + assertThat(billing.effectivePolicyVersion()).isNotEqualTo(game.effectivePolicyVersion()); + assertThatThrownBy( + () -> AccountRecentReauthenticationPolicy.resolve("UNRELATED", platform, deployment)) + .isInstanceOf(IllegalArgumentException.class); + } + @Test void deploymentCannotLoosenPlatformOrExceedHardAgeAndSkewLimits() { var platform = new PlatformValue(1L, 300L, 30L); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationReplayTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationReplayTest.java index d7a24d12be..f773bf94ce 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationReplayTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationReplayTest.java @@ -13,19 +13,76 @@ import static org.mockito.Mockito.when; import java.time.Clock; +import java.time.Instant; import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; +import java.util.function.Function; +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.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import org.junit.jupiter.api.Test; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** Controlled replay orchestration; real MAC/custody and physical storage have separate proofs. */ class AccountRecentReauthenticationReplayTest { + @Test + void freshPrimaryAuthenticationReadsBackItsExactMacWithoutEnteringReplayBudget() { + var f = new Fixture(); + Account account = new Account(); + account.setId(1L); + account.setAccountUuid(f.account); + account.setAccountUuidSourceNumericId(account.getId()); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + account.setEmail("person@example.test"); + when(f.accounts.findByAccountUuidForUpdate(f.account)).thenReturn(Optional.of(account)); + var authenticated = mock(AccountServiceImpl.ControlUiPrimaryIdentity.class); + when(authenticated.accountId()).thenReturn(f.account); + when(f.primary.authenticateControlUiPrimaryIdentity("person@example.test", "test-only-secret")) + .thenReturn(authenticated); + var policy = + AccountRecentReauthenticationPolicy.resolve( + new AccountRecentReauthenticationPolicy.PlatformValue(1L, 300L, 30L), + new AccountRecentReauthenticationPolicy.DeploymentValue(1L, 300L, 30L)); + when(f.policies.resolveCurrentForGameCreation()).thenReturn(policy); + var scope = AuthorityScope.account(f.account); + var authority = mock(ScopeState.class); + when(authority.scope()).thenReturn(scope); + when(authority.generation()).thenReturn(1L); + when(authority.sourceVersion()).thenReturn(1L); + when(authority.issuanceFence()).thenReturn(new IssuanceFence(f.account, 1L, 1L)); + when(f.generations.read(scope)).thenReturn(authority); + when(f.repository.findByRequest(f.requestId)) + .thenReturn(Optional.empty()) + .thenReturn(Optional.of(f.evidence)); + when(f.repository.countReplayFailures(f.evidence)).thenReturn(5); + when(f.crypto.currentKeyId()).thenReturn("prior-key"); + when(f.crypto.recentReauthenticationRequestMac(eq("prior-key"), any())) + .thenReturn("a".repeat(64)); + + assertThat(f.service.reauthenticate(f.request(f.operation))).isSameAs(f.evidence); + + var order = inOrder(f.accounts, f.repository); + order.verify(f.accounts).findByAccountUuidForUpdate(f.account); + order.verify(f.repository).lockRequest(f.requestId); + order.verify(f.repository).lockCreationOperation(f.operation); + order.verify(f.repository).insert(any(), any(), any()); + verify(f.repository).readExactOriginal(f.evidence); + verify(f.crypto, times(2)).recentReauthenticationRequestMac(eq("prior-key"), any()); + verify(f.repository, never()).countReplayFailures(any()); + verify(f.repository, never()).recordReplayFailure(any()); + } + @Test void exactReplayUsesRetainedKeyWithoutPrimaryAuthenticationAndClearsTransientBytes() { var f = new Fixture(); @@ -39,7 +96,8 @@ void exactReplayUsesRetainedKeyWithoutPrimaryAuthenticationAndClearsTransientByt verify(f.crypto, times(2)).recentReauthenticationRequestMac(eq("prior-key"), any()); verify(f.crypto, never()).currentKeyId(); verify(f.repository).readExactOriginal(f.evidence); - verifyNoInteractions(f.primary, f.accounts, f.generations, f.policies); + verify(f.repository).countReplayFailures(f.evidence); + verifyNoInteractions(f.primary, f.generations, f.policies); assertThat(transientRequest.get()).containsOnly((byte) 0); assertThat(f.proof.toString()).doesNotContain("prior-key", "a".repeat(64)); } @@ -70,6 +128,34 @@ void equalRequestAndCreationIdsAreRejectedBeforeAnyOwnerOrCredentialAccess() { verifyNoInteractions(f.repository, f.primary, f.accounts, f.generations, f.policies, f.crypto); } + @Test + void genericEntryRejectsTypedBillingBeforeReadingOrRetainingEvidence() { + var f = new Fixture(); + var binding = + new AccountRecentReauthenticationEvidence.BillingContext( + f.account, + UUID.randomUUID(), + f.operation, + "sha256:" + "d".repeat(64), + 1L, + Instant.parse("2027-01-01T00:00:00Z"), + f.operation, + 0L, + AccountRecentReauthenticationEvidence.BillingAuthorizationPurpose.INITIAL_CONFIRMATION); + var billing = + new AccountRecentReauthenticationService.Request( + f.requestId, + f.account, + AccountRecentReauthenticationPolicy.BILLING_PURPOSE, + f.operation, + binding, + "controlled@example.invalid", + "controlled-fixture"); + assertThatThrownBy(() -> f.service.reauthenticate(billing)) + .isInstanceOf(AccountRecentReauthenticationService.IdempotencyConflictException.class); + verifyNoInteractions(f.repository, f.primary, f.accounts, f.generations, f.policies, f.crypto); + } + @Test void changedTupleConflictsBeforeMacOrPrimaryAuthentication() { var f = new Fixture(); @@ -91,7 +177,7 @@ void mismatchCommitsFailureBeforeDenialAndDoesNotRunIndependentReadback() { order.verify(f.transactions).commit(any()); verify(f.transactions, never()).rollback(any()); verify(f.repository, never()).readExactOriginal(any()); - verifyNoInteractions(f.primary, f.accounts, f.generations, f.policies); + verifyNoInteractions(f.primary, f.generations, f.policies); } @Test @@ -103,24 +189,24 @@ void exhaustedBudgetDeniesWithoutAnyCredentialAccessOrAdditionalFailure() { verify(f.repository, never()).findReplayProof(any()); verify(f.repository, never()).recordReplayFailure(any()); verify(f.transactions).commit(any()); - verifyNoInteractions(f.crypto, f.primary, f.accounts, f.generations, f.policies); + verifyNoInteractions(f.crypto, f.primary, f.generations, f.policies); } @Test - void independentReadbackMismatchCommitsExactlyOneFailureBeforeDenial() { + void independentReadbackMismatchDeniesAsUnavailableWithoutChargingReplayBudget() { var f = new Fixture(); when(f.crypto.recentReauthenticationRequestMac(eq("prior-key"), any())) .thenReturn("a".repeat(64), "b".repeat(64)); assertThatThrownBy(() -> f.service.reauthenticate(f.request(f.operation))) - .isInstanceOf(AuthenticationException.class); + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("authority is unavailable"); verify(f.repository, times(2)).lockRequest(f.requestId); - verify(f.repository).recordReplayFailure(f.evidence); - verify(f.transactions, times(2)).commit(any()); - verify(f.transactions, never()).rollback(any()); + verify(f.repository).countReplayFailures(f.evidence); + verify(f.repository, never()).recordReplayFailure(any()); var order = inOrder(f.repository, f.transactions); - order.verify(f.repository).readExactOriginal(f.evidence); - order.verify(f.repository).recordReplayFailure(f.evidence); order.verify(f.transactions).commit(any()); + order.verify(f.repository).readExactOriginal(f.evidence); + order.verify(f.transactions).rollback(any()); } @Test @@ -135,18 +221,178 @@ void successfulReplayDoesNotResetPriorFailures() { } @Test - void independentReadbackExhaustionSkipsSecondCredentialCheck() { + void alreadyAcceptedReplayReadsBackTheMacEvenIfTheBudgetWouldNowBeExhausted() { var f = new Fixture(); when(f.repository.countReplayFailures(f.evidence)).thenReturn(4, 5); when(f.crypto.recentReauthenticationRequestMac(eq("prior-key"), any())) .thenReturn("a".repeat(64)); - assertThatThrownBy(() -> f.service.reauthenticate(f.request(f.operation))) - .isInstanceOf(AuthenticationException.class); - verify(f.crypto).recentReauthenticationRequestMac(eq("prior-key"), any()); + assertThat(f.service.reauthenticate(f.request(f.operation))).isSameAs(f.evidence); + verify(f.repository).countReplayFailures(f.evidence); + verify(f.crypto, times(2)).recentReauthenticationRequestMac(eq("prior-key"), any()); verify(f.repository, never()).recordReplayFailure(any()); verify(f.transactions, times(2)).commit(any()); } + @Test + void legacyUntypedBillingCannotReplayAtGenericEntryOrAsGameCreation() { + var f = new Fixture(AccountRecentReauthenticationPolicy.BILLING_PURPOSE); + assertThatThrownBy(() -> f.service.reauthenticate(f.request(f.operation))) + .isInstanceOf(AccountRecentReauthenticationService.IdempotencyConflictException.class); + verifyNoInteractions(f.repository, f.primary, f.accounts, f.generations, f.policies, f.crypto); + var wrongPurpose = new Fixture(AccountRecentReauthenticationPolicy.BILLING_PURPOSE); + var changed = + new AccountRecentReauthenticationService.Request( + wrongPurpose.requestId, + wrongPurpose.account, + AccountRecentReauthenticationPolicy.PURPOSE, + wrongPurpose.operation, + "person@example.test", + "test-only-secret"); + assertThatThrownBy(() -> wrongPurpose.service.reauthenticate(changed)) + .isInstanceOf(AccountRecentReauthenticationService.IdempotencyConflictException.class); + verifyNoInteractions(wrongPurpose.primary, wrongPurpose.crypto); + } + + @Test + void newBillingEvidenceRequiresTypedContextAndTypedReplayCannotChangeIt() { + var unbound = new Fixture(AccountRecentReauthenticationPolicy.BILLING_PURPOSE); + var unboundActors = mock(AccountControlUiActorService.class); + @SuppressWarnings("unchecked") + Consumer unboundBind = mock(Consumer.class); + assertThatThrownBy(() -> + unbound.service.reauthenticateAndBindBilling( + unbound.request(unbound.operation), + unboundActors, + "controlled-bearer", + unboundBind)) + .isInstanceOf(AccountRecentReauthenticationService.IdempotencyConflictException.class); + verifyNoInteractions( + unbound.repository, + unbound.primary, + unbound.accounts, + unbound.generations, + unbound.crypto, + unboundActors, + unboundBind); + + var bound = new Fixture(AccountRecentReauthenticationPolicy.BILLING_PURPOSE); + Instant expiry = Instant.parse("2026-11-02T01:02:03.123400Z"); + var context = billingContext(bound, expiry); + when(bound.evidence.billingContext()).thenReturn(context); + when(bound.crypto.recentReauthenticationRequestMac(eq("prior-key"), any())) + .thenReturn("a".repeat(64)); + when(bound.evidence.requestDigest()) + .thenReturn( + AccountRecentReauthenticationRepository.digest( + AccountRecentReauthenticationRepository.requestPayload( + bound.requestId, bound.account, bound.purpose, bound.operation, context))); + var exactRequest = + new AccountRecentReauthenticationService.Request( + bound.requestId, + bound.account, + bound.purpose, + bound.operation, + context, + "person@example.test", + "test-only-secret"); + var actor = mock(AccountControlUiActorService.AccountAuthenticatedActor.class); + when(actor.accountId()).thenReturn(bound.account); + var actors = mock(AccountControlUiActorService.class); + when(actors.withCurrentAccount(eq("controlled-bearer"), any())) + .thenAnswer(call -> { + Function action = + call.getArgument(1); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + return action.apply(actor); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + }); + var currentAccount = mock(Account.class); + when(currentAccount.getId()).thenReturn(1L); + when(currentAccount.getAccountUuid()).thenReturn(bound.account); + when(currentAccount.getAccountUuidSourceNumericId()).thenReturn(1L); + when(currentAccount.getAccountUuidProvenance()) + .thenReturn(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + when(currentAccount.getLifecycleState()).thenReturn(AccountLifecycleState.ACTIVE); + when(bound.accounts.findByAccountUuidForUpdate(bound.account)) + .thenReturn(Optional.of(currentAccount)); + var authority = mock(ScopeState.class); + var fence = new IssuanceFence(bound.account, 1L, 1L); + when(authority.scope()).thenReturn(AuthorityScope.account(bound.account)); + when(authority.generation()).thenReturn(1L); + when(authority.sourceVersion()).thenReturn(1L); + when(authority.issuanceFence()).thenReturn(fence); + when(bound.generations.read(AuthorityScope.account(bound.account))).thenReturn(authority); + when(bound.evidence.identityProvenance()) + .thenReturn(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + when(bound.evidence.identitySourceNumericId()).thenReturn(1L); + when(bound.evidence.lifecycleState()).thenReturn(AccountLifecycleState.ACTIVE); + when(bound.evidence.accountAuthorityGeneration()).thenReturn(1L); + when(bound.evidence.accountAuthoritySourceVersion()).thenReturn(1L); + when(bound.evidence.issuanceFence()).thenReturn(1L); + when(bound.evidence.issuanceFenceSourceVersion()).thenReturn(1L); + when(bound.evidence.evidenceId()).thenReturn(bound.requestId); + when(bound.evidence.effectivePolicyVersion()).thenReturn("controlled-policy"); + when(bound.evidence.issuedAt()).thenReturn(expiry); + var policy = mock(AccountRecentReauthenticationPolicy.Effective.class); + when(policy.effectivePolicyVersion()).thenReturn("controlled-policy"); + when(policy.isRecent(eq(expiry), any())).thenReturn(true); + when(bound.policies.resolveCurrentForPurpose(bound.purpose)).thenReturn(policy); + when(bound.repository.findByEvidenceId(bound.requestId)) + .thenReturn(Optional.of(bound.evidence)); + when(bound.repository.lockExact(bound.evidence)).thenReturn(bound.evidence); + @SuppressWarnings("unchecked") + Consumer bind = mock(Consumer.class); + assertThat( + bound.service.reauthenticateAndBindBilling( + exactRequest, actors, "controlled-bearer", bind)) + .isSameAs(bound.evidence); + verify(bind).accept(bound.evidence); + + var changedContext = + new AccountRecentReauthenticationEvidence.BillingContext( + context.accountId(), + context.subscriptionId(), + context.originalRequestId(), + context.tupleDigest(), + context.expectedRowVersion(), + Instant.parse("2026-11-02T01:02:03.123000Z"), + context.authorizationRequestId(), + context.expectedAuthorizationVersion(), + context.authorizationPurpose()); + var changedRequest = + new AccountRecentReauthenticationService.Request( + bound.requestId, + bound.account, + bound.purpose, + bound.operation, + changedContext, + "person@example.test", + "test-only-secret"); + assertThatThrownBy(() -> + bound.service.reauthenticateAndBindBilling( + changedRequest, actors, "controlled-bearer", bind)) + .isInstanceOf(AccountRecentReauthenticationService.IdempotencyConflictException.class); + verify(bind, times(1)).accept(any()); + verifyNoInteractions(bound.primary); + } + + private static AccountRecentReauthenticationEvidence.BillingContext billingContext( + Fixture fixture, Instant expiry) { + return new AccountRecentReauthenticationEvidence.BillingContext( + fixture.account, + UUID.randomUUID(), + UUID.randomUUID(), + "sha256:" + "e".repeat(64), + 3L, + expiry, + fixture.operation, + 0L, + AccountRecentReauthenticationEvidence.BillingAuthorizationPurpose.PRE_ROW_RENEWAL); + } + private static final class Fixture { final UUID requestId = UUID.randomUUID(), account = UUID.randomUUID(), @@ -167,18 +413,24 @@ private static final class Fixture { final AccountRecentReauthenticationRepository.ReplayProof proof = new AccountRecentReauthenticationRepository.ReplayProof("prior-key", "a".repeat(64)); final AccountRecentReauthenticationService service; + final String purpose; Fixture() { + this(AccountRecentReauthenticationPolicy.PURPOSE); + } + + Fixture(String purpose) { + this.purpose = purpose; when(transactions.getTransaction(any())) .thenAnswer(invocation -> mock(TransactionStatus.class)); when(evidence.requestId()).thenReturn(requestId); when(evidence.accountId()).thenReturn(account); - when(evidence.purpose()).thenReturn(AccountRecentReauthenticationPolicy.PURPOSE); + when(evidence.purpose()).thenReturn(purpose); when(evidence.creationOperationId()).thenReturn(operation); String requestDigest = AccountRecentReauthenticationRepository.digest( AccountRecentReauthenticationRepository.requestPayload( - requestId, account, AccountRecentReauthenticationPolicy.PURPOSE, operation)); + requestId, account, purpose, operation)); when(evidence.requestDigest()).thenReturn(requestDigest); when(repository.findByRequest(requestId)).thenReturn(Optional.of(evidence)); when(repository.findReplayProof(evidence)).thenReturn(Optional.of(proof)); @@ -199,7 +451,7 @@ AccountRecentReauthenticationService.Request request(UUID creationOperation) { return new AccountRecentReauthenticationService.Request( requestId, account, - AccountRecentReauthenticationPolicy.PURPOSE, + purpose, creationOperation, "person@example.test", "test-only-secret");