diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index f5e79e14bf..01ba0802c6 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -161,7 +161,7 @@ Explicit playtest grants remain partial: registered Account persistence and inte Account has unregistered individual Creator Party, hosted-terms catalog, and individual acceptance storage in V84/V85 through `IndividualCreatorPartyRepository` and `HostedTermsRepository`, with focused repository test sources. These are storage foundations only: authenticated party provisioning and signer verification, operative legal publication, a registered acceptance API/UI, organization acceptance, party transfer, and a commit-bound currentness gate for Game Design writes remain unavailable or unproved. The canonical authority and capability limits are recorded in [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and the [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status); Game Design must not maintain a copied catalog or authorize a creator mutation from a tenant-local flag. -`CommitTenantCapacityAdmission` has a prepared proto RPC, a shared exact contract and codec, and the Account-owned durable evaluation, usage, reservation and recovery components. Account's default runtime composition leaves the capacity receiver and recovery worker unregistered. The [strict tenant-capacity tracker](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation) owns the receiving work and proof status. +`CommitTenantCapacityAdmission` has a prepared proto RPC, shared strict contract/codec, durable Account evaluation/usage/reservation storage and owner/finalization/recovery code, and a Game Session caller adapter. These components remain unregistered and unqualified for live admission; the [strict tenant-capacity owner tracker](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation) records the supported source boundary, focused proof and remaining producer, physical and runtime gates. The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` implementation is Account/profile-local, with identity projections governed by [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity). This is partial data, not the canonical target portable-data export lifecycle, which is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route and policy remain implementation drift pending direct convergence on tenant-qualified routes. The legacy profile selector and authorization consequences are recorded under [REST APIs](#rest-apis); membership-authority-generation validation remains unimplemented. Public registration follows the response identity contract below and writes that same public identity in its platform audit outbox row; it creates only global Account state and does not create a profile or tenant membership. JOIN receiver availability and its blocked Gateway route are recorded under [Current Receiver Composition](#current-receiver-composition). Target JOIN operation, digest, retry, and commit semantics remain owned by [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md) and the linked [Authentication contract](../../system-architecture-authentication.md). The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Connect-token receiver availability is recorded under [Current Receiver Composition](#current-receiver-composition). Current text `PLAY` validates the emitted `membershipLifecycleState` and independent `membershipAuthorityGeneration` and requires coherent `ACTIVE` admitting membership. Missing or `INACTIVE` public-production membership yields `JOIN_REQUIRED` only when fresh enrollment policy permits repair; an existing active but non-admitting response is not a join fallback. The implemented consumer limits remain in [Account runtime status](./runtime-and-data.md#implementation-status); these checks do not establish the complete caller-target and atomic-freshness contract. Current non-public or non-visible target handling remains split across existing discovery, membership, and grant surfaces; the complete grant/entitlement admission predicate at connect-token issuance remains target-only. The obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware. The browser connect-token body and OpenAPI response are defined as metadata-only; any issued raw token is carried only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. The `player-bootstrap` credential/result profile uses the persisted Account UUID in its result `accountId` and matching JWT subject/Account claim; its Account-owned reader rejects noncanonical, numeric or mismatched identity before resolving the private storage row. The final ordinary receiving composition also carries UUID ordinary login results/credentials, UUID shared intake and forwarding, UUID internal selectors and UUID Account references in downstream consumers. Tenant representations follow the [Account tenant identifier boundary](#account-tenant-identifier-boundary). Full token-profile/registry qualification remains held. Derived `bootstrap-connect-scope` artifacts use the persisted Account UUID in their signed subject/Account claim, through the shared browser/direct-text producer and dedicated Account reader. Profile self-binding and REST caller identity use UUID `SessionContext`; private Account SQL rows remain numeric. The legacy GameInstance owner/StartSession boundary remains separately numeric and unqualified. The bounded response and REST selector identity contract is defined below. Scoped-role population and tenant-switching proof remain target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. @@ -233,8 +233,12 @@ 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 replays, while any changed bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest is an idempotency conflict before usage mutation. 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 `TENANT_BILLING_BLOCKED` with `RESOURCE_EXHAUSTED`. Fresh creation-eligible evidence with checked insufficient capacity returns `CAPACITY_QUOTA_EXCEEDED` with the same gRPC status. An authenticated exact retained evaluation outside its qualified time window or superseded by a qualified newer billing cutoff 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 changed exact retry. 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 attempt-and-fence retries replay; 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. +- `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 is inexact and leaves the original outcome indeterminate. A deadline crossing after Account starts writing a provisional acceptance rolls the transaction back and returns stale admission. An exact retry can evaluate the original request again. The historical read returns only a committed refusal receipt. The response contains exactly one commitment or one typed refusal. PostgreSQL time is the only clock for the retained evaluation lifetime: a fresh positive reservation requires `evaluated_at <= now < expires_at` on that clock, the exact connect-scope expiry is judged on the same sample, and PostgreSQL rechecks the evaluation after deferred inventory validation for a new reservation or rearm. Expiry at that boundary rolls back the attempt and grants no denial receipt. Exact replay and settlement of the same retained attempt remain available after expiry. If PostgreSQL time establishes 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. When PostgreSQL time already establishes expiry before fresh source qualification, an authenticated caller with the exact retained creating evaluation, current membership and exact billing cutoff may obtain this denial without renewing the expired delegation or connect scope. Live source unavailability or revocation encountered during fresh qualification retains its existing refusal. 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, `IDEMPOTENCY_CONFLICT` with `ALREADY_EXISTS` for a mismatch against an existing retained binding outside proof-backed rearm, and a fixed `INTERNAL` detail, without exception text, for an internal failure. The workload guard closes denied calls with the same bounded `AUTH_UNAVAILABLE` or `PERMISSION_DENIED` detail without dispatching them. 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. An exact retry of the currently bound attempt, fence, complete payload and digest returns the current persisted reservation state. It does not create or renew execution authority. 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`. The locked Account rearm CAS verifies the current recovery claim while it excludes a competing owner. Deferred validation separately requires the accepted entitlement evaluation to remain fresh. A stale claim or losing CAS returns `IDEMPOTENCY_CONFLICT`, which grants no settlement authority. The target typed `FENCE_REJECTED` outcome requires affirmative no-accept and 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. + +`ReadTenantCapacityAdmissionDenial` is the private read-only reconciliation operation for the exact Game Session mTLS peer while its original reserve remains active. It takes the original commit request and matches the outer identity, attempt, fence, complete payload and digest. Account returns only an original durable quota or expired-evaluation denial with its exact kind and decision UUID. Missing or ambiguous evidence keeps the original reserve and admission closed. A fresh request or automatic mutation retry does not recover the original outcome. Before enabling this composition, qualify recovery after the original response is lost, quota headroom returns and the caller restarts. Verify that no new attempt, reservation or refusal slot was used. The caller uses a fresh bounded reconciliation deadline for the read and preserves the historical request. For both a direct commit refusal and a retained read, verify in the Game Session settlement owner that the same original reserve and its current fence are still authoritative in the transaction that consumes the denial. The historical request and Account receipt authenticate the original outcome, not ownership after the RPC returns. Before composition is enabled, qualify a disposable case where the original reserve fence changes while the read is outstanding: the late denial must not advance, release or otherwise mutate that reserve, and the unchanged-fence case must preserve the original reconciliation semantics. The [strict tenant-capacity owner tracker](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation) records the remaining caller and owner proof. The shared [capacity-admission/v1 schema](../../../../services/common-platform-core/src/main/resources/capacity/capacity-admission-v1.schema.json) declares the exact ADR 0047 seven-field mapping and bounds. Its `accountEvidence` member is canonical padded base64 of the complete existing Account bundle bytes, validated by the closed variant codec with canonical re-encoding equality before hashing. This binds every evidence field and cutoff/checkpoint byte, not a digest or reconstructed subset. `capacity_delta` is `optional int64`; missing presence is invalid and a present zero remains distinct. The Game Session and World alternatives retain distinct typed contexts. The ordinary registered Account receiver does not expose this private composition, and no route is enabled by adding the proto. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index fe4f92d77d..c8a8698a7d 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -6,6 +6,10 @@ This document defines the Account Service runtime model, persistent data ownersh Account owns platform identity, hosted Creator Party/operator and terms currentness authority, durable membership, entitlement authority, Account-local authentication persistence, global `account_security_lock`/`platform_access_ban` enforcement, Stripe v1 hosting-billing state, and future marketplace financial reconciliation. The hosted terms and creator-party authority are target-only under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md); future creator commerce remains separately gated by [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md). This document records only local runtime and data consequences; fixed-category moderation and appeal ownership is defined by [Moderation Policies](../logging-admin-service/moderation-policies.md), gameplay/chat enforcement remains in Game Session and Social & Groups, gameplay admission and JOIN identity binding are defined by [Authentication](../../system-architecture-authentication.md), and token refresh, replacement, generation, revocation, fencing, and logout are defined by [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md). +### Finalized capacity usage retirement + +After [Game Session supplies authenticated terminal proof](../game-session-service/runtime-and-data.md#finalized-capacity-usage-retirement) for the exact finalized binding and reservation, Account retains a unique retirement receipt and subtracts only the units covered by that exact receipt from used units in the same owner transaction, leaving unrelated used units unchanged. Exact retirement retries replay that receipt without a second decrement. The same finalized reservation units may be retired only once across all receipt identities. Account verifies that new coverage is disjoint from the retained retirement coverage and remains within the finalized reservation before it decrements usage. Account preserves the original `FINALIZED` reservation, result and replay evidence. The retirement schema must reconcile used units as finalized units minus retained retirement coverage. The receipt and decrement commit together under that inventory constraint. + ## Implementation Status Both existing `bootstrap-connect-scope` producer paths mint the exact persisted Account UUID. Scope validation compares canonical UUID subject/Account claims before owner readback; malformed identity remains `CONNECT_SCOPE_INVALID`, while unavailable owner evidence is `AUTH_UNAVAILABLE`. Retained scope/JOIN rows and digests continue to use private Account row keys without a schema rewrite. This scope-artifact transition itself adds no Game Session text dispatch; the separately qualified ordinary receiving cohort now carries UUID Account identity through the direct-text caller context and Account-to-Entity references. Proof and retained-scope rediscovery limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#bootstrap-connect-scope-uuid-artifact) and [ordinary UUID receiving](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving). @@ -84,7 +88,13 @@ Current public bootstrap, direct-scope, JOIN, connect-token and numeric entitlem 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. -The unregistered capacity owner requires exact retained evidence and current Account membership/issuance/scope source equality before creating a new positive player-binding reservation. Exact attempt retries replay before fresh-source or usage work; changed complete payloads conflict. The Account recovery component alone can finalize, release or rearm under its current durable claim and exact selected-owner readback; an ambiguous observation records only the bounded retry/deadline and retains the hold. Account's default runtime leaves the capacity receiver, selected-owner readback and recovery worker unregistered. Controlled observations prove Account ledger transitions. Actual Game Session execution, closure and admitted-session teardown require their own retained owner receipts. World lifecycle, authoritative prior-shape/zero-delta recovery, current selected-owner activation and complete end-to-end qualification remain held as detailed in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). +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. The same baseline 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, counting both quota and `CAPACITY_EVALUATION_EXPIRED` denials, which spend the same limit ([Account API](api-contracts.md)); 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. + +For pre-v1 resets use the [database migration reset safety gate](../../system-architecture-database-migrations.md#version-aware-migration-checklist). This capacity implementation adds no reset, budget-reset, or receipt-deletion operation. + +The V1040.1 capacity-origin baseline stores one immutable refusal slot per retained `NO_ACCEPT` decision as the contiguous sequence `1..N`. After origin identity arbitration, a fresh refusal takes the existing tenant budget lock, reads the highest slot through the tenant-slot index, and appends `N+1` in the same transaction. `requireReady` uses that indexed highest slot as the retained refusal count to compute bounded headroom. Replay, conflict, and failed inserts leave the inventory unchanged. + +The unregistered capacity owner requires exact retained evidence and current Account membership/issuance/scope source equality before creating a new positive player-binding reservation. Before fresh-source or usage work, an exact retry of the reservation's current attempt replays its result and an exact retry of a retained denial replays that denial. A retry of an attempt superseded by rearm, or with a changed payload, conflicts with the existing retained binding. A non-retained billing refusal does not itself bind the attempt for replay or conflict; a retry still requires fresh current evidence. The Account recovery component alone can finalize, release or rearm under its current durable claim and exact selected-owner readback; an ambiguous observation records only the bounded retry/deadline and retains the hold. No runtime readback producer or recovery client is registered. World lifecycle, authoritative prior-shape/zero-delta recovery, current selected-owner activation and complete end-to-end qualification remain held as detailed in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). The canonical gameplay LOGIN primary-credential adapter reuses Account’s password and email-OTP authority without creating a legacy token or session. Its owner transaction retains the verified challenge identity and consumes it only after new PENDING issuance; denial accounting and expiry cleanup commit under the existing owner denial path. Exact pending retry does not reverify or reconsume. Canonical-only verification pads to two KDF comparisons with non-authorizing process-local random decoy evidence using the existing Argon2 profile. The adapter participates only in the explicitly enabled protected LOGIN composition; default deployment behavior remains unchanged. Focused unit and real PostgreSQL proof and its controlled upstream/external-owner limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). Deployed authenticated issuance and timing parity remain unproved. diff --git a/design/architecture/microservices/account-service/subscription-management.md b/design/architecture/microservices/account-service/subscription-management.md index 3c6ee18739..6d34ef86ee 100644 --- a/design/architecture/microservices/account-service/subscription-management.md +++ b/design/architecture/microservices/account-service/subscription-management.md @@ -205,7 +205,7 @@ Downstream services depend on billing events for timely entitlement enforcement, - **Periodic refresh** – even when events are flowing, every healthy runtime consumer must refresh or reconcile cached entitlements at least once per 60 seconds so extended event outages meet the `<=60-second` delayed/missed-event SLA rather than causing unbounded drift. - `CreateSubscription` – Create one hosting subscription for an immutable `tenantId` and initial `plan_code`. The caller supplies a high-entropy stable `requestId`; Account resolves the authoritative billing owner and computes and persists a versioned `requestDigest` from the normalized create tuple, including that owner, immutable `tenantId`, initial `plan_code`, and exact instrument-selection input. The digest and resolved billing owner are not request fields. A retry with the same `requestId` and normalized create fields recomputes the same digest and replays the same durable operation and outcome; changed fields that produce a different digest return `IDEMPOTENCY_CONFLICT`; the caller identity is distinct from provider operation identities. It rejects an existing `subscriptionId`, expected row version, update operation ID, or any other update-only field. Creation must resolve the authoritative billing owner before its subscription row exists, capture the owner's authority version/generation, authorize the actor against that resolved owner (or require the explicit audited cross-tenant handoff), and require either an explicit saved `paymentInstrumentId` or deterministic instrument-selection input that resolves to exactly one saved instrument owned by that owner. In one local Account transaction, Account locks or CAS-validates the resolved owner and exact captured version/generation before committing the subscription operation, immutable internal `subscriptionId` and `tenantId`, owner, owner fence, customer-operation reference, confirmed provider customer when available, instrument binding and reserved instrument version, `pending` status, immutable `subscription_provisioning_request_id`, separate cleanup/cancellation provider-operation identity, and outbox work item before customer reconciliation or provider creation. An owner-fence mismatch fails closed before any provider operation. The worker may reconcile the customer operation while the row remains pending, but its provisioning claim atomically requires a confirmed matching customer and revalidates ownership, exact instrument version, and attachability; detach racing with provisioning is serialized by that reservation/version boundary and a stale claim fails before Stripe. Creation retries retain the creation identity for lookup; cleanup retries reuse the distinct cleanup identity. Stripe customer and provider defaults are prohibited. -- `CommitTenantCapacityAdmission` – Target Account-owned internal RPC and final capacity fence described above. Its canonical callers are Game Session and World Management; it requires stable outer `(tenantId, requestId, admissionId)`, fresh per-attempt `admissionAttemptId`, current `capacityRearmFence`, the exact complete Account-authenticated evidence bundle returned by evaluation, bounded `capacityDelta`, and a versioned `mutationDigest` over the attempt identity, fence, and complete payload. An exact identity-and-payload retry replays; any changed bundle version, snapshot/evaluation identity, entitlement field, tuple, cutoff, checkpoint, delta, attempt ID, fence, or digest conflicts before usage mutation. The initial attempt needs no rearm CAS. A new attempt requires an Account-owned CAS over the same outer tuple, terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` plus durable no-commit evidence, current fence, and prior digest; that CAS advances the fence without creating a second reservation. Stale or losing fences return `FENCE_REJECTED` only with durable no-accept/no-runtime-mutation proof. It is the only contract that can turn a fresh entitlement snapshot into a strict capacity commitment. Downstream owners cannot replace it with a local compare or cached flag. The shared contract, Account durable owner and private receiver, and Game Session adapter are locally prepared without runtime registration or qualification; current source/proof limits remain 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` – Target Account-owned internal RPC and final capacity fence described above. Its canonical callers are Game Session and World Management; it requires stable outer `(tenantId, requestId, admissionId)`, fresh per-attempt `admissionAttemptId`, current `capacityRearmFence`, the exact complete Account-authenticated evidence bundle returned by evaluation, bounded `capacityDelta`, and a versioned `mutationDigest` over the attempt identity, fence, and complete payload. An exact identity-and-payload retry replays the reservation only for the currently bound attempt. A superseded attempt cannot replay a rearmed reservation. Account separately replays the retained quota denial for its own exact attempt. A change to a retained binding outside proof-backed rearm conflicts before usage mutation. A non-retained billing refusal does not create such a binding. The initial attempt needs no rearm CAS. A new attempt on an existing reservation requires an Account-owned CAS over the same outer tuple, terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` plus durable no-commit evidence, current fence, and prior digest; that CAS advances the fence without creating a second reservation. Stale or losing fences return `FENCE_REJECTED` only with durable no-accept/no-runtime-mutation proof. It is the only contract that can turn a fresh entitlement snapshot into a strict capacity commitment. Downstream owners cannot replace it with a local compare or cached flag. The shared contract, Account durable owner and private receiver, and Game Session adapter are locally prepared without runtime registration or qualification; current source/proof limits remain 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). - `UpdateSubscription` – Apply one plan, instrument, cancellation, or other supported update to an existing immutable `subscriptionId`. Period-end and immediate cancellation both use this mutation; no separate `CancelSubscription` mutation exists. It requires the target subscription identity, a distinct immutable operation-specific request ID, and the expected subscription row version/CAS; it rejects `subscription_provisioning_request_id`, creation-only fields, and any attempted `tenantId` change. Retries reuse the same update identity and guard and never reuse the initial provisioning identity. Provider activation and billing require a confirmed provider subscription ID. Caller-bound tenant variants derive actor identity from auth context; cross-tenant admin variants are separate APIs. - `GetSubscriptionTenantHighLevel` / `ListSubscriptionsTenantHighLevel` – Query subscription state for one tenant, scoped by tenant authorization. - `ListSubscriptionsCrossTenantSupportSafe` – Cross-tenant support-safe high-level listing for troubleshooting only. diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index cbb533f566..90e3ced108 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -6,6 +6,18 @@ Game Session coordinates with Redis to store volatile session state and command The service runtime model assumes replaceable workers, not authoritative in-process state. +### Finalized capacity usage retirement + +This is a target-only contract, not an enabled or runtime-qualified retirement path. + +The exact current Game Session owner establishes irreversible closure of serving and resume for the admitted binding and retains settlement of applicable effects and indexes. It fences admission of new commands for that binding before taking the final inventory of admitted operations to settle, including commands already forwarded by the edge. Game Session supplies an authenticated terminal receipt linked to the original admission, FINAL evidence, binding lineage and Account reservation. [Account owns retirement of the corresponding used capacity](../account-service/runtime-and-data.md#finalized-capacity-usage-retirement). Before irreversible closure or settlement can discard the original work state, Game Session must durably retain the exact teardown identity and progress evidence needed for a replacement owner to finish the same terminal receipt. That progress durably marks the binding closing before closure is dispatched. From the moment the marker is persisted, whether or not closure has committed, the serving and resume admission check for that binding treats the marker as closed, for the active owner as well as a replacement. A replacement owner that reads the marker keeps serving and resume closed; exact readback under the retained sub-operation identity then shows whether to record the committed closure or redispatch the same closure, never to reopen. A crash between closure/settlement and receipt retention resumes that original teardown without reopening the binding or inventing a new receipt identity. The terminal receipt remains durable and exactly readable after binding closure and worker replacement. A replacement owner recovers and redelivers that same receipt until Account's exact retirement acknowledgement is known; this recovery never reopens serving or resume. + +The target Game Session owner persists the teardown identity and progress in its own PostgreSQL storage, then retains the immutable terminal evidence under that same identity. A replacement worker reads the persisted progress and exact receipt rather than reconstructing either from Redis, an in-memory job or the current binding alone. The receipt binds the original admission, FINAL evidence, binding lineage and exact Account reservation; conflicting identities or stale owner fences must be refused. After a lost or ambiguous Account response, that retained receipt and its original fence remain historical immutable evidence, not present sender authority: redelivery is performed only by the currently authenticated replacement owner under its current owner authority, without replacing or advancing the original teardown identity or receipt fence. + +Irreversible closure of serving and resume and each applicable settlement must either commit atomically with its Game Session progress record in the same owner-local transaction, or expose exact durable owner readback under an immutable sub-operation identity and request digest retained before dispatch. For an already-admitted effect, retain its original mutation identity and participant binding under the [effect reconciliation contract](../../system-architecture-transactions.md#reconciliation-owner-of-record-spatialambient-effects); teardown must not allocate a replacement effect. If the fence holder crashes after external closure or settlement completes but before writing progress, the replacement uses the existing closure or settlement authority to read back that exact outcome and persist the recovered progress before completing the terminal receipt. Any retry uses the same sub-operation identity and existing idempotence rules. The teardown identity, a missing progress row, a timeout or Redis absence alone proves neither completion nor no-commit. Unavailable, ambiguous or mismatched owner evidence keeps teardown unresolved, serving and resume closed, and the corresponding Account used units unretired. Closure or settlement without either recovery boundary blocks retirement qualification. + +Qualification must prove a restart after irreversible closure or settlement but before the terminal receipt exists, then verify the replacement completes that same teardown from durable progress with serving and resume still closed. For independently committing closure and for every independently committing settlement, also prove completion followed by response loss and a crash before progress persistence: the replacement must recover the exact original owner outcome without repeating the logical operation or using a new sub-operation identity. Separately prove restart before send, Account commit followed by response loss and worker restart, and exact receipt replay without a second decrement. Account—not Game Session—atomically retains the retirement receipt and decrements used capacity. Wrong identity or fence must fail closed, and no failure or retry may reopen serving or resume. These are acceptance requirements, not claims that the target path or its restart proof exists today. + ## Implementation Status The manually composed initial region bridge preserves either PRESEEDED assignment provenance or the separate PLAYER_CREATED creation origin. It selects the matching authenticated Entity reader and exact purpose-versioned World placement; a sealed reference is constructed only after authenticated response validation. Preparation and bridge rows retain the closed origin independently from operation IDs, and created rows keep assignment columns NULL. Current acquisition, retry, ACK, definitive abort and final commit preserve each bridge’s own authenticated actor origin. The first actor matches its exact timeline preparation; later distinct actor transitions use that same installed region source and protected incarnation while retaining their own origins, without replacing the first preparation or its actor-bound read digest. The shared numeric runtime ID remains a scoped projection, never a creation/assignment UUID or a credential. This path is unregistered and supplies no production custody, first-OPEN or activation authority. diff --git a/design/architecture/system-architecture-database-migrations.md b/design/architecture/system-architecture-database-migrations.md index 3bd67daa0f..9b819d67ee 100644 --- a/design/architecture/system-architecture-database-migrations.md +++ b/design/architecture/system-architecture-database-migrations.md @@ -246,6 +246,8 @@ This catalog query identifies enforced references, not all domain-level reachabi [ADR 0185](decisions/adr-0185-no-data-carry-over-before-v1.md) requires every pre-v1 dev-demo deploy to use a fresh, reseeded database after the reset-safety gate. The workflow still implements a retained-database exception on `develop`. Until the fresh-deploy target is implemented, the trusted dev-demo workflow uses a clean namespace reset for ordinary pushes. A push that first adds the Game Session or Automation V2 Flyway migration, or Account V25 profile-identity migration, in the trusted deployed-to-target range instead preserves the runtime database and uses the quiesced activation path. That path first proves the reserved nonmatching selector does not match a Pod, replaces each canonical Account, Game Session, and Automation Service selector, verifies each readback, and waits until all matching EndpointSlices contain no endpoints. It then scales all three writers to zero and proves their Deployments and writer Pods are quiescent before restoring the canonical Service selectors. If selector mutation, endpoint observation, scaling, or drain proof fails, the helper aborts before migration activation and attempts to leave the canonical Services closed. If closure cannot be verified or reapplied, an operator must verify and repair admission before retrying. This includes Account because its V25 tenant-scoped uniqueness constraint must not overlap an old Account writer. Edits or deletions of an existing supported migration fail before namespace mutation because retained-database and Flyway checksum state are uncertain. Other Flyway migrations in the exact deployed-to-target Git range fail detection before namespace mutation until explicit trusted support exists; non-migration pushes retain the clean reset. Both pushes and redispatches use only the exact deployed-head annotation from the owned `dev` namespace as the classification base and require valid Git ancestry to the target. A supplied push before-SHA can add an ancestry check but never replaces that deployed-head base. Missing or ambiguous namespace evidence stops the workflow before namespace mutation. This narrow exception avoids using namespace deletion as a substitute for proving the retained V1 data prerequisites. +The trusted dev-demo classifier refuses any change in the Account V1040.x capacity-origin family before namespace mutation. Its activation requires the ADR 0185 reset-safety gate with a fresh database. + Hosted candidate previews may activate a migration only when the trusted path independently proves both an isolated fresh database and absence of old writers. A newly recreated namespace or a manifest value is not database provenance when backing storage may be retained. If the preview credential cannot verify that proof, skip or fail the candidate activation before modifying its namespace; use the trusted post-merge quiesce path instead. Migration changes use the canonical [Validation and Runtime Proof](../developer-workflows/validation-and-runtime-proof.md) workflow to select formatting, checks, and runtime proof, with execution results recorded in PR/CI evidence and, when applicable, synchronized into the owning implementation tracker. This document does not duplicate that workflow or act as a validation ledger. 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 d615bde459..9a00934f7c 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -38,9 +38,19 @@ The [shared capacity-admission/v1 schema](../../../services/common-platform-core The unregistered Account owner prepares exact initial reservation, replay and conflict. The recovery worker uses an exact selected-owner observation to finalize, release or rearm the original reservation. Missing and ambiguous observations retain the hold through bounded quarantine. Focused Account proof covers the ledger, fresh and historical bootstrap, exact replay, refusal and controlled recovery. The default Account runtime refuses the legacy numeric entitlement route and has no registered capacity receiver or recovery worker. +The staged [Game Session capacity client](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java) is manually composed and unregistered. It accepts only a plain `host:port` or `dns:///host:port` target, on a dedicated channel that ignores resolver service config. A case-insensitive `DNS` scheme and the single-slash `dns:/host:port` spelling are also accepted, and every accepted target is normalized to the canonical `dns:///host:port` form. It requires the exact same-namespace Account mTLS peer before releasing the request body, carries the complete typed request and verifies the exact response binding. Its commit call uses the minimum of the remaining absolute admission budget, incoming deadline and five-second cap, with bounded request/response sizes and no automatic mutation retry. The retained-denial recovery read runs in a forked context, so it ignores the expired admission context and is bounded only by its own absolute deadline and the five-second cap. A timeout, transport failure or inexact response leaves the original commitment indeterminate; the client neither admits gameplay nor performs an owner activation CAS. + +After exact replay/conflict and retained/current source qualification, the Account owner returns `TENANT_BILLING_BLOCKED` only when the bound evidence does not permit creation. This refusal carries no durable decision receipt and is not a retained replayable outcome; a later retry must recheck current evidence. A creating request denied by quota instead commits an exact `NO_ACCEPT` decision under the finite tenant refusal budget before returning `CAPACITY_QUOTA_EXCEEDED` with its durable denial ID. That retained denial has no reservation or usage mutation, excludes acceptance for the same original and replays even after headroom returns or the evaluation expires. The client's transport `commit` path preserves the typed distinction and requires the authenticated Account decision ID for a quota or expired-evaluation denial. Separately, `CapacityRefusedException.retainedAdmissionDenial(Refusal)` exposes the durable quota or expired-evaluation refusal after the local owner verifies its exact retained binding. Billing denial has no durable denial ID; a refusal without that receipt supplies no durable settlement proof. + +Account [V1040.1](../../../services/account-service/src/main/resources/db/migration/V1040.1__account_capacity_origin_decisions.sql) stores immutable contiguous per-tenant refusal slots for exact `NO_ACCEPT` decisions in the fresh capacity-origin baseline. After origin identity arbitration, each fresh refusal appends one slot under the existing tenant budget lock; replay, conflict and failed insertion do not spend a slot. Refusal admission and readiness headroom use the indexed highest slot rather than scanning lifetime origin history. A missing or mismatched limit, or insufficient cohort headroom, blocks readiness. A missing or exhausted installed budget blocks fresh refusal writes; the write path has no expected-limit input. The external admission producer must stay quiescent until readiness passes. Automatic producer suspension after exhaustion remains an activation requirement. No replenishment, reset or receipt-deletion authority is prepared. + +Existing focused proof anchors include the [Account owner units](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java), [creation/ledger/recovery PostgreSQL cases](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java), [player-owner retained-denial case](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java), [migration/refusal-slot cases](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java), [shared codec cases](../../../services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java) and [Game Session client mTLS cases](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java). These cover controlled owner/storage, exact refusal/replay and separate loopback transport boundaries, not a genuine cross-owner runtime-admission chain. The codec cases now prepare contradictory billing-refusal rejection on both encode and decode while preserving valid non-creating billing evidence and quota-denial invariants. + +The unregistered retained-denial read composes the Game Session client, the authenticated Account mTLS receiver, and physical PostgreSQL. The fixture recovers the original decision after quota headroom returns and the original evaluation expires, then verifies unchanged reservation, usage, refusal slot and denial rows. A separate controlled transport test verifies exact readback after an ambiguous commit call (`UNAVAILABLE` or no reply) without issuing another commit; the PostgreSQL fixture remains the proof that Account returns the original retained denial. Recovery from a persisted Game Session reserve after a real process restart still needs proof. Before activation, the Game Session settlement owner must prove that a delayed exact denial cannot mutate the reserve or its charge after its local fence advances, with an unchanged-fence control that settles the original reserve. + 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. -Game Session original-NEW execution and its authenticated recovery source, normal owner handoff, and the origin and historical FINAL receiving paths remain dependent work. Finalized usage retirement requires a genuine admitted-session teardown receipt from the selected owner and an exactly-once Account usage transition that preserves finalized replay. Bounded conservation and owner-governed evidence retention remain downstream. Preserve immutable predecessor evidence, deployed source and PKI qualification, and runtime registration and activation holds. +Game Session original-NEW execution and its authenticated recovery source, normal owner handoff, and the origin and historical FINAL receiving paths remain dependent work. Finalized usage retirement and settlement remain deferred: they require a genuine admitted-session teardown receipt from the selected owner and an exactly-once Account usage transition that preserves finalized replay. Bounded conservation and owner-governed evidence retention remain downstream. Preserve immutable predecessor evidence, deployed source and PKI qualification, and runtime registration, admission and activation holds. ### Controlled player-admission transport composition diff --git a/dev-tools/deploy/detect-hosted-v2-migration-activation.sh b/dev-tools/deploy/detect-hosted-v2-migration-activation.sh index 500c1fbeed..b4b07a2641 100644 --- a/dev-tools/deploy/detect-hosted-v2-migration-activation.sh +++ b/dev-tools/deploy/detect-hosted-v2-migration-activation.sh @@ -80,6 +80,7 @@ fi game_session_v2="services/game-session-service/src/main/resources/db/migration/V2__scope_gameplay_command_identity.sql" automation_v2="services/automation-scripting-service/src/main/resources/db/migration/V2__script_patch_readiness_single_active.sql" account_v25="services/account-service/src/main/resources/db/migration/V25__scope_profile_identity.sql" +account_migrations="services/account-service/src/main/resources/db/migration" migration_changed=false while IFS= read -r changed_path; do [[ -z "$changed_path" ]] && continue @@ -100,6 +101,10 @@ while IFS= read -r changed_path; do fi migration_changed=true ;; + "$account_migrations"/V1040.*__*.sql) + echo "refusing hosted deployment: Account capacity origin must pass the pre-v1 reset safety gate before activation: $changed_path" >&2 + exit 1 + ;; *) echo "refusing hosted deployment: unsupported Flyway migration path in exact range: $changed_path" >&2 exit 1 diff --git a/dev-tools/tests/hosted-v2-migration-activation-contract.sh b/dev-tools/tests/hosted-v2-migration-activation-contract.sh index 8ae237c90c..8bff82dbcd 100644 --- a/dev-tools/tests/hosted-v2-migration-activation-contract.sh +++ b/dev-tools/tests/hosted-v2-migration-activation-contract.sh @@ -116,6 +116,20 @@ git -C "$repo" commit -qm "Account V25 migration" account_v25_sha="$(git -C "$repo" rev-parse HEAD)" assert_activation true push "$supported_v2_sha" "$account_v25_sha" +git -C "$repo" switch -qc account-capacity-origin "$account_v25_sha" +printf '%s\n' '-- capacity origin fixture' \ + >"$repo/services/account-service/src/main/resources/db/migration/V1040.1__account_capacity_origin_decisions.sql" +git -C "$repo" add . +git -C "$repo" commit -qm "Account capacity origin migration" +capacity_sha="$(git -C "$repo" rev-parse HEAD)" +namespace_for_head "$account_v25_sha" +if output="$(cd "$repo" && bash "$detector" push "$account_v25_sha" "$capacity_sha" dev 2>&1)" || + ! grep -Fq 'Account capacity origin must pass the pre-v1 reset safety gate' <<<"$output"; then + echo "expected the Account capacity origin migration to be refused explicitly: $output" >&2 + exit 1 +fi +git -C "$repo" switch -q account-v25 + namespace_for_head "$account_v25_sha" echo '-- edited retained migration' >>"$repo/services/account-service/src/main/resources/db/migration/V25__scope_profile_identity.sql" git -C "$repo" add . diff --git a/protos/account/v1/account_service.proto b/protos/account/v1/account_service.proto index 0d5cc807cb..abf5c59261 100644 --- a/protos/account/v1/account_service.proto +++ b/protos/account/v1/account_service.proto @@ -12,6 +12,9 @@ option java_multiple_files = true; service AccountService { // Strict capacity owner. Available only through an explicitly composed bounded mTLS receiver. rpc CommitTenantCapacityAdmission(CommitTenantCapacityAdmissionRequest) returns (CommitTenantCapacityAdmissionResponse); + // Private read-only reconciliation of an exact retained admission denial. An unavailable + // outcome does not prove the original attempt did not commit. + rpc ReadTenantCapacityAdmissionDenial(CommitTenantCapacityAdmissionRequest) returns (CommitTenantCapacityAdmissionResponse); rpc Ping(PingRequest) returns (PingResponse); rpc CreateAccount(CreateAccountRequest) returns (CreateAccountResponse); rpc Authenticate(AuthenticateRequest) returns (AuthenticateResponse); diff --git a/protos/account/v1/tenant_capacity_admission.proto b/protos/account/v1/tenant_capacity_admission.proto index 973bb17cc1..8370c65e42 100644 --- a/protos/account/v1/tenant_capacity_admission.proto +++ b/protos/account/v1/tenant_capacity_admission.proto @@ -65,6 +65,28 @@ message TenantCapacityAdmissionCommitment { repeated string snapshot_identity = 11; repeated string evaluation_identity = 12; } +message TenantCapacityAdmissionRefusal { + enum Code { + CODE_UNSPECIFIED = 0; + TENANT_BILLING_BLOCKED = 1; + CAPACITY_QUOTA_EXCEEDED = 2; + CAPACITY_EVALUATION_EXPIRED = 3; + } + repeated string tenant_id = 1; + repeated string request_id = 2; + repeated string admission_id = 3; + repeated string admission_attempt_id = 4; + repeated int64 capacity_rearm_fence = 5; + repeated string mutation_digest = 6; + repeated string snapshot_identity = 7; + repeated string evaluation_identity = 8; + repeated Code code = 9; + // Exactly one receipt is required for CAPACITY_QUOTA_EXCEEDED and CAPACITY_EVALUATION_EXPIRED. + // It must be absent for TENANT_BILLING_BLOCKED. + repeated string durable_denial_id = 10; +} +// Exactly one commitment or one produced domain refusal. Transport/pre-domain failure is non-OK. message CommitTenantCapacityAdmissionResponse { repeated TenantCapacityAdmissionCommitment commitment = 1; + repeated TenantCapacityAdmissionRefusal refusal = 2; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityOriginDecisionRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityOriginDecisionRepository.java new file mode 100644 index 0000000000..8b246befcf --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityOriginDecisionRepository.java @@ -0,0 +1,164 @@ +package net.firedevops.firemud.accountservice.repository; + +import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.conflict; +import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.transaction; +import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.unavailable; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Refusal; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Immutable Account decision; unique-key arbitration also excludes caller/account aliases. */ +@SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "Private transaction collaborator.") +public final class AccountCapacityOriginDecisionRepository { + private final DSLContext dsl; + + public AccountCapacityOriginDecisionRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + /** Read only. Missing row is not a refusal. */ + public Record find(Request request) { + transaction(); + return findExact(request); + } + + private Record findExact(Request request) { + Record row = findRow(request); + if (row != null) requireExact(request, row, CapacityAdmissionDigest.preimage(request)); + return row; + } + + /** + * Must commit atomically with reservation creation/rearm, otherwise the transaction rolls back. + */ + public void accept(Request request) { + retain(request, "ACCEPTED", null); + } + + /** Replays an exact durable refusal before any mutable eligibility check. */ + public Refusal retainedAdmissionDenial(Request request) { + return admissionDenial(find(request)); + } + + /** Historical recovery SELECT, never part of the mutation transaction. */ + public Refusal readRetainedAdmissionDenial(Request request) { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) throw unavailable(); + return admissionDenial(findExact(request)); + } + + private static Refusal admissionDenial(Record row) { + if (row == null) return null; + if (!"NO_ACCEPT".equals(row.get("decision", String.class))) throw conflict(); + String code = row.get("refusal_code", String.class); + if (Failure.CAPACITY_QUOTA_EXCEEDED.name().equals(code)) + return new Refusal(Failure.CAPACITY_QUOTA_EXCEEDED, row.get("decision_id", UUID.class)); + if (Failure.CAPACITY_EVALUATION_EXPIRED.name().equals(code)) + return new Refusal(Failure.CAPACITY_EVALUATION_EXPIRED, row.get("decision_id", UUID.class)); + throw conflict(); + } + + /** Caller proved the typed refusal in the owning transaction before any reservation mutation. */ + public Refusal refuse(Request request, Failure cause) { + if (!cause.supportsDurableDenial()) throw new IllegalArgumentException("Invalid denial cause"); + return admissionDenial(retain(request, "NO_ACCEPT", cause.name())); + } + + private Record retain(Request request, String decision, String refusalCode) { + transaction(); + byte[] canonicalPayload = CapacityAdmissionDigest.preimage(request); + Record existing = find(request, canonicalPayload); + if (existing != null) return requireOutcome(existing, decision, refusalCode); + requireFreshAttemptBinding(request, canonicalPayload); + int inserted = + 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, refusal_code, evaluation_identity) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING", + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + request.capacityRearmFence(), + request.admissionAttemptId(), + request.mutationDigest(), + canonicalPayload, + decision, + UUID.randomUUID(), + refusalCode, + "ACCEPTED".equals(decision) ? request.evidence().evaluationIdentity() : null); + if (inserted != 0 && inserted != 1) throw unavailable(); + Record row = find(request, canonicalPayload); + if (row == null) { + requireFreshAttemptBinding(request, canonicalPayload); + throw unavailable(); + } + return requireOutcome(row, decision, refusalCode); + } + + /** SERIALIZABLE caller: include pre-origin reservations and retained rearm history. */ + public void requireFreshAttemptBinding(Request request) { + requireFreshAttemptBinding(request, CapacityAdmissionDigest.preimage(request)); + } + + private void requireFreshAttemptBinding(Request request, byte[] canonicalPayload) { + Record conflict = + dsl.fetchOne( + "SELECT 1 FROM (" + + "SELECT tenant_uuid, request_id, admission_id, capacity_rearm_fence, admission_attempt_id, mutation_digest, canonical_payload FROM account_capacity_origin_decisions " + + "UNION ALL SELECT tenant_uuid, request_id, admission_id, capacity_rearm_fence, admission_attempt_id, mutation_digest, canonical_payload FROM account_tenant_capacity_reservations " + + "UNION ALL SELECT tenant_uuid, request_id, admission_id, capacity_rearm_fence, admission_attempt_id, mutation_digest, canonical_payload FROM account_tenant_capacity_attempt_history" + + ") retained_attempt WHERE admission_attempt_id = ? AND (tenant_uuid <> ? OR request_id <> ? OR admission_id <> ? OR capacity_rearm_fence <> ? OR mutation_digest <> ? OR canonical_payload <> ?) LIMIT 1", + request.admissionAttemptId(), + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + request.capacityRearmFence(), + request.mutationDigest(), + canonicalPayload); + if (conflict != null) throw conflict(); + } + + private Record find(Request request, byte[] canonicalPayload) { + Record row = findRow(request); + if (row != null) requireExact(request, row, canonicalPayload); + return row; + } + + private Record findRow(Request request) { + return dsl.fetchOne( + "SELECT * FROM account_capacity_origin_decisions WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND capacity_rearm_fence = ?", + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + request.capacityRearmFence()); + } + + private static Record requireOutcome(Record row, String decision, String refusalCode) { + if (!decision.equals(row.get("decision", String.class)) + || !Objects.equals(refusalCode, row.get("refusal_code", String.class))) { + throw conflict(); + } + return row; + } + + private static void requireExact(Request request, Record row, byte[] canonicalPayload) { + String decision = row.get("decision", String.class); + if (!request.admissionAttemptId().equals(row.get("admission_attempt_id", UUID.class)) + || !request.mutationDigest().equals(row.get("mutation_digest", String.class)) + || !Arrays.equals(canonicalPayload, row.get("canonical_payload", byte[].class)) + || row.get("decision_id", UUID.class) == null + || !("NO_ACCEPT".equals(decision) + || ("ACCEPTED".equals(decision) + && request + .evidence() + .evaluationIdentity() + .equals(row.get("evaluation_identity", String.class))))) throw conflict(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityRefusalBudgetRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityRefusalBudgetRepository.java new file mode 100644 index 0000000000..24a70d9575 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityRefusalBudgetRepository.java @@ -0,0 +1,83 @@ +package net.firedevops.firemud.accountservice.repository; + +import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.conflict; +import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.transaction; +import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.unavailable; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; +import org.jooq.DSLContext; + +/** Explicit Account-local provisioning only. No bean, RPC, automatic seed or budget reset. */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Private owner transaction collaborator.") +public final class AccountCapacityRefusalBudgetRepository { + private final DSLContext dsl; + + public AccountCapacityRefusalBudgetRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + /** + * Install an explicitly sized lifetime limit for a known canonical tenant. Exact retries preserve + * the row; a different limit is a conflict, never an increase, reset or replacement. The caller + * owns the writable transaction and must commit before enabling any admission producer. + */ + public void provision(UUID tenantId, int maximumRefusals) { + validate(tenantId, maximumRefusals); + transaction(); + int inserted = + dsl.execute( + "INSERT INTO account_capacity_origin_refusal_budget (tenant_uuid,maximum_refusals) VALUES (?,?) ON CONFLICT (tenant_uuid) DO NOTHING", + tenantId, + maximumRefusals); + if (inserted != 0 && inserted != 1) throw unavailable(); + var row = + dsl.fetchOne( + "SELECT maximum_refusals FROM account_capacity_origin_refusal_budget WHERE tenant_uuid=? FOR SHARE", + tenantId); + if (row == null) throw unavailable(); + if (!Integer.valueOf(maximumRefusals).equals(row.get(0, Integer.class))) throw conflict(); + } + + /** + * Fail closed unless the exact installed policy has room for the stated bounded admission cohort. + * This is a transaction-local readiness observation, not a reservation or admission + * authorization. Callers must exclude admission writers while checking startup readiness. The + * existing SQL trigger remains authoritative for every refusal and serializes competing runtime + * writers. + */ + public long requireReady(UUID tenantId, int maximumRefusals, int requiredHeadroom) { + validate(tenantId, maximumRefusals); + if (requiredHeadroom < 1 || requiredHeadroom > maximumRefusals) + throw new IllegalArgumentException("Positive headroom within the explicit limit required"); + transaction(); + var row = + dsl.fetchOne( + "SELECT maximum_refusals FROM account_capacity_origin_refusal_budget WHERE tenant_uuid=? FOR SHARE", + tenantId); + if (row == null) throw unavailable(); + if (!Integer.valueOf(maximumRefusals).equals(row.get(0, Integer.class))) throw conflict(); + var lastSlot = + dsl.fetchOne( + "SELECT slot FROM account_capacity_origin_refusal_slots WHERE tenant_uuid = ? ORDER BY slot DESC LIMIT 1", + tenantId); + // Each retained refusal consumes one immutable slot in the tenant's contiguous sequence. + // The indexed highest slot is therefore the retained refusal count without scanning origins. + Long highestSlot = lastSlot == null ? Long.valueOf(0L) : lastSlot.get("slot", Long.class); + if (highestSlot == null || highestSlot < 0 || highestSlot > maximumRefusals) + throw unavailable(); + long remaining = maximumRefusals - highestSlot; + if (remaining < requiredHeadroom) throw unavailable(); + return remaining; + } + + private static void validate(UUID tenantId, int maximumRefusals) { + TenantCapacityAdmission.uuid(tenantId); + if (maximumRefusals < 1) + throw new IllegalArgumentException("Explicit finite refusal limit required"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java index 7ce2183cc4..ff689c6020 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java @@ -601,8 +601,6 @@ public CommittedCandidateVerificationData readCurrentCommittedCandidate(UUID req if (!requestDigest(exactIntent).equals(identity.requestDigest())) { throw new IdempotencyConflictException(); } - requireUnexpired(identity); - AccountAuthEvidenceBundle bundle; try { bundle = evidenceBundles.readStoredNonAuthorizingValue(operationId); @@ -634,25 +632,28 @@ public CommittedCandidateVerificationData readCurrentCommittedCandidate(UUID req case "EXACT_RETRY" -> PendingRegistrationOutcome.EXACT_RETRY; default -> throw new StorageUnavailableException(); }; - - return new CommittedCandidateVerificationData( - identity, - authority, - evidenceBundleReference(bundle), - candidate.tokenHash(), - candidate.kid(), - candidate.signerGeneration(), - sha256(candidate.canonicalRecordBytes()), - proofSha256, - correspondence, - envelope.keyId(), - envelope.sha256(), - envelope.length(), - envelope.expiryMillis(), - registryExpiryMillis, - registrationLocalAofCount, - registrationReplicaAofCount, - registrationOutcome); + var verified = + new CommittedCandidateVerificationData( + identity, + authority, + evidenceBundleReference(bundle), + candidate.tokenHash(), + candidate.kid(), + candidate.signerGeneration(), + sha256(candidate.canonicalRecordBytes()), + proofSha256, + correspondence, + envelope.keyId(), + envelope.sha256(), + envelope.length(), + envelope.expiryMillis(), + registryExpiryMillis, + registrationLocalAofCount, + registrationReplicaAofCount, + registrationOutcome); + // Report elapsed time only after validating the exact retained issuance. + requireUnexpired(verified); + return verified; } /** @@ -660,7 +661,9 @@ public CommittedCandidateVerificationData readCurrentCommittedCandidate(UUID req * runs the same full current-authority/commit-proof read used by the issuance owner. The JTI is a * lookup hint, never authentication or permission by itself. */ - @Transactional(propagation = Propagation.MANDATORY) + @Transactional( + propagation = Propagation.MANDATORY, + noRollbackFor = CommittedCandidateExpiredException.class) public java.util.Optional readCurrentCommittedCandidateByJti( UUID tokenJti) { requireWritableAccountTransaction(); @@ -682,24 +685,38 @@ public java.util.Optional readCurrentCommitt if (requestId == null || requestId.equals(new UUID(0L, 0L))) { throw new StorageUnavailableException(); } - CommittedCandidateVerificationData current = readCurrentCommittedCandidate(requestId); + CommittedCandidateVerificationData current; + try { + current = readCurrentCommittedCandidate(requestId); + } catch (CommittedCandidateExpiredException expired) { + requireExactCandidateLookup(expired.verifiedCandidate(), requestId, tokenJti); + throw expired; + } + requireExactCandidateLookup(current, requestId, tokenJti); + return java.util.Optional.of(current); + } + + private static void requireExactCandidateLookup( + CommittedCandidateVerificationData current, UUID requestId, UUID tokenJti) { if (current == null || !requestId.equals(current.identity().requestId()) || !tokenJti.equals(current.identity().tokenJti())) { throw new StorageUnavailableException(); } - return java.util.Optional.of(current); } - private void requireUnexpired(AccountGameplayDelegationPendingIdentity identity) { + private void requireUnexpired(CommittedCandidateVerificationData candidate) { + var identity = candidate.identity(); long now = Math.floorDiv(clock.millis(), 1_000L); long latestIssuedAt = now > Long.MAX_VALUE - 5L ? Long.MAX_VALUE : now + 5L; if (now <= 0L || identity.notBeforeEpochSecond() > now - || identity.issuedAtEpochSecond() > latestIssuedAt - || identity.expiresAtEpochSecond() <= now) { + || identity.issuedAtEpochSecond() > latestIssuedAt) { throw new StorageUnavailableException(); } + if (identity.expiresAtEpochSecond() <= now) { + throw new CommittedCandidateExpiredException(candidate); + } } private static void requireCommittedProofIdentity( @@ -2550,6 +2567,19 @@ public StorageUnavailableException() { } } + public static final class CommittedCandidateExpiredException extends StorageUnavailableException { + private final transient CommittedCandidateVerificationData verifiedCandidate; + + public CommittedCandidateExpiredException( + CommittedCandidateVerificationData verifiedCandidate) { + this.verifiedCandidate = Objects.requireNonNull(verifiedCandidate); + } + + public CommittedCandidateVerificationData verifiedCandidate() { + return verifiedCandidate; + } + } + public static final class StaleAuthorityException extends IllegalStateException { public StaleAuthorityException() { super("Account gameplay delegation authority changed"); 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 9fdb6c982d..d869ba9c67 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,16 +1,16 @@ 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; -import java.time.temporal.ChronoUnit; import java.util.Arrays; import java.util.Objects; +import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Evidence; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Identity; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; @@ -82,6 +82,37 @@ public void requireRetained(Evidence evidence) { .equals(time(row, "expires_at"))) throw unavailable(); } + /** + * PostgreSQL time alone decides the retained evaluation lifetime, from one clock sample. An + * evaluation that has not started on that clock is stale. + */ + public boolean retainedEvaluationExpired(Evidence evidence) { + return lifetime(evidence, null).evaluationExpired(); + } + + /** + * One PostgreSQL clock sample for the evaluation lifetime and, when given, the qualified + * connect-scope expiry, so both are judged on the same clock. + */ + public Lifetime lifetime(Evidence evidence, Instant scopeExpiresAt) { + transaction(); + Record observation = + dsl.fetchOne( + "SELECT observed < ?::timestamptz AS early, observed >= ?::timestamptz AS expired, observed >= COALESCE(?::timestamptz, 'infinity'::timestamptz) AS scope_elapsed FROM (SELECT clock_timestamp() AS observed) sample", + at(evidence.evaluatedAt()), + at(evidence.expiresAt()), + scopeExpiresAt == null ? null : at(scopeExpiresAt)); + if (observation == null) throw unavailable(); + Boolean early = observation.get("early", Boolean.class); + Boolean expired = observation.get("expired", Boolean.class); + Boolean scopeElapsed = observation.get("scope_elapsed", Boolean.class); + if (early == null || expired == null || scopeElapsed == null) throw unavailable(); + if (early) throw new CapacityException(Failure.CAPACITY_ADMISSION_STALE); + return new Lifetime(expired, scopeElapsed); + } + + public record Lifetime(boolean evaluationExpired, boolean scopeElapsed) {} + public Record find(Identity id) { return find(id, FIND_RESERVATION + " FOR UPDATE"); } @@ -139,13 +170,13 @@ public void requirePriorHistory(Request prior, Request next) { || history.get("owner_readback", byte[].class) == null) throw conflict(); } - public Result create(Request request, Instant expiresAt, Clock clock) { - Record usage = usage(request); - requireCurrentLifetime(request.evidence(), clock.instant()); + /** The caller holds the usage lock; deferred validation rechecks the evaluation lifetime. */ + public Optional createWithLockedUsageIfQuotaAvailable( + Request request, Record usage, Instant expiresAt) { long delta = Objects.requireNonNull(request.capacityDelta()); long occupied = Math.addExact(number(usage, "held_units"), number(usage, "used_units")); - if (delta > request.evidence().quota() - occupied) - throw new CapacityException(Failure.CAPACITY_QUOTA_EXCEEDED); + if (delta > request.evidence().quota() - occupied) return Optional.empty(); + new AccountCapacityOriginDecisionRepository(dsl).accept(request); long held = Math.addExact(number(usage, "held_units"), delta); updateUsage(request, usage, held, number(usage, "used_units")); int created = @@ -168,15 +199,7 @@ public Result create(Request request, Instant expiresAt, Clock clock) { at(expiresAt), at(expiresAt.plusSeconds(60))); if (created != 1) throw unavailable(); - return exact(request, Objects.requireNonNull(find(request.identity()))); - } - - public static void requireCurrentLifetime(Evidence evidence, Instant now) { - // PostgreSQL stores microseconds. Floor the bound, never round an expiry forward. - if (now.isBefore(evidence.evaluatedAt()) - || !now.isBefore(evidence.expiresAt().truncatedTo(ChronoUnit.MICROS))) { - throw new CapacityException(Failure.CAPACITY_ADMISSION_STALE); - } + return Optional.of(exact(request, Objects.requireNonNull(find(request.identity())))); } public void updateUsage(Request request, Record before, long held, long used) { @@ -249,14 +272,30 @@ public static CapacityException unavailable() { public static final class CapacityException extends IllegalStateException { private final Failure code; + private final UUID durableDenialId; public CapacityException(Failure code) { super(code.name()); + if (code.supportsDurableDenial()) + throw new IllegalArgumentException("This refusal requires a durable denial"); + this.code = code; + this.durableDenialId = null; + } + + public CapacityException(Failure code, UUID durableDenialId) { + super(code.name()); + if (!code.supportsDurableDenial()) + throw new IllegalArgumentException("This refusal cannot carry a durable denial"); this.code = code; + this.durableDenialId = TenantCapacityAdmission.uuid(durableDenialId); } public Failure code() { return code; } + + public UUID durableDenialId() { + return durableDenialId; + } } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuard.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuard.java index 88e1694a6f..4dfd2f50dc 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuard.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuard.java @@ -8,24 +8,30 @@ import io.grpc.ServerCallHandler; import io.grpc.ServerInterceptor; import io.grpc.Status; +import java.util.Objects; import java.util.Set; import net.firedevops.firemud.account.v1.AccountServiceGrpc; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Owner; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; /** Sole producer of the receiver's private exact-method TLS caller assertion. */ public final class AccountTenantCapacityWorkloadGuard implements ServerInterceptor { private final Context.Key caller = Context.key("tenant-capacity-authenticated-peer"); + private final Context.Key admissionDenialReader = + Context.key("tenant-capacity-denial-reader"); + private final String gameSession; private final Set allowed; public AccountTenantCapacityWorkloadGuard(String namespace) { if (!GrpcPeerIdentity.isValidNamespace(namespace)) throw new IllegalArgumentException("Namespace required"); + gameSession = TenantCapacityAdmission.expectedWorkload(namespace, Owner.GAME_SESSION); allowed = Set.of( - TenantCapacityAdmission.expectedWorkload(namespace, Owner.GAME_SESSION), + gameSession, TenantCapacityAdmission.expectedWorkload(namespace, Owner.WORLD_MANAGEMENT)); } @@ -36,20 +42,36 @@ public String requireAuthenticatedCaller() { return value; } + public String requireAdmissionDenialReader() { + String value = admissionDenialReader.get(); + if (!gameSession.equals(value) || ambient()) throw Status.UNAUTHENTICATED.asRuntimeException(); + return value; + } + @Override public ServerCall.Listener interceptCall( ServerCall call, Metadata headers, ServerCallHandler next) { var peer = GrpcPeerIdentity.fromSslSession(call.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION)); - if (peer.isEmpty()) return deny(call, Status.UNAUTHENTICATED); - if (ambient() - || !allowed.contains(peer.orElseThrow().uri()) - || !AccountServiceGrpc.getCommitTenantCapacityAdmissionMethod() + if (peer.isEmpty()) return deny(call, Failure.AUTH_UNAVAILABLE); + if (ambient()) return deny(call, Failure.PERMISSION_DENIED); + String method = call.getMethodDescriptor().getFullMethodName(); + String workload = peer.orElseThrow().uri(); + if (AccountServiceGrpc.getCommitTenantCapacityAdmissionMethod() + .getFullMethodName() + .equals(method) + && allowed.contains(workload)) { + return Contexts.interceptCall( + Context.current().withValue(caller, workload), call, headers, next); + } + if (AccountServiceGrpc.getReadTenantCapacityAdmissionDenialMethod() .getFullMethodName() - .equals(call.getMethodDescriptor().getFullMethodName())) - return deny(call, Status.PERMISSION_DENIED); - return Contexts.interceptCall( - Context.current().withValue(caller, peer.orElseThrow().uri()), call, headers, next); + .equals(method) + && gameSession.equals(workload)) { + return Contexts.interceptCall( + Context.current().withValue(admissionDenialReader, workload), call, headers, next); + } + return deny(call, Failure.PERMISSION_DENIED); } private static boolean ambient() { @@ -60,10 +82,10 @@ private static boolean ambient() { } private static ServerCall.Listener deny( - ServerCall call, Status status) { - call.close( - status.withDescription("Exact capacity owner workload and method required"), - new Metadata()); + ServerCall call, Failure failure) { + // Close with the bounded capacity detail; the RPC is never dispatched. + var denied = failure.toStatusException(); + call.close(denied.getStatus(), Objects.requireNonNull(denied.getTrailers())); return new ServerCall.Listener<>() {}; } } 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 f03de073f0..b8ef376065 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; @@ -20,18 +19,24 @@ import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import net.firedevops.firemud.accountservice.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountCapacityOriginDecisionRepository; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateExpiredException; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.CapacityException; import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Evidence; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Owner; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.PlayerContext; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Refusal; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import org.jooq.DSLContext; import org.jooq.Record; @@ -55,6 +60,7 @@ public final class AccountTenantCapacityOwner { private static final int TRANSACTION_TIMEOUT_SECONDS = 5; private static final int MAX_SERIALIZATION_ATTEMPTS = 4; private static final long INITIAL_RETRY_DELAY_MILLIS = 5; + private static final String DEFERRED_EVALUATION_EXPIRED_SQLSTATE = "P1040"; private final DSLContext dsl; private final AccountRepository accounts; @@ -62,7 +68,9 @@ public final class AccountTenantCapacityOwner { private final AccountGameplayDelegationIssuanceRepository issuances; private final AccountConnectScopeRepository scopes; private final AccountTenantCapacityRepository capacity; + private final AccountCapacityOriginDecisionRepository originDecisions; private final TransactionTemplate transaction; + private final TransactionTemplate denialReadTransaction; private final Clock clock; private final String namespace; @@ -81,6 +89,7 @@ public AccountTenantCapacityOwner( this.issuances = Objects.requireNonNull(issuances); this.scopes = Objects.requireNonNull(scopes); this.capacity = new AccountTenantCapacityRepository(dsl); + this.originDecisions = new AccountCapacityOriginDecisionRepository(dsl); this.clock = Objects.requireNonNull(clock); if (!GrpcPeerIdentity.isValidNamespace(namespace)) throw new IllegalArgumentException("Namespace required"); @@ -89,27 +98,119 @@ public AccountTenantCapacityOwner( transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); transaction.setTimeout(TRANSACTION_TIMEOUT_SECONDS); + denialReadTransaction = new TransactionTemplate(transactions); + denialReadTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + denialReadTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + denialReadTransaction.setReadOnly(true); + denialReadTransaction.setTimeout(TRANSACTION_TIMEOUT_SECONDS); + } + + /** Reads an exact historical admission refusal without mutating the original attempt. */ + public Refusal readRetainedAdmissionDenial(Request request, String authenticatedCaller) { + requireCaller(request, authenticatedCaller); + if (!TenantCapacityAdmission.expectedWorkload(namespace, Owner.GAME_SESSION) + .equals(authenticatedCaller)) throw new CapacityException(Failure.PERMISSION_DENIED); + request.requireStructurallyValid(); + requireSupportedShape(request); + if (request.capacityRearmFence() != 1 || !request.evidence().permitsCreation()) + throw unavailable(); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive() + || Context.current().isCancelled()) throw unavailable(); + try { + Refusal denial = + denialReadTransaction.execute(status -> { + if (Context.current().isCancelled()) throw unavailable(); + dsl.connection(connection -> { + if (connection.getAutoCommit() || !connection.isReadOnly()) throw unavailable(); + }); + return originDecisions.readRetainedAdmissionDenial(request); + }); + if (denial == null) throw unavailable(); + return denial; + } catch (CapacityException failure) { + // A different original or decision is not settlement evidence on this read. + if (failure.code() == Failure.IDEMPOTENCY_CONFLICT) throw unavailable(); + throw failure; + } catch (IllegalArgumentException invalidEvidence) { + throw unavailable(); + } } public Result commit(Request request, String authenticatedCaller) { requireCaller(request, authenticatedCaller); request.requireStructurallyValid(); if (!(request.context() instanceof PlayerContext)) throw unavailable(); - return commitWithFreshSnapshot(() -> { - // Exact replay/conflict can linearize at the snapshot read without taking a mutation - // lock. - Record existing = capacity.findForReplay(request.identity()); - if (existing != null) return capacity.exact(request, existing); - lockPlayerAccount(request); - if (request.capacityRearmFence() != 1) throw conflict(); - current(request); - requireSupportedShape(request); - if (!request.evidence().permitsCreation()) - throw new CapacityException(Failure.TENANT_BILLING_BLOCKED); - return capacity.create(request, request.evidence().expiresAt(), clock); - }); + CommitDecision decision = + commitWithFreshSnapshot(() -> { + // Replay precedes current sources and quota. A lost refusal response retains its + // original decision even if capacity becomes available before the caller retries. + Record existing = capacity.findForReplay(request.identity()); + if (existing != null) { + return new CommitDecision(capacity.exact(request, existing), null); + } + if (request.capacityRearmFence() != 1) throw conflict(); + Refusal retainedDenial = originDecisions.retainedAdmissionDenial(request); + if (retainedDenial != null) return new CommitDecision(null, retainedDenial); + originDecisions.requireFreshAttemptBinding(request); + lockPlayerAccount(request); + var evidence = request.evidence(); + capacity.requireRetained(evidence); + var parsed = currentMembership(request); + requireSupportedShape(request); + // PostgreSQL time alone decides the evaluation lifetime, in two checks: once before + // live source qualification, and once at the decision point after the last wait. + // Deferred validation repeats it at commit for a reservation. + if (capacity.retainedEvaluationExpired(evidence)) { + // An already elapsed original can only commit a denial. It binds the exact + // retained evaluation and membership without renewing delegation or scope. + if (!evidence.permitsCreation()) + throw new CapacityException(Failure.CAPACITY_ADMISSION_STALE); + return refuseExpired(request); + } + // An exact delegation or connect scope that elapses during qualification is accepted + // only as part of an expiry denial; missing or changed sources stay unavailable. The + // scope expiry is judged on the same PostgreSQL sample as the evaluation. + boolean delegationElapsed = false; + try { + currentDelegation(request, clock.instant()); + } catch (CommittedCandidateExpiredException elapsed) { + delegationElapsed = true; + } + Instant scopeExpiresAt = exactScopeExpiry(request, parsed); + if (!evidence.permitsCreation()) { + var lifetime = capacity.lifetime(evidence, scopeExpiresAt); + // Expiry decides first, as on the creating path; an exact source that elapsed with + // it does not turn a stale evaluation into a source failure. + if (lifetime.evaluationExpired()) + throw new CapacityException(Failure.CAPACITY_ADMISSION_STALE); + if (delegationElapsed || lifetime.scopeElapsed()) throw unavailable(); + throw new CapacityException(Failure.TENANT_BILLING_BLOCKED); + } + Record usage = capacity.usage(request); + var lifetime = capacity.lifetime(evidence, scopeExpiresAt); + boolean expired = lifetime.evaluationExpired(); + if ((delegationElapsed || lifetime.scopeElapsed()) && !expired) throw unavailable(); + if (expired) return refuseExpired(request); + var reservation = + capacity.createWithLockedUsageIfQuotaAvailable(request, usage, evidence.expiresAt()); + if (reservation.isPresent()) return new CommitDecision(reservation.orElseThrow(), null); + return new CommitDecision( + null, originDecisions.refuse(request, Failure.CAPACITY_QUOTA_EXCEEDED)); + }); + // Throw only after the transaction has committed the exact denial. + if (decision.denial() != null) + throw new CapacityException(decision.denial().code(), decision.denial().durableDenialId()); + return decision.reservation(); } + private CommitDecision refuseExpired(Request request) { + 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. */ Result rearm(Request prior, Request next, UUID recoveryOwner, long claimFence) { prior.requireCommittable(); @@ -125,7 +226,7 @@ Result rearm(Request prior, Request next, UUID recoveryOwner, long claimFence) { || !Objects.equals( prior.evidence().fields().get("authorityTuple"), next.evidence().fields().get("authorityTuple"))) throw conflict(); - return inTransaction(() -> { + return commitWithFreshSnapshot(() -> { lockPlayerAccount(next); Record row = capacity.find(prior.identity()); if (row == null) throw conflict(); @@ -138,9 +239,30 @@ 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(); - current(next); + capacity.requireRetained(next.evidence()); + // Expired evidence is stale before live sources are read; the deferred guard rechecks + // PostgreSQL time at commit. + if (capacity.retainedEvaluationExpired(next.evidence())) + throw new CapacityException(Failure.CAPACITY_ADMISSION_STALE); + var parsed = currentMembership(next); + boolean delegationElapsed = false; + try { + currentDelegation(next, clock.instant()); + } catch (CommittedCandidateExpiredException elapsed) { + delegationElapsed = true; + } + Instant scopeExpiresAt = exactScopeExpiry(next, parsed); requireSupportedShape(next); - requireCurrentLifetime(next.evidence(), clock.instant()); + // Match the fresh reservation/refusal path before arbitrating the attempt UUID. + capacity.usage(next); + // Same decision-point order as commit: expiry first, then an elapsed exact source. The + // deferred guard rechecks the evaluation at commit. + var lifetime = capacity.lifetime(next.evidence(), scopeExpiresAt); + if (lifetime.evaluationExpired()) + throw new CapacityException(Failure.CAPACITY_ADMISSION_STALE); + if (delegationElapsed || lifetime.scopeElapsed()) throw unavailable(); + originDecisions.accept(next); + requireClaim(row, recoveryOwner, claimFence, clock.instant()); int history = dsl.execute( "INSERT INTO account_tenant_capacity_attempt_history " @@ -154,10 +276,11 @@ Result rearm(Request prior, Request next, UUID recoveryOwner, long claimFence) { CapacityAdmissionDigest.preimage(prior), row.get("owner_readback", byte[].class)); if (history != 1) throw unavailable(); + requireClaim(row, recoveryOwner, claimFence, clock.instant()); int changed = dsl.execute( "UPDATE account_tenant_capacity_reservations SET admission_attempt_id = ?, capacity_rearm_fence = ?, reservation_fence = ?, mutation_digest = ?, canonical_payload = ?, evaluation_identity = ?, expires_at = ?::timestamptz, reconcile_deadline = ?::timestamptz, next_reconcile_at = NULL, recovery_attempt_count = 0, execution_status = 'OWNER_EXECUTION_PENDING', owner_readback = NULL, owner_readback_digest = NULL " - + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND admission_attempt_id = ? AND capacity_rearm_fence = ? AND mutation_digest = ? AND recovery_owner = ? AND recovery_claim_fence = ? AND state = 'RESERVED' AND execution_status = 'NOT_EXECUTED_AFTER_AUTHORIZATION'", + + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND admission_attempt_id = ? AND capacity_rearm_fence = ? AND mutation_digest = ? AND recovery_owner = ? AND recovery_claim_fence = ? AND state = 'RESERVED' AND execution_status = 'NOT_EXECUTED_AFTER_AUTHORIZATION' AND recovery_claim_expires_at > clock_timestamp()", next.admissionAttemptId(), next.capacityRearmFence(), Math.incrementExact(number(row, "reservation_fence")), @@ -180,20 +303,14 @@ Result rearm(Request prior, Request next, UUID recoveryOwner, long claimFence) { }); } - private void current(Request request) { + private RuntimePlayerAdmissionEntitlementEvidence currentMembership(Request request) { var evidence = request.evidence(); - capacity.requireRetained(evidence); - Instant now = clock.instant(); - requireCurrentLifetime(evidence, now); if (!(request.context() instanceof PlayerContext player)) throw unavailable(); var parsed = RuntimePlayerAdmissionEntitlementEvidence.parseCanonical( request.evidence().canonicalBytes()); var current = qualifiedSource(() -> memberships.readCurrent(player.accountId(), player.tenantId())); - if (!current.membershipExists() - || !current.gameplayAdmissionAllowed() - || !"ACTIVE".equals(current.membershipLifecycleState())) throw unavailable(); var fields = evidence.fields(); if (!current.equals(parsed.membershipSource())) { var billing = @@ -207,23 +324,56 @@ private void current(Request request) { throw new CapacityException(Failure.CAPACITY_ADMISSION_STALE); throw unavailable(); } - if (!(fields.get("sourceReferences") instanceof Map source)) throw unavailable(); - var issuance = - qualifiedSource(() -> - issuances.readCurrentCommittedCandidateByJti( - UUID.fromString((String) source.get("callerTokenJti")))) - .orElseThrow(AccountTenantCapacityRepository::unavailable); + if (evidence.permitsCreation() + && (!current.membershipExists() + || !current.gameplayAdmissionAllowed() + || !"ACTIVE".equals(current.membershipLifecycleState()))) throw unavailable(); + return parsed; + } + + private void currentDelegation(Request request, Instant now) { + var source = sourceReferences(request.evidence()); + var tokenJti = UUID.fromString((String) source.get("callerTokenJti")); + CommittedCandidateVerificationData issuance; + try { + issuance = + qualifiedSource(() -> issuances.readCurrentCommittedCandidateByJti(tokenJti)) + .orElseThrow(AccountTenantCapacityRepository::unavailable); + } catch (CommittedCandidateExpiredException expired) { + requireExactDelegation(request, source, tokenJti, expired.verifiedCandidate()); + throw expired; + } + requireExactDelegation(request, source, tokenJti, issuance); + if (now.getEpochSecond() < issuance.identity().notBeforeEpochSecond() + || now.getEpochSecond() >= issuance.identity().expiresAtEpochSecond()) throw unavailable(); + } + + private static void requireExactDelegation( + Request request, + Map source, + UUID tokenJti, + CommittedCandidateVerificationData issuance) { + if (!(request.context() instanceof PlayerContext player)) throw unavailable(); if (!issuance.identity().accountId().equals(player.accountId()) || !issuance.identity().callerWorkload().equals(request.evidence().callerWorkload()) || !issuance.identity().callerContextId().toString().equals(source.get("callerContextId")) || !issuance.identity().operationId().toString().equals(source.get("callerOperationId")) + || !issuance.identity().tokenJti().equals(tokenJti) + || !Instant.ofEpochSecond(issuance.identity().expiresAtEpochSecond()) + .equals(Instant.parse((String) source.get("callerTokenExpiresAt"))) || !issuance.tokenSha256().equals(source.get("callerTokenSha256")) || !issuance .canonicalRegistryRecordSha256() .equals(source.get("callerRegistryRecordSha256")) - || !issuance.commitProofSha256().equals(source.get("callerCommitProofSha256")) - || now.getEpochSecond() < issuance.identity().notBeforeEpochSecond() - || now.getEpochSecond() >= issuance.identity().expiresAtEpochSecond()) throw unavailable(); + || !issuance.commitProofSha256().equals(source.get("callerCommitProofSha256"))) + throw unavailable(); + } + + /** Requires the exact retained connect scope and returns its expiry. */ + private Instant exactScopeExpiry( + Request request, RuntimePlayerAdmissionEntitlementEvidence parsed) { + if (!(request.context() instanceof PlayerContext player)) throw unavailable(); + var source = sourceReferences(request.evidence()); var scope = qualifiedSource(() -> scopes.findCanonicalEvidenceByTokenHash(parsed.verifiedConnectScopeTokenHash())) @@ -234,13 +384,25 @@ private void current(Request request) { || !scope.gameInstanceUuid().equals(player.gameInstanceId()) || !scope.playableStateNamespaceUuid().equals(player.playableStateNamespaceId()) || !scope.realmId().equals(player.realmId()) - || !scope.playableStateScope().equals(player.playableStateScope()) - || !now.isBefore(Instant.parse(scope.connectScopeExpiresAt()))) throw unavailable(); + || !scope.playableStateScope().equals(player.playableStateScope())) throw unavailable(); + try { + return Instant.parse(scope.connectScopeExpiresAt()); + } catch (java.time.DateTimeException malformed) { + throw unavailable(); + } + } + + private static Map sourceReferences(Evidence evidence) { + if (!(evidence.fields().get("sourceReferences") instanceof Map source)) + throw unavailable(); + return source; } private static T qualifiedSource(Supplier read) { try { return read.get(); + } catch (CommittedCandidateExpiredException expired) { + throw expired; } catch (IllegalArgumentException | IllegalStateException unqualifiedSource) { throw unavailable(); } @@ -278,19 +440,30 @@ static void requireClaim(Record row, UUID owner, long fence, Instant now) { throw conflict(); } - private Result commitWithFreshSnapshot(Supplier action) { + private T commitWithFreshSnapshot(Supplier action) { Context caller = Context.current(); Deadline localDeadline = Deadline.after(TRANSACTION_TIMEOUT_SECONDS, TimeUnit.SECONDS); Deadline incoming = caller.getDeadline(); - Deadline retryDeadline = incoming == null ? localDeadline : localDeadline.minimum(incoming); + // Pick the sooner deadline without comparing their tickers. + Deadline retryDeadline = + incoming != null + && incoming.timeRemaining(TimeUnit.NANOSECONDS) + < localDeadline.timeRemaining(TimeUnit.NANOSECONDS) + ? incoming + : localDeadline; if (caller.isCancelled() || retryDeadline.isExpired()) throw unavailable(); for (int attempt = 1; ; attempt++) { try { - return inTransaction(() -> { - if (caller.isCancelled() || retryDeadline.isExpired()) throw unavailable(); - return action.get(); - }); + // Each attempt's database waits share the one retry budget. + return inTransaction( + () -> { + if (caller.isCancelled() || retryDeadline.isExpired()) throw unavailable(); + return action.get(); + }, + retryDeadline); } catch (RuntimeException failure) { + if (hasSqlState(failure, DEFERRED_EVALUATION_EXPIRED_SQLSTATE)) + throw new CapacityException(Failure.CAPACITY_ADMISSION_STALE); // A PostgreSQL serialization failure rolls back the whole transaction. Retry outside // that transaction so a concurrent original can become exact replay or conflict. if (attempt >= MAX_SERIALIZATION_ATTEMPTS @@ -317,25 +490,47 @@ private static boolean waitForFreshSnapshot(Context caller, Deadline deadline, i private static boolean serializationFailure(RuntimeException failure) { for (Throwable cause = failure; cause != null; cause = cause.getCause()) { - if (cause instanceof CannotSerializeTransactionException - || cause instanceof org.jooq.exception.DataAccessException jooq - && "40001".equals(jooq.sqlState()) - || cause instanceof SQLException sql && "40001".equals(sql.getSQLState())) return true; + if (cause instanceof CannotSerializeTransactionException) return true; + } + return hasSqlState(failure, "40001"); + } + + private static boolean hasSqlState(Throwable failure, String sqlState) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof org.jooq.exception.DataAccessException jooq + && sqlState.equals(jooq.sqlState()) + || cause instanceof SQLException sql && sqlState.equals(sql.getSQLState())) return true; } return false; } T inTransaction(Supplier action) { + return inTransaction(action, Deadline.after(TRANSACTION_TIMEOUT_SECONDS, TimeUnit.SECONDS)); + } + + private T inTransaction(Supplier action, Deadline budget) { if (TransactionSynchronizationManager.isActualTransactionActive() || TransactionSynchronizationManager.isSynchronizationActive()) throw unavailable(); + long remainingMillis = budget.timeRemaining(TimeUnit.MILLISECONDS); + if (remainingMillis <= 0) throw unavailable(); + var attempt = + new TransactionTemplate( + Objects.requireNonNull(transaction.getTransactionManager()), transaction); + // Spring times statements only in whole seconds, so it is a backstop; PostgreSQL bounds + // each statement by the remaining milliseconds. + attempt.setTimeout( + (int) Math.min(TRANSACTION_TIMEOUT_SECONDS, Math.ceilDiv(remainingMillis, 1000))); return Objects.requireNonNull( - transaction.execute(status -> { + attempt.execute(status -> { AccountTenantCapacityRepository.transaction(); dsl.connection(connection -> { if (connection.getAutoCommit() || connection.isReadOnly() || connection.getTransactionIsolation() != Connection.TRANSACTION_SERIALIZABLE) throw unavailable(); + try (var statement = connection.createStatement()) { + statement.execute("SET LOCAL statement_timeout = " + remainingMillis); + } }); return action.get(); })); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java index 22a326f5f3..67333aebbc 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java @@ -16,6 +16,7 @@ import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.CapacityException; import net.firedevops.firemud.accountservice.security.AccountTenantCapacityWorkloadGuard; import net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; @@ -66,7 +67,7 @@ public void commitTenantCapacityAdmission( Failure.ENTITLEMENT_UNAVAILABLE.toStatusException(Status.Code.FAILED_PRECONDITION)); return; } - final net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request request; + final Request request; try { request = TenantCapacityAdmissionGrpcCodec.parseRequest(wire); } catch (IllegalArgumentException | ArithmeticException invalid) { @@ -77,11 +78,86 @@ public void commitTenantCapacityAdmission( observer.onError(Failure.PERMISSION_DENIED.toStatusException()); return; } - final CommitTenantCapacityAdmissionResponse result; + CommitTenantCapacityAdmissionResponse result; try { result = TenantCapacityAdmissionGrpcCodec.toResponse(request, owner.commit(request, peer)); } catch (CapacityException denied) { - observer.onError(denied.code().toStatusException()); + if (!denied.code().isDomainRefusal()) { + observer.onError(denied.code().toStatusException()); + return; + } + try { + result = + TenantCapacityAdmissionGrpcCodec.toRefusal( + request, denied.code(), denied.durableDenialId()); + } catch (RuntimeException internal) { + observer.onError(Failure.INTERNAL.toStatusException()); + return; + } + } catch (org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException + | org.springframework.transaction.TransactionException unavailable) { + observer.onError(Failure.ENTITLEMENT_UNAVAILABLE.toStatusException()); + return; + } catch (RuntimeException internal) { + observer.onError(Failure.INTERNAL.toStatusException()); + return; + } + try { + observer.onNext(result); + } catch (RuntimeException callback) { + observer.onError(Failure.INTERNAL.toStatusException()); + return; + } + observer.onCompleted(); + } + + @Override + public void readTenantCapacityAdmissionDenial( + CommitTenantCapacityAdmissionRequest wire, + StreamObserver observer) { + Objects.requireNonNull(observer); + final String peer; + try { + peer = guard.requireAdmissionDenialReader(); + } catch (StatusRuntimeException denied) { + observer.onError(Failure.AUTH_UNAVAILABLE.toStatusException()); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + observer.onError( + Failure.ENTITLEMENT_UNAVAILABLE.toStatusException(Status.Code.FAILED_PRECONDITION)); + return; + } + final Request request; + try { + request = TenantCapacityAdmissionGrpcCodec.parseRequest(wire); + } catch (IllegalArgumentException | ArithmeticException invalid) { + observer.onError(Failure.INVALID_ARGUMENT.toStatusException()); + return; + } + if (!request.evidence().callerWorkload().equals(peer)) { + observer.onError(Failure.PERMISSION_DENIED.toStatusException()); + return; + } + final CommitTenantCapacityAdmissionResponse result; + try { + var denial = owner.readRetainedAdmissionDenial(request, peer); + if (denial == null || denial.durableDenialId() == null) { + observer.onError(Failure.ENTITLEMENT_UNAVAILABLE.toStatusException()); + return; + } + result = + TenantCapacityAdmissionGrpcCodec.toRefusal( + request, denial.code(), denial.durableDenialId()); + } catch (CapacityException denied) { + Failure code = + switch (denied.code()) { + case INVALID_ARGUMENT, PERMISSION_DENIED -> denied.code(); + default -> Failure.ENTITLEMENT_UNAVAILABLE; + }; + observer.onError(code.toStatusException()); return; } catch (org.jooq.exception.DataAccessException | org.springframework.dao.DataAccessException @@ -89,14 +165,15 @@ public void commitTenantCapacityAdmission( observer.onError(Failure.ENTITLEMENT_UNAVAILABLE.toStatusException()); return; } catch (RuntimeException internal) { - observer.onError(Status.INTERNAL.asRuntimeException()); + observer.onError(Failure.INTERNAL.toStatusException()); return; } try { observer.onNext(result); - observer.onCompleted(); } catch (RuntimeException callback) { - observer.onError(Status.INTERNAL.asRuntimeException()); + observer.onError(Failure.INTERNAL.toStatusException()); + return; } + observer.onCompleted(); } } diff --git a/services/account-service/src/main/resources/db/migration/V1040.1__account_capacity_origin_decisions.sql b/services/account-service/src/main/resources/db/migration/V1040.1__account_capacity_origin_decisions.sql new file mode 100644 index 0000000000..ec57045aca --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1040.1__account_capacity_origin_decisions.sql @@ -0,0 +1,247 @@ +-- Retain the exact Account decision before a new reservation or rearm can commit. +CREATE TABLE account_capacity_origin_decisions ( + tenant_uuid uuid NOT NULL, + request_id uuid NOT NULL, + admission_id uuid NOT NULL, + capacity_rearm_fence bigint NOT NULL CHECK (capacity_rearm_fence > 0), + admission_attempt_id uuid NOT NULL, + mutation_digest text NOT NULL CHECK (mutation_digest ~ '^[0-9a-f]{64}$'), + canonical_payload bytea NOT NULL CHECK (octet_length(canonical_payload) BETWEEN 1 AND 524288), + refusal_code text, + evaluation_identity varchar(71) REFERENCES account_tenant_capacity_evaluations(evaluation_identity), + decision text NOT NULL CHECK (decision IN ('ACCEPTED', 'NO_ACCEPT')), + decision_id uuid NOT NULL UNIQUE CHECK (decision_id <> '00000000-0000-0000-0000-000000000000'), + PRIMARY KEY (tenant_uuid, request_id, admission_id, capacity_rearm_fence), + CHECK (decision <> 'NO_ACCEPT' OR capacity_rearm_fence = 1), + CONSTRAINT account_capacity_origin_evaluation_required + CHECK (decision <> 'ACCEPTED' OR evaluation_identity IS NOT NULL), + CONSTRAINT account_capacity_origin_refusal_code_check CHECK ( + refusal_code IS NULL OR ( + decision = 'NO_ACCEPT' + AND refusal_code IN ('CAPACITY_QUOTA_EXCEEDED', 'CAPACITY_EVALUATION_EXPIRED'))), + CONSTRAINT account_capacity_origin_refusal_cause_required + CHECK (decision <> 'NO_ACCEPT' OR refusal_code IS NOT NULL) +); + +CREATE UNIQUE INDEX account_capacity_origin_attempt_unique + ON account_capacity_origin_decisions (admission_attempt_id); + +CREATE INDEX account_capacity_origin_refusals_by_tenant + ON account_capacity_origin_decisions (tenant_uuid, request_id) + WHERE decision = 'NO_ACCEPT'; + +-- Provision a finite refusal budget explicitly for each tenant. +CREATE TABLE account_capacity_origin_refusal_budget ( + tenant_uuid UUID PRIMARY KEY + REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id), + maximum_refusals INTEGER NOT NULL CHECK (maximum_refusals > 0) +); + +CREATE TABLE account_capacity_origin_refusal_slots ( + tenant_uuid UUID NOT NULL, + slot BIGINT NOT NULL CHECK (slot > 0), + decision_id UUID NOT NULL UNIQUE REFERENCES account_capacity_origin_decisions(decision_id), + PRIMARY KEY (tenant_uuid, slot) +); + +-- [jooq ignore start] +CREATE FUNCTION account_capacity_origin_decision_immutable() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Account capacity origin decisions are immutable'; +END +$$; +CREATE TRIGGER account_capacity_origin_decision_immutable +BEFORE UPDATE OR DELETE ON account_capacity_origin_decisions +FOR EACH ROW EXECUTE FUNCTION account_capacity_origin_decision_immutable(); +CREATE TRIGGER account_capacity_origin_decision_no_truncate +BEFORE TRUNCATE ON account_capacity_origin_decisions +FOR EACH STATEMENT EXECUTE FUNCTION account_capacity_origin_decision_immutable(); + +CREATE FUNCTION account_capacity_origin_reservation_guard() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + -- Existing reservation recovery does not need invented historical origin evidence. + -- The reservation state guard independently keeps the evaluation immutable within an attempt. + IF TG_OP = 'UPDATE' AND NEW.tenant_uuid = OLD.tenant_uuid + AND NEW.request_id = OLD.request_id AND NEW.admission_id = OLD.admission_id + AND NEW.mutation_digest = OLD.mutation_digest + AND NEW.admission_attempt_id = OLD.admission_attempt_id + AND NEW.capacity_rearm_fence = OLD.capacity_rearm_fence + AND NEW.canonical_payload = OLD.canonical_payload THEN + RETURN NEW; + END IF; + IF EXISTS ( + SELECT 1 FROM account_capacity_origin_decisions d + WHERE d.tenant_uuid = NEW.tenant_uuid AND d.request_id = NEW.request_id + AND d.admission_id = NEW.admission_id AND d.decision = 'NO_ACCEPT') THEN + RAISE EXCEPTION 'Retained Account refusal excludes reservation creation or rearm'; + END IF; + IF NOT EXISTS ( + SELECT 1 FROM account_capacity_origin_decisions d + WHERE d.tenant_uuid = NEW.tenant_uuid AND d.request_id = NEW.request_id + AND d.admission_id = NEW.admission_id + AND d.capacity_rearm_fence = NEW.capacity_rearm_fence + AND d.admission_attempt_id = NEW.admission_attempt_id + AND d.mutation_digest = NEW.mutation_digest + AND d.canonical_payload = NEW.canonical_payload + AND d.evaluation_identity = NEW.evaluation_identity AND d.decision = 'ACCEPTED') THEN + RAISE EXCEPTION 'Exact Account ACCEPTED origin decision required'; + END IF; + RETURN NEW; +END +$$; +CREATE TRIGGER account_capacity_origin_reservation_guard +BEFORE INSERT OR UPDATE ON account_tenant_capacity_reservations +FOR EACH ROW EXECUTE FUNCTION account_capacity_origin_reservation_guard(); + +CREATE FUNCTION account_capacity_origin_decision_completion_guard() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.decision = 'ACCEPTED' AND NOT EXISTS ( + SELECT 1 FROM account_tenant_capacity_reservations r + WHERE r.tenant_uuid = NEW.tenant_uuid AND r.request_id = NEW.request_id + AND r.admission_id = NEW.admission_id + AND r.capacity_rearm_fence = NEW.capacity_rearm_fence + AND r.admission_attempt_id = NEW.admission_attempt_id + AND r.mutation_digest = NEW.mutation_digest + AND r.canonical_payload = NEW.canonical_payload + AND r.evaluation_identity = NEW.evaluation_identity) THEN + RAISE EXCEPTION 'ACCEPTED origin decision must commit with exact reservation'; + END IF; + IF NEW.decision = 'NO_ACCEPT' AND EXISTS ( + SELECT 1 FROM account_tenant_capacity_reservations r + WHERE r.tenant_uuid = NEW.tenant_uuid AND r.request_id = NEW.request_id + AND r.admission_id = NEW.admission_id) THEN + RAISE EXCEPTION 'NO_ACCEPT cannot contradict retained reservation'; + END IF; + RETURN NULL; +END +$$; +CREATE CONSTRAINT TRIGGER account_capacity_origin_decision_completion_guard +AFTER INSERT ON account_capacity_origin_decisions +DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW EXECUTE FUNCTION account_capacity_origin_decision_completion_guard(); + +CREATE FUNCTION guard_account_capacity_origin_refusal_budget() RETURNS TRIGGER +LANGUAGE plpgsql AS $$ +BEGIN + -- A same-value update serializes competing refusal writers under SERIALIZABLE. + IF TG_OP = 'UPDATE' AND NEW IS NOT DISTINCT FROM OLD THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'Capacity refusal budget is immutable' USING ERRCODE = '23514'; +END; +$$; +CREATE TRIGGER account_capacity_origin_refusal_budget_guard + BEFORE UPDATE OR DELETE ON account_capacity_origin_refusal_budget + FOR EACH ROW EXECUTE FUNCTION guard_account_capacity_origin_refusal_budget(); +CREATE TRIGGER account_capacity_origin_refusal_budget_no_truncate + BEFORE TRUNCATE ON account_capacity_origin_refusal_budget + FOR EACH STATEMENT EXECUTE FUNCTION account_capacity_origin_decision_immutable(); + +CREATE FUNCTION guard_account_capacity_origin_refusal_slot_source() RETURNS TRIGGER +LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM account_capacity_origin_decisions + WHERE decision_id = NEW.decision_id AND tenant_uuid = NEW.tenant_uuid AND decision = 'NO_ACCEPT' + ) THEN + RAISE EXCEPTION 'Capacity refusal slot requires its original tenant refusal' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_capacity_origin_refusal_slot_source + BEFORE INSERT ON account_capacity_origin_refusal_slots + FOR EACH ROW EXECUTE FUNCTION guard_account_capacity_origin_refusal_slot_source(); + +CREATE TRIGGER account_capacity_origin_refusal_slot_immutable + BEFORE UPDATE OR DELETE ON account_capacity_origin_refusal_slots + FOR EACH ROW EXECUTE FUNCTION account_capacity_origin_decision_immutable(); + +CREATE TRIGGER account_capacity_origin_refusal_slots_no_truncate + BEFORE TRUNCATE ON account_capacity_origin_refusal_slots + FOR EACH STATEMENT EXECUTE FUNCTION account_capacity_origin_decision_immutable(); + +CREATE FUNCTION require_account_capacity_origin_refusal_budget() RETURNS TRIGGER +LANGUAGE plpgsql AS $$ +DECLARE refusal_limit INTEGER; last_slot BIGINT; +BEGIN + IF NEW.decision <> 'NO_ACCEPT' THEN RETURN NEW; END IF; + + -- Keep the same serializable tenant guard and immutable provisioned limit. + UPDATE account_capacity_origin_refusal_budget + SET maximum_refusals = maximum_refusals + WHERE tenant_uuid = NEW.tenant_uuid + RETURNING maximum_refusals INTO refusal_limit; + IF NOT FOUND THEN + RAISE EXCEPTION 'Capacity refusal budget is unavailable' USING ERRCODE = '23514'; + END IF; + + SELECT COALESCE(( + SELECT slot + FROM account_capacity_origin_refusal_slots + WHERE tenant_uuid = NEW.tenant_uuid + ORDER BY slot DESC + LIMIT 1 + ), 0) INTO last_slot; + IF last_slot >= refusal_limit THEN + RAISE EXCEPTION 'Capacity refusal budget is exhausted' USING ERRCODE = '23514'; + END IF; + + INSERT INTO account_capacity_origin_refusal_slots (tenant_uuid, slot, decision_id) + VALUES (NEW.tenant_uuid, last_slot + 1, NEW.decision_id); + RETURN NEW; +END; +$$; + +-- Charge only an inserted refusal after PostgreSQL arbitrates the attempt identity. +CREATE TRIGGER account_capacity_origin_refusal_budget_required + AFTER INSERT ON account_capacity_origin_decisions + FOR EACH ROW EXECUTE FUNCTION require_account_capacity_origin_refusal_budget(); + +CREATE OR REPLACE FUNCTION account_tenant_capacity_exact_usage() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE held NUMERIC; used NUMERIC; actual account_tenant_capacity_usage%ROWTYPE; observed TIMESTAMPTZ; +BEGIN + SELECT * INTO actual FROM account_tenant_capacity_usage + WHERE tenant_uuid = NEW.tenant_uuid AND owner_service = NEW.owner_service FOR UPDATE; + SELECT COALESCE(sum(capacity_delta) FILTER (WHERE state IN ('RESERVED', 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION')), 0), + COALESCE(sum(capacity_delta) FILTER (WHERE state = 'FINALIZED'), 0) + INTO held, used FROM account_tenant_capacity_reservations + WHERE tenant_uuid = NEW.tenant_uuid AND owner_service = NEW.owner_service; + IF actual.tenant_uuid IS NULL OR held <> actual.held_units OR used <> actual.used_units THEN + RAISE EXCEPTION 'Capacity usage differs from its complete durable reservation inventory' USING ERRCODE = '23514'; + END IF; + -- This runs after inventory validation for a new reservation attempt. PostgreSQL time + -- is the sole lifetime authority. Later recovery or settlement of the same retained + -- attempt may occur after expiry. + IF TG_TABLE_NAME = 'account_tenant_capacity_reservations' THEN + IF TG_OP = 'INSERT' OR NEW.admission_attempt_id IS DISTINCT FROM OLD.admission_attempt_id THEN + observed := clock_timestamp(); + IF NOT EXISTS ( + SELECT 1 FROM account_capacity_origin_decisions origin + JOIN account_tenant_capacity_evaluations evaluation + ON evaluation.evaluation_identity = origin.evaluation_identity + WHERE origin.tenant_uuid = NEW.tenant_uuid AND origin.request_id = NEW.request_id + AND origin.admission_id = NEW.admission_id + AND origin.capacity_rearm_fence = NEW.capacity_rearm_fence + AND origin.admission_attempt_id = NEW.admission_attempt_id + AND origin.mutation_digest = NEW.mutation_digest + AND origin.canonical_payload = NEW.canonical_payload + AND origin.decision = 'ACCEPTED' + AND origin.evaluation_identity = NEW.evaluation_identity + AND evaluation.evaluated_at <= observed AND observed < evaluation.expires_at + AND NEW.expires_at > evaluation.evaluated_at + AND NEW.expires_at <= evaluation.expires_at + ) THEN + RAISE EXCEPTION 'Retained capacity evaluation is outside its lifetime at deferred reservation validation' + USING ERRCODE = 'P1040'; + END IF; + END IF; + END IF; + RETURN NULL; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreatorBootstrapIntegrationFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreatorBootstrapIntegrationFixture.java new file mode 100644 index 0000000000..81891652b8 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreatorBootstrapIntegrationFixture.java @@ -0,0 +1,89 @@ +package integration.net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapDigest; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.Completion; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.StoredOperation; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; + +public final class AccountTenantCreatorBootstrapIntegrationFixture { + private AccountTenantCreatorBootstrapIntegrationFixture() {} + + public static StoredOperation claimBootstrap( + AccountTenantCreationBootstrapOperationRepository operations, + Account creator, + FreshTenantCreationEvidence creation) { + UUID accountId = creator.getAccountUuid(); + UUID authorizationId = UUID.randomUUID(); + String authorizationDigest = + AccountTenantCreationBootstrapDigest.sha256( + "fixture authorization".getBytes(StandardCharsets.UTF_8)); + var evidence = + new FreshTenantCreatorEvidence( + 1, + creation, + accountId, + authorizationId, + authorizationDigest, + FreshTenantCreatorDigest.evidenceDigest( + 1, creation, accountId, authorizationId, authorizationDigest)); + byte[] creatorPayload = AccountTenantCreationBootstrapDigest.creatorEvidencePayload(evidence); + byte[] sourcePayload = "fixture source snapshot".getBytes(StandardCharsets.UTF_8); + byte[] requestPayload = + AccountTenantCreationBootstrapDigest.requestPayload(creatorPayload, sourcePayload); + var claim = + operations.claim( + evidence, + creatorPayload, + sourcePayload, + AccountTenantCreationBootstrapDigest.sha256(sourcePayload), + requestPayload, + AccountTenantCreationBootstrapDigest.sha256(requestPayload), + 1, + 1); + assertThat(claim.claimed()).isTrue(); + return claim.operation(); + } + + public static Completion completion(StoredOperation operation) { + // Controlled completion receipts exercise the real storage owner's guarded transition. + byte[] event = "fixture membership event".getBytes(StandardCharsets.UTF_8); + byte[] audit = "fixture bootstrap audit".getBytes(StandardCharsets.UTF_8); + byte[] result = "fixture bootstrap result".getBytes(StandardCharsets.UTF_8); + return new Completion( + 1, + operation.baselineMembershipVersion() + 1, + operation.baselineMembershipAuthorityGeneration(), + "ACTIVE", + false, + "[\"tenantAdmin\"]".getBytes(StandardCharsets.UTF_8), + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + operation.initiatingAccountUuid() + + "/" + + operation.tenantUuid(), + operation.requestId().toString(), + 1, + "fixture-membership-event", + AccountTenantCreationBootstrapDigest.sha256(event), + false, + event, + UUID.randomUUID(), + "ACCOUNT_TENANT_CREATOR_BOOTSTRAPPED", + Instant.now().truncatedTo(ChronoUnit.MICROS), + AccountTenantCreationBootstrapDigest.sha256(audit), + audit, + result, + AccountTenantCreationBootstrapDigest.sha256(result)); + } +} 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 94645ae5aa..b2994e9e46 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 @@ -1,25 +1,25 @@ package integration.net.firedevops.firemud.accountservice.repository; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import integration.net.firedevops.firemud.accountservice.AccountTenantCreatorBootstrapIntegrationFixture; import java.nio.charset.StandardCharsets; import java.time.Instant; -import java.time.temporal.ChronoUnit; +import java.util.List; import java.util.Objects; import java.util.UUID; +import javax.sql.DataSource; import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountCapacityRefusalBudgetRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; -import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapDigest; +import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; -import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.Completion; -import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.StoredOperation; import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; -import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; -import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; -import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.configuration.FluentConfiguration; import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.AfterAll; @@ -28,9 +28,10 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionTemplate; -/** Real forward migration with retained tenant provenance. No existing usage is guessed. */ +/** PostgreSQL proof of the installed Account capacity schema and its durable write boundaries. */ class AccountTenantCapacityMigrationPostgresIntegrationTest { private static final AccountPostgresIntegrationFixture POSTGRES = new AccountPostgresIntegrationFixture(); @@ -45,21 +46,93 @@ static void stop() { POSTGRES.stop(); } + private static FluentConfiguration capacityMigrations(DataSource data, String schema) { + return Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .placeholders(java.util.Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + } + @Test - void historicalBootstrapCompletionAndPlainNewImportCannotInitializeCapacity() { - String schema = "capacity_migration_" + UUID.randomUUID().toString().replace("-", ""); + void refusalsRequireTypedCauseAndGloballyUniqueAttempt() { + String schema = "capacity_typed_refusals_" + UUID.randomUUID().toString().replace("-", ""); new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema); var data = POSTGRES.dataSource(schema); try { - Flyway.configure() - .dataSource(data) - .schemas(schema) - .defaultSchema(schema) - .placeholders(java.util.Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") - .target("1038") - .load() - .migrate(); + capacityMigrations(data, schema).load().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)); + transaction.executeWithoutResult(status -> + new AccountCapacityRefusalBudgetRepository(dsl).provision(tenant.canonicalTenantId(), 2)); + UUID retainedAttempt = UUID.randomUUID(); + String insertRefusal = + "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, refusal_code) VALUES (?, ?, ?, 1, ?, ?, ?, 'NO_ACCEPT', ?, ?)"; + Object[] exact = { + tenant.canonicalTenantId(), + UUID.randomUUID(), + UUID.randomUUID(), + retainedAttempt, + "c".repeat(64), + new byte[] {3}, + UUID.randomUUID(), + null + }; + assertThatThrownBy(() -> dsl.execute(insertRefusal, exact)) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> { + assertThat(failure.sqlState()).isEqualTo("23514"); + assertThat(failure) + .hasMessageContaining("account_capacity_origin_refusal_cause_required"); + }); + exact[exact.length - 1] = "UNKNOWN"; + assertThatThrownBy(() -> dsl.execute(insertRefusal, exact)) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> { + assertThat(failure.sqlState()).isEqualTo("23514"); + assertThat(failure) + .hasMessageContaining("account_capacity_origin_refusal_code_check"); + }); + assertThat(originRows(dsl, tenant.canonicalTenantId())).isEmpty(); + assertThat(refusalSlots(dsl)).isEmpty(); + exact[exact.length - 1] = "CAPACITY_QUOTA_EXCEEDED"; + assertThat(dsl.execute(insertRefusal, exact)).isEqualTo(1); + var original = originRows(dsl, tenant.canonicalTenantId()); + Object[] duplicate = exact.clone(); + duplicate[0] = UUID.randomUUID(); + duplicate[1] = UUID.randomUUID(); + duplicate[2] = UUID.randomUUID(); + duplicate[6] = UUID.randomUUID(); + assertThatThrownBy(() -> dsl.execute(insertRefusal, duplicate)) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> { + assertThat(failure.sqlState()).isEqualTo("23505"); + assertThat(failure).hasMessageContaining("account_capacity_origin_attempt_unique"); + }); + assertThat(originRows(dsl, tenant.canonicalTenantId())).isEqualTo(original); + assertThat(refusalSlots(dsl)) + .containsExactly(new RefusalSlot(tenant.canonicalTenantId(), 1, (UUID) exact[6])); + } finally { + new JdbcTemplate(POSTGRES.dataSource()).execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + + @Test + void bootstrapClaimedBeforeCapacitySchemaIsNotBackfilledByTheUpgrade() { + String schema = "capacity_upgrade_" + UUID.randomUUID().toString().replace("-", ""); + new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema); + var data = POSTGRES.dataSource(schema); + try { + capacityMigrations(data, schema).target("1038").load().migrate(); var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); var transaction = new TransactionTemplate(new DataSourceTransactionManager(data)); var repository = new FreshTenantIdentityAssociationRepository(dsl, "prod"); @@ -69,24 +142,18 @@ void historicalBootstrapCompletionAndPlainNewImportCannotInitializeCapacity() { Objects.requireNonNull( transaction.execute(status -> { repository.importVerified(existing); - return claimBootstrap( + return AccountTenantCreatorBootstrapIntegrationFixture.claimBootstrap( operations, new AccountRepository(dsl).save(creator()), existing); })); assertThat(historical.status()).isEqualTo("IN_PROGRESS"); - Flyway.configure() - .dataSource(data) - .schemas(schema) - .defaultSchema(schema) - .placeholders(java.util.Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") - .load() - .migrate(); - var retained = transaction.execute(status -> repository.read(existing.canonicalTenantId())); - assertThat(retained).contains(existing); + capacityMigrations(data, schema).load().migrate(); + // The upgrade must not stamp an association that predates the capacity schema. assertThat( Objects.requireNonNull( dsl.fetchOne( - "SELECT capacity_birth_transaction FROM account_fresh_tenant_identity_associations WHERE canonical_tenant_id = ?", + "SELECT capacity_birth_transaction FROM" + + " account_fresh_tenant_identity_associations WHERE" + + " canonical_tenant_id = ?", existing.canonicalTenantId())) .get("capacity_birth_transaction")) .isNull(); @@ -94,10 +161,59 @@ void historicalBootstrapCompletionAndPlainNewImportCannotInitializeCapacity() { Objects.requireNonNull( transaction.execute(status -> { var operation = operations.findForUpdate(historical.requestId()).orElseThrow(); + return operations.complete( + operation.requestId(), + AccountTenantCreatorBootstrapIntegrationFixture.completion(operation)); + })); + assertThat(completed.status()).isEqualTo("COMMITTED"); + assertThat(dsl.fetchCount(DSL.table("account_tenant_capacity_usage"))).isZero(); + assertThat(dsl.fetchCount(DSL.table("account_tenant_capacity_reservations"))).isZero(); + } finally { + new JdbcTemplate(POSTGRES.dataSource()).execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + + @Test + void lateBootstrapCompletionAndPlainNewImportCannotInitializeCapacity() { + String schema = "capacity_migration_" + UUID.randomUUID().toString().replace("-", ""); + new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema); + var data = POSTGRES.dataSource(schema); + try { + capacityMigrations(data, schema).load().migrate(); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); + var transaction = new TransactionTemplate(new DataSourceTransactionManager(data)); + var repository = new FreshTenantIdentityAssociationRepository(dsl, "prod"); + var operations = new AccountTenantCreationBootstrapOperationRepository(dsl); + var existing = source(); + var claimed = + Objects.requireNonNull( + transaction.execute(status -> { + repository.importVerified(existing); + return AccountTenantCreatorBootstrapIntegrationFixture.claimBootstrap( + operations, new AccountRepository(dsl).save(creator()), existing); + })); + assertThat(claimed.status()).isEqualTo("IN_PROGRESS"); + var retained = transaction.execute(status -> repository.read(existing.canonicalTenantId())); + assertThat(retained).contains(existing); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT capacity_birth_transaction FROM" + + " account_fresh_tenant_identity_associations WHERE" + + " canonical_tenant_id = ?", + existing.canonicalTenantId())) + .get("capacity_birth_transaction")) + .isNotNull(); + var completed = + Objects.requireNonNull( + transaction.execute(status -> { + var operation = operations.findForUpdate(claimed.requestId()).orElseThrow(); assertThat(operation.status()).isEqualTo("IN_PROGRESS"); assertThat(operation.creationOperationId()).isEqualTo(existing.operationId()); - assertThat(operation.requestPayload()).isEqualTo(historical.requestPayload()); - return operations.complete(operation.requestId(), completion(operation)); + assertThat(operation.requestPayload()).isEqualTo(claimed.requestPayload()); + return operations.complete( + operation.requestId(), + AccountTenantCreatorBootstrapIntegrationFixture.completion(operation)); })); assertThat(completed.status()).isEqualTo("COMMITTED"); assertThat(completed.tenantUuid()).isEqualTo(existing.canonicalTenantId()); @@ -107,17 +223,1052 @@ void historicalBootstrapCompletionAndPlainNewImportCannotInitializeCapacity() { assertThat( Objects.requireNonNull( dsl.fetchOne( - "SELECT capacity_birth_transaction FROM account_fresh_tenant_identity_associations WHERE canonical_tenant_id = ?", + "SELECT capacity_birth_transaction FROM" + + " account_fresh_tenant_identity_associations WHERE" + + " canonical_tenant_id = ?", later.canonicalTenantId())) .get("capacity_birth_transaction")) .isNotNull(); assertThat(dsl.fetchCount(DSL.table("account_tenant_capacity_usage"))).isZero(); assertThat(dsl.fetchCount(DSL.table("account_tenant_capacity_reservations"))).isZero(); + assertThat(dsl.fetchCount(DSL.table("account_capacity_origin_decisions"))).isZero(); + assertThat(dsl.fetchCount(DSL.table("account_capacity_origin_refusal_budget"))).isZero(); + var budgets = new AccountCapacityRefusalBudgetRepository(dsl); + assertThatThrownBy(() -> + transaction.execute( + status -> budgets.requireReady(existing.canonicalTenantId(), 4, 2))) + .isInstanceOf(AccountTenantCapacityRepository.CapacityException.class); + transaction.executeWithoutResult( + status -> budgets.provision(existing.canonicalTenantId(), 4)); + var beforeBudget = + dsl.fetchSingle( + "SELECT *, xmin::text AS row_version FROM account_capacity_origin_refusal_budget" + + " WHERE tenant_uuid=?", + existing.canonicalTenantId()) + .intoMap(); + transaction.executeWithoutResult( + status -> budgets.provision(existing.canonicalTenantId(), 4)); + assertThat( + dsl.fetchSingle( + "SELECT *, xmin::text AS row_version FROM" + + " account_capacity_origin_refusal_budget WHERE tenant_uuid=?", + existing.canonicalTenantId()) + .intoMap()) + .isEqualTo(beforeBudget); + Long readyHeadroom = + transaction.execute(status -> budgets.requireReady(existing.canonicalTenantId(), 4, 2)); + assertThat(readyHeadroom).isEqualTo(4L); + assertThatThrownBy(() -> + transaction.executeWithoutResult( + status -> budgets.provision(existing.canonicalTenantId(), 5))) + .isInstanceOf(AccountTenantCapacityRepository.CapacityException.class); + assertThatThrownBy(() -> + transaction.execute(status -> budgets.requireReady(later.canonicalTenantId(), 4, 1))) + .isInstanceOf(AccountTenantCapacityRepository.CapacityException.class); + assertThatThrownBy(() -> + transaction.executeWithoutResult( + status -> budgets.provision(existing.canonicalTenantId(), 0))) + .isInstanceOf(IllegalArgumentException.class); + assertThat(dsl.fetchCount(DSL.table("account_tenant_capacity_usage"))).isZero(); + assertThat(dsl.fetchCount(DSL.table("account_tenant_capacity_reservations"))).isZero(); + assertThat(dsl.fetchCount(DSL.table("account_capacity_origin_decisions"))).isZero(); + } finally { new JdbcTemplate(POSTGRES.dataSource()).execute("DROP SCHEMA " + schema + " CASCADE"); } } + @Test + void refusalBudgetRunsAfterIdentityArbitrationAndCountsTheInsertedLastSlot() throws Exception { + String schema = "capacity_arbitration_" + UUID.randomUUID().toString().replace("-", ""); + new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema); + var data = POSTGRES.dataSource(schema); + try { + capacityMigrations(data, schema).load().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); + new AccountCapacityRefusalBudgetRepository(dsl).provision(tenant.canonicalTenantId(), 1); + }); + UUID request = UUID.randomUUID(), + admission = UUID.randomUUID(), + attempt = UUID.randomUUID(), + decision = UUID.randomUUID(); + String insert = + """ + 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, refusal_code) + VALUES (?, ?, ?, 1, ?, ?, ?, 'NO_ACCEPT', ?, 'CAPACITY_QUOTA_EXCEEDED') + ON CONFLICT DO NOTHING + """; + Object[] original = { + tenant.canonicalTenantId(), + request, + admission, + attempt, + "a".repeat(64), + new byte[] {1}, + decision + }; + assertThat(dsl.execute(insert, original)).isEqualTo(1); + var retained = + dsl.fetchSingle( + "SELECT *, xmin::text AS row_version FROM account_capacity_origin_decisions") + .intoMap(); + var retainedBudget = + dsl.fetchSingle( + "SELECT *, xmin::text AS row_version FROM account_capacity_origin_refusal_budget") + .intoMap(); + // SQL arbitration: a different candidate decision ID for the same original is skipped + // and must not charge the budget. + Object[] retry = original.clone(); + retry[retry.length - 1] = UUID.randomUUID(); + assertThat(dsl.execute(insert, retry)).isZero(); + assertThat( + dsl.fetchSingle( + "SELECT *, xmin::text AS row_version FROM" + + " account_capacity_origin_refusal_budget") + .intoMap()) + .isEqualTo(retainedBudget); + assertThatThrownBy(() -> + dsl.execute( + insert, + tenant.canonicalTenantId(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "a".repeat(64), + new byte[] {1}, + UUID.randomUUID())) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> assertThat(failure.sqlState()).isEqualTo("23514")); + // A different outer identity with the same global attempt reaches conflict arbitration, + // not the missing budget guard. The repository then verifies exact retained identity. + assertThat( + dsl.execute( + insert, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + attempt, + "b".repeat(64), + new byte[] {2}, + UUID.randomUUID())) + .isZero(); + assertThat( + dsl.fetchSingle( + "SELECT *, xmin::text AS row_version FROM account_capacity_origin_decisions") + .intoMap()) + .usingRecursiveComparison() + .isEqualTo(retained); + // A genuinely new refusal without a budget still fails and leaves no evidence. + assertThatThrownBy(() -> + dsl.execute( + insert, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "b".repeat(64), + new byte[] {2}, + UUID.randomUUID())) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> assertThat(failure.sqlState()).isEqualTo("23514")); + assertThat(dsl.fetchCount(DSL.table("account_capacity_origin_decisions"))).isEqualTo(1); + + var concurrentTenant = source(); + transaction.executeWithoutResult(status -> { + new FreshTenantIdentityAssociationRepository(dsl, "prod").importVerified(concurrentTenant); + new AccountCapacityRefusalBudgetRepository(dsl) + .provision(concurrentTenant.canonicalTenantId(), 1); + }); + UUID winningRequest = UUID.randomUUID(); + UUID winningAdmission = UUID.randomUUID(); + UUID winningAttempt = UUID.randomUUID(); + UUID winningDecision = UUID.randomUUID(); + UUID losingRequest = UUID.randomUUID(); + UUID losingAdmission = UUID.randomUUID(); + UUID losingAttempt = UUID.randomUUID(); + UUID losingDecision = UUID.randomUUID(); + assertThat(losingRequest).isNotEqualTo(winningRequest); + assertThat(losingAdmission).isNotEqualTo(winningAdmission); + assertThat(losingAttempt).isNotEqualTo(winningAttempt); + String concurrentRefusalInsert = + "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, refusal_code) " + + "VALUES (?, ?, ?, 1, ?, ?, ?, 'NO_ACCEPT', ?, 'CAPACITY_QUOTA_EXCEEDED') " + + "ON CONFLICT DO NOTHING"; + try (var stale = data.getConnection(); + var winner = data.getConnection()) { + stale.setTransactionIsolation(java.sql.Connection.TRANSACTION_SERIALIZABLE); + stale.setAutoCommit(false); + winner.setAutoCommit(true); + var staleDsl = DSL.using(stale, SQLDialect.POSTGRES); + // Both origins are distinct and belong to one tenant with exactly one refusal slot. + // Establish the losing transaction's snapshot before the winner commits its last slot. + assertThat( + staleDsl.fetch( + "SELECT slot FROM account_capacity_origin_refusal_slots WHERE tenant_uuid = ?", + concurrentTenant.canonicalTenantId())) + .isEmpty(); + assertThat( + DSL.using(winner, SQLDialect.POSTGRES) + .execute( + concurrentRefusalInsert, + concurrentTenant.canonicalTenantId(), + winningRequest, + winningAdmission, + winningAttempt, + "c".repeat(64), + new byte[] {3}, + winningDecision)) + .isEqualTo(1); + assertThatThrownBy(() -> + staleDsl.execute( + concurrentRefusalInsert, + concurrentTenant.canonicalTenantId(), + losingRequest, + losingAdmission, + losingAttempt, + "d".repeat(64), + new byte[] {4}, + losingDecision)) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> assertThat(failure.sqlState()).isEqualTo("40001")); + stale.rollback(); + } + + var winningOrigin = + dsl.fetchSingle( + "SELECT *, xmin::text AS row_version FROM account_capacity_origin_decisions " + + "WHERE tenant_uuid = ?", + concurrentTenant.canonicalTenantId()) + .intoMap(); + assertThat(winningOrigin) + .containsEntry("request_id", winningRequest) + .containsEntry("admission_id", winningAdmission) + .containsEntry("admission_attempt_id", winningAttempt) + .containsEntry("decision", "NO_ACCEPT") + .containsEntry("decision_id", winningDecision) + .containsEntry("refusal_code", "CAPACITY_QUOTA_EXCEEDED"); + // Retry the exact rolled-back loser in a fresh transaction/snapshot, not a new original. + var retryTransaction = new TransactionTemplate(new DataSourceTransactionManager(data)); + retryTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + assertThatThrownBy(() -> + retryTransaction.executeWithoutResult(status -> + dsl.execute( + concurrentRefusalInsert, + concurrentTenant.canonicalTenantId(), + losingRequest, + losingAdmission, + losingAttempt, + "d".repeat(64), + new byte[] {4}, + losingDecision))) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> { + assertThat(failure.sqlState()).isEqualTo("23514"); + assertThat(failure).hasMessageContaining("Capacity refusal budget is exhausted"); + }); + assertThat( + dsl.fetch( + "SELECT *, xmin::text AS row_version FROM account_capacity_origin_decisions " + + "WHERE tenant_uuid = ?", + concurrentTenant.canonicalTenantId()) + .intoMaps()) + .usingRecursiveComparison() + .isEqualTo(List.of(winningOrigin)); + assertThat( + dsl.fetch( + "SELECT tenant_uuid, slot, decision_id " + + "FROM account_capacity_origin_refusal_slots WHERE tenant_uuid = ?", + concurrentTenant.canonicalTenantId()) + .map(row -> + new RefusalSlot( + row.get("tenant_uuid", UUID.class), + row.get("slot", Long.class), + row.get("decision_id", UUID.class)))) + .containsExactly( + new RefusalSlot(concurrentTenant.canonicalTenantId(), 1, winningDecision)); + } finally { + new JdbcTemplate(POSTGRES.dataSource()).execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + + @Test + void onlyFreshRefusalsSpendSlotsAndAcceptedOriginsRetainExactEvidence() { + String schema = "capacity_refusal_slots_" + UUID.randomUUID().toString().replace("-", ""); + new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema); + var data = POSTGRES.dataSource(schema); + try { + capacityMigrations(data, schema).load().migrate(); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); + var transaction = new TransactionTemplate(new DataSourceTransactionManager(data)); + var budgets = new AccountCapacityRefusalBudgetRepository(dsl); + var tenant = source(); + var otherTenant = source(); + assertThat(otherTenant.canonicalTenantId()).isNotEqualTo(tenant.canonicalTenantId()); + transaction.executeWithoutResult(status -> { + var tenants = new FreshTenantIdentityAssociationRepository(dsl, "prod"); + tenants.importVerified(tenant); + tenants.importVerified(otherTenant); + }); + + transaction.executeWithoutResult(status -> { + budgets.provision(tenant.canonicalTenantId(), 3); + budgets.provision(otherTenant.canonicalTenantId(), 3); + }); + UUID firstDecision = insertQuotaRefusal(dsl, tenant.canonicalTenantId()); + UUID secondDecision = insertQuotaRefusal(dsl, tenant.canonicalTenantId()); + UUID otherDecision = insertQuotaRefusal(dsl, otherTenant.canonicalTenantId()); + var acceptedTenant = source(); + var operations = new AccountTenantCreationBootstrapOperationRepository(dsl); + transaction.executeWithoutResult(status -> { + new FreshTenantIdentityAssociationRepository(dsl, "prod").importVerified(acceptedTenant); + var claimed = + AccountTenantCreatorBootstrapIntegrationFixture.claimBootstrap( + operations, new AccountRepository(dsl).save(creator()), acceptedTenant); + var current = operations.findForUpdate(claimed.requestId()).orElseThrow(); + assertThat(current.status()).isEqualTo("IN_PROGRESS"); + operations.complete( + current.requestId(), + AccountTenantCreatorBootstrapIntegrationFixture.completion(current)); + }); + + Long remainingHeadroom = + transaction.execute(status -> budgets.requireReady(tenant.canonicalTenantId(), 3, 1)); + assertThat(remainingHeadroom).isEqualTo(1L); + assertThatThrownBy(() -> + transaction.execute(status -> budgets.requireReady(tenant.canonicalTenantId(), 3, 2))) + .isInstanceOf(AccountTenantCapacityRepository.CapacityException.class); + Long otherRemainingHeadroom = + transaction.execute( + status -> budgets.requireReady(otherTenant.canonicalTenantId(), 3, 2)); + assertThat(otherRemainingHeadroom).isEqualTo(2L); + var expectedSlots = + List.of( + new RefusalSlot(tenant.canonicalTenantId(), 1, firstDecision), + new RefusalSlot(tenant.canonicalTenantId(), 2, secondDecision), + new RefusalSlot(otherTenant.canonicalTenantId(), 1, otherDecision)); + String insertedDecision = + "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, refusal_code, evaluation_identity) VALUES" + + " (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING"; + assertThat( + dsl.fetchOne( + "SELECT 1 FROM account_capacity_origin_refusal_budget WHERE tenant_uuid = ?", + acceptedTenant.canonicalTenantId())) + .isNull(); + var accepted = freshAcceptedAttempt(dsl); + transaction.executeWithoutResult(status -> + insertAcceptedCapacityAttempt(dsl, acceptedTenant.canonicalTenantId(), accepted, 0, 1)); + assertThat( + dsl.fetchOne( + "SELECT 1 FROM account_capacity_origin_refusal_slots WHERE tenant_uuid = ?", + acceptedTenant.canonicalTenantId())) + .isNull(); + assertThat(refusalSlots(dsl)).containsExactlyInAnyOrderElementsOf(expectedSlots); + assertTenantCapacityInventoryMatches(dsl, acceptedTenant.canonicalTenantId()); + assertThatThrownBy(() -> + dsl.execute( + "INSERT INTO account_capacity_origin_refusal_slots (tenant_uuid, slot," + + " decision_id) VALUES (?, 3, ?)", + acceptedTenant.canonicalTenantId(), + accepted.decisionId())) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> assertThat(failure.sqlState()).isEqualTo("23514")); + assertThatThrownBy(() -> + dsl.execute( + "INSERT INTO account_capacity_origin_refusal_slots (tenant_uuid, slot," + + " decision_id) VALUES (?, 3, ?)", + acceptedTenant.canonicalTenantId(), + firstDecision)) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> assertThat(failure.sqlState()).isEqualTo("23514")); + assertThat(refusalSlots(dsl)).containsExactlyInAnyOrderElementsOf(expectedSlots); + + var acceptedOriginsBeforeReplay = originRows(dsl, acceptedTenant.canonicalTenantId()); + var acceptedReservationsBeforeReplay = + reservationRows(dsl, acceptedTenant.canonicalTenantId()); + var acceptedUsageBeforeReplay = usageRows(dsl, acceptedTenant.canonicalTenantId()); + assertThat(acceptedOriginsBeforeReplay) + .anySatisfy(row -> + assertThat(row) + .containsEntry("request_id", accepted.requestId()) + .containsEntry("admission_id", accepted.admissionId()) + .containsEntry("admission_attempt_id", accepted.attemptId()) + .containsEntry("mutation_digest", accepted.digest()) + .containsEntry("decision", "ACCEPTED") + .containsEntry("evaluation_identity", accepted.evaluationIdentity()) + .containsEntry( + "payload", java.util.HexFormat.of().formatHex(accepted.payload()))); + assertThat(acceptedReservationsBeforeReplay) + .anySatisfy(row -> + assertThat(row) + .containsEntry("request_id", accepted.requestId()) + .containsEntry("admission_id", accepted.admissionId()) + .containsEntry("admission_attempt_id", accepted.attemptId()) + .containsEntry("mutation_digest", accepted.digest()) + .containsEntry("capacity_delta", 1L) + .containsEntry("evaluation_identity", accepted.evaluationIdentity()) + .containsEntry( + "payload", java.util.HexFormat.of().formatHex(accepted.payload()))); + + assertThat( + dsl.execute( + insertedDecision, + acceptedTenant.canonicalTenantId(), + accepted.requestId(), + accepted.admissionId(), + 1L, + accepted.attemptId(), + accepted.digest(), + accepted.payload(), + "ACCEPTED", + UUID.randomUUID(), + null, + accepted.evaluationIdentity())) + .isZero(); + assertThat(originRows(dsl, acceptedTenant.canonicalTenantId())) + .isEqualTo(acceptedOriginsBeforeReplay); + assertThat(reservationRows(dsl, acceptedTenant.canonicalTenantId())) + .isEqualTo(acceptedReservationsBeforeReplay); + assertThat(usageRows(dsl, acceptedTenant.canonicalTenantId())) + .isEqualTo(acceptedUsageBeforeReplay); + + var rolledBackAccepted = freshAcceptedAttempt(dsl); + transaction.executeWithoutResult(status -> { + insertAcceptedCapacityAttempt( + dsl, acceptedTenant.canonicalTenantId(), rolledBackAccepted, 1, 2); + status.setRollbackOnly(); + }); + assertThat( + dsl.fetchOne( + "SELECT 1 FROM account_capacity_origin_decisions WHERE tenant_uuid = ? AND" + + " request_id = ? AND admission_id = ?", + acceptedTenant.canonicalTenantId(), + rolledBackAccepted.requestId(), + rolledBackAccepted.admissionId())) + .isNull(); + assertThat( + dsl.fetchOne( + "SELECT 1 FROM account_tenant_capacity_reservations WHERE tenant_uuid = ? AND" + + " request_id = ? AND admission_id = ?", + acceptedTenant.canonicalTenantId(), + rolledBackAccepted.requestId(), + rolledBackAccepted.admissionId())) + .isNull(); + assertThat( + dsl.fetchOne( + "SELECT 1 FROM account_tenant_capacity_evaluations WHERE evaluation_identity = ?", + rolledBackAccepted.evaluationIdentity())) + .isNull(); + assertThat(originRows(dsl, acceptedTenant.canonicalTenantId())) + .isEqualTo(acceptedOriginsBeforeReplay); + assertThat(reservationRows(dsl, acceptedTenant.canonicalTenantId())) + .isEqualTo(acceptedReservationsBeforeReplay); + assertThat(usageRows(dsl, acceptedTenant.canonicalTenantId())) + .isEqualTo(acceptedUsageBeforeReplay); + assertTenantCapacityInventoryMatches(dsl, acceptedTenant.canonicalTenantId()); + + UUID refusedWithoutBudgetRequest = UUID.randomUUID(); + UUID refusedWithoutBudgetAdmission = UUID.randomUUID(); + assertThatThrownBy(() -> + dsl.execute( + insertedDecision, + acceptedTenant.canonicalTenantId(), + refusedWithoutBudgetRequest, + refusedWithoutBudgetAdmission, + 1L, + UUID.randomUUID(), + "7".repeat(64), + new byte[] {24, 25}, + "NO_ACCEPT", + UUID.randomUUID(), + "CAPACITY_QUOTA_EXCEEDED", + null)) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> { + assertThat(failure.sqlState()).isEqualTo("23514"); + assertThat(failure).hasMessageContaining("Capacity refusal budget is unavailable"); + }); + assertThat(originRows(dsl, acceptedTenant.canonicalTenantId())) + .isEqualTo(acceptedOriginsBeforeReplay); + assertThat(reservationRows(dsl, acceptedTenant.canonicalTenantId())) + .isEqualTo(acceptedReservationsBeforeReplay); + assertThat(usageRows(dsl, acceptedTenant.canonicalTenantId())) + .isEqualTo(acceptedUsageBeforeReplay); + assertThat(refusalSlots(dsl)).containsExactlyInAnyOrderElementsOf(expectedSlots); + + UUID freshRequest = UUID.randomUUID(); + UUID freshAdmission = UUID.randomUUID(); + UUID freshAttempt = UUID.randomUUID(); + UUID freshDecision = UUID.randomUUID(); + Object[] freshRefusal = { + tenant.canonicalTenantId(), + freshRequest, + freshAdmission, + 1L, + freshAttempt, + "f".repeat(64), + new byte[] {13, 14}, + "NO_ACCEPT", + freshDecision, + "CAPACITY_QUOTA_EXCEEDED", + null + }; + transaction.executeWithoutResult(status -> { + assertThat(dsl.execute(insertedDecision, freshRefusal)).isEqualTo(1); + status.setRollbackOnly(); + }); + assertThat(refusalSlots(dsl)).containsExactlyInAnyOrderElementsOf(expectedSlots); + assertThat(dsl.execute(insertedDecision, freshRefusal)).isEqualTo(1); + expectedSlots = + List.of( + new RefusalSlot(tenant.canonicalTenantId(), 1, firstDecision), + new RefusalSlot(tenant.canonicalTenantId(), 2, secondDecision), + new RefusalSlot(tenant.canonicalTenantId(), 3, freshDecision), + new RefusalSlot(otherTenant.canonicalTenantId(), 1, otherDecision)); + assertThat(refusalSlots(dsl)).containsExactlyInAnyOrderElementsOf(expectedSlots); + + Object[] refusalReplay = freshRefusal.clone(); + refusalReplay[8] = UUID.randomUUID(); + assertThat(dsl.execute(insertedDecision, refusalReplay)).isZero(); + assertThat(refusalSlots(dsl)).containsExactlyInAnyOrderElementsOf(expectedSlots); + assertThat( + dsl.execute( + insertedDecision, + tenant.canonicalTenantId(), + UUID.randomUUID(), + UUID.randomUUID(), + 1L, + freshAttempt, + "1".repeat(64), + new byte[] {15}, + "NO_ACCEPT", + UUID.randomUUID(), + "CAPACITY_QUOTA_EXCEEDED", + null)) + .isZero(); + assertThat(refusalSlots(dsl)).containsExactlyInAnyOrderElementsOf(expectedSlots); + + assertThatThrownBy(() -> + dsl.execute( + insertedDecision, + tenant.canonicalTenantId(), + UUID.randomUUID(), + UUID.randomUUID(), + 1L, + UUID.randomUUID(), + "2".repeat(64), + new byte[] {16}, + "NO_ACCEPT", + UUID.randomUUID(), + "CAPACITY_QUOTA_EXCEEDED", + null)) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> { + assertThat(failure.sqlState()).isEqualTo("23514"); + assertThat(failure).hasMessageContaining("Capacity refusal budget is exhausted"); + }); + assertThat(dsl.fetchCount(DSL.table("account_capacity_origin_decisions"))).isEqualTo(5); + assertThat(refusalSlots(dsl)).containsExactlyInAnyOrderElementsOf(expectedSlots); + + assertThatThrownBy(() -> + dsl.execute( + "UPDATE account_capacity_origin_refusal_slots SET slot = slot + 10 WHERE" + + " tenant_uuid = ? AND slot = 1", + tenant.canonicalTenantId())) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> + assertThat(failure) + .hasMessageContaining("Account capacity origin decisions are immutable")); + assertThatThrownBy(() -> + dsl.execute( + "DELETE FROM account_capacity_origin_refusal_slots WHERE tenant_uuid = ? AND slot" + + " = 1", + tenant.canonicalTenantId())) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> + assertThat(failure) + .hasMessageContaining("Account capacity origin decisions are immutable")); + assertThatThrownBy(() -> dsl.execute("TRUNCATE account_capacity_origin_refusal_slots")) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> + assertThat(failure) + .hasMessageContaining("Account capacity origin decisions are immutable")); + assertThat(refusalSlots(dsl)).containsExactlyInAnyOrderElementsOf(expectedSlots); + } finally { + new JdbcTemplate(POSTGRES.dataSource()).execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + + @Test + void quotaAndExpiredEvaluationRefusalsShareOneBudget() { + String schema = "capacity_expiry_" + UUID.randomUUID().toString().replace("-", ""); + new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema); + var data = POSTGRES.dataSource(schema); + try { + capacityMigrations(data, schema).load().migrate(); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); + var transaction = new TransactionTemplate(new DataSourceTransactionManager(data)); + var tenant = source(); + var tenantId = tenant.canonicalTenantId(); + transaction.executeWithoutResult(status -> { + new FreshTenantIdentityAssociationRepository(dsl, "prod").importVerified(tenant); + new AccountCapacityRefusalBudgetRepository(dsl).provision(tenantId, 2); + }); + + String insert = + """ + 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, refusal_code) + VALUES (?, ?, ?, 1, ?, ?, ?, 'NO_ACCEPT', ?, ?) + ON CONFLICT DO NOTHING + """; + UUID quotaDecision = UUID.randomUUID(); + assertThat( + dsl.execute( + insert, + tenantId, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "a".repeat(64), + new byte[] {1}, + quotaDecision, + "CAPACITY_QUOTA_EXCEEDED")) + .isOne(); + String retainedRow = + "SELECT *, xmin::text AS row_version FROM account_capacity_origin_decisions WHERE decision_id = ?"; + var quotaBefore = dsl.fetchSingle(retainedRow, quotaDecision).intoMap(); + + UUID expiredDecision = UUID.randomUUID(); + Object[] expired = { + tenantId, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "b".repeat(64), + new byte[] {2}, + expiredDecision, + "CAPACITY_EVALUATION_EXPIRED" + }; + assertThat(dsl.execute(insert, expired)).isOne(); + Object[] retry = expired.clone(); + retry[6] = UUID.randomUUID(); + assertThat(dsl.execute(insert, retry)).isZero(); + assertThatThrownBy(() -> + dsl.execute( + insert, + tenantId, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "c".repeat(64), + new byte[] {3}, + UUID.randomUUID(), + "CAPACITY_QUOTA_EXCEEDED")) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> { + assertThat(failure.sqlState()).isEqualTo("23514"); + assertThat(failure).hasMessageContaining("Capacity refusal budget is exhausted"); + }); + + assertThat(refusalSlots(dsl)) + .containsExactly( + new RefusalSlot(tenantId, 1, quotaDecision), + new RefusalSlot(tenantId, 2, expiredDecision)); + assertThat(dsl.fetchSingle(retainedRow, quotaDecision).intoMap()) + .usingRecursiveComparison() + .isEqualTo(quotaBefore); + assertThat(dsl.fetchSingle(retainedRow, expiredDecision).get("refusal_code", String.class)) + .isEqualTo("CAPACITY_EVALUATION_EXPIRED"); + assertThat(reservationRows(dsl, tenantId)).isEmpty(); + assertThat(usageRows(dsl, tenantId)).isEmpty(); + } finally { + new JdbcTemplate(POSTGRES.dataSource()).execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + + @Test + void newReservationRollsBackWhenEvaluationExpiresBeforeDeferredValidation() { + String schema = "capacity_commit_expiry_" + UUID.randomUUID().toString().replace("-", ""); + new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema); + var data = POSTGRES.dataSource(schema); + try { + capacityMigrations(data, schema).load().migrate(); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); + var transaction = new TransactionTemplate(new DataSourceTransactionManager(data)); + var tenant = source(); + var tenantId = tenant.canonicalTenantId(); + var operations = new AccountTenantCreationBootstrapOperationRepository(dsl); + transaction.executeWithoutResult(status -> { + new FreshTenantIdentityAssociationRepository(dsl, "prod").importVerified(tenant); + var claimed = + AccountTenantCreatorBootstrapIntegrationFixture.claimBootstrap( + operations, new AccountRepository(dsl).save(creator()), tenant); + var current = operations.findForUpdate(claimed.requestId()).orElseThrow(); + operations.complete( + current.requestId(), + AccountTenantCreatorBootstrapIntegrationFixture.completion(current)); + }); + // Sample inside the baseline transaction so a pause before it cannot expire the baseline. + var retained = + Objects.requireNonNull( + transaction.execute(status -> { + Instant expiry = databaseNow(dsl).plusSeconds(15); + var attempt = + acceptedAttempt(expiry.minusSeconds(60), expiry, expiry.minusSeconds(1)); + insertAcceptedCapacityAttempt(dsl, tenantId, attempt, 0, 1); + return attempt; + })); + Instant retainedExpiry = retained.evaluationExpiresAt(); + var oldReservations = reservationRows(dsl, tenantId); + var oldOrigins = originRows(dsl, tenantId); + var oldUsage = usageRows(dsl, tenantId); + var provisional = new java.util.concurrent.atomic.AtomicBoolean(); + assertThatThrownBy(() -> + transaction.executeWithoutResult(status -> { + Instant evaluatedAt = + dsl.fetchSingle("SELECT clock_timestamp() AS observed") + .get("observed", java.time.OffsetDateTime.class) + .toInstant(); + Instant expiresAt = evaluatedAt.plusSeconds(10); + var expiresDuringTransaction = + acceptedAttempt(evaluatedAt, expiresAt, expiresAt.minusMillis(1)); + insertAcceptedCapacityAttempt(dsl, tenantId, expiresDuringTransaction, 1, 2); + assertThat( + dsl.fetchSingle( + "SELECT clock_timestamp() < ?::timestamptz AS fresh", + AccountTenantCapacityRepository.at(expiresAt)) + .get("fresh", Boolean.class)) + .isTrue(); + dsl.execute("SET LOCAL statement_timeout = '15s'"); + dsl.execute( + "SELECT pg_sleep_until(?::timestamptz)", + AccountTenantCapacityRepository.at(expiresAt)); + provisional.set(true); + })) + .rootCause() + .isInstanceOfSatisfying( + java.sql.SQLException.class, + failure -> assertThat(failure.getSQLState()).isEqualTo("P1040")) + .hasMessageContaining( + "Retained capacity evaluation is outside its lifetime at deferred reservation validation"); + assertThat(provisional).isTrue(); + assertThat(originRows(dsl, tenantId)).isEqualTo(oldOrigins); + assertThat(reservationRows(dsl, tenantId)).isEqualTo(oldReservations); + assertThat(usageRows(dsl, tenantId)).isEqualTo(oldUsage); + assertThat(dsl.fetchCount(DSL.table("account_tenant_capacity_evaluations"))).isOne(); + + // An evaluation that has not started on the PostgreSQL clock cannot commit either. + Instant future = databaseNow(dsl).plusSeconds(30); + var notStarted = acceptedAttempt(future, future.plusSeconds(60), future.plusSeconds(30)); + assertThatThrownBy(() -> + transaction.executeWithoutResult( + status -> insertAcceptedCapacityAttempt(dsl, tenantId, notStarted, 1, 2))) + .rootCause() + .isInstanceOfSatisfying( + java.sql.SQLException.class, + failure -> assertThat(failure.getSQLState()).isEqualTo("P1040")); + assertThat(reservationRows(dsl, tenantId)).isEqualTo(oldReservations); + assertThat(dsl.fetchCount(DSL.table("account_tenant_capacity_evaluations"))).isOne(); + + // A reservation may not be stored to outlive its retained evaluation. + Instant evaluatedNow = databaseNow(dsl); + var outlivesEvaluation = + acceptedAttempt(evaluatedNow, evaluatedNow.plusSeconds(60), evaluatedNow.plusSeconds(90)); + assertThatThrownBy(() -> + transaction.executeWithoutResult( + status -> insertAcceptedCapacityAttempt(dsl, tenantId, outlivesEvaluation, 1, 2))) + .rootCause() + .isInstanceOfSatisfying( + java.sql.SQLException.class, + failure -> assertThat(failure.getSQLState()).isEqualTo("P1040")); + assertThat(reservationRows(dsl, tenantId)).isEqualTo(oldReservations); + + var fresh = freshAcceptedAttempt(dsl); + transaction.executeWithoutResult( + status -> insertAcceptedCapacityAttempt(dsl, tenantId, fresh, 1, 2)); + assertThat(reservationRows(dsl, tenantId)).hasSize(2); + assertThat(originRows(dsl, tenantId)).hasSize(2); + assertTenantCapacityInventoryMatches(dsl, tenantId); + + // Recovery of the retained attempt is exercised after an explicit, bounded database wait. + transaction.executeWithoutResult(status -> { + dsl.execute("SET LOCAL statement_timeout = '30s'"); + dsl.execute( + "SELECT pg_sleep_until(?::timestamptz)", + AccountTenantCapacityRepository.at(retainedExpiry)); + }); + assertThat( + dsl.fetchSingle( + "SELECT clock_timestamp() > ?::timestamptz AS expired", + AccountTenantCapacityRepository.at(retainedExpiry)) + .get("expired", Boolean.class)) + .isTrue(); + String recoverEvaluation = + "UPDATE account_tenant_capacity_reservations SET evaluation_identity = ? " + + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?"; + transaction.executeWithoutResult(status -> + assertThat( + dsl.execute( + recoverEvaluation, + retained.evaluationIdentity(), + tenantId, + retained.requestId(), + retained.admissionId())) + .isOne()); + var reservationsBeforeMismatch = reservationRows(dsl, tenantId); + assertThatThrownBy(() -> + transaction.executeWithoutResult(status -> + dsl.execute( + recoverEvaluation, + fresh.evaluationIdentity(), + tenantId, + retained.requestId(), + retained.admissionId()))) + .rootCause() + .isInstanceOfSatisfying( + java.sql.SQLException.class, + failure -> assertThat(failure.getSQLState()).isEqualTo("23514")) + .hasMessageContaining("Changed capacity attempt is an idempotency conflict"); + assertThat(reservationRows(dsl, tenantId)).isEqualTo(reservationsBeforeMismatch); + assertTenantCapacityInventoryMatches(dsl, tenantId); + } finally { + new JdbcTemplate(POSTGRES.dataSource()).execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + + private static UUID insertQuotaRefusal(org.jooq.DSLContext dsl, UUID tenantId) { + UUID decision = UUID.randomUUID(); + assertThat( + 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, refusal_code)" + + " VALUES (?, ?, ?, 1, ?, ?, ?, 'NO_ACCEPT', ?, 'CAPACITY_QUOTA_EXCEEDED')", + tenantId, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "a".repeat(64), + new byte[] {1}, + decision)) + .isOne(); + return decision; + } + + private static List refusalSlots(org.jooq.DSLContext dsl) { + return dsl.fetch( + "SELECT tenant_uuid, slot, decision_id FROM account_capacity_origin_refusal_slots ORDER" + + " BY tenant_uuid, slot") + .map(row -> + new RefusalSlot( + row.get("tenant_uuid", UUID.class), + row.get("slot", Long.class), + row.get("decision_id", UUID.class))); + } + + /** The deferred guard checks PostgreSQL time, so fixtures start from a database sample. */ + private static AcceptedCapacityAttempt freshAcceptedAttempt(org.jooq.DSLContext dsl) { + Instant evaluatedAt = databaseNow(dsl); + return acceptedAttempt(evaluatedAt, evaluatedAt.plusSeconds(60), evaluatedAt.plusSeconds(30)); + } + + private static Instant databaseNow(org.jooq.DSLContext dsl) { + return dsl.fetchSingle("SELECT clock_timestamp() AS observed") + .get("observed", java.time.OffsetDateTime.class) + .toInstant(); + } + + private static AcceptedCapacityAttempt acceptedAttempt( + Instant evaluatedAt, Instant evaluationExpiresAt, Instant reservationExpiresAt) { + UUID requestId = UUID.randomUUID(); + return new AcceptedCapacityAttempt( + requestId, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID().toString().replace("-", "").repeat(2), + ("fresh accepted capacity payload " + requestId).getBytes(StandardCharsets.UTF_8), + "sha256:" + UUID.randomUUID().toString().replace("-", "").repeat(2), + "sha256:" + UUID.randomUUID().toString().replace("-", "").repeat(2), + evaluatedAt, + evaluationExpiresAt, + reservationExpiresAt, + reservationExpiresAt.plusSeconds(60)); + } + + private static void insertAcceptedCapacityAttempt( + org.jooq.DSLContext dsl, + UUID tenantUuid, + AcceptedCapacityAttempt attempt, + long expectedHeldUnits, + long newHeldUnits) { + String callerWorkload = "controlled-capacity-fixture"; + 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)", + attempt.evaluationIdentity(), + attempt.snapshotIdentity(), + tenantUuid, + callerWorkload, + ("fresh accepted evaluation " + attempt.requestId()).getBytes(StandardCharsets.UTF_8), + AccountTenantCapacityRepository.at(attempt.evaluatedAt()), + AccountTenantCapacityRepository.at(attempt.evaluationExpiresAt())); + assertThat( + dsl.execute( + "UPDATE account_tenant_capacity_usage SET held_units = ?, usage_revision = ? WHERE" + + " tenant_uuid = ? AND owner_service = 'game-session-service' AND held_units =" + + " ? AND used_units = 0 AND usage_revision = ?", + newHeldUnits, + newHeldUnits + 1, + tenantUuid, + expectedHeldUnits, + expectedHeldUnits + 1)) + .isEqualTo(1); + assertThat( + 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, refusal_code, evaluation_identity)" + + " VALUES (?, ?, ?, 1, ?, ?, ?, 'ACCEPTED', ?, NULL, ?)", + tenantUuid, + attempt.requestId(), + attempt.admissionId(), + attempt.attemptId(), + attempt.digest(), + attempt.payload(), + attempt.decisionId(), + attempt.evaluationIdentity())) + .isEqualTo(1); + assertThat( + 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) VALUES (?, ?, ?," + + " ?, 'game-session-service', ?, ?, 1, 1, ?, ?, ?, 1, ?::timestamptz," + + " ?::timestamptz, 'RESERVED', 'OWNER_EXECUTION_PENDING')", + tenantUuid, + attempt.requestId(), + attempt.admissionId(), + attempt.reservationId(), + callerWorkload, + attempt.attemptId(), + attempt.digest(), + attempt.payload(), + attempt.evaluationIdentity(), + AccountTenantCapacityRepository.at(attempt.reservationExpiresAt()), + AccountTenantCapacityRepository.at(attempt.reconcileDeadline()))) + .isEqualTo(1); + } + + private static List> originRows( + org.jooq.DSLContext dsl, UUID tenantUuid) { + return dsl.fetch( + "SELECT tenant_uuid, request_id, admission_id, capacity_rearm_fence," + + " admission_attempt_id, mutation_digest, encode(canonical_payload, 'hex') AS" + + " payload, decision, decision_id, refusal_code, evaluation_identity, xmin::text" + + " AS row_version FROM" + + " account_capacity_origin_decisions WHERE tenant_uuid = ? ORDER BY decision_id", + tenantUuid) + .intoMaps(); + } + + private static List> reservationRows( + org.jooq.DSLContext dsl, UUID tenantUuid) { + return dsl.fetch( + "SELECT tenant_uuid, request_id, admission_id, reservation_id, owner_service," + + " caller_workload, admission_attempt_id, capacity_rearm_fence, reservation_fence," + + " mutation_digest, encode(canonical_payload, 'hex') AS payload," + + " evaluation_identity, capacity_delta, expires_at, reconcile_deadline, state," + + " execution_status, recovery_owner, recovery_claim_fence," + + " recovery_claim_expires_at, next_reconcile_at, recovery_policy_version," + + " recovery_attempt_count, recovery_escalated_at, encode(owner_readback, 'hex') AS" + + " owner_readback, owner_readback_digest, xmin::text AS row_version FROM" + + " account_tenant_capacity_reservations WHERE tenant_uuid = ? ORDER BY request_id," + + " admission_id", + tenantUuid) + .intoMaps(); + } + + private static List> usageRows( + org.jooq.DSLContext dsl, UUID tenantUuid) { + return dsl.fetch( + "SELECT tenant_uuid, owner_service, bootstrap_request_id, creation_evidence_digest," + + " held_units, used_units, usage_revision, xmin::text AS row_version FROM" + + " account_tenant_capacity_usage WHERE tenant_uuid = ? ORDER BY owner_service", + tenantUuid) + .intoMaps(); + } + + private static void assertTenantCapacityInventoryMatches( + org.jooq.DSLContext dsl, UUID tenantUuid) { + var rows = + dsl.fetch( + "SELECT u.owner_service, u.held_units, u.used_units, COALESCE(sum(r.capacity_delta)" + + " FILTER (WHERE r.state IN ('RESERVED'," + + " 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION')), 0) AS" + + " reservation_held_units, COALESCE(sum(r.capacity_delta) FILTER (WHERE" + + " r.state = 'FINALIZED'), 0) AS reservation_used_units FROM" + + " account_tenant_capacity_usage u LEFT JOIN" + + " account_tenant_capacity_reservations r ON r.tenant_uuid = u.tenant_uuid AND" + + " r.owner_service = u.owner_service WHERE u.tenant_uuid = ? GROUP BY" + + " u.owner_service, u.held_units, u.used_units ORDER BY u.owner_service", + tenantUuid) + .intoMaps(); + assertThat(rows).hasSize(2); + for (var row : rows) { + assertThat(((Number) row.get("held_units")).longValue()) + .isEqualTo(((Number) row.get("reservation_held_units")).longValue()); + assertThat(((Number) row.get("used_units")).longValue()) + .isEqualTo(((Number) row.get("reservation_used_units")).longValue()); + } + } + + private record AcceptedCapacityAttempt( + UUID requestId, + UUID admissionId, + UUID attemptId, + UUID decisionId, + UUID reservationId, + String digest, + byte[] payload, + String evaluationIdentity, + String snapshotIdentity, + Instant evaluatedAt, + Instant evaluationExpiresAt, + Instant reservationExpiresAt, + Instant reconcileDeadline) {} + + private record RefusalSlot(UUID tenantUuid, long slot, UUID decisionId) {} + private static Account creator() { String suffix = UUID.randomUUID().toString().replace("-", ""); var account = new Account(); @@ -128,74 +1279,6 @@ private static Account creator() { return account; } - private static StoredOperation claimBootstrap( - AccountTenantCreationBootstrapOperationRepository operations, - Account creator, - FreshTenantCreationEvidence creation) { - UUID accountId = creator.getAccountUuid(); - UUID authorizationId = UUID.randomUUID(); - String authorizationDigest = - AccountTenantCreationBootstrapDigest.sha256( - "fixture authorization".getBytes(StandardCharsets.UTF_8)); - var evidence = - new FreshTenantCreatorEvidence( - 1, - creation, - accountId, - authorizationId, - authorizationDigest, - FreshTenantCreatorDigest.evidenceDigest( - 1, creation, accountId, authorizationId, authorizationDigest)); - byte[] creatorPayload = AccountTenantCreationBootstrapDigest.creatorEvidencePayload(evidence); - byte[] sourcePayload = "fixture source snapshot".getBytes(StandardCharsets.UTF_8); - byte[] requestPayload = - AccountTenantCreationBootstrapDigest.requestPayload(creatorPayload, sourcePayload); - var claim = - operations.claim( - evidence, - creatorPayload, - sourcePayload, - AccountTenantCreationBootstrapDigest.sha256(sourcePayload), - requestPayload, - AccountTenantCreationBootstrapDigest.sha256(requestPayload), - 1, - 1); - assertThat(claim.claimed()).isTrue(); - return claim.operation(); - } - - private static Completion completion(StoredOperation operation) { - // Controlled completion receipts exercise the real storage owner's guarded transition. - byte[] event = "fixture membership event".getBytes(StandardCharsets.UTF_8); - byte[] audit = "fixture bootstrap audit".getBytes(StandardCharsets.UTF_8); - byte[] result = "fixture bootstrap result".getBytes(StandardCharsets.UTF_8); - return new Completion( - 1, - operation.baselineMembershipVersion() + 1, - operation.baselineMembershipAuthorityGeneration(), - "ACTIVE", - false, - "[\"tenantAdmin\"]".getBytes(StandardCharsets.UTF_8), - MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX - + "membership/" - + operation.initiatingAccountUuid() - + "/" - + operation.tenantUuid(), - operation.requestId().toString(), - 1, - "fixture-membership-event", - AccountTenantCreationBootstrapDigest.sha256(event), - false, - event, - UUID.randomUUID(), - "ACCOUNT_TENANT_CREATOR_BOOTSTRAPPED", - Instant.now().truncatedTo(ChronoUnit.MICROS), - AccountTenantCreationBootstrapDigest.sha256(audit), - audit, - result, - AccountTenantCreationBootstrapDigest.sha256(result)); - } - private static FreshTenantCreationEvidence source() { UUID request = UUID.randomUUID(), operation = UUID.randomUUID(), tenant = UUID.randomUUID(); String slug = "capacity-" + UUID.randomUUID().toString().substring(0, 8); 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 b416eed6ae..2abf3abab7 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 @@ -1,5 +1,6 @@ package net.firedevops.firemud.accountservice.service; +import static integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture.transactionalIssuanceOwner; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; @@ -9,6 +10,7 @@ import static org.mockito.Mockito.when; import com.google.protobuf.ByteString; +import integration.net.firedevops.firemud.accountservice.AccountTenantCreatorBootstrapIntegrationFixture; import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; import java.nio.charset.StandardCharsets; import java.nio.file.Path; @@ -17,15 +19,22 @@ import java.sql.SQLException; import java.time.Clock; import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneId; import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; import java.util.HexFormat; +import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; @@ -37,10 +46,12 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; import net.firedevops.firemud.accountservice.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountCapacityRefusalBudgetRepository; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBinding; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateExpiredException; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; @@ -50,6 +61,8 @@ 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.CapacityException; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; @@ -58,10 +71,13 @@ import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner.Request; import net.firedevops.firemud.accountservice.service.impl.AccountPlayerAdmissionEntitlementGrpcService; +import net.firedevops.firemud.accountservice.service.impl.AccountTenantCapacityGrpcService; import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier.VerifiedCaller; import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner.AuthenticatedSignerCorrespondence; import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; @@ -75,6 +91,7 @@ import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.gamesession.client.AccountPlayerAdmissionEntitlementClient; +import net.firedevops.firemud.gamesession.client.AccountTenantCapacityClient; import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; @@ -88,10 +105,14 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; @@ -331,7 +352,8 @@ void actualFirstJoinRetainsItsPositiveMembershipAndExactScopeBinding() { assertThat(value.membershipSource().gameplayAdmissionAllowed()).isTrue(); var retained = f.dsl.fetchOne( - "SELECT canonical_evidence, snapshot_identity FROM account_tenant_capacity_evaluations WHERE evaluation_identity = ?", + "SELECT canonical_evidence, snapshot_identity FROM account_tenant_capacity_evaluations" + + " WHERE evaluation_identity = ?", value.fields().get("evaluationIdentity")); assertThat(retained).isNotNull(); byte[] retainedEvidence = retained.get("canonical_evidence", byte[].class); @@ -359,6 +381,502 @@ void actualFirstJoinRetainsItsPositiveMembershipAndExactScopeBinding() { assertThat(value.toString()).doesNotContain(f.scope.connectScopeId(), CONTROLLED_COMPACT_TOKEN); } + @Test + void exactCapacityRefusalRemainsReadableAfterHeadroomReturnsAndEvaluationExpires() + throws Exception { + Fixture f = fixture(true, true); + var firstHold = capacityRequest(f); + long quota = firstHold.evidence().quota(); + assertThat(quota).isBetween(1L, 10L); + var firstReservation = f.capacityOwner.commit(firstHold, PEER); + assertThat(firstReservation.state()).isEqualTo(TenantCapacityAdmission.State.RESERVED); + for (long used = 1; used < quota; used++) { + var occupying = capacityRequest(f); + assertThat(f.capacityOwner.commit(occupying, PEER).state()) + .isEqualTo(TenantCapacityAdmission.State.RESERVED); + } + String readUsage = + "SELECT held_units, used_units, usage_revision FROM account_tenant_capacity_usage" + + " WHERE tenant_uuid=? AND owner_service='game-session-service'"; + var usageBeforeDenial = f.dsl.fetchSingle(readUsage, f.tenantId).intoMap(); + assertThat(usageBeforeDenial) + .containsEntry("held_units", quota) + .containsEntry("used_units", 0L); + var request = capacityRequest(f); + assertThat(request.evidence().quota()).isEqualTo(quota); + UUID requestId = request.identity().requestId(); + var bothReadOriginal = new CountDownLatch(2); + doAnswer( + invocation -> { + // Both SERIALIZABLE snapshots miss the denial before either can lock the account. + bothReadOriginal.countDown(); + assertThat(bothReadOriginal.await(5, TimeUnit.SECONDS)).isTrue(); + return invocation.callRealMethod(); + }) + .when(f.capacityAccounts) + .findByAccountUuidForUpdate(f.account.getAccountUuid()); + java.util.Objects.requireNonNull( + f.dataSource.getConnectionProperties(), "fixture connection properties") + .setProperty("socketTimeout", "8"); + var executor = Executors.newFixedThreadPool(2, Thread.ofPlatform().daemon().factory()); + var first = executor.submit(() -> requireQuotaDenial(f, request)); + var second = executor.submit(() -> requireQuotaDenial(f, request)); + UUID decision; + try (AutoCloseable stopWorkers = + () -> { + first.cancel(true); + second.cancel(true); + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)) + .as("quota test workers terminated") + .isTrue(); + }) { + decision = first.get(10, TimeUnit.SECONDS); + assertThat(second.get(10, TimeUnit.SECONDS)).isEqualTo(decision); + } + assertThat(f.dsl.fetchSingle(readUsage, f.tenantId).intoMap()).isEqualTo(usageBeforeDenial); + String readDenial = + "SELECT *, xmin::text AS row_version FROM account_capacity_origin_decisions" + + " WHERE tenant_uuid=? AND request_id=? AND admission_id=?"; + Object[] identity = {f.tenantId, requestId, request.identity().admissionId()}; + var retained = f.dsl.fetchSingle(readDenial, identity).intoMap(); + assertThat(retained) + .containsEntry("decision", "NO_ACCEPT") + .containsEntry("refusal_code", "CAPACITY_QUOTA_EXCEEDED") + .containsEntry("decision_id", decision); + String countDeniedReservations = + "SELECT count(*) AS n FROM account_tenant_capacity_reservations" + + " WHERE tenant_uuid=? AND request_id=? AND admission_id=?"; + assertThat(f.dsl.fetchSingle(countDeniedReservations, identity).get("n", Long.class)).isZero(); + + // The external no-execution observation is controlled; all Account storage mutations are real. + var recovery = + new AccountTenantCapacityRecoveryWorker( + f.capacityOwner, + f.dsl, + (occupying, reservation, deadline) -> + new AccountTenantCapacityRecoveryWorker.Observation( + PEER, + reservation, + net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest.preimage( + occupying), + AccountTenantCapacityRecoveryWorker.Disposition + .NOT_EXECUTED_AFTER_AUTHORIZATION, + occupying.admissionAttemptId(), + 7, + "sha256:" + "e".repeat(64), + "controlled-owner-no-execution".getBytes(StandardCharsets.US_ASCII)), + databaseClock(f.dsl)); + Instant evaluationExpiresAt = request.evidence().expiresAt(); + assertThat(f.clock.instant()).isBefore(evaluationExpiresAt); + f.clock.setInstant(evaluationExpiresAt.plus(1, ChronoUnit.MICROS)); + assertThat(f.clock.instant()).isAfter(evaluationExpiresAt); + awaitDatabaseExpiry(f.dsl, evaluationExpiresAt); + var heldWindow = + f.dsl.fetchSingle( + "SELECT clock_timestamp() AS observed_at, reconcile_deadline " + + "FROM account_tenant_capacity_reservations WHERE reservation_id = ?", + firstReservation.reservationId()); + Instant observedAt = heldWindow.get("observed_at", OffsetDateTime.class).toInstant(); + assertThat(observedAt).isAfterOrEqualTo(firstHold.evidence().expiresAt()); + assertThat(observedAt) + .isBefore(heldWindow.get("reconcile_deadline", OffsetDateTime.class).toInstant()); + assertThat( + recovery + .reconcile(firstHold, AccountTenantCapacityRecoveryWorker.NoCommitAction.RELEASE) + .state()) + .isEqualTo(TenantCapacityAdmission.State.RELEASED); + var usageBeforeReplay = f.dsl.fetchSingle(readUsage, f.tenantId).intoMap(); + assertThat(usageBeforeReplay) + .containsEntry("held_units", quota - 1) + .containsEntry("used_units", 0L); + // The exact durable refusal must win over both returned quota headroom and expired evidence. + var retainedReservations = + f.dsl + .fetch( + "SELECT *, xmin::text AS row_version FROM account_tenant_capacity_reservations " + + "ORDER BY reservation_id") + .intoMaps(); + var retainedSlots = + f.dsl + .fetch( + "SELECT tenant_uuid, slot, decision_id " + + "FROM account_capacity_origin_refusal_slots WHERE tenant_uuid = ?", + f.tenantId) + .intoMaps(); + assertThat(retainedSlots).hasSize(1); + assertThat(retainedSlots.get(0)).containsEntry("decision_id", decision); + var pki = + LoopbackMtlsTestPki.create( + certificateDirectory, + "Retained quota denial read", + new LoopbackMtlsTestPki.IdentitySpec("client", PEER, false), + new LoopbackMtlsTestPki.IdentitySpec( + "account", "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service", true)); + var server = + new AccountTenantCapacityGrpcService(f.capacityOwner, NAMESPACE) + .createUnregisteredServer( + "127.0.0.1:0", + pki.keyManagerFactory(pki.identity("account")), + pki.trustManagerFactory()) + .start(); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + server.getPort()); + try (var recovered = + new AccountTenantCapacityClient( + endpoints, + pki.clientProperties(certificateDirectory, pki.identity("client")), + new GrpcChannelFactory(), + NAMESPACE, + f.clock)) { + recovered.init(); + var refusal = recovered.readRetainedAdmissionDenial(request, f.clock.millis() + 5_000L); + assertThat(refusal.code()).isEqualTo(Failure.CAPACITY_QUOTA_EXCEEDED); + assertThat(refusal.durableDenialId()).isEqualTo(decision); + } finally { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + assertThatThrownBy(() -> f.capacityOwner.commit(request, PEER)) + .isInstanceOfSatisfying( + CapacityException.class, + error -> { + assertThat(error.code()).isEqualTo(Failure.CAPACITY_QUOTA_EXCEEDED); + assertThat(error.durableDenialId()).isEqualTo(decision); + }); + assertThat(f.dsl.fetchSingle(readUsage, f.tenantId).intoMap()).isEqualTo(usageBeforeReplay); + assertThat(f.dsl.fetchSingle(readDenial, identity).intoMap()) + .usingRecursiveComparison() + .isEqualTo(retained); + assertThat( + f.dsl + .fetch( + "SELECT *, xmin::text AS row_version FROM account_tenant_capacity_reservations " + + "ORDER BY reservation_id") + .intoMaps()) + .usingRecursiveComparison() + .isEqualTo(retainedReservations); + assertThat( + f.dsl + .fetch( + "SELECT tenant_uuid, slot, decision_id " + + "FROM account_capacity_origin_refusal_slots WHERE tenant_uuid = ?", + f.tenantId) + .intoMaps()) + .isEqualTo(retainedSlots); + assertThat(f.dsl.fetchCount(DSL.table("account_capacity_origin_decisions"))) + .isEqualTo(Math.toIntExact(quota + 1)); + assertThat(f.dsl.fetchSingle(countDeniedReservations, identity).get("n", Long.class)).isZero(); + } + + @Test + void expiredOriginalEvaluationRetainsOnlyTheExactDenial() { + Fixture f = fixture(true, true); + var request = capacityRequest(f); + var expiry = request.evidence().expiresAt(); + awaitDatabaseExpiry(f.dsl, expiry); + String usage = + "SELECT held_units, used_units, usage_revision FROM account_tenant_capacity_usage" + + " WHERE tenant_uuid=? AND owner_service='game-session-service'"; + var originalUsage = f.dsl.fetchSingle(usage, f.tenantId).intoMap(); + + // PostgreSQL already shows the evaluation expired, so the owner denies before it reads the + // delegation or connect scope. Live sources are read delegation first, so a delegation + // read here would mean the denial no longer precedes source qualification. + f.onCapacitySourceRead.set(candidate -> { + throw new AssertionError("Expired evaluation must not read live sources"); + }); + var decisionId = new AtomicReference(); + assertThatThrownBy(() -> f.capacityOwner.commit(request, PEER)) + .isInstanceOfSatisfying( + CapacityException.class, + error -> { + assertThat(error.code()).isEqualTo(Failure.CAPACITY_EVALUATION_EXPIRED); + assertThat(error.durableDenialId()).isNotNull(); + decisionId.set(error.durableDenialId()); + }); + + assertThat(f.onCapacitySourceRead.getAndSet(null)).as("no live source read").isNotNull(); + var retained = f.capacityOwner.readRetainedAdmissionDenial(request, PEER); + assertThat(retained.code()).isEqualTo(Failure.CAPACITY_EVALUATION_EXPIRED); + assertThat(retained.durableDenialId()).isEqualTo(decisionId.get()); + assertThatThrownBy(() -> f.capacityOwner.commit(request, PEER)) + .isInstanceOfSatisfying( + CapacityException.class, + error -> { + assertThat(error.code()).isEqualTo(Failure.CAPACITY_EVALUATION_EXPIRED); + assertThat(error.durableDenialId()).isEqualTo(decisionId.get()); + }); + assertThat(f.dsl.fetchSingle(usage, f.tenantId).intoMap()).isEqualTo(originalUsage); + assertThat(f.dsl.fetchCount(DSL.table("account_tenant_capacity_reservations"))).isZero(); + assertThat(f.dsl.fetchCount(DSL.table("account_capacity_origin_refusal_slots"))).isOne(); + } + + @Test + void delegationExpiryDuringQualificationCommitsExactDenialAndSlot() { + Fixture f = fixture(true, true); + var request = capacityRequest(f); + var original = capacityRows(f.dsl); + f.onCapacitySourceRead.set(candidate -> { + assertThat(databaseNow(f.dsl)).isBefore(request.evidence().expiresAt()); + awaitDatabaseExpiry( + DSL.using(f.dataSource, SQLDialect.POSTGRES), request.evidence().expiresAt()); + var tokenExpiry = Instant.ofEpochSecond(candidate.identity().expiresAtEpochSecond()); + f.clock.setInstant( + tokenExpiry.isAfter(request.evidence().expiresAt()) + ? tokenExpiry + : request.evidence().expiresAt()); + throw new CommittedCandidateExpiredException(candidate); + }); + + // This case tests receipt commit across actual source expiry, independent of the + // separately tested production transaction-time limit. + f.allowControlledClockCrossing = true; + f.clock.setInstant(databaseNow(f.dsl)); + assertThat(f.clock.instant()).isBefore(request.evidence().expiresAt()); + var decisionId = new AtomicReference(); + assertThatThrownBy(() -> f.capacityOwner.commit(request, PEER)) + .isInstanceOfSatisfying( + CapacityException.class, + error -> { + assertThat(error.code()) + .withFailMessage( + "Unexpected refusal %s at %s", error.code(), error.getStackTrace()[0]) + .isEqualTo(Failure.CAPACITY_EVALUATION_EXPIRED); + assertThat(error.durableDenialId()).isNotNull(); + decisionId.set(error.durableDenialId()); + }); + assertThat(f.onCapacitySourceRead).hasValue(null); + assertThat(f.capacityOwner.readRetainedAdmissionDenial(request, PEER).durableDenialId()) + .isEqualTo(decisionId.get()); + assertThat(f.dsl.fetchCount(DSL.table("account_capacity_origin_refusal_slots"))).isOne(); + assertThat(capacityRows(f.dsl).get("usage")).isEqualTo(original.get("usage")); + assertThat(capacityRows(f.dsl).get("reservations")).isEmpty(); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void deferredEvaluationExpiryRollsBackAccountReservationOrRearm(boolean rearm) { + Fixture f = fixture(true, true); + var entitlementRequest = f.request(); + var prior = capacityRequest(f, entitlementRequest); + var next = prior; + UUID reservationId = null; + UUID claimOwner = null; + long claimFence = 0; + Instant claimExpiry = null; + var recovery = + new AccountTenantCapacityRecoveryWorker( + f.capacityOwner, + f.dsl, + (request, reservation, deadline) -> + new AccountTenantCapacityRecoveryWorker.Observation( + PEER, + reservation, + net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest.preimage( + request), + AccountTenantCapacityRecoveryWorker.Disposition + .NOT_EXECUTED_AFTER_AUTHORIZATION, + request.admissionAttemptId(), + 7, + "sha256:" + "e".repeat(64), + "controlled-owner-no-execution".getBytes(StandardCharsets.US_ASCII)), + databaseClock(f.dsl)); + if (rearm) { + var reservation = f.capacityOwner.commit(prior, PEER); + assertThat(reservation.state()).isEqualTo(TenantCapacityAdmission.State.RESERVED); + reservationId = reservation.reservationId(); + assertThat( + recovery + .reconcile( + prior, AccountTenantCapacityRecoveryWorker.NoCommitAction.RETAIN_FOR_REARM) + .state()) + .isEqualTo(TenantCapacityAdmission.State.RESERVED); + next = freshRearmRequest(f, entitlementRequest, prior); + assertThat(next.evidence().evaluationIdentity()) + .isNotEqualTo(prior.evidence().evaluationIdentity()); + // Advance the same recovery worker's claim after evaluation capture. + awaitDatabaseExpiry(f.dsl, f.clock.instant().plusSeconds(3)); + recovery.reconcile( + prior, AccountTenantCapacityRecoveryWorker.NoCommitAction.RETAIN_FOR_REARM); + var claim = + f.dsl.fetchSingle( + "SELECT recovery_owner, recovery_claim_fence, recovery_claim_expires_at FROM account_tenant_capacity_reservations"); + claimOwner = claim.get("recovery_owner", UUID.class); + claimFence = claim.get("recovery_claim_fence", Long.class); + claimExpiry = + claim.get("recovery_claim_expires_at", java.time.OffsetDateTime.class).toInstant(); + assertThat(claimExpiry).isAfter(next.evidence().expiresAt()); + } + var attempt = next; + var recoveryOwner = claimOwner; + var recoveryFence = claimFence; + var recoveryExpiry = claimExpiry; + var original = capacityRows(f.dsl); + var beforeCommitReached = new AtomicBoolean(); + f.onCapacitySourceRead.set(candidate -> + TransactionSynchronizationManager.registerSynchronization( + new TransactionSynchronization() { + @Override + public void beforeCommit(boolean readOnly) { + assertThat(readOnly).isFalse(); + assertThat( + f.dsl + .fetchSingle( + "SELECT admission_attempt_id FROM account_tenant_capacity_reservations") + .get("admission_attempt_id", UUID.class)) + .isEqualTo(attempt.admissionAttemptId()); + assertThat(f.dsl.fetchCount(DSL.table("account_capacity_origin_decisions"))) + .isEqualTo(rearm ? 2 : 1); + assertThat(f.dsl.fetchCount(DSL.table("account_tenant_capacity_attempt_history"))) + .isEqualTo(rearm ? 1 : 0); + assertThat(databaseNow(f.dsl)).isBefore(attempt.evidence().expiresAt()); + // Use a separate connection past the transaction's JDBC statement budget. + var outsideTransaction = DSL.using(f.dataSource, SQLDialect.POSTGRES); + awaitDatabaseExpiry(outsideTransaction, attempt.evidence().expiresAt()); + if (rearm) { + assertThat(databaseNow(outsideTransaction)).isBefore(recoveryExpiry); + } + beforeCommitReached.set(true); + } + })); + assertThatThrownBy( + () -> { + if (rearm) f.capacityOwner.rearm(prior, attempt, recoveryOwner, recoveryFence); + else f.capacityOwner.commit(attempt, PEER); + }) + .isInstanceOfSatisfying( + CapacityException.class, + error -> { + assertThat(error.code()).isEqualTo(Failure.CAPACITY_ADMISSION_STALE); + assertThat(error.durableDenialId()).isNull(); + }); + assertThat(beforeCommitReached).isTrue(); + assertThat(capacityRows(f.dsl)).usingRecursiveComparison().isEqualTo(original); + + if (!rearm) { + f.clock.setInstant(attempt.evidence().expiresAt()); + var decision = new AtomicReference(); + assertThatThrownBy(() -> f.capacityOwner.commit(attempt, PEER)) + .isInstanceOfSatisfying( + CapacityException.class, + error -> { + assertThat(error.code()).isEqualTo(Failure.CAPACITY_EVALUATION_EXPIRED); + assertThat(error.durableDenialId()).isNotNull(); + decision.set(error.durableDenialId()); + }); + assertThat(f.capacityOwner.readRetainedAdmissionDenial(attempt, PEER).durableDenialId()) + .isEqualTo(decision.get()); + assertThat(f.dsl.fetchCount(DSL.table("account_capacity_origin_refusal_slots"))).isOne(); + } else { + var fresh = freshRearmRequest(f, entitlementRequest, prior); + var committed = recovery.rearm(prior, fresh); + assertThat(committed.state()).isEqualTo(TenantCapacityAdmission.State.RESERVED); + assertThat(committed.reservationId()).isEqualTo(reservationId); + assertThat(committed.admissionAttemptId()).isEqualTo(fresh.admissionAttemptId()); + assertThat(committed.capacityRearmFence()).isEqualTo(fresh.capacityRearmFence()); + assertThat(f.capacityOwner.commit(fresh, PEER)).isEqualTo(committed); + assertThat(capacityRows(f.dsl).get("usage")) + .usingRecursiveComparison() + .isEqualTo(original.get("usage")); + } + } + + private static TenantCapacityAdmission.Request freshRearmRequest( + Fixture f, Request entitlementRequest, TenantCapacityAdmission.Request prior) { + return new TenantCapacityAdmission.Request( + prior.identity(), + UUID.randomUUID(), + prior.capacityRearmFence() + 1, + prior.targetNamespace(), + prior.context(), + prior.operation(), + prior.priorShape(), + prior.requestedShape(), + capacityEvidence(f, entitlementRequest), + prior.capacityDelta(), + null) + .withDigest(); + } + + private static Map>> capacityRows(DSLContext dsl) { + return Map.of( + "usage", dsl.fetch("SELECT * FROM account_tenant_capacity_usage").intoMaps(), + "reservations", dsl.fetch("SELECT * FROM account_tenant_capacity_reservations").intoMaps(), + "origins", dsl.fetch("SELECT * FROM account_capacity_origin_decisions").intoMaps(), + "attemptHistory", + dsl.fetch("SELECT * FROM account_tenant_capacity_attempt_history").intoMaps(), + "refusalSlots", + dsl.fetch("SELECT * FROM account_capacity_origin_refusal_slots").intoMaps()); + } + + private static UUID requireQuotaDenial(Fixture f, TenantCapacityAdmission.Request request) { + var denial = + org.assertj.core.api.Assertions.catchThrowableOfType( + CapacityException.class, () -> f.capacityOwner.commit(request, PEER)); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(denial).isNotNull(); + assertThat(denial.code()).isEqualTo(Failure.CAPACITY_QUOTA_EXCEEDED); + assertThat(denial.durableDenialId()).isNotNull(); + return denial.durableDenialId(); + } + + private static void awaitDatabaseExpiry(DSLContext dsl, Instant expiry) { + org.awaitility.Awaitility.await("PostgreSQL reaches the retained evaluation expiry") + .atMost(java.time.Duration.ofSeconds(20)) + .until(() -> !databaseNow(dsl).isBefore(expiry)); + } + + private static Instant databaseNow(DSLContext dsl) { + return dsl.fetchSingle("SELECT clock_timestamp()").get(0, OffsetDateTime.class).toInstant(); + } + + private static Clock databaseClock(DSLContext dsl) { + // Recovery claim windows use PostgreSQL time independently of the controlled Account clock. + Clock clock = mock(Clock.class); + when(clock.instant()).thenAnswer(ignored -> databaseNow(dsl)); + return clock; + } + + private static TenantCapacityAdmission.Evidence capacityEvidence(Fixture f, Request request) { + f.clock.setInstant(databaseNow(f.dsl)); + var entitlement = f.owner.evaluate(request, CONTROLLED_COMPACT_TOKEN); + return TenantCapacityAdmission.Evidence.parse( + entitlement.canonicalBytes(), TenantCapacityAdmission.Owner.GAME_SESSION); + } + + private static TenantCapacityAdmission.Request capacityRequest(Fixture f) { + return capacityRequest(f, f.request()); + } + + private static TenantCapacityAdmission.Request capacityRequest( + Fixture f, Request entitlementRequest) { + var evidence = capacityEvidence(f, entitlementRequest); + UUID requestId = entitlementRequest.requestId(); + return new TenantCapacityAdmission.Request( + new TenantCapacityAdmission.Identity(f.tenantId, requestId, UUID.randomUUID()), + UUID.randomUUID(), + 1, + NAMESPACE, + new TenantCapacityAdmission.PlayerContext( + f.account.getAccountUuid(), + f.tenantId, + f.scope.playableStateNamespaceId(), + f.scope.gameInstanceId(), + UUID.randomUUID(), + UUID.randomUUID(), + f.scope.realmId(), + requestId, + f.scope.playableStateScope()), + TenantCapacityAdmission.Operation.CAPACITY_CREATING, + new TenantCapacityAdmission.Shape(0, 0, 0), + new TenantCapacityAdmission.Shape(1, 0, 0), + evidence, + 1L, + null) + .withDigest(); + } + @Test void blockedAccountSourceReadIsCancelledWithinOwnerTransactionBudget() throws Exception { Fixture f = fixture(false); @@ -438,6 +956,10 @@ public void beforeCommit(boolean readOnly) { } private Fixture fixture(boolean join) { + return fixture(join, false); + } + + private Fixture fixture(boolean join, boolean initializeCapacity) { String schema = SCHEMA_PREFIX + UUID.randomUUID().toString().replace("-", ""); schemas.add(schema); DriverManagerDataSource dataSource = POSTGRES.dataSource(schema); @@ -449,7 +971,7 @@ private Fixture fixture(boolean join) { .locations("classpath:db/migration") .load() .migrate(); - return new Fixture(dataSource, join); + return new Fixture(dataSource, join, initializeCapacity); } /** Controlled protected-client double: no physical GS/World source provenance is claimed. */ @@ -537,6 +1059,8 @@ 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; @@ -545,11 +1069,30 @@ private static final class Fixture { private final UUID tenantId = UUID.randomUUID(); private final CanonicalJoinScopeV2 scope; private final AccountPlayerAdmissionEntitlementOwner owner; + private final AccountTenantCapacityOwner capacityOwner; + private final AccountRepository capacityAccounts; + private boolean allowControlledClockCrossing; + private final AtomicReference> + onCapacitySourceRead = new AtomicReference<>(); - private Fixture(DriverManagerDataSource dataSource, boolean join) { + private Fixture(DriverManagerDataSource dataSource, boolean join, boolean initializeCapacity) { this.dataSource = dataSource; dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); - var transactions = new DataSourceTransactionManager(dataSource); + now = initializeCapacity ? databaseNow(dsl) : NOW; + clock = new MutableClock(now, ZoneOffset.UTC); + var transactions = + new DataSourceTransactionManager(dataSource) { + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) { + if (allowControlledClockCrossing && !definition.isReadOnly()) { + var clockCrossing = new DefaultTransactionDefinition(definition); + clockCrossing.setTimeout(25); + super.doBegin(transaction, clockCrossing); + return; + } + super.doBegin(transaction, definition); + } + }; transaction = new TransactionTemplate(transactions); accounts = new AccountRepository(dsl); var tenants = new FreshTenantIdentityAssociationRepository(dsl, NAMESPACE); @@ -635,12 +1178,21 @@ private Fixture(DriverManagerDataSource dataSource, boolean join) { UUID.randomUUID(), 7, 3, - NOW.minusSeconds(20).toString(), - NOW.plusSeconds(120).toString()); + now.minusSeconds(20).toString(), + now.plusSeconds(120).toString()); String joinRequestId = UUID.randomUUID().toString(); String callerBinding = "controlled-join-caller"; transaction.execute(status -> { tenants.importVerified(tenantSource); + if (initializeCapacity) { + var bootstrap = new AccountTenantCreationBootstrapOperationRepository(dsl); + var claim = + AccountTenantCreatorBootstrapIntegrationFixture.claimBootstrap( + bootstrap, account, tenantSource); + bootstrap.complete( + claim.requestId(), AccountTenantCreatorBootstrapIntegrationFixture.completion(claim)); + new AccountCapacityRefusalBudgetRepository(dsl).provision(tenantId, 1); + } sources.initializeIssuerIfAbsent(ISSUER); generations.initializeTenantIfAbsent(tenantId); generations.initialize( @@ -695,9 +1247,9 @@ private Fixture(DriverManagerDataSource dataSource, boolean join) { mock(AccountGameplayCredentialRequestBinding.class), "a".repeat(64), UUID.randomUUID(), - NOW.minusSeconds(10).getEpochSecond(), - NOW.minusSeconds(10).getEpochSecond(), - NOW.plusSeconds(120).getEpochSecond()); + now.minusSeconds(10).getEpochSecond(), + now.minusSeconds(10).getEpochSecond(), + now.plusSeconds(120).getEpochSecond()); var candidate = mock(CommittedCandidateVerificationData.class); when(candidate.identity()).thenReturn(identity); when(candidate.authoritySnapshot()) @@ -725,8 +1277,21 @@ private Fixture(DriverManagerDataSource dataSource, boolean join) { dsl.connection(connection -> assertThat(connection.getTransactionIsolation()) .isEqualTo(Connection.TRANSACTION_SERIALIZABLE)); + var onRead = onCapacitySourceRead.getAndSet(null); + if (onRead != null) onRead.accept(candidate); return Optional.of(candidate); }); + capacityAccounts = spy(new AccountRepository(dsl)); + capacityOwner = + new AccountTenantCapacityOwner( + dsl, + capacityAccounts, + snapshots, + transactionalIssuanceOwner(issuances, transactions), + scopes, + transactions, + clock, + NAMESPACE); var targets = mock(CanonicalGameplayAdmissionDecisionReadClient.class); controlledTarget(targets); owner = @@ -743,7 +1308,7 @@ private Fixture(DriverManagerDataSource dataSource, boolean join) { tenantEvents, targets, transactions, - Clock.fixed(NOW, ZoneOffset.UTC), + clock, NAMESPACE); } @@ -768,6 +1333,39 @@ private Request request() { } } + private static final class MutableClock extends Clock { + private final AtomicReference current; + private final ZoneId zone; + + private MutableClock(Instant instant, ZoneId zone) { + this(new AtomicReference<>(instant), zone); + } + + private MutableClock(AtomicReference current, ZoneId zone) { + this.current = current; + this.zone = zone; + } + + @Override + public ZoneId getZone() { + return zone; + } + + @Override + public Clock withZone(ZoneId newZone) { + return zone.equals(newZone) ? this : new MutableClock(current, newZone); + } + + @Override + public Instant instant() { + return current.get(); + } + + private void setInstant(Instant instant) { + current.set(instant); + } + } + private static FreshTenantCreationEvidence tenantSource(UUID tenantId) { UUID requestId = UUID.randomUUID(); UUID operationId = UUID.randomUUID(); 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 980b0fb520..9ff4e5afe7 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,59 +639,47 @@ void boundedIndeterminateCapacityRecoveryQuarantinesTheOriginalCompleteHold() { } @Test - void firstRecoveryAfterDeadlineFinalizesAnExactPositiveOnce() { - var f = capacityPersistenceFixture(true); - assertThat(Instant.now()).isAfter(f.initial.expiresAt().plusSeconds(60)); - var calls = new java.util.concurrent.atomic.AtomicInteger(); - var recovery = - new net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker( - f.owner, - f.context.dsl, - (request, reservation, deadline) -> { - calls.incrementAndGet(); - assertThat(deadline).isAfter(Instant.now()); - assertThat(deadline).isBeforeOrEqualTo(Instant.now().plusSeconds(5)); - return capacityObservation( - request, - reservation, - net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker - .Disposition.COMMITTED); - }, - java.time.Clock.systemUTC()); - var result = - recovery.reconcile( - f.request, - net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker - .NoCommitAction.RELEASE); - assertThat(result.state()) - .isEqualTo( - net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State.FINALIZED); - assertThat(result.reservationId()).isEqualTo(f.initial.reservationId()); - assertThat(result.reservationFence()).isEqualTo(f.initial.reservationFence()); + void firstRecoveryAfterStoredDeadlineFinalizesPositiveAndQuarantinesOtherReads() + throws Exception { + var outcomes = + List.of("positive", "negative", "indeterminate", "malformed", "unavailable", "late"); + var fixtures = outcomes.stream().map(ignored -> capacityPersistenceFixture()).toList(); + // All fixtures share one PostgreSQL clock: one bounded sleep covers every stored deadline. + var latestDeadline = + fixtures.stream() + .map(f -> + f.context + .dsl + .fetchSingle( + "SELECT reconcile_deadline FROM account_tenant_capacity_reservations") + .get(0, java.time.OffsetDateTime.class)) + .max(java.util.Comparator.naturalOrder()) + .orElseThrow(); + var waiterContext = fixtures.getFirst().context; + var waiter = waiterContext.dsl; assertThat( - recovery.reconcile( - f.request, - net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker - .NoCommitAction.RELEASE)) - .isEqualTo(result); - assertThat(calls).hasValue(1); - var usage = - f.context.dsl.fetchSingle( - "SELECT held_units, used_units FROM account_tenant_capacity_usage WHERE tenant_uuid = ? AND owner_service = 'world-management-service'", - f.request.identity().tenantId()); - assertThat(usage.get("held_units", Long.class)).isZero(); - assertThat(usage.get("used_units", Long.class)).isEqualTo(17); - assertThat(f.context.dsl.fetchCount(DSL.table("account_tenant_capacity_recovery_evidence"))) - .isEqualTo(1); - } - - @Test - void firstLateNegativeMalformedUnavailableAndOverBudgetReadsQuarantineWithoutReleasing() { - for (String outcome : - List.of("negative", "indeterminate", "malformed", "unavailable", "late")) { - var f = capacityPersistenceFixture(true); - assertThat(Instant.now()).isAfter(f.initial.expiresAt().plusSeconds(60)); - var now = new java.util.concurrent.atomic.AtomicReference<>(Instant.now()); + waiter + .fetchSingle( + "SELECT ?::timestamptz - clock_timestamp() < interval '90 seconds'", + latestDeadline) + .get(0, Boolean.class)) + .isTrue(); + // The timeout and the sleep share one transaction, so a database clock step cannot stall it. + waiterContext.tx(() -> { + waiter.execute("SET LOCAL statement_timeout = '100s'"); + return waiter.execute("SELECT pg_sleep_until(?::timestamptz)", latestDeadline); + }); + for (int index = 0; index < outcomes.size(); index++) { + String outcome = outcomes.get(index); + boolean positive = outcome.equals("positive"); + var f = fixtures.get(index); + var observed = + f.context + .dsl + .fetchSingle("SELECT clock_timestamp()") + .get(0, java.time.OffsetDateTime.class) + .toInstant(); + var now = new java.util.concurrent.atomic.AtomicReference<>(observed); var recoveryClock = new java.time.Clock() { @Override @@ -710,6 +698,10 @@ public Instant instant() { } }; var calls = new java.util.concurrent.atomic.AtomicInteger(); + var ownerObservation = + new java.util.concurrent.atomic.AtomicReference< + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .Observation>(); var recovery = new net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker( f.owner, @@ -721,16 +713,20 @@ public Instant instant() { throw new IllegalStateException("Controlled source unavailable"); if (outcome.equals("late")) now.set(deadline); var disposition = - outcome.equals("negative") + positive ? net.firedevops.firemud.accountservice.service - .AccountTenantCapacityRecoveryWorker.Disposition - .NOT_EXECUTED_AFTER_AUTHORIZATION - : outcome.equals("indeterminate") + .AccountTenantCapacityRecoveryWorker.Disposition.COMMITTED + : outcome.equals("negative") ? net.firedevops.firemud.accountservice.service - .AccountTenantCapacityRecoveryWorker.Disposition.INDETERMINATE - : net.firedevops.firemud.accountservice.service - .AccountTenantCapacityRecoveryWorker.Disposition.COMMITTED; + .AccountTenantCapacityRecoveryWorker.Disposition + .NOT_EXECUTED_AFTER_AUTHORIZATION + : outcome.equals("indeterminate") + ? net.firedevops.firemud.accountservice.service + .AccountTenantCapacityRecoveryWorker.Disposition.INDETERMINATE + : net.firedevops.firemud.accountservice.service + .AccountTenantCapacityRecoveryWorker.Disposition.COMMITTED; var observation = capacityObservation(request, reservation, disposition); + ownerObservation.set(observation); if (!outcome.equals("malformed")) return observation; return new net.firedevops.firemud.accountservice.service .AccountTenantCapacityRecoveryWorker.Observation( @@ -752,8 +748,11 @@ public Instant instant() { assertThat(result.state()) .as(outcome) .isEqualTo( - net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State - .QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION); + positive + ? net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State + .FINALIZED + : net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State + .QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION); assertThat(result.reservationId()).isEqualTo(f.initial.reservationId()); assertThat(result.reservationFence()).isEqualTo(f.initial.reservationFence()); assertThat( @@ -767,23 +766,71 @@ public Instant instant() { f.context.dsl.fetchSingle( "SELECT held_units, used_units FROM account_tenant_capacity_usage WHERE tenant_uuid = ? AND owner_service = 'world-management-service'", f.request.identity().tenantId()); - assertThat(usage.get("held_units", Long.class)).isEqualTo(17); - assertThat(usage.get("used_units", Long.class)).isZero(); + assertThat(usage.get("held_units", Long.class)).isEqualTo(positive ? 0 : 17); + assertThat(usage.get("used_units", Long.class)).isEqualTo(positive ? 17 : 0); var retained = f.context.dsl.fetchSingle( - "SELECT outcome, canonical_readback FROM account_tenant_capacity_recovery_evidence"); + "SELECT admission_attempt_id, outcome, canonical_readback, readback_digest" + + " FROM account_tenant_capacity_recovery_evidence"); + if (positive) { + // The late positive keeps its owner proof bound to the original attempt. + assertThat(retained.get("admission_attempt_id", UUID.class)) + .isEqualTo(f.request.admissionAttemptId()); + assertThat(retained.get("outcome", String.class)).isEqualTo("COMMITTED"); + // Decode the stored v1 proof field by field and bind every field to the observation. + byte[] proof = retained.get("canonical_readback", byte[].class); + var expected = ownerObservation.get(); + var ascii = java.nio.charset.StandardCharsets.US_ASCII; + var fields = lengthPrefixedFields(proof); + assertThat(fields).hasSize(10); + assertThat(new String(fields.get(0), ascii)) + .isEqualTo("account-capacity-owner-readback/v1"); + assertThat(fields.get(1)).isEqualTo(expected.canonicalAttemptPayload()); + assertThat(new String(fields.get(2), ascii)) + .isEqualTo(expected.reservation().reservationId().toString()); + assertThat(new String(fields.get(3), ascii)) + .isEqualTo(Long.toString(expected.reservation().reservationFence())); + assertThat(new String(fields.get(4), ascii)) + .isEqualTo(expected.authenticatedOwnerWorkload()); + assertThat(new String(fields.get(5), ascii)).isEqualTo(expected.disposition().name()); + assertThat(new String(fields.get(6), ascii)).isEqualTo(expected.proofId().toString()); + assertThat(new String(fields.get(7), ascii)) + .isEqualTo(Long.toString(expected.currentOwnerFence())); + assertThat(new String(fields.get(8), ascii)).isEqualTo(expected.authoritativeStateDigest()); + assertThat(fields.get(9)).isEqualTo(expected.canonicalOwnerReadback()); + // Separately, the stored digest is SHA-256 of the stored proof bytes. + assertThat(retained.get("readback_digest", String.class)) + .isEqualTo( + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(proof))); + continue; + } assertThat(retained.get("outcome", String.class)) .isEqualTo("QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION"); assertThat(retained.get("canonical_readback")).isNull(); } } - /** Genuine same-transaction fresh creation; controlled entitlement and owner execution source. */ - private static CapacityPersistenceFixture capacityPersistenceFixture() { - return capacityPersistenceFixture(false); + /** Splits a proof of {@code :} fields, failing on any trailing data. */ + private static List lengthPrefixedFields(byte[] proof) { + var fields = new java.util.ArrayList(); + int position = 0; + while (position < proof.length) { + int colon = position; + while (proof[colon] != ':') colon++; + int length = + Integer.parseInt( + new String( + proof, position, colon - position, java.nio.charset.StandardCharsets.US_ASCII)); + fields.add(java.util.Arrays.copyOfRange(proof, colon + 1, colon + 1 + length)); + position = colon + 1 + length; + } + assertThat(position).isEqualTo(proof.length); + return fields; } - private static CapacityPersistenceFixture capacityPersistenceFixture(boolean expired) { + /** 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,12 +843,12 @@ 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. + // The deferred guard checks PostgreSQL time, so the evaluation starts from a database sample. var now = - java.time.Instant.now() - .minusSeconds(expired ? 120 : 0) - .truncatedTo(java.time.temporal.ChronoUnit.MICROS); + c.dsl + .fetchSingle("SELECT clock_timestamp()") + .get(0, java.time.OffsetDateTime.class) + .toInstant(); String json = new String(base.evidence().canonicalBytes(), java.nio.charset.StandardCharsets.UTF_8) .replace(base.identity().tenantId().toString(), tenant.toString()) @@ -858,8 +905,10 @@ private static CapacityPersistenceFixture capacityPersistenceFixture(boolean exp evidence.evaluatedAt()), net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.at( evidence.expiresAt())); - return repository.create( - request, evidence.expiresAt(), Clock.fixed(evidence.evaluatedAt(), ZoneOffset.UTC)); + return repository + .createWithLockedUsageIfQuotaAvailable( + request, repository.usage(request), evidence.expiresAt()) + .orElseThrow(() -> new AssertionError("Controlled fixture must have capacity")); }); var owner = new net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner( @@ -1751,14 +1800,14 @@ private static StorageContext storageContext(int recentAgeSeconds, int maxClockS new DriverManagerDataSource( postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); source.setSchema(schema); - Flyway.configure() - .dataSource(source) - .schemas(schema) - .defaultSchema(schema) - .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") - .load() - .migrate(); + var migrations = + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + migrations.load().migrate(); DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); var manager = new DataSourceTransactionManager(source); var transaction = new TransactionTemplate(manager); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java index 61a29963a4..2a883016ab 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java @@ -2,7 +2,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -16,6 +15,7 @@ import io.grpc.ServerCallHandler; import io.grpc.Status; import io.grpc.StatusRuntimeException; +import io.grpc.protobuf.StatusProto; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.List; @@ -23,6 +23,7 @@ import java.util.concurrent.atomic.AtomicInteger; import javax.net.ssl.SSLSession; import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; import org.junit.jupiter.api.AfterEach; @@ -89,6 +90,23 @@ void arbitraryPeerContextAndSessionClaimsNeverAuthenticate() throws Exception { } } + @Test + void quotaDenialReadRequiresExactGameSessionTlsWithoutAmbientAuthority() throws Exception { + var method = AccountServiceGrpc.getReadTenantCapacityAdmissionDenialMethod(); + var gameSession = tls("firemud", "game-session-service"); + assertThat(invoke(method, gameSession, "spiffe://firemud/ns/firemud/sa/game-session-service")) + .isNull(); + assertThatThrownBy(guard::requireAdmissionDenialReader) + .isInstanceOf(StatusRuntimeException.class); + assertThat(invoke(method, null).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(invoke(method, tls("firemud", "world-management-service")).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(invoke(method, tls("other", "game-session-service")).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + SessionContext.setContext("caller", List.of(), Map.of()); + assertThat(invoke(method, gameSession).getCode()).isEqualTo(Status.Code.PERMISSION_DENIED); + } + private Status invoke(MethodDescriptor method, SSLSession ssl) { return invoke(method, ssl, null); } @@ -105,14 +123,34 @@ private Status invoke(MethodDescriptor method, SSLSession ssl, String expectedCa AtomicInteger starts = new AtomicInteger(); ServerCallHandler next = (ignored, headers) -> { - assertThat(guard.requireAuthenticatedCaller()).isEqualTo(expectedCallerUri); + if (AccountServiceGrpc.getReadTenantCapacityAdmissionDenialMethod() + .getFullMethodName() + .equals(method.getFullMethodName())) { + assertThat(guard.requireAdmissionDenialReader()).isEqualTo(expectedCallerUri); + assertThatThrownBy(guard::requireAuthenticatedCaller) + .isInstanceOf(StatusRuntimeException.class); + } else { + assertThat(guard.requireAuthenticatedCaller()).isEqualTo(expectedCallerUri); + assertThatThrownBy(guard::requireAdmissionDenialReader) + .isInstanceOf(StatusRuntimeException.class); + } starts.incrementAndGet(); return new ServerCall.Listener() {}; }; guard.interceptCall(call, new Metadata(), next); var captured = ArgumentCaptor.forClass(Status.class); - verify(call, org.mockito.Mockito.atMostOnce()).close(captured.capture(), any(Metadata.class)); + var trailers = ArgumentCaptor.forClass(Metadata.class); + verify(call, org.mockito.Mockito.atMostOnce()).close(captured.capture(), trailers.capture()); assertThat(starts.get()).isEqualTo(captured.getAllValues().isEmpty() ? 1 : 0); + if (!captured.getAllValues().isEmpty()) { + // Denials carry exactly the bounded capacity detail for their status, not bare status. + var expected = + captured.getValue().getCode() == Status.Code.UNAUTHENTICATED + ? Failure.AUTH_UNAVAILABLE + : Failure.PERMISSION_DENIED; + assertThat(StatusProto.fromStatusAndTrailers(captured.getValue(), trailers.getValue())) + .isEqualTo(StatusProto.fromThrowable(expected.toStatusException())); + } return captured.getAllValues().isEmpty() ? null : captured.getValue(); } 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 3fb9605d9d..aa5f0a6abf 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 @@ -2,8 +2,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.AdditionalMatchers.aryEq; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.startsWith; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; @@ -11,21 +13,28 @@ 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 io.grpc.Context; 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; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateExpiredException; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository; import net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner; @@ -42,6 +51,8 @@ import org.jooq.Record; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; @@ -66,6 +77,8 @@ void sharedRejectedUsageVectorsReachAccountReservationGuardWithoutWrites() throw assertThat(resource).isNotNull(); try (resource) { var corpus = JsonMapper.builder().build().readTree(resource); + assertThat(corpus.path("rejectedUsage").isArray()).isTrue(); + assertThat(corpus.path("rejectedUsage").size()).isPositive(); for (var vector : corpus.path("rejectedUsage")) { DSLContext dsl = mock(DSLContext.class); Record usage = mock(Record.class); @@ -80,14 +93,12 @@ void sharedRejectedUsageVectorsReachAccountReservationGuardWithoutWrites() throw request.requireCommittable(); TransactionSynchronizationManager.setActualTransactionActive(true); try { - assertThatThrownBy(() -> - new AccountTenantCapacityRepository(dsl) - .create( - request, - request.evidence().expiresAt(), - Clock.fixed(request.evidence().evaluatedAt(), ZoneOffset.UTC))) + var repository = new AccountTenantCapacityRepository(dsl); + assertThat( + repository.createWithLockedUsageIfQuotaAvailable( + request, repository.usage(request), request.evidence().expiresAt())) .as(vector.path("name").asText()) - .hasMessage(vector.path("expected").asText()); + .isEmpty(); verify(dsl, never()).execute(anyString(), any(Object[].class)); } finally { TransactionSynchronizationManager.setActualTransactionActive(false); @@ -97,35 +108,624 @@ void sharedRejectedUsageVectorsReachAccountReservationGuardWithoutWrites() throw } @Test - 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); + void exactReplayPrecedesFreshnessCurrentSourcesAndUsageEvenAfterOriginalExpiry() + throws Exception { + var f = new Fixture(true); + f.databaseExpired = true; + var result = f.owner.commit(f.request, f.request.evidence().callerWorkload()); + assertThat(result.reservationId()).isEqualTo(f.reservation); + assertThat(f.owner.commit(f.request, f.request.evidence().callerWorkload())).isEqualTo(result); + verifyNoInteractions(f.accounts, f.memberships, f.issuances, f.scopes); + verify(f.dsl, never()).fetchOne(startsWith("SELECT observed < ?"), any(Object[].class)); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void genericNoAcceptCannotReplayAsQuotaDenial() throws Exception { + var f = new Fixture(false); + f.existing = false; + Record genericRefusal = mock(Record.class); + UUID decisionId = UUID.randomUUID(); + when(genericRefusal.get("tenant_uuid", UUID.class)).thenReturn(f.request.identity().tenantId()); + when(genericRefusal.get("request_id", UUID.class)).thenReturn(f.request.identity().requestId()); + when(genericRefusal.get("admission_id", UUID.class)) + .thenReturn(f.request.identity().admissionId()); + when(genericRefusal.get("admission_attempt_id", UUID.class)) + .thenReturn(f.request.admissionAttemptId()); + when(genericRefusal.get("mutation_digest", String.class)) + .thenReturn(f.request.mutationDigest()); + when(genericRefusal.get("canonical_payload", byte[].class)) + .thenReturn(CapacityAdmissionDigest.preimage(f.request)); + when(genericRefusal.get("decision", String.class)).thenReturn("NO_ACCEPT"); + when(genericRefusal.get("decision_id", UUID.class)).thenReturn(decisionId); + when(genericRefusal.get("refusal_code", String.class)).thenReturn(null); + f.originDecision = genericRefusal; + + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> assertThat(failure.code()).isEqualTo(Failure.IDEMPOTENCY_CONFLICT)); + verifyNoInteractions(f.accounts, f.memberships, f.issuances, f.scopes); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + private enum InitialDenialPath { + QUOTA, + EXPIRES_DURING_MEMBERSHIP_READ, + SCOPE_ALREADY_ELAPSED, + DELEGATION_ALREADY_ELAPSED, + EXPIRES_DURING_SCOPE_QUALIFICATION, + EXPIRES_DURING_DELEGATION_READ, + EXPIRES_DURING_USAGE_LOCK, + EXACT_SCOPE_EXPIRES_WITH_EVALUATION + } + + @ParameterizedTest + @EnumSource(InitialDenialPath.class) + void durableDenialReplaysWithoutConsultingMutableCapacity(InitialDenialPath path) + throws Exception { + Failure cause = + path == InitialDenialPath.QUOTA + ? Failure.CAPACITY_QUOTA_EXCEEDED + : Failure.CAPACITY_EVALUATION_EXPIRED; + var f = + new Fixture( + false, + path == InitialDenialPath.EXACT_SCOPE_EXPIRES_WITH_EVALUATION + ? qualifiedRequestWithScopeAtEvaluationExpiry(true) + : qualifiedRequest(true)); + f.existing = false; + Record genericRefusal = mock(Record.class); + UUID decisionId = UUID.randomUUID(); + String originLookupSql = + "SELECT * FROM account_capacity_origin_decisions WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND capacity_rearm_fence = ?"; + String originInsertSql = + "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, refusal_code, evaluation_identity) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING"; + Object[] originKey = { + f.request.identity().tenantId(), + f.request.identity().requestId(), + f.request.identity().admissionId(), + f.request.capacityRearmFence() + }; + doAnswer( + invocation -> { + Object[] arguments = (Object[]) invocation.getRawArguments()[1]; + assertThat(arguments).hasSize(4); + assertThat(arguments[0]).isEqualTo(f.request.identity().tenantId()); + assertThat(arguments[1]).isEqualTo(f.request.identity().requestId()); + assertThat(arguments[2]).isEqualTo(f.request.identity().admissionId()); + assertThat(arguments[3]).isEqualTo(f.request.capacityRearmFence()); + return f.pendingOriginDecision != null ? f.pendingOriginDecision : f.originDecision; + }) + .when(f.dsl) + .fetchOne(eq(originLookupSql), any(Object[].class)); + when(genericRefusal.get("tenant_uuid", UUID.class)).thenReturn(f.request.identity().tenantId()); + when(genericRefusal.get("request_id", UUID.class)).thenReturn(f.request.identity().requestId()); + when(genericRefusal.get("admission_id", UUID.class)) + .thenReturn(f.request.identity().admissionId()); + when(genericRefusal.get("admission_attempt_id", UUID.class)) + .thenReturn(f.request.admissionAttemptId()); + when(genericRefusal.get("mutation_digest", String.class)) + .thenReturn(f.request.mutationDigest()); + when(genericRefusal.get("canonical_payload", byte[].class)) + .thenReturn(CapacityAdmissionDigest.preimage(f.request)); + when(genericRefusal.get("decision", String.class)).thenReturn("NO_ACCEPT"); + when(genericRefusal.get("decision_id", UUID.class)).thenReturn(decisionId); + when(genericRefusal.get("refusal_code", String.class)).thenReturn(cause.name()); + Record 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)); + doAnswer( + invocation -> { + Object[] arguments = (Object[]) invocation.getRawArguments()[1]; + assertThat(arguments).hasSize(11); + assertThat(arguments[0]).isEqualTo(f.request.identity().tenantId()); + assertThat(arguments[1]).isEqualTo(f.request.identity().requestId()); + assertThat(arguments[2]).isEqualTo(f.request.identity().admissionId()); + assertThat(arguments[3]).isEqualTo(f.request.capacityRearmFence()); + assertThat(arguments[4]).isEqualTo(f.request.admissionAttemptId()); + assertThat(arguments[5]).isEqualTo(f.request.mutationDigest()); + assertThat( + java.util.Arrays.equals( + (byte[]) arguments[6], CapacityAdmissionDigest.preimage(f.request))) + .isTrue(); + assertThat(arguments[7]).isEqualTo("NO_ACCEPT"); + assertThat(arguments[8]).isInstanceOf(UUID.class); + assertThat(arguments[9]).isEqualTo(cause.name()); + assertThat(arguments[10]).isNull(); + when(genericRefusal.get("decision_id", UUID.class)).thenReturn((UUID) arguments[8]); + f.pendingOriginDecision = genericRefusal; + return 1; + }) + .when(f.dsl) + .execute(eq(originInsertSql), any(Object[].class)); + f.retained = true; + var exactSources = qualifySources(f); + Runnable expire = + () -> { + when(f.clock.instant()).thenReturn(f.request.evidence().expiresAt()); + f.databaseExpired = true; + }; + switch (path) { + case QUOTA -> {} + case EXPIRES_DURING_MEMBERSHIP_READ -> { + var player = (TenantCapacityAdmission.PlayerContext) f.request.context(); + var membership = f.memberships.readCurrent(player.accountId(), player.tenantId()); + when(f.memberships.readCurrent(player.accountId(), player.tenantId())) + .thenAnswer(ignored -> { + expire.run(); + return membership; + }); + } + case SCOPE_ALREADY_ELAPSED -> { + f.databaseExpired = true; + var scopeExpiry = Instant.parse(exactSources.scope().connectScopeExpiresAt()); + when(f.clock.instant()).thenReturn(scopeExpiry); + } + case DELEGATION_ALREADY_ELAPSED -> markDelegationExpired(f, exactSources.delegation()); + case EXPIRES_DURING_DELEGATION_READ -> + when(f.issuances.readCurrentCommittedCandidateByJti( + CapacityAdmissionTestFixture.DELEGATION_JTI)) + .thenAnswer(ignored -> { + throw markDelegationExpired(f, exactSources.delegation()); + }); + case EXPIRES_DURING_SCOPE_QUALIFICATION -> + when(f.scopes.findCanonicalEvidenceByTokenHash(verifiedScopeTokenHash(f.request))) + .thenAnswer(ignored -> { + expire.run(); + return Optional.of(exactSources.scope()); + }); + case EXACT_SCOPE_EXPIRES_WITH_EVALUATION -> { + // The scope and evaluation share one deadline; one PostgreSQL sample at that instant, + // taken at the decision point, shows both expired. + f.databaseNow = CapacityAdmissionTestFixture.NOW.plusSeconds(1); + doAnswer( + ignored -> { + f.databaseNow = f.request.evidence().expiresAt(); + return usage; + }) + .when(f.dsl) + .fetchOne( + startsWith("SELECT * FROM account_tenant_capacity_usage "), any(Object[].class)); + } + case EXPIRES_DURING_USAGE_LOCK -> + doAnswer( + ignored -> { + expire.run(); + return usage; + }) + .when(f.dsl) + .fetchOne( + startsWith("SELECT * FROM account_tenant_capacity_usage "), any(Object[].class)); + } + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(failure.code()).isEqualTo(cause); + assertThat(failure.durableDenialId()) + .isEqualTo(genericRefusal.get("decision_id", UUID.class)); + }); + assertThat(f.originDecision).isSameAs(genericRefusal); + assertThat(f.pendingOriginDecision).isNull(); + UUID committedId = genericRefusal.get("decision_id", UUID.class); + if (path == InitialDenialPath.EXPIRES_DURING_MEMBERSHIP_READ + || path == InitialDenialPath.SCOPE_ALREADY_ELAPSED + || path == InitialDenialPath.DELEGATION_ALREADY_ELAPSED) { + verifyNoInteractions(f.issuances, f.scopes); + } else { + verify(f.issuances) + .readCurrentCommittedCandidateByJti(CapacityAdmissionTestFixture.DELEGATION_JTI); + verify(f.scopes).findCanonicalEvidenceByTokenHash(verifiedScopeTokenHash(f.request)); + } + if (path == InitialDenialPath.EXPIRES_DURING_MEMBERSHIP_READ + || path == InitialDenialPath.SCOPE_ALREADY_ELAPSED + || path == InitialDenialPath.DELEGATION_ALREADY_ELAPSED) { + verify(f.dsl, never()) + .fetchOne( + startsWith("SELECT * FROM account_tenant_capacity_usage "), any(Object[].class)); + } + verify(f.dsl, never()) + .execute(startsWith("UPDATE account_tenant_capacity_usage "), any(Object[].class)); + verify(f.dsl, never()) + .execute( + startsWith("INSERT INTO account_tenant_capacity_reservations "), any(Object[].class)); + verify(f.dsl, times(1)).execute(eq(originInsertSql), any(Object[].class)); + verify(f.dsl, times(3)).fetchOne(eq(originLookupSql), aryEq(originKey)); + 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. + for (int retry = 0; retry < 2; retry++) { + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> { + assertThat(failure.code()).isEqualTo(cause); + assertThat(failure.durableDenialId()).isEqualTo(committedId); + }); + } + verifyNoInteractions(f.accounts, f.memberships, f.issuances, f.scopes); + // Replay reads only the reservation and the retained origin decision; no evaluation lookup. + verify(f.dsl, times(2)) + .fetchOne( + startsWith("SELECT * FROM account_tenant_capacity_reservations "), any(Object[].class)); + verify(f.dsl, times(2)).fetchOne(eq(originLookupSql), aryEq(originKey)); + verify(f.dsl, times(2)).connection(any(ConnectionRunnable.class)); + verifyNoMoreInteractions(f.dsl); + } + + @Test + void mismatchedScopeWithLiveDatabaseEvaluationIsUnavailableWithoutWrites() throws Exception { + var f = new Fixture(false, qualifiedRequest(true)); + f.existing = false; + f.retained = true; + var scope = qualifySources(f).scope(); + // The evaluation is live; only the qualified scope differs from the retained one. + when(scope.scopeDigest()).thenReturn("sha256:" + "f".repeat(64)); + Record usage = mock(Record.class); + org.mockito.Mockito.doReturn(usage) + .when(f.dsl) + .fetchOne(startsWith("SELECT * FROM account_tenant_capacity_usage "), any(Object[].class)); + + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> { + assertThat(failure.code()).isEqualTo(Failure.ENTITLEMENT_UNAVAILABLE); + assertThat(failure.durableDenialId()).isNull(); + }); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void nonCreatingEvidenceWhoseExactScopeExpiresWithItIsStale() throws Exception { + var f = new Fixture(false, qualifiedRequestWithScopeAtEvaluationExpiry(false)); + f.existing = false; + f.retained = true; + var scope = qualifySources(f).scope(); + // Fresh at the first sample; the shared scope and evaluation deadline then passes. + f.databaseNow = CapacityAdmissionTestFixture.NOW.plusSeconds(1); + when(f.scopes.findCanonicalEvidenceByTokenHash(verifiedScopeTokenHash(f.request))) + .thenAnswer(ignored -> { + f.databaseNow = f.request.evidence().expiresAt(); + return Optional.of(scope); }); - TransactionSynchronizationManager.setActualTransactionActive(true); - assertThatThrownBy(() -> - new AccountTenantCapacityRepository(dsl) - .create(request, request.evidence().expiresAt(), clock)) + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) .isInstanceOfSatisfying( AccountTenantCapacityRepository.CapacityException.class, failure -> assertThat(failure.code()).isEqualTo(Failure.CAPACITY_ADMISSION_STALE)); - verify(dsl, never()).execute(anyString(), any(Object[].class)); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); } @Test - void exactReplayPrecedesFreshnessCurrentSourcesAndUsageEvenAfterOriginalExpiry() - throws Exception { - var f = new Fixture(true); - var result = f.owner.commit(f.request, f.request.evidence().callerWorkload()); - assertThat(result.reservationId()).isEqualTo(f.reservation); - assertThat(f.owner.commit(f.request, f.request.evidence().callerWorkload())).isEqualTo(result); - verifyNoInteractions(f.accounts, f.memberships, f.issuances, f.scopes); + void delegationExpiryDuringLiveQualificationRequiresAnExactScope() throws Exception { + var f = new Fixture(false, qualifiedRequest(true)); + f.existing = false; + f.retained = true; + var exactSources = qualifySources(f); + String scopeTokenHash = verifiedScopeTokenHash(f.request); + when(f.scopes.findCanonicalEvidenceByTokenHash(scopeTokenHash)).thenReturn(Optional.empty()); + when(f.issuances.readCurrentCommittedCandidateByJti( + CapacityAdmissionTestFixture.DELEGATION_JTI)) + .thenAnswer(ignored -> { + throw markDelegationExpired(f, exactSources.delegation()); + }); + + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> { + assertThat(failure.code()).isEqualTo(Failure.ENTITLEMENT_UNAVAILABLE); + assertThat(failure.durableDenialId()).isNull(); + }); + verify(f.scopes).findCanonicalEvidenceByTokenHash(scopeTokenHash); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void delegationExpiringDuringReadWithDifferentCommitProofDoesNotRetainDenial() throws Exception { + var f = new Fixture(false, qualifiedRequest(true)); + f.existing = false; + f.retained = true; + var exactSources = qualifySources(f); + when(exactSources.delegation().commitProofSha256()).thenReturn("f".repeat(64)); + when(f.issuances.readCurrentCommittedCandidateByJti( + CapacityAdmissionTestFixture.DELEGATION_JTI)) + .thenAnswer(ignored -> { + throw markDelegationExpired(f, exactSources.delegation()); + }); + + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> { + assertThat(failure.code()).isEqualTo(Failure.ENTITLEMENT_UNAVAILABLE); + assertThat(failure.durableDenialId()).isNull(); + }); + verify(f.issuances) + .readCurrentCommittedCandidateByJti(CapacityAdmissionTestFixture.DELEGATION_JTI); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + private static CommittedCandidateExpiredException markDelegationExpired( + Fixture f, CommittedCandidateVerificationData candidate) { + f.databaseExpired = true; + Instant tokenExpiry = sourceTokenExpiry(f.request); + assertThat(tokenExpiry).isAfter(f.request.evidence().expiresAt()); + when(f.clock.instant()).thenReturn(tokenExpiry); + return new CommittedCandidateExpiredException(candidate); + } + + @Test + void unavailableDelegationDuringExpiryDoesNotRetainDenial() throws Exception { + var f = new Fixture(false, qualifiedRequest(true)); + f.existing = false; + f.retained = true; + qualifySources(f); + when(f.issuances.readCurrentCommittedCandidateByJti( + CapacityAdmissionTestFixture.DELEGATION_JTI)) + .thenAnswer(ignored -> { + when(f.clock.instant()).thenReturn(f.request.evidence().expiresAt()); + f.databaseExpired = true; + throw new AccountGameplayDelegationIssuanceRepository.StorageUnavailableException(); + }); + + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> { + assertThat(failure.code()).isEqualTo(Failure.ENTITLEMENT_UNAVAILABLE); + assertThat(failure.durableDenialId()).isNull(); + }); + verifyNoInteractions(f.scopes); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void notYetValidExactEvaluationDoesNotRetainDenial() throws Exception { + var f = new Fixture(false, qualifiedRequest(true)); + f.existing = false; + f.retained = true; + f.databaseEarly = true; + qualifySources(f); + + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .hasMessage("CAPACITY_ADMISSION_STALE"); + verify(f.dsl).fetchOne(startsWith("SELECT observed < ?"), any(Object[].class)); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + verifyNoInteractions(f.issuances, f.scopes); + } + + @Test + void expiryAtDeferredValidationRollsBackReservationAndDoesNotSupplyDenial() throws Exception { + var f = new Fixture(false, qualifiedRequest(true)); + f.databaseRejectsDeferredCommit = true; + f.existing = false; + f.retained = true; + qualifySources(f); + Record usage = mock(Record.class); + when(usage.get("held_units", Long.class)).thenReturn(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)); + retainOriginThen(f, f.request, "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; + }); + + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> { + assertThat(failure.code()).isEqualTo(Failure.CAPACITY_ADMISSION_STALE); + assertThat(failure.durableDenialId()).isNull(); + }); + verify(f.dsl).execute(startsWith("UPDATE account_tenant_capacity_usage "), any(Object[].class)); + verify(f.dsl) + .execute( + startsWith("INSERT INTO account_tenant_capacity_reservations "), any(Object[].class)); + assertThat(f.transactionEvents).containsExactly("begin", "deferred-commit", "rollback"); + assertThat(f.originDecision).isNull(); + assertThat(f.pendingReservation).isFalse(); + } + + private enum RearmExpiry { + EVALUATION_BEFORE_SOURCES, + DELEGATION_WITH_EVALUATION_DURING_QUALIFICATION, + CLAIM_AFTER_ACCEPTANCE, + CLAIM_DURING_HISTORY_INSERT + } + + @ParameterizedTest + @EnumSource(RearmExpiry.class) + void expiryDuringRearmRollsBackBeforeFenceMutation(RearmExpiry expiry) throws Exception { + boolean evaluationExpires = expiry == RearmExpiry.EVALUATION_BEFORE_SOURCES; + boolean delegationExpires = + expiry == RearmExpiry.DELEGATION_WITH_EVALUATION_DURING_QUALIFICATION; + boolean stale = evaluationExpires || delegationExpires; + var f = new Fixture(false, qualifiedRequest(true)); + f.retained = true; + var exactSources = qualifySources(f); + 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(); + var claimExpiry = + stale + ? sourceTokenExpiry(next).plusSeconds(1) + : next.evidence().expiresAt().minusSeconds(1); + 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(claimExpiry)); + when(row.get("execution_status", String.class)).thenReturn("NOT_EXECUTED_AFTER_AUTHORIZATION"); + when(row.get("owner_readback", byte[].class)).thenReturn(new byte[] {1}); + String usageLock = + "SELECT * FROM account_tenant_capacity_usage WHERE tenant_uuid = ? AND owner_service = ? FOR UPDATE"; + Record usage = mock(Record.class); + org.mockito.Mockito.doReturn(usage) + .when(f.dsl) + .fetchOne(startsWith(usageLock), any(Object[].class)); + // Expiry during source qualification is left to the deferred PostgreSQL guard. + f.databaseExpired = evaluationExpires; + if (delegationExpires) { + // The exact delegation and its evaluation expire during qualification: still stale. + when(f.issuances.readCurrentCommittedCandidateByJti( + CapacityAdmissionTestFixture.DELEGATION_JTI)) + .thenAnswer(ignored -> { + throw markDelegationExpired(f, exactSources.delegation()); + }); + } + if (!stale) { + retainOriginThen( + f, + next, + "ACCEPTED", + () -> { + if (expiry == RearmExpiry.CLAIM_AFTER_ACCEPTANCE) { + when(f.clock.instant()).thenReturn(claimExpiry); + } + }); + } + if (expiry == RearmExpiry.CLAIM_DURING_HISTORY_INSERT) { + when(f.dsl.execute( + startsWith("INSERT INTO account_tenant_capacity_attempt_history "), + any(Object[].class))) + .thenAnswer(ignored -> { + when(f.clock.instant()).thenReturn(claimExpiry); + return 1; + }); + } + 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)) + .cause() + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> + assertThat(failure.code()) + .isEqualTo( + stale ? Failure.CAPACITY_ADMISSION_STALE : Failure.IDEMPOTENCY_CONFLICT)); + var lockOrder = org.mockito.Mockito.inOrder(f.dsl); + if (evaluationExpires) { + verify(f.dsl, never()).fetchOne(startsWith(usageLock), any(Object[].class)); + verifyNoInteractions(f.memberships, f.issuances, f.scopes); + verify(f.dsl, never()) + .execute( + startsWith("INSERT INTO account_capacity_origin_decisions "), any(Object[].class)); + } else if (delegationExpires) { + verify(f.dsl).fetchOne(startsWith(usageLock), any(Object[].class)); + verify(f.dsl, never()) + .execute( + startsWith("INSERT INTO account_capacity_origin_decisions "), any(Object[].class)); + } else { + lockOrder.verify(f.dsl).fetchOne(startsWith(usageLock), any(Object[].class)); + lockOrder + .verify(f.dsl) + .execute( + startsWith("INSERT INTO account_capacity_origin_decisions "), any(Object[].class)); + } + verify(f.dsl, times(expiry == RearmExpiry.CLAIM_DURING_HISTORY_INSERT ? 1 : 0)) + .execute( + startsWith("INSERT INTO account_tenant_capacity_attempt_history "), + any(Object[].class)); + verify(f.dsl, never()) + .execute(startsWith("UPDATE account_tenant_capacity_reservations "), any(Object[].class)); + assertThat(f.originDecision).isNull(); + assertThat(f.pendingOriginDecision).isNull(); + assertThat(f.transactionEvents).containsExactly("begin", "rollback"); + } + + private static void retainOriginThen( + 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()); + when(retained.get("canonical_payload", byte[].class)) + .thenReturn(CapacityAdmissionDigest.preimage(request)); + when(retained.get("decision", String.class)).thenReturn(decision); + when(retained.get("evaluation_identity", String.class)) + .thenReturn("ACCEPTED".equals(decision) ? request.evidence().evaluationIdentity() : null); + when(retained.get("decision_id", UUID.class)).thenReturn(UUID.randomUUID()); + when(retained.get("refusal_code", String.class)) + .thenReturn("NO_ACCEPT".equals(decision) ? "CAPACITY_QUOTA_EXCEEDED" : null); + when(f.dsl.execute( + startsWith("INSERT INTO account_capacity_origin_decisions "), any(Object[].class))) + .thenAnswer(invocation -> { + f.pendingOriginDecision = retained; + afterWrite.run(); + return 1; + }); + } + + @Test + void rearmRetriesSerializationInFreshTransactionThenRechecksAccount() throws Exception { + var f = new Fixture(false, qualifiedRequest(true)); + 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(); + var aborted = serializationFailure(); + var lookups = new AtomicInteger(); + when(f.accounts.findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT)) + .thenAnswer(invocation -> { + f.transactionEvents.add("lookup"); + if (lookups.incrementAndGet() == 1) { + throw aborted; + } + return Optional.empty(); + }); + 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, UUID.randomUUID(), 7L)) + .cause() + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> assertThat(failure.code()).isEqualTo(Failure.ENTITLEMENT_UNAVAILABLE)); + assertThat(f.transactionEvents) + .containsExactly("begin", "lookup", "rollback", "begin", "lookup", "rollback"); + verify(f.accounts, times(2)).findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT); verify(f.dsl, never()).execute(anyString(), any(Object[].class)); } @@ -185,6 +785,46 @@ void cancelledCallDoesNotRetryAnAbortedTransaction() throws Exception { verify(f.dsl, never()).execute(anyString(), any(Object[].class)); } + @Test + void retryAttemptsShareTheIncomingDeadlineBudget() throws Exception { + var f = new Fixture(true); + f.existing = false; + var aborted = serializationFailure(); + var elapsed = new AtomicLong(); + var ticker = + new io.grpc.Deadline.Ticker() { + @Override + public long nanoTime() { + return elapsed.get(); + } + }; + // Each aborted attempt spends one controlled second of the caller's 1.9 s budget. + when(f.accounts.findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT)) + .thenAnswer(ignored -> { + elapsed.addAndGet(java.util.concurrent.TimeUnit.SECONDS.toNanos(1)); + throw aborted; + }); + // The cancellation callback never runs; only the controlled deadline ends the retries. + var scheduler = mock(java.util.concurrent.ScheduledExecutorService.class); + org.mockito.Mockito.doReturn(mock(java.util.concurrent.ScheduledFuture.class)) + .when(scheduler) + .schedule(any(Runnable.class), org.mockito.ArgumentMatchers.anyLong(), any()); + try (var caller = + Context.current() + .withDeadline( + io.grpc.Deadline.after(1900, java.util.concurrent.TimeUnit.MILLISECONDS, ticker), + scheduler)) { + caller.run(() -> + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .isSameAs(aborted)); + } + // PostgreSQL bounds each attempt by the exact remaining milliseconds; Spring's whole-second + // timeout is only a backstop. No transaction starts once the budget is spent. + assertThat(f.statementTimeouts) + .containsExactly("SET LOCAL statement_timeout = 1900", "SET LOCAL statement_timeout = 900"); + assertThat(f.timeouts).containsExactly(2, 1); + } + private static org.jooq.exception.DataAccessException serializationFailure() { return new org.jooq.exception.DataAccessException( "concurrent reservation", new SQLException("serialization failure", "40001")); @@ -340,20 +980,28 @@ void unretainedNonCreatingEvidenceRemainsUnavailableWithoutAnyUsageWrite() throw @Test void exactRetainedNonCreatingEvidenceOutsideWindowIsStale() throws Exception { - var f = new Fixture(true, CapacityAdmissionTestFixture.playerRequest(false)); + var f = new Fixture(true, qualifiedRequest(false)); f.existing = false; f.retained = true; + f.databaseExpired = 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)); } - @Test - void qualifiedNewerBillingCutoffMakesExactRetainedEvaluationStale() throws Exception { + @ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void qualifiedNewerBillingCutoffMakesExactRetainedEvaluationStale(boolean expired) + throws Exception { var f = new Fixture(false); f.existing = false; f.retained = true; + if (expired) { + when(f.clock.instant()).thenReturn(f.request.evidence().expiresAt()); + f.databaseExpired = true; + } var current = mock(Snapshot.class); var tuple = mock(AuthorityTuple.class); var tenant = f.request.identity().tenantId().toString(); @@ -375,6 +1023,8 @@ void qualifiedNewerBillingCutoffMakesExactRetainedEvaluationStale() throws Excep .thenReturn(current); assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) .hasMessage("CAPACITY_ADMISSION_STALE"); + verify(f.memberships) + .readCurrent(CapacityAdmissionTestFixture.ACCOUNT, f.request.identity().tenantId()); verifyNoInteractions(f.issuances, f.scopes); verify(f.dsl, never()).execute(anyString(), any(Object[].class)); } @@ -393,6 +1043,25 @@ void currentOwnerReadWithoutQualifiedEvidenceIsUnavailable() throws Exception { verify(f.dsl, never()).execute(anyString(), any(Object[].class)); } + @Test + void exactNonCreatingMissingMembershipReturnsTheTypedBillingRefusal() throws Exception { + var f = new Fixture(false, CapacityAdmissionTestFixture.playerRequest(false)); + f.existing = false; + f.retained = true; + qualifySources(f); + assertThatThrownBy(() -> f.owner.commit(f.request, CapacityAdmissionTestFixture.PEER)) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> { + assertThat(failure.code()).isEqualTo(Failure.TENANT_BILLING_BLOCKED); + assertThat(failure.durableDenialId()).isNull(); + }); + verify(f.issuances) + .readCurrentCommittedCandidateByJti(CapacityAdmissionTestFixture.DELEGATION_JTI); + verify(f.scopes).findCanonicalEvidenceByTokenHash(verifiedScopeTokenHash(f.request)); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + @Test void nonCreatingEvidenceCannotStartRecoveryOrRearmWork() throws Exception { var f = new Fixture(false); @@ -429,7 +1098,193 @@ void nonCreatingEvidenceCannotStartRecoveryOrRearmWork() throws Exception { verifyNoInteractions(f.accounts, f.dsl, f.memberships, f.issuances, f.scopes, source); } + @Test + void attemptAlreadyBoundToAnotherReservationCannotBecomeQuotaDenial() 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(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)); + // A retained reservation/history/origin with this attempt but a different outer identity. + stubRetainedAttemptConflict(f); + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> assertThat(failure.code()).isEqualTo(Failure.IDEMPOTENCY_CONFLICT)); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void globalAttemptConflictPrecedesFreshOrExpiredNonCreatingEvidence() throws Exception { + for (boolean expired : new boolean[] {false, true}) { + var f = new Fixture(false, qualifiedRequest(false)); + f.existing = false; + f.retained = true; + when(f.clock.instant()) + .thenReturn( + expired + ? f.request.evidence().expiresAt() + : CapacityAdmissionTestFixture.NOW.plusSeconds(1)); + f.databaseExpired = expired; + stubRetainedAttemptConflict(f); + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> assertThat(failure.code()).isEqualTo(Failure.IDEMPOTENCY_CONFLICT)); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + verify(f.dsl, never()).fetchOne(startsWith("SELECT observed < ?"), any(Object[].class)); + verifyNoInteractions(f.accounts, f.memberships, f.issuances, f.scopes); + } + } + + private static void stubRetainedAttemptConflict(Fixture f) { + org.mockito.Mockito.doAnswer( + invocation -> { + Object[] parameters = (Object[]) invocation.getRawArguments()[1]; + assertThat(parameters[0]).isEqualTo(f.request.admissionAttemptId()); + return mock(Record.class); + }) + .when(f.dsl) + .fetchOne(startsWith("SELECT 1 FROM (SELECT tenant_uuid"), any(Object[].class)); + } + + @Test + void expiryDuringSourceQualificationCannotBecomeBillingRefusal() throws Exception { + var f = new Fixture(false, qualifiedRequest(false)); + f.existing = false; + f.retained = true; + var scope = qualifySources(f).scope(); + 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.databaseExpired = true; + return Optional.of(scope); + }); + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> assertThat(failure.code()).isEqualTo(Failure.CAPACITY_ADMISSION_STALE)); + verify(f.issuances) + .readCurrentCommittedCandidateByJti(CapacityAdmissionTestFixture.DELEGATION_JTI); + verify(f.scopes).findCanonicalEvidenceByTokenHash(scopeTokenHash); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @SuppressWarnings("unchecked") + private static Request qualifiedRequest(boolean creating) { + var original = CapacityAdmissionTestFixture.playerRequest(); + var player = (TenantCapacityAdmission.PlayerContext) original.context(); + var target = (Map) original.evidence().fields().get("target"); + return CapacityAdmissionTestFixture.playerRequestFor( + player, + original.identity().admissionId(), + original.admissionAttemptId(), + "prod", + target, + CapacityAdmissionTestFixture.NOW, + creating); + } + + /** The exact connect scope expires at the same instant as the capacity evaluation. */ + @SuppressWarnings("unchecked") + private static Request qualifiedRequestWithScopeAtEvaluationExpiry(boolean creating) { + var original = CapacityAdmissionTestFixture.playerRequest(); + var player = (TenantCapacityAdmission.PlayerContext) original.context(); + var target = + new java.util.HashMap( + (Map) original.evidence().fields().get("target")); + target.put( + "connectScopeExpiresAt", qualifiedRequest(creating).evidence().expiresAt().toString()); + var request = + CapacityAdmissionTestFixture.playerRequestFor( + player, + original.identity().admissionId(), + original.admissionAttemptId(), + "prod", + target, + CapacityAdmissionTestFixture.NOW, + creating); + assertThat( + Instant.parse( + (String) + ((Map) request.evidence().fields().get("target")) + .get("connectScopeExpiresAt"))) + .isEqualTo(request.evidence().expiresAt()); + return request; + } + + private static Instant sourceTokenExpiry(Request request) { + var source = (Map) request.evidence().fields().get("sourceReferences"); + return Instant.parse((String) source.get("callerTokenExpiresAt")); + } + + private static String verifiedScopeTokenHash(Request request) { + return net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence + .parseCanonical(request.evidence().canonicalBytes()) + .verifiedConnectScopeTokenHash(); + } + + private record QualifiedSources( + AccountConnectScopeRepository.CanonicalConnectScopeEvidence scope, + CommittedCandidateVerificationData delegation) {} + + private static QualifiedSources qualifySources(Fixture f) { + var player = (TenantCapacityAdmission.PlayerContext) f.request.context(); + var parsed = + net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence + .parseCanonical(f.request.evidence().canonicalBytes()); + when(f.memberships.readCurrent(player.accountId(), player.tenantId())) + .thenReturn(parsed.membershipSource()); + var source = (Map) f.request.evidence().fields().get("sourceReferences"); + var issuance = + mock(CommittedCandidateVerificationData.class, org.mockito.Mockito.RETURNS_DEEP_STUBS); + when(issuance.identity().accountId()).thenReturn(player.accountId()); + when(issuance.identity().callerWorkload()).thenReturn(f.request.evidence().callerWorkload()); + when(issuance.identity().callerContextId()) + .thenReturn(UUID.fromString((String) source.get("callerContextId"))); + when(issuance.identity().operationId()) + .thenReturn(UUID.fromString((String) source.get("callerOperationId"))); + when(issuance.identity().notBeforeEpochSecond()) + .thenReturn(CapacityAdmissionTestFixture.NOW.minusSeconds(60).getEpochSecond()); + when(issuance.identity().expiresAtEpochSecond()) + .thenReturn(sourceTokenExpiry(f.request).getEpochSecond()); + when(issuance.tokenSha256()).thenReturn((String) source.get("callerTokenSha256")); + when(issuance.canonicalRegistryRecordSha256()) + .thenReturn((String) source.get("callerRegistryRecordSha256")); + when(issuance.commitProofSha256()).thenReturn((String) source.get("callerCommitProofSha256")); + var delegationJti = UUID.fromString((String) source.get("callerTokenJti")); + when(issuance.identity().tokenJti()).thenReturn(delegationJti); + when(f.issuances.readCurrentCommittedCandidateByJti(delegationJti)) + .thenReturn(Optional.of(issuance)); + var scope = mock(AccountConnectScopeRepository.CanonicalConnectScopeEvidence.class); + when(scope.accountUuid()).thenReturn(player.accountId()); + when(scope.tenantUuid()).thenReturn(player.tenantId()); + when(scope.scopeDigest()).thenReturn((String) source.get("scopeDigest")); + when(scope.gameInstanceUuid()).thenReturn(player.gameInstanceId()); + when(scope.playableStateNamespaceUuid()).thenReturn(player.playableStateNamespaceId()); + when(scope.realmId()).thenReturn(player.realmId()); + when(scope.playableStateScope()).thenReturn(player.playableStateScope()); + var target = (Map) f.request.evidence().fields().get("target"); + when(scope.connectScopeExpiresAt()).thenReturn((String) target.get("connectScopeExpiresAt")); + when(f.scopes.findCanonicalEvidenceByTokenHash(parsed.verifiedConnectScopeTokenHash())) + .thenReturn(Optional.of(scope)); + return new QualifiedSources(scope, issuance); + } + private static final class Fixture { + private final List transactionEvents = new ArrayList<>(); + private final List timeouts = new ArrayList<>(); + private final List statementTimeouts = new ArrayList<>(); private final DSLContext dsl = mock(DSLContext.class); private final AccountRepository accounts = mock(AccountRepository.class); private final AccountCanonicalRuntimeMembershipSnapshotRepository memberships = @@ -437,11 +1292,20 @@ private static final class Fixture { private final AccountGameplayDelegationIssuanceRepository issuances = mock(AccountGameplayDelegationIssuanceRepository.class); private final AccountConnectScopeRepository scopes = mock(AccountConnectScopeRepository.class); + private final Clock clock = mock(Clock.class); private final Request request; private final UUID reservation = UUID.randomUUID(); private final AccountTenantCapacityOwner owner; private boolean existing = true; private boolean retained; + private boolean databaseEarly; + // When set, each PostgreSQL sample derives all flags from this one instant and its bounds. + private Instant databaseNow; + private boolean databaseExpired; + private boolean databaseRejectsDeferredCommit; + private boolean pendingReservation; + private Record originDecision; + private Record pendingOriginDecision; private Fixture(boolean expired) throws Exception { this(expired, CapacityAdmissionTestFixture.playerRequest()); @@ -453,9 +1317,26 @@ private Fixture(boolean expired, Request request) throws Exception { private Fixture(boolean expired, Request request, String namespace) throws Exception { this.request = request; + when(clock.instant()) + .thenReturn(CapacityAdmissionTestFixture.NOW.plusSeconds(expired ? 60 : 1)); when(accounts.findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT)) .thenReturn(Optional.of(new Account())); - Connection connection = mock(Connection.class); + // Statement handling is answered by the mocks, so the test opens no JDBC resource. + java.sql.Statement statement = + mock( + java.sql.Statement.class, + invocation -> { + if (invocation.getMethod().getName().equals("execute")) + statementTimeouts.add(invocation.getArgument(0)); + return org.mockito.Mockito.RETURNS_DEFAULTS.answer(invocation); + }); + Connection connection = + mock( + Connection.class, + invocation -> + invocation.getMethod().getName().equals("createStatement") + ? statement + : org.mockito.Mockito.RETURNS_DEFAULTS.answer(invocation)); when(connection.getTransactionIsolation()).thenReturn(Connection.TRANSACTION_SERIALIZABLE); doAnswer( invocation -> { @@ -499,12 +1380,44 @@ private Fixture(boolean expired, Request request, String namespace) throws Excep .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; if (sql.startsWith( "SELECT snapshot_identity FROM account_tenant_capacity_evaluations ")) return evaluation; if (sql.startsWith("SELECT * FROM account_tenant_capacity_evaluations ")) return retained ? evaluation : null; + if (sql.startsWith("SELECT observed < ?")) { + // One PostgreSQL sample; scope expiry is observable only when a bound is passed. + Object[] bounds = (Object[]) invocation.getRawArguments()[1]; + boolean scopeBound = bounds.length > 2 && bounds[2] != null; + Instant sample = databaseNow; + boolean early = + sample == null + ? databaseEarly + : sample.isBefore(((java.time.OffsetDateTime) bounds[0]).toInstant()); + boolean lifetimeExpired = + sample == null + ? databaseExpired + : !sample.isBefore(((java.time.OffsetDateTime) bounds[1]).toInstant()); + boolean scope = + scopeBound + && sample != null + && !sample.isBefore(((java.time.OffsetDateTime) bounds[2]).toInstant()); + return mock( + Record.class, + read -> + read.getArguments().length == 0 + ? null + : switch (read.getArguments()[0].toString()) { + case "early" -> early; + case "expired" -> lifetimeExpired; + case "scope_elapsed" -> scope; + default -> throw new AssertionError(read.getArgument(0)); + }); + } throw new AssertionError(sql); }); owner = @@ -514,14 +1427,19 @@ private Fixture(boolean expired, Request request, String namespace) throws Excep memberships, issuances, scopes, - new ControlledTransactions(), - Clock.fixed( - CapacityAdmissionTestFixture.NOW.plusSeconds(expired ? 60 : 1), ZoneOffset.UTC), + new ControlledTransactions(this), + clock, namespace); } } private static final class ControlledTransactions implements PlatformTransactionManager { + private final Fixture fixture; + + private ControlledTransactions(Fixture fixture) { + this.fixture = fixture; + } + @Override public TransactionStatus getTransaction( @org.jspecify.annotations.Nullable TransactionDefinition definition) { @@ -530,19 +1448,35 @@ public TransactionStatus getTransaction( .isEqualTo(TransactionDefinition.ISOLATION_SERIALIZABLE); assertThat(definition.getPropagationBehavior()) .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - assertThat(definition.getTimeout()).isEqualTo(5); + assertThat(definition.getTimeout()).isBetween(1, 5); + fixture.timeouts.add(definition.getTimeout()); assertThat(definition.isReadOnly()).isFalse(); + fixture.transactionEvents.add("begin"); + fixture.pendingOriginDecision = null; TransactionSynchronizationManager.setActualTransactionActive(true); return new SimpleTransactionStatus(); } @Override public void commit(TransactionStatus status) { + if (fixture.databaseRejectsDeferredCommit) { + fixture.transactionEvents.add("deferred-commit"); + rollback(status); + throw new org.springframework.transaction.TransactionSystemException( + "Deferred transaction validation failed", + new SQLException("Evaluation expired", "P1040")); + } + if (fixture.pendingOriginDecision != null) + fixture.originDecision = fixture.pendingOriginDecision; + fixture.pendingOriginDecision = null; TransactionSynchronizationManager.setActualTransactionActive(false); } @Override public void rollback(TransactionStatus status) { + fixture.transactionEvents.add("rollback"); + fixture.pendingReservation = false; + fixture.pendingOriginDecision = null; TransactionSynchronizationManager.setActualTransactionActive(false); } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java index 0bda32761b..5f31595d3b 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java @@ -1,34 +1,76 @@ package net.firedevops.firemud.accountservice.service.impl; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockConstruction; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; +import com.google.protobuf.Any; import io.grpc.Status; import io.grpc.protobuf.StatusProto; import io.grpc.stub.StreamObserver; +import java.sql.Connection; +import java.time.Clock; +import java.util.UUID; import java.util.stream.Stream; import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionRequest; import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionResponse; +import net.firedevops.firemud.accountservice.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.CapacityException; import net.firedevops.firemud.accountservice.security.AccountTenantCapacityWorkloadGuard; import net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest; import net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Refusal; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import org.jooq.ConnectionRunnable; +import org.jooq.DSLContext; +import org.jooq.Record; 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.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.mockito.MockedConstruction; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; -/** Controlled handler classification only, not authenticated transport or owner-source proof. */ +/** Controlled handler and owner SQL-path tests, not physical database or mTLS proof. */ class AccountTenantCapacityGrpcServiceTest { + /** A fixed attempt ID that differs from {@link CapacityAdmissionTestFixture#ATTEMPT}. */ + private static final UUID WRONG_ATTEMPT_ID = + UUID.fromString("5a5a5a5a-5a5a-4a5a-8a5a-5a5a5a5a5a5a"); + + private enum RetainedEvidence { + EXACT_QUOTA_DENIAL, + EXACT_EXPIRY_DENIAL, + ABSENT, + ACCEPTED, + GENERIC_NO_ACCEPT, + WRONG_ATTEMPT, + WRONG_DIGEST, + WRONG_FINGERPRINT, + WRITABLE_CONNECTION, + AUTOCOMMIT_CONNECTION + } + @Test void malformedWireAndStructurallyInvalidRequestsRefuseBeforeOwner() { var valid = @@ -65,32 +107,356 @@ void unexpectedOwnerFailuresAreSanitizedInternal(RuntimeException cause) { .commitTenantCapacityAdmission( TenantCapacityAdmissionGrpcCodec.toRequest(request), observer); - var error = ArgumentCaptor.forClass(Throwable.class); - verify(observer).onError(error.capture()); - Status status = Status.fromThrowable(error.getValue()); - assertThat(status.getCode()).isEqualTo(Status.Code.INTERNAL); - assertThat(status.getDescription()).isNull(); - assertThat(status.getCause()).isNull(); - assertThat(error.getValue().getCause()).isNull(); - verify(observer, never()).onNext(any()); - verify(observer, never()).onCompleted(); + assertFailure(observer, Failure.INTERNAL); verify(owner).commit(request, CapacityAdmissionTestFixture.PEER); } } @Test - void typedOwnerEvidenceUnavailableKeepsItsPublicFailure() { + void quotaExceptionRequiresDurableDecisionIdentity() { + org.assertj.core.api.Assertions.assertThatThrownBy( + () -> { + throw new CapacityException(Failure.CAPACITY_QUOTA_EXCEEDED); + }) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void invalidDomainRefusalIsSanitizedInternal() { + // Noncreating evidence cannot authorize a quota refusal, even with a decision UUID. + var request = CapacityAdmissionTestFixture.playerRequest(false); + try (var guards = authenticatedCaller()) { + AccountTenantCapacityOwner owner = mock(); + when(owner.commit(request, CapacityAdmissionTestFixture.PEER)) + .thenThrow( + new CapacityException(Failure.CAPACITY_QUOTA_EXCEEDED, java.util.UUID.randomUUID())); + StreamObserver observer = mock(); + new AccountTenantCapacityGrpcService(owner, "prod") + .commitTenantCapacityAdmission( + TenantCapacityAdmissionGrpcCodec.toRequest(request), observer); + assertFailure(observer, Failure.INTERNAL); + verify(owner).commit(request, CapacityAdmissionTestFixture.PEER); + } + } + + @ParameterizedTest + @MethodSource("ownerUnavailableFailures") + void unavailableOwnerFailureKeepsItsPublicNonOkStatus(RuntimeException failure) { var request = CapacityAdmissionTestFixture.playerRequest(); + try (var guards = authenticatedCaller()) { + AccountTenantCapacityOwner owner = mock(); + when(owner.commit(request, CapacityAdmissionTestFixture.PEER)).thenThrow(failure); + StreamObserver observer = mock(); + new AccountTenantCapacityGrpcService(owner, "prod") + .commitTenantCapacityAdmission( + TenantCapacityAdmissionGrpcCodec.toRequest(request), observer); + assertFailure(observer, Failure.ENTITLEMENT_UNAVAILABLE); + } + } + + @Test + void producedBillingDenialReturnsAnExactTypedResponse() { + Failure code = Failure.TENANT_BILLING_BLOCKED; + var request = CapacityAdmissionTestFixture.playerRequest(false); try (var guards = authenticatedCaller()) { AccountTenantCapacityOwner owner = mock(); when(owner.commit(request, CapacityAdmissionTestFixture.PEER)) - .thenThrow(new CapacityException(Failure.ENTITLEMENT_UNAVAILABLE)); + .thenThrow(new CapacityException(code)); StreamObserver observer = mock(); new AccountTenantCapacityGrpcService(owner, "prod") .commitTenantCapacityAdmission( TenantCapacityAdmissionGrpcCodec.toRequest(request), observer); + var response = ArgumentCaptor.forClass(CommitTenantCapacityAdmissionResponse.class); + var ordered = inOrder(observer); + ordered.verify(observer).onNext(response.capture()); + assertThat(TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, response.getValue())) + .contains(new Refusal(code, null)); + ordered.verify(observer).onCompleted(); + verify(observer, never()).onError(any()); + verifyNoMoreInteractions(observer); + } + } + + @Test + void retainedQuotaDenialCarriesTheExactAccountDecision() { + var request = CapacityAdmissionTestFixture.playerRequest(); + var decisionId = UUID.randomUUID(); + try (var guards = authenticatedCaller()) { + AccountTenantCapacityOwner owner = mock(); + when(owner.commit(request, CapacityAdmissionTestFixture.PEER)) + .thenThrow(new CapacityException(Failure.CAPACITY_QUOTA_EXCEEDED, decisionId)); + StreamObserver observer = mock(); + new AccountTenantCapacityGrpcService(owner, "prod") + .commitTenantCapacityAdmission( + TenantCapacityAdmissionGrpcCodec.toRequest(request), observer); + var response = ArgumentCaptor.forClass(CommitTenantCapacityAdmissionResponse.class); + var ordered = inOrder(observer); + ordered.verify(observer).onNext(response.capture()); + assertThat(TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, response.getValue())) + .contains(new Refusal(Failure.CAPACITY_QUOTA_EXCEEDED, decisionId)); + ordered.verify(observer).onCompleted(); + verify(observer, never()).onError(any()); + verifyNoMoreInteractions(observer); + } + } + + @Test + void ambientSqlScopeBlocksTheDenialReadAsAPrecondition() { + var request = CapacityAdmissionTestFixture.playerRequest(); + var peer = request.evidence().callerWorkload(); + try (var guards = quotaDenialReader(peer)) { + AccountTenantCapacityOwner owner = mock(); + StreamObserver observer = mock(); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + new AccountTenantCapacityGrpcService(owner, "prod") + .readTenantCapacityAdmissionDenial( + TenantCapacityAdmissionGrpcCodec.toRequest(request), observer); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + var error = ArgumentCaptor.forClass(Throwable.class); + verify(observer).onError(error.capture()); + // Retrying inside the same SQL scope cannot succeed, so this is not UNAVAILABLE. + assertThat(StatusProto.fromThrowable(error.getValue())) + .isEqualTo( + StatusProto.fromThrowable( + Failure.ENTITLEMENT_UNAVAILABLE.toStatusException( + Status.Code.FAILED_PRECONDITION))); + verifyNoMoreInteractions(observer); + verifyNoInteractions(owner); + } + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void completionCallbackFailureDoesNotSignalAnotherTerminalEvent(boolean readDenial) { + var request = CapacityAdmissionTestFixture.playerRequest(); + var wire = TenantCapacityAdmissionGrpcCodec.toRequest(request); + var peer = request.evidence().callerWorkload(); + var decisionId = UUID.randomUUID(); + var completionFailure = new IllegalStateException("Controlled completion callback failure"); + try (var guards = readDenial ? quotaDenialReader(peer) : authenticatedCaller()) { + AccountTenantCapacityOwner owner = mock(); + if (readDenial) { + when(owner.readRetainedAdmissionDenial(request, peer)) + .thenReturn(new Refusal(Failure.CAPACITY_QUOTA_EXCEEDED, decisionId)); + } else { + when(owner.commit(request, peer)) + .thenThrow(new CapacityException(Failure.CAPACITY_QUOTA_EXCEEDED, decisionId)); + } + StreamObserver observer = mock(); + doThrow(completionFailure).when(observer).onCompleted(); + var service = new AccountTenantCapacityGrpcService(owner, "prod"); + + assertThatThrownBy( + () -> { + if (readDenial) { + service.readTenantCapacityAdmissionDenial(wire, observer); + } else { + service.commitTenantCapacityAdmission(wire, observer); + } + }) + .isSameAs(completionFailure); + + var ordered = inOrder(observer); + ordered.verify(observer).onNext(any()); + ordered.verify(observer).onCompleted(); + verifyNoMoreInteractions(observer); + } + } + + @ParameterizedTest + @EnumSource(RetainedEvidence.class) + void retainedDenialReadUsesOnlyTheImmutableSelect(RetainedEvidence evidence) throws Exception { + var request = CapacityAdmissionTestFixture.playerRequest(); + var decisionId = UUID.randomUUID(); + var expectedCode = + evidence == RetainedEvidence.EXACT_EXPIRY_DENIAL + ? Failure.CAPACITY_EVALUATION_EXPIRED + : Failure.CAPACITY_QUOTA_EXCEEDED; + DSLContext dsl = mock(); + Connection connection = mock(); + when(connection.isReadOnly()).thenReturn(evidence != RetainedEvidence.WRITABLE_CONNECTION); + when(connection.getAutoCommit()).thenReturn(evidence == RetainedEvidence.AUTOCOMMIT_CONNECTION); + doAnswer( + invocation -> { + invocation.getArgument(0, ConnectionRunnable.class).run(connection); + return null; + }) + .when(dsl) + .connection(any(ConnectionRunnable.class)); + Record row = evidence == RetainedEvidence.ABSENT ? null : mock(Record.class); + if (row != null) { + when(row.get("admission_attempt_id", UUID.class)) + .thenReturn( + evidence == RetainedEvidence.WRONG_ATTEMPT + ? WRONG_ATTEMPT_ID + : request.admissionAttemptId()); + when(row.get("mutation_digest", String.class)) + .thenReturn( + evidence == RetainedEvidence.WRONG_DIGEST + ? "0".repeat(64) + : request.mutationDigest()); + when(row.get("canonical_payload", byte[].class)) + .thenReturn( + evidence == RetainedEvidence.WRONG_FINGERPRINT + ? new byte[] {0} + : CapacityAdmissionDigest.preimage(request)); + when(row.get("decision_id", UUID.class)).thenReturn(decisionId); + when(row.get("decision", String.class)) + .thenReturn(evidence == RetainedEvidence.ACCEPTED ? "ACCEPTED" : "NO_ACCEPT"); + when(row.get("evaluation_identity", String.class)) + .thenReturn( + evidence == RetainedEvidence.ACCEPTED + ? request.evidence().evaluationIdentity() + : null); + when(row.get("refusal_code", String.class)) + .thenReturn( + evidence == RetainedEvidence.ACCEPTED + || evidence == RetainedEvidence.GENERIC_NO_ACCEPT + ? null + : expectedCode.name()); + } + String sql = + "SELECT * FROM account_capacity_origin_decisions WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND capacity_rearm_fence = ?"; + Object[] key = { + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + request.capacityRearmFence() + }; + when(dsl.fetchOne(sql, key)) + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isTrue(); + return row; + }); + PlatformTransactionManager transactions = mock(); + Runnable endReadTransaction = + () -> { + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setActualTransactionActive(false); + }; + doAnswer( + invocation -> { + endReadTransaction.run(); + return null; + }) + .when(transactions) + .commit(any()); + doAnswer( + invocation -> { + endReadTransaction.run(); + return null; + }) + .when(transactions) + .rollback(any()); + when(transactions.getTransaction(any(TransactionDefinition.class))) + .thenAnswer(invocation -> { + var definition = invocation.getArgument(0, TransactionDefinition.class); + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getTimeout()).isEqualTo(5); + assertThat(definition.isReadOnly()).isTrue(); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + return new SimpleTransactionStatus(); + }); + AccountRepository accounts = mock(); + AccountCanonicalRuntimeMembershipSnapshotRepository memberships = mock(); + AccountGameplayDelegationIssuanceRepository issuances = mock(); + AccountConnectScopeRepository scopes = mock(); + Clock clock = mock(); + var owner = + new AccountTenantCapacityOwner( + dsl, accounts, memberships, issuances, scopes, transactions, clock, "prod"); + StreamObserver observer = mock(); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return null; + }) + .when(observer) + .onNext(any()); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return null; + }) + .when(observer) + .onCompleted(); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + return null; + }) + .when(observer) + .onError(any()); + try (var guards = quotaDenialReader(CapacityAdmissionTestFixture.PEER)) { + new AccountTenantCapacityGrpcService(owner, "prod") + .readTenantCapacityAdmissionDenial( + TenantCapacityAdmissionGrpcCodec.toRequest(request), observer); + } finally { + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setActualTransactionActive(false); + } + if (evidence == RetainedEvidence.EXACT_QUOTA_DENIAL + || evidence == RetainedEvidence.EXACT_EXPIRY_DENIAL) { + var response = ArgumentCaptor.forClass(CommitTenantCapacityAdmissionResponse.class); + var ordered = inOrder(observer); + ordered.verify(observer).onNext(response.capture()); + assertThat(TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, response.getValue())) + .contains(new Refusal(expectedCode, decisionId)); + ordered.verify(observer).onCompleted(); + } else { assertFailure(observer, Failure.ENTITLEMENT_UNAVAILABLE); } + verifyNoMoreInteractions(observer); + verify(dsl).connection(any(ConnectionRunnable.class)); + if (evidence == RetainedEvidence.WRITABLE_CONNECTION + || evidence == RetainedEvidence.AUTOCOMMIT_CONNECTION) { + verify(dsl, never()).fetchOne(sql, key); + } else { + verify(dsl).fetchOne(sql, key); + } + verifyNoMoreInteractions(dsl); + verifyNoInteractions(accounts, memberships, issuances, scopes, clock); + } + + @Test + void quotaDenialReadRejectsWrongCallerBindingAndMalformedOriginalBeforeOwner() { + var request = CapacityAdmissionTestFixture.playerRequest(); + var wire = TenantCapacityAdmissionGrpcCodec.toRequest(request); + AccountTenantCapacityOwner owner = mock(); + try (var guards = quotaDenialReader("spiffe://firemud/ns/prod/sa/world-management-service")) { + StreamObserver observer = mock(); + new AccountTenantCapacityGrpcService(owner, "prod") + .readTenantCapacityAdmissionDenial(wire, observer); + assertFailure(observer, Failure.PERMISSION_DENIED); + } + try (var guards = quotaDenialReader(CapacityAdmissionTestFixture.PEER)) { + StreamObserver observer = mock(); + new AccountTenantCapacityGrpcService(owner, "prod") + .readTenantCapacityAdmissionDenial( + wire.toBuilder().setCapacityDelta(0).build(), observer); + assertFailure(observer, Failure.INVALID_ARGUMENT); + } + verifyNoInteractions(owner); + } + + private static Stream ownerUnavailableFailures() { + return Stream.of( + new CapacityException(Failure.ENTITLEMENT_UNAVAILABLE), + new org.jooq.exception.DataAccessException( + "Controlled retained refusal failure", + new java.sql.SQLException("constraint", "23514")), + new org.springframework.dao.DataAccessResourceFailureException( + "Controlled storage failure"), + new org.springframework.transaction.TransactionSystemException( + "Controlled transaction failure")); } private static Stream ownerEvidenceFailures() { @@ -107,13 +473,39 @@ private static MockedConstruction authentica when(guard.requireAuthenticatedCaller()).thenReturn(CapacityAdmissionTestFixture.PEER)); } + private static MockedConstruction quotaDenialReader( + String peer) { + return mockConstruction( + AccountTenantCapacityWorkloadGuard.class, + (guard, context) -> when(guard.requireAdmissionDenialReader()).thenReturn(peer)); + } + private static void assertFailure( StreamObserver observer, Failure expected) { var error = ArgumentCaptor.forClass(Throwable.class); verify(observer).onError(error.capture()); var expectedFailure = expected.toStatusException(); + if (expected == Failure.ENTITLEMENT_UNAVAILABLE) { + assertThat(Status.fromThrowable(error.getValue()).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE); + var status = StatusProto.fromThrowable(error.getValue()); + assertThat(status.getDetailsList()) + .containsExactly( + Any.pack( + ErrorDetail.newBuilder() + .setCode("ENTITLEMENT_UNAVAILABLE") + .setMessage(status.getMessage()) + .build())); + } + if (expected == Failure.INTERNAL) { + // Pin the transport code independently of the shared codec's mapping. + assertThat(Status.fromThrowable(error.getValue()).getCode()).isEqualTo(Status.Code.INTERNAL); + } assertThat(Status.fromThrowable(error.getValue()).getCode()) .isEqualTo(expectedFailure.getStatus().getCode()); + // The transport description stays fixed too, so no exception text leaks there. + assertThat(Status.fromThrowable(error.getValue()).getDescription()) + .isEqualTo(expectedFailure.getStatus().getDescription()); assertThat(StatusProto.fromThrowable(error.getValue())) .isEqualTo(StatusProto.fromThrowable(expectedFailure)); assertThat(error.getValue().getCause()).isNull(); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/OriginalNewCapacityExecution.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/OriginalNewCapacityExecution.java index 79f345925b..8d0bfd82e2 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/OriginalNewCapacityExecution.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/OriginalNewCapacityExecution.java @@ -20,18 +20,12 @@ public record OriginalNewCapacityExecution( String selectedOwnerId, long selectedOwnerFence) { public OriginalNewCapacityExecution { - Objects.requireNonNull(request).requireCommittable(); + requireOriginalNewRequest(request); Objects.requireNonNull(reservation).requireBinding(request); TenantCapacityAdmission.uuid(transitionId); if (selectedOwnerId == null || !selectedOwnerId.matches("[A-Za-z0-9._:-]{1,120}")) throw new IllegalArgumentException("Exact selected owner instance required"); - if (!(request.context() instanceof TenantCapacityAdmission.PlayerContext player) - || !"SHARED".equals(player.playableStateScope()) - || request.operation() != TenantCapacityAdmission.Operation.CAPACITY_CREATING - || !Long.valueOf(1).equals(request.capacityDelta()) - || !request.priorShape().equals(new TenantCapacityAdmission.Shape(0, 0, 0)) - || !request.requestedShape().equals(new TenantCapacityAdmission.Shape(1, 0, 0)) - || (reservation.state() != TenantCapacityAdmission.State.RESERVED + if ((reservation.state() != TenantCapacityAdmission.State.RESERVED && reservation.state() != TenantCapacityAdmission.State.FINALIZED) || !request.identity().admissionId().equals(transitionId) || selectedOwnerFence <= 0 @@ -40,6 +34,18 @@ public record OriginalNewCapacityExecution( throw new IllegalArgumentException("Exact original NEW capacity execution required"); } + public static void requireOriginalNewRequest(TenantCapacityAdmission.Request request) { + Objects.requireNonNull(request).requireCommittable(); + if (!(request.context() instanceof TenantCapacityAdmission.PlayerContext player) + || !"SHARED".equals(player.playableStateScope()) + || request.operation() != TenantCapacityAdmission.Operation.CAPACITY_CREATING + || !Long.valueOf(1).equals(request.capacityDelta()) + || !request.priorShape().equals(new TenantCapacityAdmission.Shape(0, 0, 0)) + || !request.requestedShape().equals(new TenantCapacityAdmission.Shape(1, 0, 0))) { + throw new IllegalArgumentException("Exact original NEW capacity request required"); + } + } + /** All strings have closed grammars; the complete canonical attempt includes Account evidence. */ public byte[] canonicalBytes() { Map fields = new LinkedHashMap<>(); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java index 8840f13cee..ca6161c251 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java @@ -6,6 +6,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.List; +import java.util.function.Function; import javax.net.ssl.SSLException; import net.firedevops.firemud.common.LoggingUtil; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; @@ -20,11 +21,13 @@ public abstract class AbstractReloadingBlockingGrpcClient R withPublishedInitializedStub( + String unavailableMessage, Function call) { + ChannelGeneration selected; + TStub selectedStub; + synchronized (generationLock) { + selectedStub = requirePublishedInitializedStub(unavailableMessage); + selected = generation; + if (selected == null) { + throw new IllegalStateException(unavailableMessage); + } + selected.activeCalls++; + } + try { + return call.apply(selectedStub); + } finally { + boolean shutdown; + synchronized (generationLock) { + selected.activeCalls--; + shutdown = selected.retired && selected.activeCalls == 0; + } + if (shutdown) shutdownRetired(selected); + } } protected final synchronized void reloadChannel() throws SSLException { @@ -147,7 +185,10 @@ protected final synchronized void reloadChannel() throws SSLException { target = defaultTarget(); } ManagedChannel newChannel = - channelFactory.buildChannel(target, defaultPort(), tlsProps, keepAliveEnabled()); + channelRetriesEnabled() + ? channelFactory.buildChannel(target, defaultPort(), tlsProps, keepAliveEnabled()) + : channelFactory.buildChannelWithoutRetries( + target, defaultPort(), tlsProps, keepAliveEnabled()); TStub newStub; try { newStub = buildStub(newChannel); @@ -155,11 +196,17 @@ protected final synchronized void reloadChannel() throws SSLException { newChannel.shutdown(); throw e; } - if (channel != null) { - channel.shutdown(); + retire(publishGeneration(new ChannelGeneration(newChannel), newStub)); + } + + private ChannelGeneration publishGeneration( + ChannelGeneration replacement, TStub replacementStub) { + synchronized (generationLock) { + ChannelGeneration previous = generation; + generation = replacement; + stub = replacementStub; + return previous; } - channel = newChannel; - stub = newStub; } protected final TStub stub() { @@ -174,6 +221,11 @@ protected boolean keepAliveEnabled() { return true; } + /** Retains standard channel behavior unless a dedicated client owns explicit mutation replay. */ + protected boolean channelRetriesEnabled() { + return true; + } + protected Logger logger() { return logger; } @@ -191,25 +243,20 @@ protected final TStub applyStubCustomizer(TStub stub) { @Override public void close() throws IOException { TlsCertificateWatcher watcherToClose; + ChannelGeneration generationToRetire; synchronized (this) { closed = true; explicitlyInitialized = false; watcherToClose = watcher; watcher = null; + generationToRetire = publishGeneration(null, stub); } try { if (watcherToClose != null) { watcherToClose.close(); } } finally { - ManagedChannel channelToShutdown; - synchronized (this) { - channelToShutdown = channel; - channel = null; - } - if (channelToShutdown != null) { - channelToShutdown.shutdown(); - } + retire(generationToRetire); } } @@ -233,19 +280,48 @@ private void cleanupAfterInitialisationFailure(Throwable failure) { } } - ManagedChannel initialChannel; + ChannelGeneration initialGeneration; synchronized (this) { closed = true; - initialChannel = channel; - channel = null; - stub = null; + initialGeneration = publishGeneration(null, null); } - if (initialChannel != null) { + if (markRetiredAndReadyToShutdown(initialGeneration)) { try { - initialChannel.shutdown(); + initialGeneration.channel.shutdown(); } catch (RuntimeException cleanupFailure) { - failure.addSuppressed(cleanupFailure); + if (cleanupFailure != failure) failure.addSuppressed(cleanupFailure); } } } + + private void retire(ChannelGeneration previous) { + if (markRetiredAndReadyToShutdown(previous)) shutdownRetired(previous); + } + + private boolean markRetiredAndReadyToShutdown(ChannelGeneration previous) { + synchronized (generationLock) { + if (previous == null || previous.retired) return false; + previous.retired = true; + return previous.activeCalls == 0; + } + } + + private void shutdownRetired(ChannelGeneration retired) { + try { + retired.channel.shutdown(); + } catch (RuntimeException shutdownFailure) { + // Cleanup cannot invalidate a published replacement or replace an RPC outcome. + logger.warn("Failed to shut down retired gRPC channel", shutdownFailure); + } + } + + private static final class ChannelGeneration { + private final ManagedChannel channel; + private int activeCalls; + private boolean retired; + + private ChannelGeneration(ManagedChannel channel) { + this.channel = channel; + } + } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcChannelFactory.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcChannelFactory.java index cbdd32ecc6..ad9eff8014 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcChannelFactory.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcChannelFactory.java @@ -24,6 +24,27 @@ public ManagedChannel buildChannel( boolean keepAlive, ResolvedGrpcTlsMaterial tlsMaterial) throws SSLException { + return buildChannel(target, defaultPort, properties, keepAlive, tlsMaterial, true); + } + + /** + * Builds a dedicated channel whose mutations require explicit reconciliation before replay. It + * ignores resolver service config, so only the caller's deadline bounds a call. + */ + public ManagedChannel buildChannelWithoutRetries( + String target, int defaultPort, CommonGrpcClientProperties properties, boolean keepAlive) + throws SSLException { + return buildChannel(target, defaultPort, properties, keepAlive, null, false); + } + + private ManagedChannel buildChannel( + String target, + int defaultPort, + CommonGrpcClientProperties properties, + boolean keepAlive, + ResolvedGrpcTlsMaterial tlsMaterial, + boolean retriesEnabled) + throws SSLException { String resolved = target; if (resolved == null || resolved.isBlank()) { resolved = "localhost:" + defaultPort; @@ -32,6 +53,7 @@ public ManagedChannel buildChannel( if (properties.isPlaintext()) { ManagedChannelBuilder builder = createPlaintextBuilder(resolved, defaultPort); configureKeepAlive(builder, keepAlive); + if (!retriesEnabled) builder.disableRetry().disableServiceConfigLookUp(); return builder.build(); } @@ -61,6 +83,8 @@ public ManagedChannel buildChannel( builder = builder.sslContext(sslBuilder.build()); } configureKeepAlive(builder, keepAlive); + // Resolver-supplied service config must not add retries, hedging or method timeouts here. + if (!retriesEnabled) builder.disableRetry().disableServiceConfigLookUp(); return builder.build(); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java index 420399cfef..ff753f2f59 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java @@ -2,24 +2,46 @@ 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.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import io.grpc.ManagedChannel; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.stub.StreamObserver; import java.io.IOException; +import java.net.InetSocketAddress; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.BooleanSupplier; +import java.util.function.Function; import javax.net.ssl.SSLException; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.PingRequest; +import net.firedevops.firemud.gamedesign.v1.PingResponse; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.boot.health.contributor.Health; class AbstractReloadingBlockingGrpcClientTest { @@ -52,6 +74,8 @@ void explicitLifecycleInitializesOnceAndRejectsUseAfterClose() throws Exception assertThatThrownBy(client::requireExplicitStub) .isInstanceOf(IllegalStateException.class) .hasMessage("test client is not initialized and available"); + assertThatThrownBy(client::requirePublishedExplicitStub) + .isInstanceOf(IllegalStateException.class); client.initExplicit(); GameDesignServiceGrpc.GameDesignServiceBlockingStub initializedStub = @@ -60,17 +84,289 @@ void explicitLifecycleInitializesOnceAndRejectsUseAfterClose() throws Exception assertThat(factory.buildAttempts.get()).isEqualTo(1); assertThat(client.requireExplicitStub()).isSameAs(initializedStub); + assertThat(client.requirePublishedExplicitStub()).isSameAs(initializedStub); client.close(); assertThatThrownBy(client::requireExplicitStub) .isInstanceOf(IllegalStateException.class) .hasMessage("test client is not initialized and available"); + assertThatThrownBy(client::requirePublishedExplicitStub) + .isInstanceOf(IllegalStateException.class); assertThatThrownBy(client::initExplicit) .isInstanceOf(IllegalStateException.class) .hasMessage("test client is closed"); } + @Test + void publishedStubIsUnavailableToLeasedCallsUntilExplicitInitialization() throws Exception { + var grpc = new CommonGrpcClientProperties(); + grpc.setPlaintext(true); + var beforeInit = mock(ManagedChannel.class); + var afterInit = mock(ManagedChannel.class); + var factory = mock(GrpcChannelFactory.class); + when(factory.buildChannel(anyString(), anyInt(), any(), anyBoolean())) + .thenReturn(beforeInit, afterInit); + try (var client = new TestClient(new ServiceEndpointsProperties(), grpc, factory)) { + client.reloadChannel(); + assertThat(client.currentStub()).isNotNull(); + assertThat(client.currentStub().getChannel()).isSameAs(beforeInit); + assertThatThrownBy(client::requirePublishedExplicitStub) + .isInstanceOf(IllegalStateException.class) + .hasMessage("test client is not initialized and available"); + + client.initExplicit(); + assertThat(client.requirePublishedExplicitStub().getChannel()).isSameAs(afterInit); + } + } + + @Test + void replacementStubIsPublishedWhenPreviousChannelStartsShutdown() throws Exception { + var grpc = new CommonGrpcClientProperties(); + grpc.setPlaintext(true); + var previous = mock(ManagedChannel.class); + var replacement = mock(ManagedChannel.class); + var factory = mock(GrpcChannelFactory.class); + when(factory.buildChannel(anyString(), anyInt(), any(), anyBoolean())) + .thenReturn(previous, replacement); + var stubAtShutdown = new AtomicReference(); + try (var client = new TestClient(new ServiceEndpointsProperties(), grpc, factory)) { + client.initExplicit(); + var original = client.requirePublishedExplicitStub(); + when(previous.shutdown()) + .thenAnswer(invocation -> { + stubAtShutdown.set(client.requirePublishedExplicitStub()); + return previous; + }); + + client.reloadChannel(); + + var published = client.requirePublishedExplicitStub(); + assertThat(published).isNotSameAs(original); + assertThat(stubAtShutdown.get()).isSameAs(published); + verify(previous).shutdown(); + } + verify(replacement).shutdown(); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void selectedChannelSurvivesReplacementOrCloseUntilBothBlockingCallsReturn(boolean close) + throws Exception { + var calls = new AtomicInteger(); + var expectedResponse = PingResponse.getDefaultInstance(); + var server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .addService( + new GameDesignServiceGrpc.GameDesignServiceImplBase() { + @Override + public void ping(PingRequest request, StreamObserver observer) { + calls.incrementAndGet(); + observer.onNext(expectedResponse); + observer.onCompleted(); + } + }) + .build() + .start(); + // Resources close in reverse order and keep a body failure primary with cleanup suppressed. + try (AutoCloseable stopServer = + () -> assertThat(server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS)).isTrue()) { + var previous = + NettyChannelBuilder.forAddress("127.0.0.1", server.getPort()).usePlaintext().build(); + try (AutoCloseable stopPrevious = terminate(previous)) { + var replacement = + NettyChannelBuilder.forAddress("127.0.0.1", server.getPort()).usePlaintext().build(); + try (AutoCloseable stopReplacement = terminate(replacement)) { + var grpc = new CommonGrpcClientProperties(); + grpc.setPlaintext(true); + var factory = mock(GrpcChannelFactory.class); + when(factory.buildChannel(anyString(), anyInt(), any(), anyBoolean())) + .thenReturn(previous, replacement); + var selected = new CountDownLatch(2); + var startFirst = new CountDownLatch(1); + var startSecond = new CountDownLatch(1); + try (var client = new TestClient(new ServiceEndpointsProperties(), grpc, factory)) { + client.initExplicit(); + var executor = Executors.newFixedThreadPool(2); + Function> submitCall = + ready -> + executor.submit(() -> + client.withPublishedInitializedStub( + "test client has no stub", + stub -> { + assertThat(stub.getChannel()).isSameAs(previous); + selected.countDown(); + try { + // The second call waits through selection (15 s), the lifecycle + // call (10 s) and the first RPC (10 s), so it outlasts them all. + assertThat(ready.await(60, TimeUnit.SECONDS)) + .as( + "the selected call must be released before its bounded wait") + .isTrue(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new AssertionError(interrupted); + } + return stub.withDeadlineAfter(5, TimeUnit.SECONDS) + .ping(PingRequest.getDefaultInstance()); + })); + // Releases both calls before the bounded wait; as a resource, a cleanup failure is + // suppressed under a body failure instead of replacing it. + try (AutoCloseable stopExecutor = + () -> { + startFirst.countDown(); + startSecond.countDown(); + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + }) { + var first = submitCall.apply(startFirst); + var second = submitCall.apply(startSecond); + assertThat(selected.await(15, TimeUnit.SECONDS)).isTrue(); + // Bound the lifecycle call: if it waited for the selected calls, the latches would + // never be released. A timeout fails here and the executor cleanup releases them. + var lifecycle = + Executors.newSingleThreadExecutor(Thread.ofPlatform().daemon().factory()); + try { + lifecycle + .submit(() -> { + if (close) client.close(); + else client.reloadChannel(); + return null; + }) + .get(10, TimeUnit.SECONDS); + } finally { + lifecycle.shutdownNow(); + } + if (close) { + assertThatThrownBy(client::requirePublishedExplicitStub) + .isInstanceOf(IllegalStateException.class); + } else { + assertThat(client.requirePublishedExplicitStub().getChannel()) + .isSameAs(replacement); + } + assertThat(previous.isShutdown()).isFalse(); + assertThat(calls).hasValue(0); + startFirst.countDown(); + assertThat(first.get(10, TimeUnit.SECONDS)).isEqualTo(expectedResponse); + assertThat(calls).hasValue(1); + assertThat(previous.isShutdown()).isFalse(); + startSecond.countDown(); + assertThat(second.get(10, TimeUnit.SECONDS)).isEqualTo(expectedResponse); + assertThat(calls).hasValue(2); + assertThat(previous.isShutdown()).isTrue(); + } + } + } + } + } + } + + private static AutoCloseable terminate(ManagedChannel channel) { + return () -> assertThat(channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + + @Test + void idleRetirementFailureDoesNotInvalidatePublishedReplacement() throws Exception { + var grpc = new CommonGrpcClientProperties(); + grpc.setPlaintext(true); + var previous = mock(ManagedChannel.class); + var replacement = mock(ManagedChannel.class); + var factory = mock(GrpcChannelFactory.class); + when(factory.buildChannel(anyString(), anyInt(), any(), anyBoolean())) + .thenReturn(previous, replacement); + when(previous.shutdown()).thenThrow(new IllegalStateException("shutdown failure")); + try (var client = new TestClient(new ServiceEndpointsProperties(), grpc, factory)) { + client.initExplicit(); + client.reloadChannel(); + assertThat(client.requirePublishedExplicitStub().getChannel()).isSameAs(replacement); + verify(previous).shutdown(); + } + } + + @Test + void retiredChannelShutdownFailureDoesNotReplaceCallOutcome() throws Exception { + var grpc = new CommonGrpcClientProperties(); + grpc.setPlaintext(true); + for (boolean failCall : new boolean[] {false, true}) { + var previous = mock(ManagedChannel.class); + var replacement = mock(ManagedChannel.class); + var factory = mock(GrpcChannelFactory.class); + when(factory.buildChannel(anyString(), anyInt(), any(), anyBoolean())) + .thenReturn(previous, replacement); + when(previous.shutdown()).thenThrow(new IllegalStateException("shutdown failure")); + var originalFailure = new IllegalArgumentException("original call failure"); + try (var client = new TestClient(new ServiceEndpointsProperties(), grpc, factory)) { + client.initExplicit(); + java.util.function.Supplier invoke = + () -> + client.withPublishedInitializedStub( + "missing", + stub -> { + try { + client.reloadChannel(); + } catch (SSLException failure) { + throw new AssertionError(failure); + } + if (failCall) throw originalFailure; + return "response"; + }); + if (failCall) { + assertThatThrownBy(invoke::get).isSameAs(originalFailure); + } else { + assertThat(invoke.get()).isEqualTo("response"); + } + verify(previous).shutdown(); + } + } + } + + @Test + @Timeout(value = 15, threadMode = Timeout.ThreadMode.SAME_THREAD) + void callSelectionDoesNotWaitForReplacementChannelConstruction() throws Exception { + var grpc = new CommonGrpcClientProperties(); + grpc.setPlaintext(true); + var previous = mock(ManagedChannel.class); + var replacement = mock(ManagedChannel.class); + var factory = mock(GrpcChannelFactory.class); + var building = new CountDownLatch(1); + var release = new CountDownLatch(1); + when(factory.buildChannel(anyString(), anyInt(), any(), anyBoolean())) + .thenReturn(previous) + .thenAnswer(invocation -> { + building.countDown(); + release.await(); + return replacement; + }); + var client = new TestClient(new ServiceEndpointsProperties(), grpc, factory); + var executor = Executors.newFixedThreadPool(2, Thread.ofPlatform().daemon().factory()); + try { + client.initExplicit(); + var reload = + executor.submit(() -> { + client.reloadChannel(); + return null; + }); + try { + building.await(); + var call = + executor.submit( + () -> client.withPublishedInitializedStub("missing", stub -> stub.getChannel())); + assertThat(call.get()).isSameAs(previous); + assertThat(release.getCount()).isEqualTo(1); + } finally { + release.countDown(); + } + reload.get(); + } finally { + release.countDown(); + executor.shutdownNow(); + boolean terminated = executor.awaitTermination(5, TimeUnit.SECONDS); + // A regression may deadlock on non-interruptible monitors. Do not block cleanup on them. + if (terminated) client.close(); + assertThat(terminated).isTrue(); + } + } + @Test void initialisationFailurePreventsLateReloadFromCreatingAnotherChannel(@TempDir Path directory) throws Exception { @@ -91,6 +387,37 @@ void initialisationFailurePreventsLateReloadFromCreatingAnotherChannel(@TempDir assertThat(factory.buildAttempts.get()).isEqualTo(1); } + @Test + void watcherStartFailureRetainsChannelShutdownFailure(@TempDir Path directory) throws Exception { + var grpc = new CommonGrpcClientProperties(); + grpc.setCertChain(directory.resolve("tls.crt").toString()); + grpc.setPrivateKey(directory.resolve("tls.key").toString()); + grpc.setCaCert(directory.resolve("ca.crt").toString()); + var factory = mock(GrpcChannelFactory.class); + var channel = mock(ManagedChannel.class); + when(factory.buildChannel(anyString(), anyInt(), any(), anyBoolean())).thenReturn(channel); + var startup = new IllegalStateException("watcher start failed"); + var shutdown = new IllegalStateException("channel shutdown failed"); + when(channel.shutdown()).thenThrow(shutdown); + + try (var policy = mockStatic(GrpcTlsReloadPolicy.class); + var watchers = + mockConstruction( + TlsCertificateWatcher.class, + (watcher, context) -> doThrow(startup).when(watcher).start()); + var client = new TestClient(new ServiceEndpointsProperties(), grpc, factory)) { + policy.when(GrpcTlsReloadPolicy::isEnabled).thenReturn(true); + assertThatThrownBy(client::initExplicit) + .isSameAs(startup) + .satisfies(failure -> assertThat(failure.getSuppressed()).containsExactly(shutdown)); + assertThat(client.currentStub()).isNull(); + assertThatThrownBy(client::requirePublishedExplicitStub) + .isInstanceOf(IllegalStateException.class); + verify(watchers.constructed().getFirst()).close(); + verify(channel).shutdown(); + } + } + @Test void certificateChangeDuringInitialChannelBuildTriggersReload(@TempDir Path directory) throws Exception { @@ -245,6 +572,11 @@ private GameDesignServiceGrpc.GameDesignServiceBlockingStub requireExplicitStub( return requireInitializedStub("test client is not initialized and available"); } + private GameDesignServiceGrpc.GameDesignServiceBlockingStub requirePublishedExplicitStub() { + return withPublishedInitializedStub( + "test client is not initialized and available", selected -> selected); + } + private GameDesignServiceGrpc.GameDesignServiceBlockingStub currentStub() { return stub(); } @@ -262,7 +594,7 @@ protected String defaultTarget() { @Override protected GameDesignServiceGrpc.GameDesignServiceBlockingStub buildStub( ManagedChannel channel) { - return mock(GameDesignServiceGrpc.GameDesignServiceBlockingStub.class); + return GameDesignServiceGrpc.newBlockingStub(channel); } } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcChannelFactoryTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcChannelFactoryTest.java new file mode 100644 index 0000000000..30ddbc817c --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcChannelFactoryTest.java @@ -0,0 +1,159 @@ +package net.firedevops.firemud.common.grpc; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.EquivalentAddressGroup; +import io.grpc.ManagedChannel; +import io.grpc.NameResolver; +import io.grpc.NameResolverProvider; +import io.grpc.NameResolverRegistry; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.stub.StreamObserver; +import java.net.InetSocketAddress; +import java.net.URI; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.PingRequest; +import net.firedevops.firemud.gamedesign.v1.PingResponse; +import org.junit.jupiter.api.Test; + +class GrpcChannelFactoryTest { + private static final String SCHEME = "firemud-short-method-timeout"; + + @Test + void dedicatedChannelIgnoresResolverMethodTimeouts() throws Exception { + // A call carrying the resolver's short deadline (the control) is held until cleanup, so only + // a timeout can end it; the dedicated call answers after a delay longer than 50 ms. + var releaseControl = new java.util.concurrent.CountDownLatch(1); + var server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .addService( + new GameDesignServiceGrpc.GameDesignServiceImplBase() { + @Override + public void ping(PingRequest request, StreamObserver observer) { + try { + var deadline = io.grpc.Context.current().getDeadline(); + if (deadline != null && deadline.timeRemaining(TimeUnit.SECONDS) < 1) { + if (!releaseControl.await(10, TimeUnit.SECONDS)) { + observer.onError(Status.ABORTED.asRuntimeException()); + return; + } + } else { + TimeUnit.MILLISECONDS.sleep(300); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + } + observer.onNext(PingResponse.getDefaultInstance()); + observer.onCompleted(); + } + }) + .build() + .start(); + var properties = new CommonGrpcClientProperties(); + properties.setPlaintext(true); + var factory = new GrpcChannelFactory(); + var target = SCHEME + ":///capacity"; + // Each resource is released by the scope opened right after it is acquired. + try (AutoCloseable stopServer = + () -> assertThat(server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + AutoCloseable release = releaseControl::countDown) { + var provider = new ShortTimeoutResolverProvider(server.getPort()); + NameResolverRegistry.getDefaultRegistry().register(provider); + try (AutoCloseable unregister = + () -> NameResolverRegistry.getDefaultRegistry().deregister(provider)) { + var standard = factory.buildChannel(target, 0, properties, false); + try (AutoCloseable stopStandard = terminate(standard)) { + var dedicated = factory.buildChannelWithoutRetries(target, 0, properties, false); + var executor = Executors.newSingleThreadExecutor(); + try (AutoCloseable stopDedicated = terminate(dedicated); + AutoCloseable stopExecutor = executor::shutdownNow) { + // Control: with no caller deadline, only the resolver's 50 ms method timeout can + // end the standard call before the test's own wait. + var control = + executor.submit(() -> + GameDesignServiceGrpc.newBlockingStub(standard) + .ping(PingRequest.getDefaultInstance())); + assertThatThrownBy(() -> control.get(5, TimeUnit.SECONDS)) + .isInstanceOf(ExecutionException.class) + .cause() + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + assertThat(releaseControl.getCount()).as("control response still held").isOne(); + assertThat(ping(dedicated)).isEqualTo(PingResponse.getDefaultInstance()); + } + } + } + } + } + + private static PingResponse ping(ManagedChannel channel) { + return GameDesignServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .ping(PingRequest.getDefaultInstance()); + } + + private static AutoCloseable terminate(ManagedChannel channel) { + return () -> assertThat(channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + + private static final class ShortTimeoutResolverProvider extends NameResolverProvider { + private final int port; + + private ShortTimeoutResolverProvider(int port) { + this.port = port; + } + + @Override + protected boolean isAvailable() { + return true; + } + + @Override + protected int priority() { + return 5; + } + + @Override + public String getDefaultScheme() { + return SCHEME; + } + + @Override + public NameResolver newNameResolver(URI target, NameResolver.Args args) { + if (!SCHEME.equals(target.getScheme())) return null; + return new NameResolver() { + @Override + public String getServiceAuthority() { + return "capacity"; + } + + @Override + public void start(Listener2 listener) { + Map config = + Map.of( + "methodConfig", List.of(Map.of("name", List.of(Map.of()), "timeout", "0.05s"))); + listener.onResult( + ResolutionResult.newBuilder() + .setAddresses( + List.of(new EquivalentAddressGroup(new InetSocketAddress("127.0.0.1", port)))) + .setServiceConfig(args.getServiceConfigParser().parseServiceConfig(config)) + .build()); + } + + @Override + public void shutdown() {} + }; + } + } +} diff --git a/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionTestFixture.java b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionTestFixture.java index 3dbb82c187..1bd430c7f9 100644 --- a/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionTestFixture.java +++ b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionTestFixture.java @@ -34,6 +34,7 @@ public final class CapacityAdmissionTestFixture { public static final UUID CHARACTER = UUID.fromString("88888888-8888-4888-8888-888888888888"); public static final UUID SESSION = UUID.fromString("99999999-9999-4999-8999-999999999999"); public static final UUID REALM = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + public static final UUID DELEGATION_JTI = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); public static final String PEER = "spiffe://firemud/ns/prod/sa/game-session-service"; public static final Instant NOW = Instant.parse("2026-11-02T00:00:00Z"); private static final String HASH = "a".repeat(64); @@ -85,8 +86,21 @@ public static TenantCapacityAdmission.Request playerRequestFor( String namespace, Map target, Instant at) { + return playerRequestFor(player, admission, attempt, namespace, target, at, true); + } + + public static TenantCapacityAdmission.Request playerRequestFor( + TenantCapacityAdmission.PlayerContext player, + UUID admission, + UUID attempt, + String namespace, + Map target, + Instant at, + boolean permitsCreation) { Map source = new LinkedHashMap<>(sources()); source.put("callerTokenExpiresAt", at.plusSeconds(90).toString()); + Map policy = new LinkedHashMap<>(facts()); + policy.put("allowNewGameplayBindings", permitsCreation); var evidence = RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( player.requestId(), @@ -95,7 +109,7 @@ public static TenantCapacityAdmission.Request playerRequestFor( RuntimePlayerAdmissionEntitlementEvidence.connectScopeTokenHash("controlled-scope"), admittingMembership(player.accountId(), player.tenantId(), player.requestId()), target, - facts(), + policy, source, at); return new TenantCapacityAdmission.Request( @@ -260,9 +274,10 @@ private static Map sources() { Map source = new LinkedHashMap<>(); source.put("callerTokenExpiresAt", NOW.plusSeconds(90).toString()); source.put("paidReceiptValidUntil", null); - for (String key : - List.of("callerTokenJti", "callerContextId", "callerOperationId", "worldCaptureId")) - source.put(key, REQUEST.toString()); + source.put("callerTokenJti", DELEGATION_JTI.toString()); + source.put("callerContextId", "cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + source.put("callerOperationId", "dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + source.put("worldCaptureId", REQUEST.toString()); for (String key : List.of( "callerTokenSha256", diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java index 537c57c303..3ec3c307f2 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java @@ -9,11 +9,13 @@ import io.grpc.protobuf.StatusProto; import java.time.Instant; import java.util.List; +import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionRequest; import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionResponse; import net.firedevops.firemud.account.v1.TenantCapacityAdmissionAttempt; import net.firedevops.firemud.account.v1.TenantCapacityAdmissionCommitment; +import net.firedevops.firemud.account.v1.TenantCapacityAdmissionRefusal; import net.firedevops.firemud.account.v1.TenantCapacityPlayerContext; import net.firedevops.firemud.account.v1.TenantCapacityShape; import net.firedevops.firemud.account.v1.TenantCapacityWorldContext; @@ -47,7 +49,9 @@ public enum Failure { CAPACITY_ADMISSION_STALE(Status.Code.UNAVAILABLE), ENTITLEMENT_UNAVAILABLE(Status.Code.UNAVAILABLE), TENANT_BILLING_BLOCKED(Status.Code.RESOURCE_EXHAUSTED), - CAPACITY_QUOTA_EXCEEDED(Status.Code.RESOURCE_EXHAUSTED); + CAPACITY_QUOTA_EXCEEDED(Status.Code.RESOURCE_EXHAUSTED), + CAPACITY_EVALUATION_EXPIRED(Status.Code.FAILED_PRECONDITION), + INTERNAL(Status.Code.INTERNAL); private final Status.Code code; @@ -55,6 +59,14 @@ public enum Failure { this.code = code; } + public boolean isDomainRefusal() { + return this == TENANT_BILLING_BLOCKED || supportsDurableDenial(); + } + + public boolean supportsDurableDenial() { + return this == CAPACITY_QUOTA_EXCEEDED || this == CAPACITY_EVALUATION_EXPIRED; + } + public StatusRuntimeException toStatusException() { return toStatusException(code); } @@ -74,8 +86,21 @@ private ErrorDetail detail() { } private boolean matches(Status.Code status) { - return status == code - || (this == ENTITLEMENT_UNAVAILABLE && status == Status.Code.FAILED_PRECONDITION); + return !isDomainRefusal() + && (status == code + || (this == ENTITLEMENT_UNAVAILABLE && status == Status.Code.FAILED_PRECONDITION)); + } + } + + /** Request-bound refusal content. A missing durable decision supplies no settlement proof. */ + public record Refusal(Failure code, UUID durableDenialId) { + public Refusal { + if (code == null || !code.isDomainRefusal()) throw invalid(); + if (code.supportsDurableDenial() && durableDenialId == null) throw invalid(); + if (durableDenialId != null) { + if (!code.supportsDurableDenial()) throw invalid(); + TenantCapacityAdmission.uuid(durableDenialId); + } } } @@ -180,6 +205,7 @@ public static CommitTenantCapacityAdmissionResponse toResponse(Request request, public static Result requireResponse( Request request, CommitTenantCapacityAdmissionResponse wire) { clean(wire, MAX_RESPONSE_WIRE_BYTES); + if (wire.getRefusalCount() != 0) throw invalid(); var result = one(wire.getCommitmentList()); clean(result, MAX_RESPONSE_WIRE_BYTES); String expires = one(result.getExpiresAtList()); @@ -209,6 +235,86 @@ public static Result requireResponse( return parsed; } + public static CommitTenantCapacityAdmissionResponse toRefusal(Request request, Failure failure) { + return toRefusal(request, failure, null); + } + + public static CommitTenantCapacityAdmissionResponse toRefusal( + Request request, Failure failure, UUID durableDenialId) { + request.requireStructurallyValid(); + var refusal = new Refusal(failure, durableDenialId); + requireRefusalAuthority(request, refusal); + var exact = + TenantCapacityAdmissionRefusal.newBuilder() + .addTenantId(request.identity().tenantId().toString()) + .addRequestId(request.identity().requestId().toString()) + .addAdmissionId(request.identity().admissionId().toString()) + .addAdmissionAttemptId(request.admissionAttemptId().toString()) + .addCapacityRearmFence(request.capacityRearmFence()) + .addMutationDigest(request.mutationDigest()) + .addSnapshotIdentity(request.evidence().snapshotIdentity()) + .addEvaluationIdentity(request.evidence().evaluationIdentity()) + .addCode(TenantCapacityAdmissionRefusal.Code.valueOf(refusal.code().name())); + if (refusal.durableDenialId() != null) + exact.addDurableDenialId(refusal.durableDenialId().toString()); + var wire = CommitTenantCapacityAdmissionResponse.newBuilder().addRefusal(exact).build(); + clean(wire, MAX_RESPONSE_WIRE_BYTES); + return wire; + } + + /** Returns empty for the commitment envelope, which callers then verify with requireResponse. */ + public static Optional readRefusal( + Request request, CommitTenantCapacityAdmissionResponse wire) { + return readRefusalDetails(request, wire).map(Refusal::code); + } + + /** Decodes the exact refusal, including the optional durable Account decision. */ + public static Optional readRefusalDetails( + Request request, CommitTenantCapacityAdmissionResponse wire) { + clean(wire, MAX_RESPONSE_WIRE_BYTES); + if (wire.getRefusalCount() == 0) { + clean(one(wire.getCommitmentList()), MAX_RESPONSE_WIRE_BYTES); + return Optional.empty(); + } + if (wire.getCommitmentCount() != 0) throw invalid(); + var refusal = one(wire.getRefusalList()); + clean(refusal, MAX_RESPONSE_WIRE_BYTES); + request.requireStructurallyValid(); + if (!request.identity().tenantId().toString().equals(one(refusal.getTenantIdList())) + || !request.identity().requestId().toString().equals(one(refusal.getRequestIdList())) + || !request.identity().admissionId().toString().equals(one(refusal.getAdmissionIdList())) + || !request.admissionAttemptId().toString().equals(one(refusal.getAdmissionAttemptIdList())) + || request.capacityRearmFence() != one(refusal.getCapacityRearmFenceList()) + || !request.mutationDigest().equals(one(refusal.getMutationDigestList())) + || !request.evidence().snapshotIdentity().equals(one(refusal.getSnapshotIdentityList())) + || !request + .evidence() + .evaluationIdentity() + .equals(one(refusal.getEvaluationIdentityList()))) throw invalid(); + Failure code = + switch (one(refusal.getCodeList())) { + case TENANT_BILLING_BLOCKED -> Failure.TENANT_BILLING_BLOCKED; + case CAPACITY_QUOTA_EXCEEDED -> Failure.CAPACITY_QUOTA_EXCEEDED; + case CAPACITY_EVALUATION_EXPIRED -> Failure.CAPACITY_EVALUATION_EXPIRED; + default -> throw invalid(); + }; + UUID durableDenialId = + refusal.getDurableDenialIdCount() == 0 ? null : uuid(one(refusal.getDurableDenialIdList())); + var result = new Refusal(code, durableDenialId); + requireRefusalAuthority(request, result); + return Optional.of(result); + } + + private static void requireRefusalAuthority(Request request, Refusal refusal) { + if (request.capacityRearmFence() != 1) throw invalid(); + if (refusal.code() == Failure.TENANT_BILLING_BLOCKED + && (request.evidence().permitsCreation() + || request.operation() != Operation.CAPACITY_CREATING)) throw invalid(); + if (refusal.code().supportsDurableDenial() + && (!request.evidence().permitsCreation() + || request.operation() != Operation.CAPACITY_CREATING)) throw invalid(); + } + private static TenantCapacityShape shape(Shape value) { return TenantCapacityShape.newBuilder() .addActiveSessions(value.activeSessions()) diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java index bea9dda822..a5c38f5114 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java @@ -8,20 +8,79 @@ import io.grpc.Status; import io.grpc.protobuf.StatusProto; import java.util.List; +import java.util.Locale; import java.util.UUID; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Refusal; import net.firedevops.firemud.shared.v1.ErrorDetail; import org.junit.jupiter.api.Test; class TenantCapacityAdmissionGrpcCodecTest { + @Test + void expiredEvaluationCarriesTheExactDurableDenial() { + var request = CapacityAdmissionTestFixture.playerRequest(); + var decisionId = UUID.randomUUID(); + var code = Failure.CAPACITY_EVALUATION_EXPIRED; + var response = TenantCapacityAdmissionGrpcCodec.toRefusal(request, code, decisionId); + + assertThat(TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, response)) + .contains(new Refusal(code, decisionId)); + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.toRefusal(request, code)) + .isInstanceOf(IllegalArgumentException.class); + + var commitment = TenantCapacityAdmissionGrpcCodec.toResponse(request, result(request)); + for (var invalid : + List.of( + response.toBuilder().addCommitment(commitment.getCommitment(0)).build(), + response.toBuilder().addRefusal(response.getRefusal(0)).build(), + response.toBuilder() + .setRefusal(0, response.getRefusal(0).toBuilder().clearDurableDenialId()) + .build())) { + assertThatThrownBy( + () -> TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, invalid)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.requireResponse(request, invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + } + @Test void onlyCanonicalFailureDetailsSurviveWithoutChangingTransportStatus() { + var domainCodes = + java.util.Set.of( + Failure.TENANT_BILLING_BLOCKED, + Failure.CAPACITY_QUOTA_EXCEEDED, + Failure.CAPACITY_EVALUATION_EXPIRED); for (var failure : Failure.values()) { - var canonical = failure.toStatusException(); - assertThat(TenantCapacityAdmissionGrpcCodec.validateFailure(canonical)).isSameAs(canonical); + assertThat(failure.isDomainRefusal()).isEqualTo(domainCodes.contains(failure)); + if (domainCodes.contains(failure)) { + assertThatThrownBy(failure::toStatusException).isInstanceOf(IllegalArgumentException.class); + var status = + failure == Failure.CAPACITY_EVALUATION_EXPIRED + ? Status.Code.FAILED_PRECONDITION + : Status.Code.RESOURCE_EXHAUSTED; + var oldTransport = + StatusProto.toStatusRuntimeException( + com.google.rpc.Status.newBuilder() + .setCode(status.value()) + .setMessage("Tenant capacity commitment did not complete") + .addDetails( + Any.pack( + ErrorDetail.newBuilder() + .setCode(failure.name()) + .setMessage("Tenant capacity commitment did not complete") + .build())) + .build()); + var verified = TenantCapacityAdmissionGrpcCodec.validateFailure(oldTransport); + assertThat(verified.getStatus().getCode()).isEqualTo(status); + assertThat(StatusProto.fromThrowable(verified).getDetailsList()).isEmpty(); + } else { + var canonical = failure.toStatusException(); + assertThat(TenantCapacityAdmissionGrpcCodec.validateFailure(canonical)).isSameAs(canonical); + } } var deadline = Status.DEADLINE_EXCEEDED.asRuntimeException(); assertThat(TenantCapacityAdmissionGrpcCodec.validateFailure(deadline)).isSameAs(deadline); @@ -36,6 +95,294 @@ void onlyCanonicalFailureDetailsSurviveWithoutChangingTransportStatus() { assertThat(StatusProto.fromThrowable(verified).getDetailsList()).isEmpty(); } + @Test + void domainRefusalsRequireTheExactOriginalAndExclusiveResponseAlternative() { + Request creatingRequest = CapacityAdmissionTestFixture.playerRequest(); + var commitment = + TenantCapacityAdmissionGrpcCodec.toResponse(creatingRequest, result(creatingRequest)); + assertThat(TenantCapacityAdmissionGrpcCodec.readRefusal(creatingRequest, commitment)).isEmpty(); + assertThat(TenantCapacityAdmissionGrpcCodec.requireResponse(creatingRequest, commitment)) + .isEqualTo(result(creatingRequest)); + var exactRefusal = + TenantCapacityAdmissionGrpcCodec.toRefusal( + creatingRequest, Failure.CAPACITY_QUOTA_EXCEEDED, UUID.randomUUID()); + var mixed = commitment.toBuilder().addRefusal(exactRefusal.getRefusal(0)).build(); + assertThatThrownBy( + () -> TenantCapacityAdmissionGrpcCodec.requireResponse(creatingRequest, mixed)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.readRefusal(creatingRequest, mixed)) + .isInstanceOf(IllegalArgumentException.class); + for (var code : List.of(Failure.TENANT_BILLING_BLOCKED, Failure.CAPACITY_QUOTA_EXCEEDED)) { + Request request = + CapacityAdmissionTestFixture.playerRequest(code == Failure.CAPACITY_QUOTA_EXCEEDED); + UUID decisionId = code.supportsDurableDenial() ? UUID.randomUUID() : null; + var response = TenantCapacityAdmissionGrpcCodec.toRefusal(request, code, decisionId); + assertThat(TenantCapacityAdmissionGrpcCodec.readRefusal(request, response)).contains(code); + assertThat(TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, response)) + .contains(new Refusal(code, decisionId)); + if (decisionId != null) { + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.toRefusal(request, code)) + .isInstanceOf(IllegalArgumentException.class); + var withoutReceipt = + response.toBuilder() + .setRefusal(0, response.getRefusal(0).toBuilder().clearDurableDenialId()) + .build(); + assertThatThrownBy( + () -> TenantCapacityAdmissionGrpcCodec.readRefusal(request, withoutReceipt)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.requireResponse(request, response)) + .isInstanceOf(IllegalArgumentException.class); + for (var malformed : + List.of( + response.toBuilder().clearRefusal().build(), + response.toBuilder().addRefusal(response.getRefusal(0)).build(), + response.toBuilder().addCommitment(commitment.getCommitment(0)).build(), + response.toBuilder() + .setRefusal(0, response.getRefusal(0).toBuilder().setCapacityRearmFence(0, 2)) + .build(), + response.toBuilder() + .setRefusal( + 0, + response.getRefusal(0).toBuilder() + .setTenantId(0, "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa")) + .build(), + response.toBuilder() + .setRefusal( + 0, + response.getRefusal(0).toBuilder() + .setAdmissionAttemptId(0, "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")) + .build(), + response.toBuilder() + .setRefusal( + 0, response.getRefusal(0).toBuilder().setMutationDigest(0, "b".repeat(64))) + .build(), + response.toBuilder() + .setRefusal(0, response.getRefusal(0).toBuilder().setCodeValue(0, 999)) + .build())) { + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.readRefusal(request, malformed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + } + + @Test + void creatingEvidenceCannotCarryBillingRefusalOnEncodeOrDecode() { + var request = CapacityAdmissionTestFixture.playerRequest(); + assertThat(request.evidence().permitsCreation()).isTrue(); + assertThatThrownBy(() -> + TenantCapacityAdmissionGrpcCodec.toRefusal(request, Failure.TENANT_BILLING_BLOCKED)) + .isInstanceOf(IllegalArgumentException.class); + var quota = + TenantCapacityAdmissionGrpcCodec.toRefusal( + request, Failure.CAPACITY_QUOTA_EXCEEDED, UUID.randomUUID()); + var billing = + quota.toBuilder() + .setRefusal( + 0, + quota.getRefusal(0).toBuilder() + .clearDurableDenialId() + .setCode( + 0, + net.firedevops.firemud.account.v1.TenantCapacityAdmissionRefusal.Code + .TENANT_BILLING_BLOCKED)) + .build(); + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, billing)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void nonCreatingEvidenceCannotCarryQuotaRefusal() { + var request = CapacityAdmissionTestFixture.playerRequest(false); + var billing = + TenantCapacityAdmissionGrpcCodec.toRefusal(request, Failure.TENANT_BILLING_BLOCKED); + assertThat(TenantCapacityAdmissionGrpcCodec.readRefusal(request, billing)) + .contains(Failure.TENANT_BILLING_BLOCKED); + var denialId = UUID.randomUUID(); + assertThatThrownBy(() -> + TenantCapacityAdmissionGrpcCodec.toRefusal( + request, Failure.CAPACITY_QUOTA_EXCEEDED, denialId)) + .isInstanceOf(IllegalArgumentException.class); + var quota = + billing.toBuilder() + .setRefusal( + 0, + billing.getRefusal(0).toBuilder() + .addDurableDenialId(denialId.toString()) + .setCode( + 0, + net.firedevops.firemud.account.v1.TenantCapacityAdmissionRefusal.Code + .CAPACITY_QUOTA_EXCEEDED)) + .build(); + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.readRefusal(request, quota)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void nonExpandingRequestCannotCarryQuotaRefusal() { + var original = CapacityAdmissionTestFixture.playerRequest(); + var request = + new Request( + original.identity(), + original.admissionAttemptId(), + 1, + original.targetNamespace(), + original.context(), + TenantCapacityAdmission.Operation.NON_EXPANDING_RECOVERY, + original.requestedShape(), + original.requestedShape(), + original.evidence(), + 0L, + null) + .withDigest(); + request.requireStructurallyValid(); + var id = UUID.randomUUID(); + assertThatThrownBy(() -> + TenantCapacityAdmissionGrpcCodec.toRefusal( + request, Failure.CAPACITY_QUOTA_EXCEEDED, id)) + .isInstanceOf(IllegalArgumentException.class); + var quota = + TenantCapacityAdmissionGrpcCodec.toRefusal(original, Failure.CAPACITY_QUOTA_EXCEEDED, id); + var forged = + quota.toBuilder() + .setRefusal( + 0, quota.getRefusal(0).toBuilder().setMutationDigest(0, request.mutationDigest())) + .build(); + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, forged)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void nonExpandingRequestCannotCarryBillingRefusal() { + var original = CapacityAdmissionTestFixture.playerRequest(false); + var request = + new Request( + original.identity(), + original.admissionAttemptId(), + 1, + original.targetNamespace(), + original.context(), + TenantCapacityAdmission.Operation.NON_EXPANDING_RECOVERY, + original.requestedShape(), + original.requestedShape(), + original.evidence(), + 0L, + null) + .withDigest(); + request.requireStructurallyValid(); + assertThatThrownBy(() -> + TenantCapacityAdmissionGrpcCodec.toRefusal(request, Failure.TENANT_BILLING_BLOCKED)) + .isInstanceOf(IllegalArgumentException.class); + var billing = + TenantCapacityAdmissionGrpcCodec.toRefusal(original, Failure.TENANT_BILLING_BLOCKED); + var mismatchedOperation = + billing.toBuilder() + .setRefusal( + 0, billing.getRefusal(0).toBuilder().setMutationDigest(0, request.mutationDigest())) + .build(); + assertThatThrownBy( + () -> TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, mismatchedOperation)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void matchedRearmCannotCarryEitherOriginalRefusal() { + for (var code : List.of(Failure.TENANT_BILLING_BLOCKED, Failure.CAPACITY_QUOTA_EXCEEDED)) { + var original = + CapacityAdmissionTestFixture.playerRequest(code == Failure.CAPACITY_QUOTA_EXCEEDED); + var request = + new Request( + original.identity(), + UUID.randomUUID(), + 2, + original.targetNamespace(), + original.context(), + original.operation(), + original.priorShape(), + original.requestedShape(), + original.evidence(), + original.capacityDelta(), + null) + .withDigest(); + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.toRefusal(request, code)) + .isInstanceOf(IllegalArgumentException.class); + var originalRefusal = + TenantCapacityAdmissionGrpcCodec.toRefusal( + original, code, code.supportsDurableDenial() ? UUID.randomUUID() : null); + var wire = + originalRefusal.toBuilder() + .setRefusal( + 0, + originalRefusal.getRefusal(0).toBuilder() + .setAdmissionAttemptId(0, request.admissionAttemptId().toString()) + .setCapacityRearmFence(0, request.capacityRearmFence()) + .setMutationDigest(0, request.mutationDigest())) + .build(); + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, wire)) + .isInstanceOf(IllegalArgumentException.class); + if (code == Failure.CAPACITY_QUOTA_EXCEEDED) { + var id = UUID.randomUUID(); + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.toRefusal(request, code, id)) + .isInstanceOf(IllegalArgumentException.class); + var forged = + wire.toBuilder() + .setRefusal(0, wire.getRefusal(0).toBuilder().addDurableDenialId(id.toString())) + .build(); + assertThatThrownBy( + () -> TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, forged)) + .isInstanceOf(IllegalArgumentException.class); + } + } + } + + @Test + void onlyExactQuotaRefusalMayCarryOneCanonicalNonnilAccountDecisionId() { + var request = CapacityAdmissionTestFixture.playerRequest(); + var decisionId = UUID.fromString("aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee"); + var response = + TenantCapacityAdmissionGrpcCodec.toRefusal( + request, Failure.CAPACITY_QUOTA_EXCEEDED, decisionId); + assertThat(TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, response)) + .contains(new Refusal(Failure.CAPACITY_QUOTA_EXCEEDED, decisionId)); + assertThat(TenantCapacityAdmissionGrpcCodec.readRefusal(request, response)) + .contains(Failure.CAPACITY_QUOTA_EXCEEDED); + + var receipt = response.getRefusal(0); + for (var malformed : + List.of( + receipt.toBuilder().addDurableDenialId(decisionId.toString()).build(), + receipt.toBuilder().setDurableDenialId(0, "").build(), + receipt.toBuilder().setDurableDenialId(0, new UUID(0, 0).toString()).build(), + receipt.toBuilder() + .setDurableDenialId(0, decisionId.toString().toUpperCase(Locale.ROOT)) + .build(), + receipt.toBuilder().setCapacityRearmFence(0, 2).build())) { + assertThatThrownBy(() -> + TenantCapacityAdmissionGrpcCodec.readRefusalDetails( + request, response.toBuilder().setRefusal(0, malformed).build())) + .isInstanceOf(IllegalArgumentException.class); + } + var billingRequest = CapacityAdmissionTestFixture.playerRequest(false); + var billing = + TenantCapacityAdmissionGrpcCodec.toRefusal(billingRequest, Failure.TENANT_BILLING_BLOCKED); + var forgedBilling = + billing.toBuilder() + .setRefusal( + 0, billing.getRefusal(0).toBuilder().addDurableDenialId(decisionId.toString())) + .build(); + assertThatThrownBy(() -> + TenantCapacityAdmissionGrpcCodec.readRefusalDetails(billingRequest, forgedBilling)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> + TenantCapacityAdmissionGrpcCodec.toRefusal( + billingRequest, Failure.TENANT_BILLING_BLOCKED, decisionId)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> + TenantCapacityAdmissionGrpcCodec.toRefusal( + request, Failure.CAPACITY_QUOTA_EXCEEDED, new UUID(0, 0))) + .isInstanceOf(IllegalArgumentException.class); + } + @Test void exactBothAlternativesRoundTripWithCompleteBundleAndReservationBinding() { for (Request request : diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java index 052cef8630..fc39d68fb4 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java @@ -14,6 +14,7 @@ import java.time.ZoneOffset; import java.util.List; import java.util.Set; +import java.util.concurrent.TimeUnit; import net.firedevops.firemud.account.v1.AccountServiceGrpc; import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionRequest; import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeRequest; @@ -47,9 +48,9 @@ class AccountRuntimeStubServerCompatibilityTest { "RequestEmailVerification", "VerifyEmail", "VerifyEmailLoginOtp"); - // Private runtime mutations require their actual bounded mTLS owner, never fake authority. + // Private capacity RPCs require their actual bounded mTLS owner. private static final Set UNIMPLEMENTED_RUNTIME_METHODS = - Set.of("CommitTenantCapacityAdmission"); + Set.of("CommitTenantCapacityAdmission", "ReadTenantCapacityAdmissionDenial"); @Test void accountServiceMethodSetIsFullyCategorized() { @@ -72,17 +73,24 @@ void accountServiceMethodSetIsFullyCategorized() { } @Test - void privateCapacityMutationRemainsUnimplementedOnSharedFakeRuntimeServer() throws Exception { + void privateCapacityRpcsRemainUnimplementedOnSharedFakeRuntimeServer() throws Exception { assertThat(AccountRuntimeStubServer.implementedRuntimeMethodNames()) - .doesNotContain("CommitTenantCapacityAdmission"); + .doesNotContain("CommitTenantCapacityAdmission", "ReadTenantCapacityAdmissionDenial"); try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); try { var stub = AccountServiceGrpc.newBlockingStub(channel); + var request = CommitTenantCapacityAdmissionRequest.getDefaultInstance(); assertThatThrownBy(() -> - stub.commitTenantCapacityAdmission( - CommitTenantCapacityAdmissionRequest.getDefaultInstance())) + stub.withDeadlineAfter(2, TimeUnit.SECONDS).commitTenantCapacityAdmission(request)) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNIMPLEMENTED)); + assertThatThrownBy(() -> + stub.withDeadlineAfter(2, TimeUnit.SECONDS) + .readTenantCapacityAdmissionDenial(request)) .isInstanceOfSatisfying( StatusRuntimeException.class, failure -> diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java new file mode 100644 index 0000000000..88348ad994 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java @@ -0,0 +1,306 @@ +package net.firedevops.firemud.gamesession.client; + +import io.grpc.Context; +import io.grpc.Deadline; +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.function.BiFunction; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.AccountServiceGrpc.AccountServiceBlockingStub; +import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionRequest; +import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionResponse; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Refusal; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; + +/** + * Unregistered exact Account capacity adapter. It performs no admission or owner activation CAS. + */ +public final class AccountTenantCapacityClient + extends AbstractReloadingBlockingGrpcClient { + private final String namespace; + private final Clock clock; + private final String expectedPeer; + + public AccountTenantCapacityClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + String namespace, + Clock clock) { + super( + endpoints, + requireFileBackedMtls(tls, "Tenant capacity commitment"), + channels, + AccountTenantCapacityClient.class); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Namespace required"); + this.namespace = namespace; + this.expectedPeer = "spiffe://firemud/ns/" + namespace + "/sa/account-service"; + this.clock = Objects.requireNonNull(clock); + } + + private static final long MAX_CLOCK_BRACKET_MILLIS = 50; + private static final int MAX_CLOCK_BRACKETS = 3; + + public void init() throws IOException { + requireNoAmbientSql("Capacity client initialization requires no SQL transaction"); + initOnce("Capacity client is closed", "Account capacity unavailable"); + } + + /** + * The caller must obtain its typed context from current owned player state, not text/metadata. + * Retries retain this exact request. The Account call consumes the remaining absolute admission + * budget, capped at five seconds and the incoming deadline. A timeout or an inexact response + * leaves the commitment indeterminate. Collect read-only evidence for the original attempt first; + * only replay this mutation with the exact original request when reconciliation permits it. + */ + public Result commit(Request request, long absoluteDeadlineMillis) { + var response = + invoke( + request, + absoluteDeadlineMillis, + AccountServiceBlockingStub::commitTenantCapacityAdmission); + try { + var refusal = TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, response); + if (refusal.isPresent()) throw new CapacityRefusedException(refusal.orElseThrow()); + // Exact retry may replay an expired/terminal reservation. The final owner still checks it. + return TenantCapacityAdmissionGrpcCodec.requireResponse(request, response); + } catch (IllegalArgumentException inexactResponse) { + throw Status.UNKNOWN + .withDescription("Account capacity commitment response was inexact") + .asRuntimeException(); + } + } + + /** + * Recovers an exact immutable denial while the caller owns the original held attempt. Recovery + * usually follows an expired or cancelled admission call, so the read runs in a forked Context + * bounded only by its own absolute deadline and the five-second cap. + */ + public Refusal readRetainedAdmissionDenial(Request request, long absoluteDeadlineMillis) { + Context recovery = Context.current().fork(); + Context previous = recovery.attach(); + final CommitTenantCapacityAdmissionResponse response; + try { + response = + invoke( + request, + absoluteDeadlineMillis, + AccountServiceBlockingStub::readTenantCapacityAdmissionDenial); + } finally { + recovery.detach(previous); + } + try { + return TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, response) + .filter(refusal -> refusal.durableDenialId() != null) + .orElseThrow(IllegalArgumentException::new); + } catch (IllegalArgumentException inexactResponse) { + throw Status.UNKNOWN + .withDescription("Account retained admission denial was not proven") + .asRuntimeException(); + } + } + + private CommitTenantCapacityAdmissionResponse invoke( + Request request, + long absoluteDeadlineMillis, + BiFunction< + AccountServiceBlockingStub, + CommitTenantCapacityAdmissionRequest, + CommitTenantCapacityAdmissionResponse> + call) { + long maximumMillis = + TimeUnit.SECONDS.toMillis(TenantCapacityAdmissionGrpcCodec.CALL_DEADLINE_SECONDS); + Deadline maximum = Deadline.after(maximumMillis, TimeUnit.MILLISECONDS); + requireNoAmbientSql("Capacity request requires no ambient SQL"); + // Bracket the wall-clock read with monotonic samples and anchor on the earlier edge, so the + // conversion can only shorten the caller budget. A bracket widened by a pause would waste + // that pause, so it is sampled again while the invocation cap still allows. + Deadline sampledAt; + Instant sampledInstant; + int brackets = 0; + do { + sampledAt = Deadline.after(0, TimeUnit.NANOSECONDS); + sampledInstant = clock.instant(); + } while (bracketWastesBudget(sampledAt, sampledInstant, absoluteDeadlineMillis) + && ++brackets < MAX_CLOCK_BRACKETS + && !maximum.isExpired()); + var wire = TenantCapacityAdmissionGrpcCodec.toRequest(request); + if (request.context().owner() != TenantCapacityAdmission.Owner.GAME_SESSION + || !namespace.equals(request.targetNamespace())) + throw new IllegalArgumentException("Exact Game Session context required"); + Deadline deadline = + selectDeadline( + maximum, + sampledAt, + Context.current().getDeadline(), + absoluteDeadlineMillis, + sampledInstant); + try { + return withPublishedInitializedStub( + "Account capacity unavailable", + stub -> { + if (deadline.isExpired()) throw Status.DEADLINE_EXCEEDED.asRuntimeException(); + var bounded = + stub.withDeadline(deadline) + .withMaxOutboundMessageSize( + TenantCapacityAdmissionGrpcCodec.MAX_REQUEST_WIRE_BYTES) + .withMaxInboundMessageSize( + TenantCapacityAdmissionGrpcCodec.MAX_RESPONSE_WIRE_BYTES); + return call.apply(bounded, wire); + }); + } catch (StatusRuntimeException failure) { + throw TenantCapacityAdmissionGrpcCodec.validateFailure(failure); + } + } + + /** + * A bracket is retried when it is wide, or when the pause inside it already used up a budget that + * the wall sample still shows as positive. + */ + private static boolean bracketWastesBudget( + Deadline sampledAt, Instant sampledInstant, long absoluteDeadlineMillis) { + long bracketMillis = -sampledAt.timeRemaining(TimeUnit.MILLISECONDS); + long wallRemainingMillis = absoluteDeadlineMillis - sampledInstant.toEpochMilli(); + return bracketMillis > MAX_CLOCK_BRACKET_MILLIS + || (wallRemainingMillis > 0 && bracketMillis >= wallRemainingMillis); + } + + /** Converts paired clock samples without resetting the invocation or incoming cap. */ + static Deadline selectDeadline( + Deadline maximum, + Deadline sampledAt, + Deadline incoming, + long absoluteDeadlineMillis, + Instant sampledInstant) { + Duration maximumBudget = + Duration.ofSeconds(TenantCapacityAdmissionGrpcCodec.CALL_DEADLINE_SECONDS); + Duration remaining = + Duration.between(sampledInstant, Instant.ofEpochMilli(absoluteDeadlineMillis)); + // Cap before converting to nanos: extreme epoch-millisecond deadlines may exceed long nanos. + long remainingNanos = + remaining.isNegative() + ? 0 + : (remaining.compareTo(maximumBudget) > 0 ? maximumBudget : remaining).toNanos(); + Deadline absoluteDeadline = sampledAt.offset(remainingNanos, TimeUnit.NANOSECONDS); + Deadline selected = maximum.minimum(absoluteDeadline); + return incoming == null ? selected : selected.minimum(incoming); + } + + /** Exact Account domain refusal without a capacity commitment. */ + public static final class CapacityRefusedException extends IllegalStateException { + private final TenantCapacityAdmissionGrpcCodec.Failure code; + private final UUID durableDenialId; + + private CapacityRefusedException(TenantCapacityAdmissionGrpcCodec.Refusal refusal) { + super(refusal.code().name()); + this.code = refusal.code(); + this.durableDenialId = refusal.durableDenialId(); + } + + /** Replays a denial after the local owner verifies its exact retained binding. */ + public static CapacityRefusedException retainedAdmissionDenial(Refusal denial) { + if (denial == null || denial.durableDenialId() == null) { + throw new IllegalArgumentException("A retained capacity denial requires its decision ID"); + } + return new CapacityRefusedException(denial); + } + + public TenantCapacityAdmissionGrpcCodec.Failure code() { + return code; + } + + /** The exact Account denial receipt, if the authenticated response carried one. */ + public UUID durableDenialId() { + return durableDenialId; + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + String target = endpoints.getAccountService(); + if (target == null || target.isBlank()) { + return null; + } + // Supported targets are a plain host:port or dns:///host:port. Any other resolver scheme + // fails the address checks below and is refused. + boolean dnsTarget = target.regionMatches(true, 0, "dns:/", 0, 5); + // The gRPC DNS provider accepts only the lowercase scheme. A single-slash path has no + // authority, so write it in the canonical empty-authority form. + if (dnsTarget) target = "dns:" + (target.startsWith("//", 4) ? "" : "//") + target.substring(4); + try { + String endpoint = target; + if (dnsTarget) { + URI resolver = URI.create(target); + String path = resolver.getPath(); + // The pinned gRPC DNS provider ignores a resolver authority, so refuse one. + if (resolver.getRawAuthority() != null + || path == null + || path.length() <= 1 + || path.indexOf('/', 1) >= 0 + || resolver.getRawQuery() != null + || resolver.getRawFragment() != null) { + return null; + } + endpoint = path.substring(1); + } + URI address = URI.create("grpc://" + endpoint); + int port = address.getPort(); + if (address.getHost() != null + && address.getRawUserInfo() == null + && address.getRawPath().isEmpty() + && address.getRawQuery() == null + && address.getRawFragment() == null + && port > 0 + && port <= 65535) { + // Give every bare address an explicit DNS target: the shared builder splits bare targets + // on colons (IPv6), and a host named like a scheme (dns:7443) would read as one. + if (!dnsTarget) { + return new URI("dns", "", "/" + endpoint, null).toASCIIString(); + } + return target; + } + } catch (IllegalArgumentException | URISyntaxException ignored) { + // Treat a malformed address as an absent explicit target. + } + return null; + } + + @Override + protected String defaultTarget() { + throw new IllegalStateException("Explicit private Account capacity target is required"); + } + + @Override + protected boolean channelRetriesEnabled() { + // Even a trailers-only failure is indeterminate until the exact original is reconciled. + return false; + } + + @Override + protected AccountServiceGrpc.AccountServiceBlockingStub buildStub(ManagedChannel channel) { + return AccountServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeer)); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java new file mode 100644 index 0000000000..6ff854c7f7 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java @@ -0,0 +1,1586 @@ +package net.firedevops.firemud.gamesession.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.CallOptions; +import io.grpc.ClientCall; +import io.grpc.ConnectivityState; +import io.grpc.Context; +import io.grpc.Deadline; +import io.grpc.EquivalentAddressGroup; +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.NameResolver; +import io.grpc.NameResolverProvider; +import io.grpc.NameResolverRegistry; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.ServerStreamTracer; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.time.Clock; +import java.time.ZoneOffset; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.FutureTask; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionRequest; +import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionResponse; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Refusal; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.api.parallel.ResourceLock; +import org.junit.jupiter.api.parallel.Resources; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.NullAndEmptySource; +import org.junit.jupiter.params.provider.ValueSource; + +/** Real loopback mTLS with a controlled Account result; not Account sources or final admission. */ +@Timeout(90) +class AccountTenantCapacityClientMtlsTest { + private static final String TLS_RELOAD_PROPERTY = "firemud.grpc.tls-reload.enabled"; + private static final UUID ACCOUNT_RESERVATION_ID = + UUID.fromString("a0577a29-9be2-42a0-9770-4c2a90581358"); + @TempDir static Path directory; + private static LoopbackMtlsTestPki.Pki pki; + + @ParameterizedTest + @NullAndEmptySource + @ValueSource( + strings = { + " \t ", + "account.internal", + "dns:///account.internal", + "dns:///account.internal/extra:7443", + "dns:///account.internal%2Fextra:7443", + "dns:///account.internal:7443?alternate=1", + "dns://resolver.internal/account.internal:7443", + "account.internal:7443/path://ignored", + "test:///account", + "capacity-retry-test:/account", + "account.internal:0", + "account.internal:65536" + }) + void initializationRequiresAnExplicitPrivateTarget(String target) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService(target); + var factory = mock(GrpcChannelFactory.class); + try (var client = + new AccountTenantCapacityClient( + endpoints, + pki.clientProperties(directory, pki.identity("client")), + factory, + "prod", + Clock.fixed(CapacityAdmissionTestFixture.NOW, ZoneOffset.UTC))) { + assertThatThrownBy(client::init) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Explicit private Account capacity target is required"); + verifyNoInteractions(factory); + } + } + + @BeforeAll + static void certificates() throws Exception { + pki = + LoopbackMtlsTestPki.create( + directory, + "Capacity client test CA", + new LoopbackMtlsTestPki.IdentitySpec( + "client", "spiffe://firemud/ns/prod/sa/game-session-service", false), + new LoopbackMtlsTestPki.IdentitySpec( + "account", "spiffe://firemud/ns/prod/sa/account-service", true), + new LoopbackMtlsTestPki.IdentitySpec( + "wrong", "spiffe://firemud/ns/prod/sa/world-management-service", true)); + } + + @ParameterizedTest + @CsvSource({ + "account.internal:7443, dns:///account.internal:7443", + "dns:7443, dns:///dns:7443", + "dns:///account.internal:7443, dns:///account.internal:7443", + "DNS:///account.internal:7443, dns:///account.internal:7443", + "dns:/account.internal:7443, dns:///account.internal:7443", + "[::1]:7443, dns:///%5B::1%5D:7443" + }) + void channelFactoryReceivesValidatedAccountEndpoint(String configured, String target) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService(configured); + var factory = mock(GrpcChannelFactory.class); + when(factory.buildChannelWithoutRetries(eq(target), anyInt(), any(), anyBoolean())) + .thenReturn(mock(ManagedChannel.class)); + try (var client = + new AccountTenantCapacityClient( + endpoints, + pki.clientProperties(directory, pki.identity("client")), + factory, + "prod", + Clock.fixed(CapacityAdmissionTestFixture.NOW, ZoneOffset.UTC))) { + client.init(); + verify(factory).buildChannelWithoutRetries(eq(target), anyInt(), any(), anyBoolean()); + } + } + + @ParameterizedTest + @ValueSource( + strings = { + "[::1]:7443", + "dns:///%5B::1%5D:7443", + "dns:///account.internal:7443", + "DNS:///account.internal:7443" + }) + void resolverEndpointBuildsARealNettyChannel(String target) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService(target); + try (var client = + new AccountTenantCapacityClient( + endpoints, + pki.clientProperties(directory, pki.identity("client")), + new GrpcChannelFactory(), + "prod", + Clock.fixed(CapacityAdmissionTestFixture.NOW, ZoneOffset.UTC))) { + client.init(); + } + } + + @Test + void exactAccountPeerReceivesCompleteRequestAndExactRetryKeepsReservation() throws Exception { + AtomicInteger calls = new AtomicInteger(); + AtomicInteger messages = new AtomicInteger(); + AtomicReference serverFailure = new AtomicReference<>(); + Server server = + server( + "account", + calls, + false, + new AtomicLong(), + new AtomicBoolean(true), + serverFailure, + null, + messages); + try (AutoCloseable stopServer = () -> stop(server); + var client = client(server)) { + client.init(); + var request = CapacityAdmissionTestFixture.playerRequest(); + var first = client.commit(request, deadline()); + var replay = client.commit(request, deadline()); + assertThat(first.reservationId()).isEqualTo(ACCOUNT_RESERVATION_ID); + assertThat(replay).isEqualTo(first); + assertThat(first.identity()).isEqualTo(request.identity()); + assertThat(serverFailure.get()).isNull(); + assertThat(calls).hasValue(2); + assertThat(messages).hasValue(2); + } + } + + @Test + void unavailableAfterAccountReceivedRequestDoesNotRetryCommit() throws Exception { + AtomicInteger calls = new AtomicInteger(); + Server server = + startServer( + "account", + new AccountServiceGrpc.AccountServiceImplBase() { + @Override + public void commitTenantCapacityAdmission( + CommitTenantCapacityAdmissionRequest request, + StreamObserver observer) { + calls.incrementAndGet(); + observer.onError( + Status.UNAVAILABLE.withDescription("Response lost").asRuntimeException()); + } + }); + try (var client = client(server)) { + client.init(); + assertThatThrownBy( + () -> client.commit(CapacityAdmissionTestFixture.playerRequest(), deadline())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE)); + assertThat(calls).hasValue(1); + } finally { + stop(server); + } + } + + @Test + void resolverMethodTimeoutShortensStandardTlsChannelButNotCapacityChannel() throws Exception { + var observedMillis = new AtomicLong(-1); + var releaseStalled = new CountDownLatch(1); + Server server = + startServer( + "account", + new AccountServiceGrpc.AccountServiceImplBase() { + @Override + public void commitTenantCapacityAdmission( + CommitTenantCapacityAdmissionRequest request, + StreamObserver observer) { + long remaining = + Objects.requireNonNull(Context.current().getDeadline()) + .timeRemaining(TimeUnit.MILLISECONDS); + observedMillis.set(remaining); + if (remaining < 1_000) { + // Stall a short-deadline call so only its deadline can end it. + try { + if (!releaseStalled.await(10, TimeUnit.SECONDS)) { + observer.onError(Status.ABORTED.asRuntimeException()); + return; + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + } + } + // A recognizable response, distinct from a client-side timeout. + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + } + }); + var resolver = + new ServiceConfigNameResolverProvider( + server.getPort(), "capacity-timeout-test", Map.of("timeout", "0.05s")); + var registry = NameResolverRegistry.getDefaultRegistry(); + registry.register(resolver); + try { + String target = resolver.getDefaultScheme() + ":///account"; + var tls = pki.clientProperties(directory, pki.identity("client")); + var factory = new GrpcChannelFactory(); + var wire = + TenantCapacityAdmissionGrpcCodec.toRequest(CapacityAdmissionTestFixture.playerRequest()); + for (boolean dedicated : new boolean[] {false, true}) { + var channel = + dedicated + ? factory.buildChannelWithoutRetries(target, 6565, tls, true) + : factory.buildChannel(target, 6565, tls, true); + try { + var stub = AccountServiceGrpc.newBlockingStub(channel); + // Warm the channel with an RPC that has no resolver method timeout. + assertThatThrownBy(() -> + stub.withDeadlineAfter(5, TimeUnit.SECONDS) + .getProfile( + net.firedevops.firemud.account.v1.GetProfileRequest.getDefaultInstance())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()) + .isNotEqualTo(Status.Code.DEADLINE_EXCEEDED)); + observedMillis.set(-1); + assertThatThrownBy(() -> + stub.withDeadlineAfter(5, TimeUnit.SECONDS).commitTenantCapacityAdmission(wire)) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()) + .isEqualTo( + dedicated + ? Status.Code.FAILED_PRECONDITION + : Status.Code.DEADLINE_EXCEEDED)); + // The deadline Account saw shows which bound applied to each channel. + if (dedicated) { + assertThat(observedMillis.get()).isGreaterThan(1_000); + } else { + assertThat(observedMillis.get()).isBetween(0L, 50L); + } + } finally { + channel.shutdownNow(); + assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + } finally { + releaseStalled.countDown(); + registry.deregister(resolver); + stop(server); + } + } + + @Test + void resolverRetryPolicyRetriesStandardChannelButNotCapacityCommit() throws Exception { + AtomicInteger calls = new AtomicInteger(); + Server server = + startServer( + "account", + new AccountServiceGrpc.AccountServiceImplBase() { + @Override + public void commitTenantCapacityAdmission( + CommitTenantCapacityAdmissionRequest request, + StreamObserver observer) { + calls.incrementAndGet(); + // No response headers/message: the service-config policy can retry this failure. + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + }); + var resolver = ServiceConfigNameResolverProvider.retryPolicy(server.getPort()); + var registry = NameResolverRegistry.getDefaultRegistry(); + registry.register(resolver); + try { + String target = resolver.getDefaultScheme() + ":///account"; + var tls = pki.clientProperties(directory, pki.identity("client")); + var factory = new GrpcChannelFactory(); + var request = CapacityAdmissionTestFixture.playerRequest(); + var standard = factory.buildChannel(target, 6565, tls, true); + try { + assertThatThrownBy(() -> + AccountServiceGrpc.newBlockingStub(standard) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .commitTenantCapacityAdmission( + TenantCapacityAdmissionGrpcCodec.toRequest(request))) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE)); + assertThat(calls) + .hasValue(2); // Positive control: the resolver policy really enables replay. + } finally { + standard.shutdownNow(); + assertThat(standard.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + // The client accepts only address targets, so prove the dedicated channel directly. + var dedicated = factory.buildChannelWithoutRetries(target, 6565, tls, true); + try { + assertThatThrownBy(() -> + AccountServiceGrpc.newBlockingStub(dedicated) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .commitTenantCapacityAdmission( + TenantCapacityAdmissionGrpcCodec.toRequest(request))) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE)); + assertThat(calls).hasValue(3); // Exactly one additional transport attempt, not two. + } finally { + dedicated.shutdownNow(); + assertThat(dedicated.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } finally { + registry.deregister(resolver); + stop(server); + } + } + + @Test + void nonCreatingEvidenceReachesControlledAccountAndReturnsStructuredPolicyDenial() + throws Exception { + AtomicInteger calls = new AtomicInteger(); + Server server = server("account", calls, false); + try (var client = client(server)) { + client.init(); + var request = CapacityAdmissionTestFixture.playerRequest(false); + assertThatThrownBy(() -> client.commit(request, deadline())) + .isInstanceOfSatisfying( + AccountTenantCapacityClient.CapacityRefusedException.class, + refusal -> { + assertThat(refusal.code()) + .isEqualTo(TenantCapacityAdmissionGrpcCodec.Failure.TENANT_BILLING_BLOCKED); + assertThat(refusal.durableDenialId()).isNull(); + }); + assertThat(calls).hasValue(1); + } finally { + stop(server); + } + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void quotaRefusalRequiresTheAuthenticatedAccountReceipt(boolean retained) throws Exception { + var request = CapacityAdmissionTestFixture.playerRequest(); + UUID decisionId = UUID.randomUUID(); + var response = denialResponse(request, Failure.CAPACITY_QUOTA_EXCEEDED, decisionId, retained); + var capturedRequest = new AtomicReference(); + Server server = + startServer( + "account", + new AccountServiceGrpc.AccountServiceImplBase() { + @Override + public void commitTenantCapacityAdmission( + CommitTenantCapacityAdmissionRequest wire, + StreamObserver observer) { + capturedRequest.set(wire); + observer.onNext(response); + observer.onCompleted(); + } + }); + try (var client = client(server)) { + client.init(); + if (retained) { + assertThatThrownBy(() -> client.commit(request, deadline())) + .isInstanceOfSatisfying( + AccountTenantCapacityClient.CapacityRefusedException.class, + refusal -> { + assertThat(refusal.code()).isEqualTo(Failure.CAPACITY_QUOTA_EXCEEDED); + assertThat(refusal.durableDenialId()).isEqualTo(decisionId); + }); + } else { + assertThatThrownBy(() -> client.commit(request, deadline())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> { + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNKNOWN); + assertThat(failure.getStatus().getDescription()) + .isEqualTo("Account capacity commitment response was inexact"); + }); + } + assertThat(capturedRequest.get()) + .isEqualTo(TenantCapacityAdmissionGrpcCodec.toRequest(request)); + } finally { + stop(server); + } + } + + private static CommitTenantCapacityAdmissionResponse denialResponse( + TenantCapacityAdmission.Request request, Failure code, UUID decisionId, boolean retained) { + var response = TenantCapacityAdmissionGrpcCodec.toRefusal(request, code, decisionId); + return retained + ? response + : response.toBuilder() + .setRefusal(0, response.getRefusal(0).toBuilder().clearDurableDenialId()) + .build(); + } + + @Test + void restartedClientRecoversTheOriginalQuotaDenialWithoutAnotherCommit() throws Exception { + assertOriginalDenialRecovery(Failure.CAPACITY_QUOTA_EXCEEDED, DenialReadback.RECOVERED, false); + } + + @Test + void restartedClientRefusesQuotaDenialWithoutAReceiptAndDoesNotCommitAgain() throws Exception { + assertOriginalDenialRecovery( + Failure.CAPACITY_QUOTA_EXCEEDED, DenialReadback.MISSING_RECEIPT, false); + } + + @Test + void restartedClientRecoversTheOriginalExpiredEvaluationDenialWithoutAnotherCommit() + throws Exception { + assertOriginalDenialRecovery( + Failure.CAPACITY_EVALUATION_EXPIRED, DenialReadback.RECOVERED, false); + } + + @Test + void restartedClientRecoversOriginalDenialWithFreshBudgetAfterCommitTimesOut() throws Exception { + assertOriginalDenialRecovery(Failure.CAPACITY_QUOTA_EXCEEDED, DenialReadback.RECOVERED, true); + } + + @Test + void restartedClientRejectsRetainedDenialFromADifferentAttempt() throws Exception { + assertOriginalDenialRecovery( + Failure.CAPACITY_QUOTA_EXCEEDED, DenialReadback.DIFFERENT_ATTEMPT, false); + } + + @Test + void restartedClientPreservesUnavailableWhenAccountHasNoDenialAndDoesNotCommitAgain() + throws Exception { + assertOriginalDenialRecovery( + Failure.CAPACITY_QUOTA_EXCEEDED, DenialReadback.UNAVAILABLE, false); + } + + @Test + void restartedClientRejectsCommitmentOnTheDenialReadAndDoesNotCommitAgain() throws Exception { + assertOriginalDenialRecovery(Failure.CAPACITY_QUOTA_EXCEEDED, DenialReadback.COMMITMENT, false); + } + + @Test + void restartedClientRejectsReceiptlessBillingRefusalOnTheDenialRead() throws Exception { + assertOriginalDenialRecovery( + Failure.TENANT_BILLING_BLOCKED, DenialReadback.BILLING_REFUSAL, false); + } + + private enum DenialReadback { + RECOVERED, + MISSING_RECEIPT, + DIFFERENT_ATTEMPT, + UNAVAILABLE, + // Valid commit outcomes that are not a durable denial. + COMMITMENT, + BILLING_REFUSAL + } + + @Test + void recoveryReadIgnoresTheExpiredAdmissionCallContext() throws Exception { + assertOriginalDenialRecovery( + Failure.CAPACITY_QUOTA_EXCEEDED, DenialReadback.RECOVERED, true, true); + } + + private void assertOriginalDenialRecovery(Failure code, DenialReadback readback, boolean timeOut) + throws Exception { + assertOriginalDenialRecovery(code, readback, timeOut, false); + } + + private void assertOriginalDenialRecovery( + Failure code, DenialReadback readback, boolean timeOut, boolean expiredCaller) + throws Exception { + var clock = mock(Clock.class); + var now = new AtomicReference<>(CapacityAdmissionTestFixture.NOW); + when(clock.instant()).thenAnswer(ignored -> now.get()); + long originalDeadline = deadline(); + var tls = pki.clientProperties(directory, pki.identity("client")); + var request = + CapacityAdmissionTestFixture.playerRequest(readback != DenialReadback.BILLING_REFUSAL); + var denialRequest = + readback == DenialReadback.DIFFERENT_ATTEMPT + ? new net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request( + request.identity(), + UUID.randomUUID(), + request.capacityRearmFence(), + request.targetNamespace(), + request.context(), + request.operation(), + request.priorShape(), + request.requestedShape(), + request.evidence(), + request.capacityDelta(), + null) + .withDigest() + : request; + UUID denialId = + (readback == DenialReadback.RECOVERED || readback == DenialReadback.DIFFERENT_ATTEMPT) + ? UUID.randomUUID() + : null; + var commits = new AtomicInteger(); + var reads = new AtomicInteger(); + var failedCommit = new AtomicReference(); + var retainedRead = new AtomicReference(); + Server server = + startServer( + "account", + new AccountServiceGrpc.AccountServiceImplBase() { + @Override + public void commitTenantCapacityAdmission( + CommitTenantCapacityAdmissionRequest wire, + StreamObserver observer) { + commits.incrementAndGet(); + failedCommit.set(wire); + if (!timeOut) observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + + @Override + public void readTenantCapacityAdmissionDenial( + CommitTenantCapacityAdmissionRequest wire, + StreamObserver observer) { + reads.incrementAndGet(); + retainedRead.set(wire); + if (readback == DenialReadback.UNAVAILABLE) { + observer.onError(Failure.ENTITLEMENT_UNAVAILABLE.toStatusException()); + return; + } + if (readback == DenialReadback.COMMITMENT) { + observer.onNext( + TenantCapacityAdmissionGrpcCodec.toResponse( + request, + new TenantCapacityAdmission.Result( + request.identity(), + request.admissionAttemptId(), + request.capacityRearmFence(), + request.mutationDigest(), + UUID.randomUUID(), + 1, + request.evidence().expiresAt(), + TenantCapacityAdmission.State.RESERVED, + request.evidence().snapshotIdentity(), + request.evidence().evaluationIdentity()))); + observer.onCompleted(); + return; + } + if (readback == DenialReadback.BILLING_REFUSAL) { + observer.onNext(TenantCapacityAdmissionGrpcCodec.toRefusal(request, code, null)); + observer.onCompleted(); + return; + } + observer.onNext( + denialResponse( + denialRequest, + code, + denialId == null ? UUID.randomUUID() : denialId, + denialId != null)); + observer.onCompleted(); + } + }); + try (AutoCloseable stopServer = () -> stop(server)) { + try (var original = client(server, tls, new GrpcChannelFactory(), clock)) { + original.init(); + assertThatThrownBy(() -> original.commit(request, originalDeadline)) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()) + .isEqualTo( + timeOut ? Status.Code.DEADLINE_EXCEEDED : Status.Code.UNAVAILABLE)); + } + assertThat(failedCommit.get()).isEqualTo(TenantCapacityAdmissionGrpcCodec.toRequest(request)); + now.set(request.evidence().expiresAt().plusMillis(1)); + long readDeadline = now.get().plusSeconds(5).toEpochMilli(); + try (var restarted = client(server, tls, new GrpcChannelFactory(), clock)) { + restarted.init(); + if (readback == DenialReadback.RECOVERED && expiredCaller) { + // The admission call that timed out has an expired Context; recovery must still read. + var scheduler = java.util.concurrent.Executors.newSingleThreadScheduledExecutor(); + try (var expired = + io.grpc.Context.current().withDeadlineAfter(0, TimeUnit.NANOSECONDS, scheduler)) { + assertThat(expired.isCancelled()).isTrue(); + assertThat( + expired.call( + () -> restarted.readRetainedAdmissionDenial(request, readDeadline))) + .isEqualTo(new Refusal(code, denialId)); + } finally { + scheduler.shutdownNow(); + } + } else if (readback == DenialReadback.RECOVERED) { + assertThat(restarted.readRetainedAdmissionDenial(request, readDeadline)) + .isEqualTo(new Refusal(code, denialId)); + } else if (readback == DenialReadback.UNAVAILABLE) { + assertThatThrownBy(() -> restarted.readRetainedAdmissionDenial(request, readDeadline)) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + // The detail, not only the status, distinguishes it from a stale admission. + assertThat(io.grpc.protobuf.StatusProto.fromThrowable(failure)) + .isEqualTo( + io.grpc.protobuf.StatusProto.fromThrowable( + Failure.ENTITLEMENT_UNAVAILABLE.toStatusException()))); + } else { + assertThatThrownBy(() -> restarted.readRetainedAdmissionDenial(request, readDeadline)) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> { + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNKNOWN); + assertThat(failure.getStatus().getDescription()) + .isEqualTo("Account retained admission denial was not proven"); + }); + } + } + assertThat(commits).hasValue(1); + assertThat(reads).hasValue(1); + assertThat(retainedRead.get()).isEqualTo(TenantCapacityAdmissionGrpcCodec.toRequest(request)); + } + } + + @Test + void localDenialReplayRequiresADurableDecisionId() { + var denialId = UUID.randomUUID(); + var replay = + AccountTenantCapacityClient.CapacityRefusedException.retainedAdmissionDenial( + new Refusal(Failure.CAPACITY_QUOTA_EXCEEDED, denialId)); + assertThat(replay.code()) + .isEqualTo(TenantCapacityAdmissionGrpcCodec.Failure.CAPACITY_QUOTA_EXCEEDED); + assertThat(replay.durableDenialId()).isEqualTo(denialId); + var receiptless = new Refusal(Failure.TENANT_BILLING_BLOCKED, null); + var created = new AtomicReference(); + assertThatThrownBy(() -> + created.set( + AccountTenantCapacityClient.CapacityRefusedException.retainedAdmissionDenial( + receiptless))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A retained capacity denial requires its decision ID"); + assertThat(created.get()).isNull(); + } + + @Test + void mismatchedTypedRefusalDoesNotBecomeAnAccountDecision() throws Exception { + AtomicInteger calls = new AtomicInteger(); + AtomicReference serverFailure = new AtomicReference<>(); + Server server = server("account", calls, true, serverFailure); + try (var client = client(server)) { + client.init(); + var request = CapacityAdmissionTestFixture.playerRequest(false); + assertThatThrownBy(() -> client.commit(request, deadline())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNKNOWN)) + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getDescription()) + .isEqualTo("Account capacity commitment response was inexact")); + assertThat(calls).hasValue(1); + assertThat(serverFailure.get()).isNull(); + } finally { + stop(server); + } + } + + @Test + void wrongAccountPeerIsRejectedBeforeRequestBodyRelease() throws Exception { + AtomicInteger calls = new AtomicInteger(); + AtomicInteger messages = new AtomicInteger(); + Server server = + server( + "wrong", calls, false, new AtomicLong(), new AtomicBoolean(true), null, null, messages); + try (var client = client(server)) { + client.init(); + assertThatThrownBy( + () -> client.commit(CapacityAdmissionTestFixture.playerRequest(), deadline())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> { + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(failure.getStatus().getDescription()) + .isEqualTo("Request requires the exact authenticated server workload identity"); + }); + assertThat(messages).hasValue(0); + assertThat(calls).hasValue(0); + } finally { + stop(server); + } + } + + @Test + void changedResponseFenceLeavesTheOriginalCommitmentIndeterminate() throws Exception { + AtomicInteger calls = new AtomicInteger(); + AtomicReference serverFailure = new AtomicReference<>(); + Server server = server("account", calls, true, serverFailure); + try (var client = client(server)) { + client.init(); + assertThatThrownBy( + () -> client.commit(CapacityAdmissionTestFixture.playerRequest(), deadline())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.UNKNOWN)) + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getDescription()) + .isEqualTo("Account capacity commitment response was inexact")); + assertThat(calls).hasValue(1); + assertThat(serverFailure.get()).isNull(); + } finally { + stop(server); + } + } + + @ParameterizedTest + @CsvSource({"3000, 60000, 3000", "60000, 3000, 3000", "60000, 60000, 5000"}) + void successfulRpcPropagatesMinimumOfExplicitIncomingAndMaximumDeadline( + long explicitMillis, long incomingMillis, long expectedMaximumMillis) throws Exception { + AtomicInteger calls = new AtomicInteger(); + AtomicLong observedNanos = new AtomicLong(); + var channelFactory = new CallOptionsCapturingChannelFactory(); + // Warm the channel, then reset the sample before the measured RPC. + Server server = server("account", calls, false, observedNanos, new AtomicBoolean(true)); + var scheduler = Executors.newSingleThreadScheduledExecutor(); + try (var client = + client(server, pki.clientProperties(directory, pki.identity("client")), channelFactory)) { + client.init(); + var request = CapacityAdmissionTestFixture.playerRequest(); + client.commit(request, deadline()); + observedNanos.set(0); + channelFactory.resetCapturedDeadline(); + var earliest = Deadline.after(expectedMaximumMillis, TimeUnit.MILLISECONDS); + try (var context = + Context.current().withDeadlineAfter(incomingMillis, TimeUnit.MILLISECONDS, scheduler)) { + var result = + context.call(() -> + client.commit( + request, CapacityAdmissionTestFixture.NOW.toEpochMilli() + explicitMillis)); + assertThat(result.identity()).isEqualTo(request.identity()); + } + assertThat(calls).hasValue(2); + // Delivery can consume any portion of the budget; the controlled ticker asserts selection. + assertThat(observedNanos.get()) + .isPositive() + .isLessThanOrEqualTo(TimeUnit.MILLISECONDS.toNanos(expectedMaximumMillis)); + var latest = Deadline.after(expectedMaximumMillis, TimeUnit.MILLISECONDS); + var captured = channelFactory.capturedDeadline.get(); + assertThat(captured).isNotNull(); + assertThat(captured.isBefore(earliest)).isFalse(); + assertThat(latest.isBefore(captured)).isFalse(); + } finally { + scheduler.shutdownNow(); + stop(server); + } + } + + @ParameterizedTest + @CsvSource({"1000, 60000, 1000", "3000, 60000, 3000", "60000, 3000, 3000", "60000, 60000, 5000"}) + void deadlineSelectionKeepsTheWholeChosenBudget( + long explicitMillis, long incomingMillis, long expectedMillis) { + var nanos = new AtomicLong(); + var ticker = + new Deadline.Ticker() { + @Override + public long nanoTime() { + return nanos.get(); + } + }; + var maximum = Deadline.after(5, TimeUnit.SECONDS, ticker); + var incoming = Deadline.after(incomingMillis, TimeUnit.MILLISECONDS, ticker); + var sample = Deadline.after(0, TimeUnit.NANOSECONDS, ticker); + var selected = + AccountTenantCapacityClient.selectDeadline( + maximum, sample, incoming, explicitMillis, java.time.Instant.EPOCH); + assertThat(selected.timeRemaining(TimeUnit.MILLISECONDS)).isEqualTo(expectedMillis); + } + + @ParameterizedTest + @CsvSource({"-9223372036854775808, 1, 0", "9223372036854775807, -1, 5000", "0, 0, 0"}) + void extremeWallClockDeadlinesRemainExpiredOrCapped( + long absoluteMillis, long sampledMillis, long expectedMillis) { + var ticker = + new Deadline.Ticker() { + @Override + public long nanoTime() { + return 0; + } + }; + var sample = Deadline.after(0, TimeUnit.NANOSECONDS, ticker); + var maximum = Deadline.after(5, TimeUnit.SECONDS, ticker); + assertThat( + AccountTenantCapacityClient.selectDeadline( + maximum, + sample, + null, + absoluteMillis, + java.time.Instant.ofEpochMilli(sampledMillis)) + .timeRemaining(TimeUnit.MILLISECONDS)) + .isEqualTo(expectedMillis); + } + + @Test + void fractionalWallClockSampleDoesNotExtendTheCallerBudget() { + var ticker = + new Deadline.Ticker() { + @Override + public long nanoTime() { + return 0; + } + }; + var sample = Deadline.after(0, TimeUnit.NANOSECONDS, ticker); + var maximum = Deadline.after(5, TimeUnit.SECONDS, ticker); + var selected = + AccountTenantCapacityClient.selectDeadline( + maximum, sample, null, 1001, java.time.Instant.ofEpochMilli(1000).plusNanos(900_000)); + assertThat(selected.timeRemaining(TimeUnit.NANOSECONDS)).isEqualTo(100_000); + } + + @Test + void setupDelayIsNotDeductedTwiceAndOriginalInvocationCapStillApplies() { + var nanos = new AtomicLong(); + var ticker = + new Deadline.Ticker() { + @Override + public long nanoTime() { + return nanos.get(); + } + }; + var maximum = Deadline.after(5, TimeUnit.SECONDS, ticker); + nanos.set(TimeUnit.SECONDS.toNanos(1)); // Pause before the paired conversion samples. + var sample = Deadline.after(0, TimeUnit.NANOSECONDS, ticker); + assertThat( + AccountTenantCapacityClient.selectDeadline( + maximum, sample, null, 3000, java.time.Instant.ofEpochMilli(1000)) + .timeRemaining(TimeUnit.MILLISECONDS)) + .isEqualTo(2000); + assertThat( + AccountTenantCapacityClient.selectDeadline( + maximum, sample, null, 60000, java.time.Instant.ofEpochMilli(1000)) + .timeRemaining(TimeUnit.MILLISECONDS)) + .isEqualTo(4000); + nanos.addAndGet(TimeUnit.MILLISECONDS.toNanos(200)); // Delay after sampling consumes budget. + assertThat( + AccountTenantCapacityClient.selectDeadline( + maximum, sample, null, 3000, java.time.Instant.ofEpochMilli(1000)) + .timeRemaining(TimeUnit.MILLISECONDS)) + .isEqualTo(1800); + } + + @Test + void pauseBetweenPairedClockSamplesIsSampledAgainInsteadOfSpendingTheBudget() throws Exception { + var calls = new AtomicInteger(); + var observedNanos = new AtomicLong(); + Server server = server("account", calls, false, observedNanos, new AtomicBoolean(true)); + var armed = new AtomicBoolean(); + var advanced = new AtomicBoolean(); + var clock = mock(Clock.class); + var afterPause = CapacityAdmissionTestFixture.NOW.plusMillis(1_500); + when(clock.instant()) + .thenAnswer(ignored -> { + // The first read after arming pauses between the monotonic and wall-clock samples; + // the wall clock then stays advanced for the retried sample. + if (armed.compareAndSet(true, false)) { + TimeUnit.MILLISECONDS.sleep(1_500); + advanced.set(true); + } + return advanced.get() ? afterPause : CapacityAdmissionTestFixture.NOW; + }); + try (var client = + client( + server, + pki.clientProperties(directory, pki.identity("client")), + new GrpcChannelFactory(), + clock)) { + client.init(); + var request = CapacityAdmissionTestFixture.playerRequest(); + var first = client.commit(request, deadline()); + armed.set(true); + // 1.5 s remain after the pause; anchoring on the pre-pause sample would leave none. + long absoluteDeadline = CapacityAdmissionTestFixture.NOW.toEpochMilli() + 3_000L; + assertThat(client.commit(request, absoluteDeadline)).isEqualTo(first); + assertThat(calls).hasValue(2); + // Account saw at most the post-pause budget, never the pre-pause three seconds. + assertThat(observedNanos.get()) + .isPositive() + .isLessThanOrEqualTo(TimeUnit.MILLISECONDS.toNanos(1_500)); + } finally { + stop(server); + } + } + + @Test + void explicitRemainingBudgetBoundsAStalledAccountCall() throws Exception { + AtomicInteger calls = new AtomicInteger(); + AtomicBoolean respond = new AtomicBoolean(true); + AtomicLong observedNanos = new AtomicLong(); + var measuredSecondInvocationEntered = new CountDownLatch(1); + Server server = + server("account", calls, false, observedNanos, respond, measuredSecondInvocationEntered); + try (var client = client(server)) { + client.init(); + var request = CapacityAdmissionTestFixture.playerRequest(); + client.commit(request, deadline()); + respond.set(false); + // Leave dispatch headroom while still bounding this attempt below the client's five seconds. + long explicitDeadline = CapacityAdmissionTestFixture.NOW.toEpochMilli() + 3_000L; + assertThatThrownBy(() -> client.commit(request, explicitDeadline)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + assertThat(measuredSecondInvocationEntered.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat(calls).hasValue(2); // The timed-out invocation reached the nonresponding handler. + assertThat(observedNanos.get()).isLessThanOrEqualTo(TimeUnit.SECONDS.toNanos(3)); + } finally { + stop(server); + } + } + + @Test + @ResourceLock(Resources.SYSTEM_PROPERTIES) + void commitReachesItsTransportDeadlineWhileTlsReloadIsBlocked() throws Exception { + String previousReloadPolicy = System.getProperty(TLS_RELOAD_PROPERTY); + System.setProperty(TLS_RELOAD_PROPERTY, "true"); + try { + var calls = new AtomicInteger(); + var respond = new AtomicBoolean(true); + var measuredSecondInvocationEntered = new CountDownLatch(1); + var tls = pki.clientProperties(directory, pki.identity("client")); + var factory = new BlockingReloadChannelFactory(); + var observedNanos = new AtomicLong(); + var server = + server("account", calls, false, observedNanos, respond, measuredSecondInvocationEntered); + try (AutoCloseable stopServer = () -> stop(server)) { + var client = client(server, tls, factory); + var executor = Executors.newSingleThreadExecutor(Thread.ofPlatform().daemon().factory()); + try (AutoCloseable stopClient = + () -> { + factory.releaseReload.countDown(); + executor.shutdownNow(); + stopReloadingClient(client, factory); + assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)) + .as("capacity RPC worker terminated") + .isTrue(); + }) { + client.init(); + assertThat(factory.singleAttemptBuilds).hasValue(1); + assertThat(factory.standardBuilds).hasValue(0); + var request = CapacityAdmissionTestFixture.playerRequest(); + client.commit(request, deadline()); + respond.set(false); + try { + Files.writeString(Path.of(tls.getCertChain()), "\n", StandardOpenOption.APPEND); + assertThat(factory.reloadStarted.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat(factory.singleAttemptBuilds).hasValue(2); + assertThat(factory.standardBuilds).hasValue(0); + long explicitDeadline = CapacityAdmissionTestFixture.NOW.toEpochMilli() + 3_000L; + var timedOut = + executor.submit(() -> + assertThatThrownBy(() -> client.commit(request, explicitDeadline)) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED))); + assertThat(measuredSecondInvocationEntered.await(4, TimeUnit.SECONDS)).isTrue(); + timedOut.get(4, TimeUnit.SECONDS); + assertThat(factory.releaseReload.getCount()).isEqualTo(1); + assertThat(calls).hasValue(2); + // The deadline Account observed is the three-second budget, not the five-second cap. + assertThat(observedNanos.get()).isLessThanOrEqualTo(TimeUnit.SECONDS.toNanos(3)); + } finally { + factory.releaseReload.countDown(); + } + assertThat(factory.reloadBuilt.await(5, TimeUnit.SECONDS)).isTrue(); + } + } + } finally { + if (previousReloadPolicy == null) { + System.clearProperty(TLS_RELOAD_PROPERTY); + } else { + System.setProperty(TLS_RELOAD_PROPERTY, previousReloadPolicy); + } + } + } + + @Test + void incomingDeadlineBoundsAStalledAccountCall() throws Exception { + AtomicInteger calls = new AtomicInteger(); + AtomicBoolean respond = new AtomicBoolean(true); + AtomicLong observedNanos = new AtomicLong(); + var measuredSecondInvocationEntered = new CountDownLatch(1); + Server server = + server("account", calls, false, observedNanos, respond, measuredSecondInvocationEntered); + var scheduler = Executors.newSingleThreadScheduledExecutor(); + try (var client = client(server)) { + client.init(); + var request = CapacityAdmissionTestFixture.playerRequest(); + client.commit(request, CapacityAdmissionTestFixture.NOW.toEpochMilli() + 60_000L); + respond.set(false); + assertThatThrownBy(() -> + Context.current() + .withDeadlineAfter(3_000, TimeUnit.MILLISECONDS, scheduler) + .call(() -> client.commit(request, deadline()))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + assertThat(measuredSecondInvocationEntered.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat(calls).hasValue(2); // The incoming deadline bounded an actual in-flight call. + assertThat(observedNanos.get()).isLessThanOrEqualTo(TimeUnit.SECONDS.toNanos(3)); + } finally { + scheduler.shutdownNow(); + stop(server); + } + } + + @Test + void expiredExplicitBudgetSendsNoAccountRequest() throws Exception { + AtomicInteger calls = new AtomicInteger(); + var channelFactory = new CallOptionsCapturingChannelFactory(); + Server server = server("account", calls, false); + try (var client = + client(server, pki.clientProperties(directory, pki.identity("client")), channelFactory)) { + client.init(); + assertThatThrownBy(() -> + client.commit( + CapacityAdmissionTestFixture.playerRequest(), + CapacityAdmissionTestFixture.NOW.toEpochMilli() - 1L)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + assertThat(channelFactory.callsCreated).hasValue(0); + assertThat(calls).hasValue(0); + } finally { + stop(server); + } + } + + private static long deadline() { + return CapacityAdmissionTestFixture.NOW.toEpochMilli() + 5_000L; + } + + private static AccountTenantCapacityClient client(Server server) throws Exception { + return client( + server, pki.clientProperties(directory, pki.identity("client")), new GrpcChannelFactory()); + } + + private static AccountTenantCapacityClient client( + Server server, CommonGrpcClientProperties tls, GrpcChannelFactory factory) { + return client( + server, tls, factory, Clock.fixed(CapacityAdmissionTestFixture.NOW, ZoneOffset.UTC)); + } + + private static AccountTenantCapacityClient client( + Server server, CommonGrpcClientProperties tls, GrpcChannelFactory factory, Clock clock) { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + server.getPort()); + return new AccountTenantCapacityClient(endpoints, tls, factory, "prod", clock); + } + + private static Server server(String identity, AtomicInteger calls, boolean wrongFence) + throws Exception { + return server(identity, calls, wrongFence, new AtomicLong(), new AtomicBoolean(true)); + } + + private static Server server( + String identity, + AtomicInteger calls, + boolean wrongFence, + AtomicReference serverFailure) + throws Exception { + return server( + identity, calls, wrongFence, new AtomicLong(), new AtomicBoolean(true), serverFailure); + } + + private static Server server( + String identity, + AtomicInteger calls, + boolean wrongFence, + AtomicLong observedNanos, + AtomicBoolean respond) + throws Exception { + return server(identity, calls, wrongFence, observedNanos, respond, null, null); + } + + private static Server server( + String identity, + AtomicInteger calls, + boolean wrongFence, + AtomicLong observedNanos, + AtomicBoolean respond, + CountDownLatch measuredSecondInvocationEntered) + throws Exception { + return server( + identity, calls, wrongFence, observedNanos, respond, null, measuredSecondInvocationEntered); + } + + private static Server server( + String identity, + AtomicInteger calls, + boolean wrongFence, + AtomicLong observedNanos, + AtomicBoolean respond, + AtomicReference serverFailure) + throws Exception { + return server(identity, calls, wrongFence, observedNanos, respond, serverFailure, null); + } + + private static Server server( + String identity, + AtomicInteger calls, + boolean wrongFence, + AtomicLong observedNanos, + AtomicBoolean respond, + AtomicReference serverFailure, + CountDownLatch measuredSecondInvocationEntered) + throws Exception { + return server( + identity, + calls, + wrongFence, + observedNanos, + respond, + serverFailure, + measuredSecondInvocationEntered, + null); + } + + private static Server server( + String identity, + AtomicInteger calls, + boolean wrongFence, + AtomicLong observedNanos, + AtomicBoolean respond, + AtomicReference serverFailure, + CountDownLatch measuredSecondInvocationEntered, + AtomicInteger messages) + throws Exception { + UUID reservationId = ACCOUNT_RESERVATION_ID; + var service = + new AccountServiceGrpc.AccountServiceImplBase() { + @Override + public void commitTenantCapacityAdmission( + CommitTenantCapacityAdmissionRequest wire, + StreamObserver observer) { + observedNanos.set( + Objects.requireNonNull(Context.current().getDeadline()) + .timeRemaining(TimeUnit.NANOSECONDS)); + int invocation = calls.incrementAndGet(); + if (invocation == 2 && measuredSecondInvocationEntered != null) { + measuredSecondInvocationEntered.countDown(); + } + if (!respond.get()) return; + assertServerSide( + serverFailure, + () -> + assertThat(GrpcPeerIdentity.current().uri()) + .isEqualTo("spiffe://firemud/ns/prod/sa/game-session-service")); + var request = TenantCapacityAdmissionGrpcCodec.parseRequest(wire); + assertServerSide( + serverFailure, + () -> + assertThat(request) + .isEqualTo( + CapacityAdmissionTestFixture.playerRequest( + request.evidence().permitsCreation()))); + if (!request.evidence().permitsCreation()) { + var response = + TenantCapacityAdmissionGrpcCodec.toRefusal( + request, TenantCapacityAdmissionGrpcCodec.Failure.TENANT_BILLING_BLOCKED); + if (wrongFence) + response = + response.toBuilder() + .setRefusal( + 0, response.getRefusal(0).toBuilder().setCapacityRearmFence(0, 2)) + .build(); + observer.onNext(response); + observer.onCompleted(); + return; + } + var result = + new TenantCapacityAdmission.Result( + request.identity(), + request.admissionAttemptId(), + request.capacityRearmFence(), + request.mutationDigest(), + reservationId, + 1, + request.evidence().expiresAt(), + TenantCapacityAdmission.State.RESERVED, + request.evidence().snapshotIdentity(), + request.evidence().evaluationIdentity()); + var response = TenantCapacityAdmissionGrpcCodec.toResponse(request, result); + if (wrongFence) + response = + response.toBuilder() + .setCommitment( + 0, response.getCommitment(0).toBuilder().setCapacityRearmFence(0, 2)) + .build(); + observer.onNext(response); + observer.onCompleted(); + } + }; + return startServer(identity, service, messages); + } + + private static Server startServer( + String identity, AccountServiceGrpc.AccountServiceImplBase service) throws Exception { + return startServer(identity, service, null); + } + + private static Server startServer( + String identity, AccountServiceGrpc.AccountServiceImplBase service, AtomicInteger messages) + throws Exception { + var peer = pki.identity(identity); + var builder = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(peer.privateKey(), peer.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())); + if (messages != null) { + builder.addStreamTracerFactory( + new ServerStreamTracer.Factory() { + @Override + public ServerStreamTracer newServerStreamTracer(String method, Metadata headers) { + return new ServerStreamTracer() { + @Override + public void inboundMessage(int sequence) { + messages.incrementAndGet(); + } + }; + } + }); + } + return builder.build().start(); + } + + private static void assertServerSide( + AtomicReference serverFailure, Runnable assertion) { + try { + assertion.run(); + } catch (AssertionError failure) { + if (serverFailure != null) serverFailure.compareAndSet(null, failure); + throw failure; + } + } + + private static void stop(Server server) throws InterruptedException { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + + private static void stopReloadingClient( + AccountTenantCapacityClient client, BlockingReloadChannelFactory factory) throws Exception { + var close = + new FutureTask(() -> { + client.close(); + return null; + }); + Thread.ofPlatform().daemon().start(close); + // Independently cancel calls holding retired generations, even if close times out. + try (AutoCloseable stopChannels = + () -> { + factory.channels.forEach(ManagedChannel::shutdownNow); + for (ManagedChannel channel : factory.channels) { + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)) + .as("capacity RPC transport terminated") + .isTrue(); + } + }) { + close.get(8, TimeUnit.SECONDS); + } + } + + private static final class BlockingReloadChannelFactory extends GrpcChannelFactory { + private final List channels = new CopyOnWriteArrayList<>(); + private final AtomicBoolean initialBuild = new AtomicBoolean(true); + private final AtomicInteger standardBuilds = new AtomicInteger(); + private final AtomicInteger singleAttemptBuilds = new AtomicInteger(); + private final CountDownLatch reloadStarted = new CountDownLatch(1); + private final CountDownLatch releaseReload = new CountDownLatch(1); + private final CountDownLatch reloadBuilt = new CountDownLatch(1); + + @Override + public ManagedChannel buildChannel( + String target, int defaultPort, CommonGrpcClientProperties properties, boolean keepAlive) + throws SSLException { + standardBuilds.incrementAndGet(); + awaitReload(); + ManagedChannel channel = super.buildChannel(target, defaultPort, properties, keepAlive); + channels.add(channel); + return channel; + } + + @Override + public ManagedChannel buildChannelWithoutRetries( + String target, int defaultPort, CommonGrpcClientProperties properties, boolean keepAlive) + throws SSLException { + int builds = singleAttemptBuilds.incrementAndGet(); + awaitReload(); + ManagedChannel channel = + super.buildChannelWithoutRetries(target, defaultPort, properties, keepAlive); + channels.add(channel); + if (builds > 1) reloadBuilt.countDown(); + return channel; + } + + private void awaitReload() throws SSLException { + if (!initialBuild.getAndSet(false)) { + reloadStarted.countDown(); + try { + releaseReload.await(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new SSLException("Test reload wait interrupted", interrupted); + } + } + } + } + + private static final class CallOptionsCapturingChannelFactory extends GrpcChannelFactory { + private final AtomicReference capturedDeadline = new AtomicReference<>(); + private final AtomicInteger callsCreated = new AtomicInteger(); + + @Override + public ManagedChannel buildChannel( + String target, int defaultPort, CommonGrpcClientProperties properties, boolean keepAlive) + throws SSLException { + return new CallOptionsCapturingManagedChannel( + super.buildChannel(target, defaultPort, properties, keepAlive), this); + } + + @Override + public ManagedChannel buildChannelWithoutRetries( + String target, int defaultPort, CommonGrpcClientProperties properties, boolean keepAlive) + throws SSLException { + return new CallOptionsCapturingManagedChannel( + super.buildChannelWithoutRetries(target, defaultPort, properties, keepAlive), this); + } + + private void resetCapturedDeadline() { + capturedDeadline.set(null); + } + } + + /** Test-only resolver that supplies one Account commit method config. */ + private static final class ServiceConfigNameResolverProvider extends NameResolverProvider { + private final int port; + private final String scheme; + private final Map methodSettings; + + private static ServiceConfigNameResolverProvider retryPolicy(int port) { + return new ServiceConfigNameResolverProvider( + port, + "capacity-retry-test", + Map.of( + "retryPolicy", + Map.of( + "maxAttempts", + 2.0, + "initialBackoff", + "0.01s", + "maxBackoff", + "0.01s", + "backoffMultiplier", + 1.0, + "retryableStatusCodes", + List.of("UNAVAILABLE")))); + } + + private ServiceConfigNameResolverProvider( + int port, String scheme, Map methodSettings) { + this.port = port; + this.scheme = scheme; + this.methodSettings = methodSettings; + } + + @Override + protected boolean isAvailable() { + return true; + } + + @Override + protected int priority() { + return 0; // The test-only scheme must not replace the registry's default resolver. + } + + @Override + public String getDefaultScheme() { + return scheme; + } + + @Override + public Collection> getProducedSocketAddressTypes() { + return List.of(InetSocketAddress.class); + } + + @Override + public NameResolver newNameResolver(URI targetUri, NameResolver.Args args) { + if (!getDefaultScheme().equals(targetUri.getScheme())) return null; + var methodConfig = + new java.util.HashMap( + Map.of( + "name", + List.of( + Map.of( + "service", + AccountServiceGrpc.SERVICE_NAME, + "method", + "CommitTenantCapacityAdmission")))); + methodConfig.putAll(methodSettings); + var serviceConfig = + args.getServiceConfigParser() + .parseServiceConfig(Map.of("methodConfig", List.of(methodConfig))); + return new NameResolver() { + @Override + public String getServiceAuthority() { + return "localhost"; + } + + @Override + public void start(Listener2 listener) { + listener.onResult( + ResolutionResult.newBuilder() + .setAddresses( + List.of(new EquivalentAddressGroup(new InetSocketAddress("127.0.0.1", port)))) + .setServiceConfig(serviceConfig) + .build()); + } + + @Override + public void shutdown() {} + }; + } + } + + private static final class CallOptionsCapturingManagedChannel extends ManagedChannel { + private final ManagedChannel delegate; + private final CallOptionsCapturingChannelFactory capture; + + private CallOptionsCapturingManagedChannel( + ManagedChannel delegate, CallOptionsCapturingChannelFactory capture) { + this.delegate = delegate; + this.capture = capture; + } + + @Override + public ClientCall newCall( + MethodDescriptor methodDescriptor, CallOptions callOptions) { + capture.callsCreated.incrementAndGet(); + capture.capturedDeadline.set(callOptions.getDeadline()); + return delegate.newCall(methodDescriptor, callOptions); + } + + @Override + public String authority() { + return delegate.authority(); + } + + @Override + public ManagedChannel shutdown() { + assertThat(delegate.shutdown()).isNotNull(); + return this; + } + + @Override + public boolean isShutdown() { + return delegate.isShutdown(); + } + + @Override + public boolean isTerminated() { + return delegate.isTerminated(); + } + + @Override + public ManagedChannel shutdownNow() { + assertThat(delegate.shutdownNow()).isNotNull(); + return this; + } + + @Override + public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { + return delegate.awaitTermination(timeout, unit); + } + + @Override + public ConnectivityState getState(boolean requestConnection) { + return delegate.getState(requestConnection); + } + + @Override + public void notifyWhenStateChanged(ConnectivityState source, Runnable callback) { + delegate.notifyWhenStateChanged(source, callback); + } + + @Override + public void resetConnectBackoff() { + delegate.resetConnectBackoff(); + } + + @Override + public void enterIdle() { + delegate.enterIdle(); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterReferenceGrpcMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterReferenceGrpcMtlsTest.java index ddb98af268..51e42d6a5d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterReferenceGrpcMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterReferenceGrpcMtlsTest.java @@ -604,8 +604,7 @@ private Channel channel(String alias) throws Exception { private record Channel(ManagedChannel channel) implements AutoCloseable { @Override public void close() throws Exception { - channel.shutdownNow(); - assertThat(channel.awaitTermination(2L, TimeUnit.SECONDS)).isTrue(); + assertThat(channel.shutdownNow().awaitTermination(2L, TimeUnit.SECONDS)).isTrue(); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcMtlsTest.java index 8672b58dba..946a9f08ab 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcMtlsTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -88,17 +89,96 @@ static void createTestPki() throws Exception { @AfterEach void stopTransportAndClearAuthContext() throws Exception { - if (noCertificateChannel != null) { - noCertificateChannel.shutdownNow(); - assertThat(noCertificateChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); - noCertificateChannel = null; + ManagedChannel channel = noCertificateChannel; + Server receiver = server; + noCertificateChannel = null; + server = null; + // Close in reverse order. A server failure is suppressed beneath the first channel failure. + try (AutoCloseable clearAuthContext = SessionContext::clear; + AutoCloseable stopServer = + () -> { + if (receiver != null) { + receiver.shutdownNow(); + assertThat(receiver.awaitTermination(2, TimeUnit.SECONDS)) + .as("server termination") + .isTrue(); + } + }; + AutoCloseable stopChannel = + () -> { + if (channel != null) { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)) + .as("channel termination") + .isTrue(); + } + }) { + // All cleanup is owned by the resources. } - if (server != null) { - server.shutdownNow(); - assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); - server = null; - } - SessionContext.clear(); + } + + @Test + void channelTerminationFailureStillStopsServerAndClearsAuthContext() throws Exception { + var channel = mock(ManagedChannel.class); + var receiver = mock(Server.class); + when(channel.shutdownNow()).thenReturn(channel); + when(channel.awaitTermination(2, TimeUnit.SECONDS)).thenReturn(false); + when(receiver.awaitTermination(2, TimeUnit.SECONDS)).thenReturn(true); + noCertificateChannel = channel; + server = receiver; + SessionContext.setContext("42", List.of("tenantAdmin"), java.util.Map.of()); + + assertThatThrownBy(this::stopTransportAndClearAuthContext).isInstanceOf(AssertionError.class); + + verify(receiver).shutdownNow(); + verify(receiver).awaitTermination(2, TimeUnit.SECONDS); + assertThat(noCertificateChannel).isNull(); + assertThat(server).isNull(); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + } + + @Test + void bothTerminationFailuresPreserveTheChannelFailureAndClearAuthContext() throws Exception { + var channel = mock(ManagedChannel.class); + var receiver = mock(Server.class); + when(channel.awaitTermination(2, TimeUnit.SECONDS)).thenReturn(false); + when(receiver.awaitTermination(2, TimeUnit.SECONDS)).thenReturn(false); + noCertificateChannel = channel; + server = receiver; + SessionContext.setContext("42", List.of("tenantAdmin"), java.util.Map.of()); + + assertThatThrownBy(this::stopTransportAndClearAuthContext) + .isInstanceOfSatisfying( + AssertionError.class, + failure -> { + assertThat(failure).hasMessageContaining("channel termination"); + assertThat(failure.getSuppressed()) + .singleElement() + .satisfies(suppressed -> + assertThat(suppressed) + .isInstanceOf(AssertionError.class) + .hasMessageContaining("server termination")); + }); + + verify(channel).shutdownNow(); + verify(receiver).shutdownNow(); + assertThat(noCertificateChannel).isNull(); + assertThat(server).isNull(); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + } + + @Test + void serverTerminationFailureStillClearsAuthContext() throws Exception { + var receiver = mock(Server.class); + when(receiver.awaitTermination(2, TimeUnit.SECONDS)).thenReturn(false); + server = receiver; + SessionContext.setContext("42", List.of("tenantAdmin"), java.util.Map.of()); + + assertThatThrownBy(this::stopTransportAndClearAuthContext).isInstanceOf(AssertionError.class); + + verify(receiver).shutdownNow(); + assertThat(server).isNull(); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java index 1d022d7f9e..8c20cb624b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java @@ -5,6 +5,7 @@ import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import java.util.List; +import java.util.concurrent.TimeUnit; import net.firedevops.firemud.entitymanagement.v1.Character; import net.firedevops.firemud.entitymanagement.v1.EntityManagementServiceGrpc; import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountRequest; @@ -18,12 +19,19 @@ class EntityManagementStubServerTest { + private static AutoCloseable verifyChannelShutdown(ManagedChannel channel) { + return () -> { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + }; + } + @Test void returnsPongToPingOverLoopbackGrpc() throws Exception { try (EntityManagementStubServer server = new EntityManagementStubServer(0)) { ManagedChannel channel = ManagedChannelBuilder.forTarget(server.endpoint()).usePlaintext().build(); - try { + try (var shutdown = verifyChannelShutdown(channel)) { EntityManagementServiceGrpc.EntityManagementServiceBlockingStub stub = EntityManagementServiceGrpc.newBlockingStub(channel); @@ -31,8 +39,6 @@ void returnsPongToPingOverLoopbackGrpc() throws Exception { assertThat(response.getMessage()).isEqualTo("pong"); assertThat(response.hasError()).isFalse(); - } finally { - channel.shutdownNow(); } } } @@ -42,7 +48,7 @@ void listsOnlyThePersistedSharedCharacterForTheRequestedTenantAndAccount() throw try (EntityManagementStubServer server = new EntityManagementStubServer(0)) { ManagedChannel channel = ManagedChannelBuilder.forTarget(server.endpoint()).usePlaintext().build(); - try { + try (var shutdown = verifyChannelShutdown(channel)) { EntityManagementServiceGrpc.EntityManagementServiceBlockingStub stub = EntityManagementServiceGrpc.newBlockingStub(channel); @@ -58,8 +64,6 @@ void listsOnlyThePersistedSharedCharacterForTheRequestedTenantAndAccount() throw assertThat(response.hasError()).isFalse(); assertThat(response.getCharactersList()).containsExactly(sharedCharacter(fixture.name())); } - } finally { - channel.shutdownNow(); } } } @@ -70,7 +74,7 @@ void resetCharactersRestoresDefaultSharedCharactersAfterAnEmptyOverride() throws server.setCharacters(List.of()); ManagedChannel channel = ManagedChannelBuilder.forTarget(server.endpoint()).usePlaintext().build(); - try { + try (var shutdown = verifyChannelShutdown(channel)) { EntityManagementServiceGrpc.EntityManagementServiceBlockingStub stub = EntityManagementServiceGrpc.newBlockingStub(channel); @@ -87,8 +91,6 @@ void resetCharactersRestoresDefaultSharedCharactersAfterAnEmptyOverride() throws stub, "1", accountUuid(7L), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); assertThat(resetResponse.hasError()).isFalse(); assertThat(resetResponse.getCharactersList()).containsExactly(sharedCharacter("Emberline")); - } finally { - channel.shutdownNow(); } } } @@ -114,7 +116,7 @@ void listsLoadActorsByTheirPersistedTenantAndAccountOwner() throws Exception { server.setCharacters(List.of(firstPlayer, secondPlayer)); ManagedChannel channel = ManagedChannelBuilder.forTarget(server.endpoint()).usePlaintext().build(); - try { + try (var shutdown = verifyChannelShutdown(channel)) { EntityManagementServiceGrpc.EntityManagementServiceBlockingStub stub = EntityManagementServiceGrpc.newBlockingStub(channel); @@ -142,8 +144,6 @@ void listsLoadActorsByTheirPersistedTenantAndAccountOwner() throws Exception { PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .getCharactersList()) .isEmpty(); - } finally { - channel.shutdownNow(); } } } @@ -153,7 +153,7 @@ void unknownOrMismatchedTenantAndAccountReturnNoCharacters() throws Exception { try (EntityManagementStubServer server = new EntityManagementStubServer(0)) { ManagedChannel channel = ManagedChannelBuilder.forTarget(server.endpoint()).usePlaintext().build(); - try { + try (var shutdown = verifyChannelShutdown(channel)) { EntityManagementServiceGrpc.EntityManagementServiceBlockingStub stub = EntityManagementServiceGrpc.newBlockingStub(channel); @@ -170,8 +170,6 @@ void unknownOrMismatchedTenantAndAccountReturnNoCharacters() throws Exception { PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .getCharactersList()) .isEmpty(); - } finally { - channel.shutdownNow(); } } } @@ -181,7 +179,7 @@ void unsupportedPlayableStateScopesReturnNoCharacters() throws Exception { try (EntityManagementStubServer server = new EntityManagementStubServer(0)) { ManagedChannel channel = ManagedChannelBuilder.forTarget(server.endpoint()).usePlaintext().build(); - try { + try (var shutdown = verifyChannelShutdown(channel)) { EntityManagementServiceGrpc.EntityManagementServiceBlockingStub stub = EntityManagementServiceGrpc.newBlockingStub(channel); @@ -201,8 +199,6 @@ void unsupportedPlayableStateScopesReturnNoCharacters() throws Exception { PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) .getCharactersList()) .isEmpty(); - } finally { - channel.shutdownNow(); } } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/GameDesignStubServerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/GameDesignStubServerTest.java index 59ea0c6b3e..db49f9b393 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/GameDesignStubServerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/GameDesignStubServerTest.java @@ -4,6 +4,7 @@ import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; +import java.util.concurrent.TimeUnit; import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleRequest; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse; @@ -17,7 +18,8 @@ void returnsTheReleaseBundleIdentityUsedByGameplayFixtures() throws Exception { try (GameDesignStubServer server = new GameDesignStubServer(0)) { ManagedChannel channel = ManagedChannelBuilder.forTarget(server.endpoint()).usePlaintext().build(); - try { + try (AutoCloseable stopChannel = + () -> assertThat(channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)).isTrue()) { GetPublishedReleaseBundleResponse response = GameDesignServiceGrpc.newBlockingStub(channel) .getPublishedReleaseBundle( @@ -31,8 +33,6 @@ void returnsTheReleaseBundleIdentityUsedByGameplayFixtures() throws Exception { assertThat(response.getBundle().getVersionId()).isEqualTo(7L); assertThat(response.getBundle().getCommandDefinitionsList()).isEmpty(); assertThat(server.publishedReleaseBundleRequests()).isEqualTo(1); - } finally { - channel.shutdownNow(); } } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/WorldManagementStubServerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/WorldManagementStubServerTest.java index be0d8f8d68..3cee1cdfed 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/WorldManagementStubServerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/WorldManagementStubServerTest.java @@ -2,10 +2,12 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.StatusRuntimeException; +import java.util.concurrent.TimeUnit; import net.firedevops.firemud.gamesession.test.LookTestFixtures; import net.firedevops.firemud.shared.v1.RoomInstanceRef; import net.firedevops.firemud.worldmanagement.v1.GetRoomSnapshotRequest; @@ -21,7 +23,8 @@ void returnsRoomSnapshotForRequestedRoomInstanceId() throws Exception { int port = server.port(); ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", port).usePlaintext().build(); - try { + try (AutoCloseable stopChannel = + () -> assertTrue(channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS))) { WorldManagementServiceGrpc.WorldManagementServiceBlockingStub stub = WorldManagementServiceGrpc.newBlockingStub(channel); @@ -51,8 +54,6 @@ void returnsRoomSnapshotForRequestedRoomInstanceId() throws Exception { assertEquals( LookTestFixtures.DESTINATION_ROOM_NAME, destination.getSnapshot().getRoomName()); assertEquals("SOUTH", destination.getSnapshot().getExits(0).getDirection()); - } finally { - channel.shutdownNow(); } } } @@ -63,7 +64,8 @@ void returnsRoomSnapshotInTheRequestedRuntimeScope() throws Exception { int port = server.port(); ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", port).usePlaintext().build(); - try { + try (AutoCloseable stopChannel = + () -> assertTrue(channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS))) { WorldManagementServiceGrpc.WorldManagementServiceBlockingStub stub = WorldManagementServiceGrpc.newBlockingStub(channel); RoomInstanceRef requestedRoom = @@ -83,8 +85,6 @@ void returnsRoomSnapshotInTheRequestedRuntimeScope() throws Exception { assertEquals("1", response.getSnapshot().getTenantId()); assertEquals("42", response.getSnapshot().getGameInstanceId()); assertEquals(LookTestFixtures.ROOM_INSTANCE_ID, response.getSnapshot().getRoomInstanceId()); - } finally { - channel.shutdownNow(); } } } @@ -95,7 +95,8 @@ void unknownRoomInstanceIdReturnsNotFound() throws Exception { int port = server.port(); ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", port).usePlaintext().build(); - try { + try (AutoCloseable stopChannel = + () -> assertTrue(channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS))) { WorldManagementServiceGrpc.WorldManagementServiceBlockingStub stub = WorldManagementServiceGrpc.newBlockingStub(channel); @@ -108,8 +109,6 @@ void unknownRoomInstanceIdReturnsNotFound() throws Exception { .setRoomInstance( RoomInstanceRef.newBuilder().setRoomInstanceId("unknown-room").build()) .build())); - } finally { - channel.shutdownNow(); } } }