diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 5872b447d7..f5e79e14bf 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` is target-only. Its canonical request contract requires the stable identity, expected complete applicable `authorityTuple`, separate expected `entitlementVersion`, exact expected billing stream/checkpoint evidence, capacity delta, and versioned `mutationDigest`, but no proto RPC, durable authority/usage ledger, caller integration, or reservation-finalization path is implemented. The target replay rule is exact identity-and-payload replay with any changed tuple, entitlement, checkpoint, delta, or digest producing an idempotency conflict; implementation and focused proof remain future capability work rather than a nonfunctional service seam. +`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. 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,11 @@ 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` – **target-state internal RPC** 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 exact complete Account-authenticated evidence bundle returned by `GetTenantEntitlementsForRuntime` including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. 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. Stale evidence, exhausted quota, unavailable authority, malformed identity, and conflicting retries fail closed. No proto RPC, caller integration, durable usage ledger, or reservation lifecycle is implemented yet. See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). +- `CommitTenantCapacityAdmission` – **internal RPC with an unregistered receiving implementation** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the target contract's exact complete Account-authenticated entitlement bundle from `GetTenantEntitlementsForRuntime`, including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. The current numeric runtime endpoint returns `ENTITLEMENT_UNAVAILABLE` and is not qualified player evidence; the separately prepared `PLAYER_ADMISSION` evidence comes from Account's manually composed caller-bound `AccountPlayerAdmissionEntitlementOwner`/receiver and Game Session client. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry 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. + +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. + - `ExportTenantData` – tenant-wide billing-safe export for one tenant, available to the caller's live `tenantAdmin` membership while gameplay is billing-blocked and limited to tenant-owned exportable records plus minimum stable subject references. The target request is tenant-only. The legacy account-targeted gRPC handler returns `FAILED_PRECONDITION` before parsing selectors or reading Account data because no authorized internal caller is configured; the target tenant-only transport and authorization remain unimplemented. This containment does not change the separately authorized REST/service export path. - `DeleteAccount` – begins or completes global account deletion according to the account lifecycle state machine; it is not a tenant-scoped membership deletion. - Pending-deletion access is a separate opaque Account credential, not a JWT or normal account session. The non-export deletion-specific routes are `GET /accounts/{accountId}/deletion`, `POST /accounts/{accountId}/deletion/cancel`, and `POST /accounts/{accountId}/deletion/billing-settlement`; each is classified `pending_deletion_scoped` for its exact action and bound to the Account-owned deletion workflow registry. The account export lifecycle is state-dependent but always uses the canonical asynchronous `POST /accounts/{accountId}/exports`, `GET /accounts/{accountId}/exports/{exportId}`, and `GET /accounts/{accountId}/exports/{exportId}/content` resources: active accounts use the ordinary authenticated account subject, while pending-deletion accounts use the pending-deletion credential and `pending_deletion_scoped` classification on that same lifecycle. These target routes are not currently routable. @@ -461,7 +464,7 @@ Every tenant-targeted request identifies its tenant in the route or request cont | Security-locked export recovery | `/accounts/{accountId}/exports/**` while the account is `security_locked` | Account-issued `security-lock-export` credential from the Account-owned recovery workflow; no ordinary JWT, pending-deletion credential, or support-only access | Exact global account subject and export-job binding, no tenant selector, single-use initiation and expiring status/content authorization. The credential authorizes only this export lifecycle and cannot restore login, cancel deletion, mutate billing, or enter gameplay. | | Pending-deletion access | `/accounts/{accountId}/deletion`, `/accounts/{accountId}/deletion/cancel`, `/accounts/{accountId}/exports/**`, `/accounts/{accountId}/deletion/billing-settlement` | Opaque `pending-deletion-access` credential through the Account-owned workflow registry | Target-only exact `pending_deletion_scoped` route classification for deletion-specific routes and the canonical asynchronous export lifecycle. Once the account enters pending deletion, this row takes precedence over ordinary control-plane classification: `control-ui` authority is revoked and cannot access export or any other pending-deletion route. | | Internal service gRPC | `Authenticate`, `GetCallerTenantMembership`, `GetTenantMembershipForAccount`, `GetTenantMembershipForRuntime`, `GetTenantEntitlementsForRuntime`, `ListPresenceVisibilityPolicies`, payment and profile gRPC APIs | Authenticated mTLS workload identity plus method-level authorization | Internal service surfaces are not edge-exposed directly; an end-user REST JWT is not a substitute for the declared workload and method contract. Ordinary REST/admin JWTs are validated by the consuming service, not by Gateway; the gameplay-connect JWT is the separate Gateway handshake-validation exception. | -| Target internal capacity RPC | `CommitTenantCapacityAdmission` | Disjunctive method-level caller policy: exact Game Session mTLS identity plus typed `PlayerExecutionContext` and live player-binding checks, or exact World Management mTLS identity plus tenant/operation-bound instance-lifecycle context and live lifecycle checks | Target-only and not present in the current proto or service implementation. | +| Prepared internal capacity RPC | `CommitTenantCapacityAdmission` | Target disjunctive method-level caller policy: exact Game Session mTLS identity plus typed `PlayerExecutionContext` and live player-binding checks, or exact World Management mTLS identity plus tenant/operation-bound instance-lifecycle context and live lifecycle checks | Proto, strict codec, Account ledger/owner and Game Session adapter are prepared but unregistered; live owner/readback qualification and admission remain held. See [strict tenant-capacity owner status](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). | `/auth/login` and `/auth/player-bootstrap` may share the same underlying credential-verification and abuse-policy implementation, but they are separate authentication products. `/auth/login` establishes a `control-ui` control-plane session for admin/creator surfaces; `/auth/player-bootstrap` establishes only the short-lived `player-bootstrap` gameplay-discovery context. Neither endpoint may substitute one profile for the other. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 1f047b9e27..fe4f92d77d 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -72,7 +72,7 @@ The current public registration path creates only a global Account row and a pla Account has source-only persistence for individual Creator Party identity, hosted-terms acceptance/environment-binding evidence, and (from V98) disclosure handoffs with immutable captured source evidence. The V98 database guards constrain handoff identity, result transitions, and source-evidence insertion. A passive Account source-fence seam now excludes unsettled World participation from applicable source mutation/abort settlement and hosted-terms disclosure preparation/dispatch admission; `HostedTermsDisclosureHandoff` and its repository use the existing V98 journal. The unregistered historical World-participation reader resolves retained participation coordinates from the complete unchanged original tuple, verifies the retained capture and source-child vector, and can read after lease expiry or immutable terminal settlement; it uses existing rows and introduces no migration or table. It does not establish currentness, renew or admit authorization, or classify an Account expiry or failed response as World `ABORTED`; only the World owner can produce that terminal outcome with its original commit/fence evidence. The handoff retains opaque authority evidence as supplied and does not authenticate it. No verifier, dispatcher, transport, registry/runtime binding, creator UI, or Game Design evidence binding is registered. Reserve, claim, and publication paths that require the hosted-terms workflow remain unavailable. The acceptance/currentness authority remains target-only under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md), with changed-terms continuity under [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md); local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner workflow is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled. -The live `GetTenantMembershipForRuntime` producer emits `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`; `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent from the proto and producer. Current text `PLAY` consumes the emitted lifecycle and independent authority generation alongside version and admission evidence; this does not establish the complete atomic-freshness contract. Account-first bootstrap and credential-bearing gameplay `Authenticate` authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current receiver composition and refusal boundaries belong to [Account API Contracts](./api-contracts.md#rest-apis) and its [gRPC inventory](./api-contracts.md#grpc-apis). The held boundary, preserved positive obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving). Current text `PLAY` evaluates fresh entitlement before membership/grant and later actor/binding checks; public `JOIN_REQUIRED` is limited to coherent missing or `INACTIVE` membership when enrollment permits repair. An active but non-admitting response is not a join fallback. Complete caller-target/atomic authority and the remaining AA-2.1 / Unit 1B boundaries remain open. These flows do not create or restore membership. The Account-owned public-production JOIN writer remains a prepared persistence component with atomic membership, operation-outcome, and audit-outbox evidence; the API composition contract linked above governs access to it. Its HTTP exposure remains blocked by the Gateway route guard; Game Session text `JOIN`/`Join & Play` dispatch remains with #2898, while durable recovery after an unknown database commit and Logging receipt receiver/readback remain with #2848. Focused PostgreSQL/component proof and its limits are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#validation-and-proof); those controlled fixtures do not establish genuine deployed receiving custody or complete public admission. See [Account API Contracts](./api-contracts.md) for the public and internal API boundary and [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the canonical direct-text scope and JOIN contract. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The numeric runtime entitlement endpoint remains unavailable under the [Account API contract](./api-contracts.md#grpc-apis). Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and canonical snapshot fields/freshness remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Earlier focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof is limited to the prior cardinality guard and retry boundary; it does not establish current positive entitlement production. `CommitTenantCapacityAdmission` has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. +The live `GetTenantMembershipForRuntime` producer emits `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`; `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent from the proto and producer. Current text `PLAY` consumes the emitted lifecycle and independent authority generation alongside version and admission evidence; this does not establish the complete atomic-freshness contract. Account-first bootstrap and credential-bearing gameplay `Authenticate` authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current receiver composition and refusal boundaries belong to [Account API Contracts](./api-contracts.md#rest-apis) and its [gRPC inventory](./api-contracts.md#grpc-apis). The held boundary, preserved positive obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving). Current text `PLAY` evaluates fresh entitlement before membership/grant and later actor/binding checks; public `JOIN_REQUIRED` is limited to coherent missing or `INACTIVE` membership when enrollment permits repair. An active but non-admitting response is not a join fallback. Complete caller-target/atomic authority and the remaining AA-2.1 / Unit 1B boundaries remain open. These flows do not create or restore membership. The Account-owned public-production JOIN writer remains a prepared persistence component with atomic membership, operation-outcome, and audit-outbox evidence; the API composition contract linked above governs access to it. Its HTTP exposure remains blocked by the Gateway route guard; Game Session text `JOIN`/`Join & Play` dispatch remains with #2898, while durable recovery after an unknown database commit and Logging receipt receiver/readback remain with #2848. Focused PostgreSQL/component proof and its limits are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#validation-and-proof); those controlled fixtures do not establish genuine deployed receiving custody or complete public admission. See [Account API Contracts](./api-contracts.md) for the public and internal API boundary and [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the canonical direct-text scope and JOIN contract. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The numeric runtime entitlement endpoint remains unavailable under the [Account API contract](./api-contracts.md#grpc-apis). Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and canonical snapshot fields/freshness remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Earlier focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof is limited to the prior cardinality guard and retry boundary; it does not establish current positive entitlement production. `CommitTenantCapacityAdmission` and its Account/client persistence and reservation components are locally prepared but remain manually composed and unregistered; cross-implementation vector consumption, remaining physical PostgreSQL qualification, deployed custody, and selected-owner/final activation proof remain open. The [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) owns the capability and proof status. The current `application.yml` and `application-prod.yml` retain `GetTenantMembershipForRuntime`, `GetRealmAccessGrantForRuntime`, `GetTenantEntitlementsForRuntime`, and `ListPresenceVisibilityPolicies` in the gRPC bearer-validation bypass list. Their handlers independently require certificate-derived workload identity in the exact configured namespace: Game Session for membership and realm-grant reads, Game Session or World Management for entitlement reads, and Social & Groups for presence-policy reads. Handler and configured-interceptor tests cover permitted peers without bearer credentials and refusal of unauthorized or wrong-namespace peers. This workload-only bypass does not make the methods unauthenticated public APIs. Complete typed caller-context and tenant-binding qualification, membership/currentness consumption, and the remaining canonical admission and registry contracts remain separate gaps under the [Account API contract](./api-contracts.md); these workload checks alone do not establish readiness. @@ -82,7 +82,9 @@ Recovery/verification foundations are live. Password-reset completion now uses a Current public bootstrap, direct-scope, JOIN, connect-token and numeric entitlement receiving boundaries are defined by [Account API Contracts](./api-contracts.md#rest-apis) and its [gRPC inventory](./api-contracts.md#grpc-apis). The held boundary, preserved positive component obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Game Session text `REALMS`/`JOIN` dispatch remains unimplemented under #2898; unknown JOIN outcome recovery and Logging receipt receiver/readback remain #2848, and direct text-client end-to-end proof remains open. The target scope and transport contract remains in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). -The target capacity retry contract uses stable outer `(tenantId, requestId, admissionId)`, fresh per-attempt `admissionAttemptId`, current `capacityRearmFence`, exact complete entitlement evidence, bounded `capacityDelta`, and a versioned `mutationDigest` over that attempt identity, fence, and complete payload. Exact retries replay the stored result. A new attempt requires an Account-owned atomic CAS over the same outer tuple, terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` plus durable no-commit evidence, current fence, and prior digest; the CAS advances the fence without creating a second reservation. Changed fields without a matching rearm return `IDEMPOTENCY_CONFLICT`; stale or losing fences return `FENCE_REJECTED` only with durable no-accept/no-runtime-mutation proof. This remains target-only and follows the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). +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). 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. @@ -318,7 +320,9 @@ Entitlement producer contract: - `provisioningStatus` is `pending`, `provisioning`, or null; while non-null, `subscriptionStatus` is null and all new gameplay/admission/instance-start flags are false. `tenantAuthorityGeneration` is opaque and may be compared only for exact equality, never ordered or used as an event identity. - The focused producer proof must show that every entitlement response is one Account-authenticated bundle from the same authoritative committed evaluation, that `tenantAuthorityGeneration` is the Account-committed fence rather than a value reconstructed from a later projection read, and that no caller reconstructs or separately sources bundle identities, tuple members, cutoff evidence, or checkpoints. -The numeric runtime entitlement endpoint follows the [Account API refusal boundary](./api-contracts.md#endpoint-authentication-classes). The separate manually composed PLAYER_ADMISSION owner/receiver and Game Session client preserve canonical V2 scope/current-owner evidence under the [private purpose contract](./api-contracts.md#private-player-admission-entitlement-read); their presence does not wire or qualify a runtime cutover. Canonical UUID billing and the distinct unregistered `TENANT_OPERATION` source are prepared separately; the complete public `PLAYER_ADMISSION` consumer is not yet qualified. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving) owns public receiving proof and gaps. +The numeric runtime entitlement endpoint follows the [Account API refusal boundary](./api-contracts.md#endpoint-authentication-classes). The separate manually composed PLAYER_ADMISSION owner/receiver and Game Session client preserve canonical V2 scope/current-owner evidence under the [private purpose contract](./api-contracts.md#private-player-admission-entitlement-read); their presence does not wire or qualify a runtime cutover. Canonical UUID billing and the distinct unregistered `TENANT_OPERATION` source are prepared separately; the complete public `PLAYER_ADMISSION` consumer is not yet qualified. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving) owns public receiving proof and gaps. `V1040` prepares immutable capacity-evaluation, attempt-history, and recovery-evidence records plus guarded reservations, but no capacity-family retention entry, horizon, or owner-safe cleanup/archive contract is defined under [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) and [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md). This remains an open Account activation limitation; existing guards and holds remain in force. + +Retained player-admission version-1 evidence remains immutable and held for owner-governed retention. Player-admission version 2 is required for new capacity requests and their replay. Before activation or reuse of predecessor-populated storage, establish the retained Account and Game Session SQL and Redis inventory and resolve its outstanding confirmation, replay, recovery and restore obligations under the [objective compatibility gates](../../decisions/adr-0081-objective-compatibility-gates-for-database-evolution.md). ### Playtest Grant Persistence and Authority Consequences diff --git a/design/architecture/microservices/account-service/subscription-management.md b/design/architecture/microservices/account-service/subscription-management.md index ea6dd50a10..3c6ee18739 100644 --- a/design/architecture/microservices/account-service/subscription-management.md +++ b/design/architecture/microservices/account-service/subscription-management.md @@ -13,7 +13,7 @@ Payment-instrument ownership, explicit per-subscription binding, initial billing ## Implementation Status -The plan-change timing, over-quota behavior, pending-plan metadata, and full quota-bearing runtime entitlement response described below are canonical target-state behavior. Current implementation has the first runtime availability surface, but quota fields, pending plan metadata, downgrade/cancellation enforcement, strict capacity admission, and the target separation between create and existing-subscription update APIs still need implementation follow-through. Account now has unregistered customer-first-dispatch and exact-customer saved-method owner sources, but these prerequisites do not create a subscription or enable a caller path. The current `CreateSubscriptionRequest` carries only tenant/account/plan fields: it lacks the caller-supplied stable `requestId`, exact instrument-selection input, and immutable creation-operation identities. Account computes the versioned `requestDigest` from normalized request fields; that digest is not a caller-supplied request field. Account must also resolve the authoritative billing owner, which is not supplied as a request field. Account therefore rejects this incomplete create method with `FAILED_PRECONDITION` before any membership, account, subscription, or provider mutation; it must not be treated as proof of the target contract. Expected row-version/CAS is not a creation precondition and is required for every supported existing-subscription mutation through `UpdateSubscription`. The durable authority/usage ledger and reservation lifecycle for strict capacity admission are also not implemented. +The plan-change timing, over-quota behavior, pending-plan metadata, and full quota-bearing runtime entitlement response described below are canonical target-state behavior. Current implementation has the first runtime availability surface, but quota fields, pending plan metadata, downgrade/cancellation enforcement, strict capacity admission, and the target separation between create and existing-subscription update APIs still need implementation follow-through. Account now has unregistered customer-first-dispatch and exact-customer saved-method owner sources, but these prerequisites do not create a subscription or enable a caller path. The current `CreateSubscriptionRequest` carries only tenant/account/plan fields: it lacks the caller-supplied stable `requestId`, exact instrument-selection input, and immutable creation-operation identities. Account computes the versioned `requestDigest` from normalized request fields; that digest is not a caller-supplied request field. Account must also resolve the authoritative billing owner, which is not supplied as a request field. Account therefore rejects this incomplete create method with `FAILED_PRECONDITION` before any membership, account, subscription, or provider mutation; it must not be treated as proof of the target contract. Expected row-version/CAS is not a creation precondition and is required for every supported existing-subscription mutation through `UpdateSubscription`. The strict capacity owner and durable usage/reservation source are locally prepared but remain unregistered and unqualified; see [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). The target `CreateSubscription` request accepts a high-entropy stable caller-supplied `requestId` as the sole logical create-operation key, along with the normalized tenant, plan, and instrument-selection inputs. Account resolves the authoritative billing owner and computes a versioned `requestDigest` from those normalized inputs and the resolved owner; neither the digest nor billing-owner resolution is supplied as a request field. Account captures the resolved owner's authority version/generation and validates that exact fence in the same local intent/outbox transaction before persisting the pair or creating provider work; an owner change or generation/version mismatch fails closed. A retry with the same `requestId` and normalized create fields recomputes the same digest and replays the same `subscriptionId`, durable operation, and outcome; changed fields that produce a different digest return `IDEMPOTENCY_CONFLICT`. The provider `subscription_provisioning_request_id` and cleanup identity remain separate provider-operation keys and must not replace the caller identity. @@ -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. No proto RPC, caller integration, durable usage ledger, or reservation lifecycle is implemented yet. 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; 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). - `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/system-architecture-authz-route-matrix.yaml b/design/architecture/system-architecture-authz-route-matrix.yaml index 93293d9b42..721fbbcc52 100644 --- a/design/architecture/system-architecture-authz-route-matrix.yaml +++ b/design/architecture/system-architecture-authz-route-matrix.yaml @@ -3171,7 +3171,7 @@ routes: changed_attempt_without_rearm_ordering: rejected_before_any_mutation mutation_contract: account_owned_fenced_capacity_reservation_create_or_replay canonical_errors: - any_of: [CAPACITY_ADMISSION_STALE, CAPACITY_QUOTA_EXCEEDED, FENCE_REJECTED, IDEMPOTENCY_CONFLICT, AUTH_UNAVAILABLE] + any_of: [CAPACITY_ADMISSION_STALE, CAPACITY_QUOTA_EXCEEDED, TENANT_BILLING_BLOCKED, ENTITLEMENT_UNAVAILABLE, FENCE_REJECTED, IDEMPOTENCY_CONFLICT, AUTH_UNAVAILABLE, PERMISSION_DENIED, INVALID_ARGUMENT] fence_rejection_requirements: no_accept_no_runtime_mutation_proof - service: account-service route: GetTenantEntitlementsTenant diff --git a/design/architecture/system-architecture-versioning-runtime.md b/design/architecture/system-architecture-versioning-runtime.md index a43c074d23..eb6cb274f1 100644 --- a/design/architecture/system-architecture-versioning-runtime.md +++ b/design/architecture/system-architecture-versioning-runtime.md @@ -32,7 +32,7 @@ Purge failure status is also not durable in the current implementation: `Finaliz Asset repair now reads and verifies the existing durable version-scoped source snapshot and independently reads the retained export candidate, checks that candidate against the release attestation before writes, and conditionally writes content-addressed objects with exact object readback. Repair does not create a snapshot or candidate. This source implementation does not yet prove physical object-store or PostgreSQL behavior, restart recovery, or a global publication/purge fence; those remain unproved. -Capacity admission is also target-state only. Account's `CommitTenantCapacityAdmission` RPC and both caller integrations (Game Session and World Management) are unimplemented, as are the durable Account authority/usage ledger, the exact `capacityDelta` wire contract, the capacity-admission action-family schema and cross-language `mutationDigest/v1` golden vectors, and the reservation create/finalize/release/reconciliation lifecycle. The capacity-admission sections below are normative contracts and must not be read as evidence that these RPC, caller, ledger, schema/vector, or reservation components exist. +Capacity admission remains unregistered and unqualified. Prepared source, proof definitions and remaining activation gates are recorded in [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation); the sections below remain normative target contracts rather than runtime qualification. The live Account runtime does not yet produce the complete authority evidence required by recovery and capacity-admission consumers. `roles`, `membershipAuthorityGeneration`, `authorityTuple`, and `outboxCheckpoints` remain target-state fields until Account exposes them together from one authoritative snapshot; these flows must not infer or synthesize them from the current partial response. See [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#implementation-status) for the owning implementation status. @@ -478,7 +478,7 @@ The serving operation is classified before the read: ### Capacity Delta Wire and Digest Contract -The target `CommitTenantCapacityAdmission` protobuf request declares `capacity_delta` as `optional int64`; its canonical JSON/proto-JSON spelling is `capacityDelta`, represented as a base-10 decimal string. Explicit protobuf presence is mandatory: generated `hasCapacityDelta()`/presence checks must be used, and a missing field, JSON `null`, wrapper message, or implicit scalar default is not the value zero. There is no accepted alternate field or numeric type. The signed wire type is intentional: negative values are representable for diagnostic rejection but are never valid capacity mutations. This is a target-state contract because the current Account proto does not expose this RPC. +The target `CommitTenantCapacityAdmission` protobuf request declares `capacity_delta` as `optional int64`; its canonical JSON/proto-JSON spelling is `capacityDelta`, represented as a base-10 decimal string. Explicit protobuf presence is mandatory: generated `hasCapacityDelta()`/presence checks must be used, and a missing field, JSON `null`, wrapper message, or implicit scalar default is not the value zero. There is no accepted alternate field or numeric type. The signed wire type is intentional: negative values are representable for diagnostic rejection but are never valid capacity mutations. Prepared wire support and remaining qualification are recorded in [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). The logical range is the non-negative signed-`int64` range `0 <= capacityDelta <= 9223372036854775807`, but presence and operation class are separate mandatory checks. An absent `capacityDelta` is always invalid; it must be rejected by Game Session and World Management before calling Account and again by Account before any commitment, reservation, usage mutation, or owner activation CAS. A present zero is valid only after the operation has been classified as eligible entitlement-preserving non-expanding recovery or one-for-one replacement and the complete Account evidence proves that classification; it reserves and changes no usage. A present positive value is valid only for a capacity-creating activation/cutover and must also be no greater than the operation's net requested capacity, available Account quota, and remaining plan entitlement. Account, Game Session, and World Management must apply these same absent/zero/positive rules, rather than relying on a generated getter, a local re-read, or the other caller's validation. Negative values, values outside the signed `int64` wire range, malformed decimal JSON spellings, and any parse or checked-arithmetic overflow are rejected before an Account commitment, reservation, usage mutation, or owner activation CAS. Account must perform checked addition and comparison for usage and quota; it must reject rather than wrap, saturate, narrow, or coerce through a floating-point type. @@ -486,7 +486,7 @@ For the capacity action-family schema, `capacityDelta` is a declared member of t The absent encoding exists only to produce a deterministic rejected digest vector; an absent request can never commit. -The capacity vector fixture is normative proof work for Account, Game Session, and World Management. It fixes every non-`capacityDelta` field in the published `capacity-admission/v1` schema, including the complete capacity shape used for non-expanding comparison, and publishes canonical preimage bytes plus the expected lowercase SHA-256 digest for `absent`, `present(0)`, a representative valid positive value such as `17`, and the boundary `present(9223372036854775807)`. It also publishes request candidates for `9223372036854775808`, signed negatives, malformed decimal spellings, signed-`int64`/JSON overflow, changed capacity-shape fields, and checked usage/quota addition overflow, with the expected rejection before commitment and no accepted mutation digest. Every implementation in Account and both callers must consume the same vectors and produce the same accepted/rejected result; until that schema/vector corpus and focused proof exist, capacity admission remains unsupported target state. Use the shared [validation and runtime-proof workflow](../developer-workflows/validation-and-runtime-proof.md) to select the focused proof and record fixture execution results in PR/CI or implementation-tracking evidence; it supplements these owner-local requirements and does not create an execution ledger. +The capacity vector fixture is normative proof work for Account, Game Session, and World Management. It fixes every non-`capacityDelta` field in the published `capacity-admission/v1` schema, including the complete capacity shape used for non-expanding comparison, and publishes canonical preimage bytes plus the expected lowercase SHA-256 digest for `absent`, `present(0)`, a representative valid positive value such as `17`, and the boundary `present(9223372036854775807)`. It also publishes request candidates for `9223372036854775808`, signed negatives, malformed decimal spellings, signed-`int64`/JSON overflow, changed capacity-shape fields, and checked usage/quota addition overflow, with the expected rejection before commitment and no accepted mutation digest. Every implementation in Account and both callers must consume the same vectors and produce the same accepted/rejected result. The [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation) records the existing shared schema/vector fixtures and scoped proof; complete cross-language consumption, physical owner proof and runtime qualification remain required before capacity admission is enabled. Use the shared [validation and runtime-proof workflow](../developer-workflows/validation-and-runtime-proof.md) to select the focused proof and record fixture execution results in PR/CI or implementation-tracking evidence; it supplements these owner-local requirements and does not create an execution ledger. The changed-capacity-shape candidates in this fixture represent expanding or unvalidated changes and therefore must reject before commitment. A changed shape with Account-authenticated proof of a non-expanding effective resource delta is covered by the eligible replacement rule and is not an unconditional rejection case. 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 9b7a31ce69..87dd792aa8 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -26,6 +26,16 @@ This is an intentionally breaking preproduction format cutover of the manually c The Account source/transport foundation contains unregistered TENANT_OPERATION and PLAYER_ADMISSION owners, transports and controlled proof, Entity persisted-actor discovery, and policy-aware Game Session discovery. These do not replace live PLAY authority. The public receiving boundary contains canonical UUID schema retirement, the public facade/JOIN cutover, initial hosting provider-write source with its focused units, and dependent physical proof. Private FRESH/World preparation remains a separate receiving obligation. A functioning canonical PLAY replacement remains unqualified; no caller custody, runtime registration, admission or activation is established by these source boundaries. +### Strict tenant-capacity owner preparation + +The [shared capacity-admission/v1 schema](../../../services/common-platform-core/src/main/resources/capacity/capacity-admission-v1.schema.json), typed digest, exact-presence RPC and codec prepare the Account commitment boundary. [V1040](../../../services/account-service/src/main/resources/db/migration/V1040__account_tenant_capacity_owner.sql) stores immutable hash-bound Account evaluation, stable reservation and attempt identity, fenced recovery evidence, and held and used units. The actual player entitlement owner retains its evaluation in the final source transaction. The exact fresh tenant association and same-transaction creator bootstrap are the only source of initial zero usage. + +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 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. + ### Controlled player-admission transport composition The prepared `controlledOwnerReceiverAndGameSessionClientComposeWithoutGrantingAdmission` case in [AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java) connects the actual Account PostgreSQL entitlement owner and unregistered mTLS receiver to the actual Game Session client. It checks both absent and joined membership, unchanged membership count, exact canonical response bytes, credential exclusion and refusal after the custody callback becomes false. LOGIN issuance/currentness and protected Game Session/World target inputs remain explicit controlled doubles; this does not establish genuine custody, a complete source chain, admission or production registration. Local compilation, enabled integration static analysis, Java formatting, Markdown and link checks pass, but all four PostgreSQL cases were skipped because Docker is unavailable. Physical execution remains outstanding. Required full-stack smoke on `89ae1be` / `e8fa889` still fails at the intentionally denied numeric entitlement endpoint; this test preparation does not replace that evidence or change the default-off runtime. @@ -632,7 +642,7 @@ With canonical scope consumers absent from the default composition, Account conn | `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql); [CanonicalGameplayAccountInitialBarrierInitializerRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java); [CanonicalGameplayAccountInitialBarrierRedisOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java); [V1047__canonical_initial_account_admission_barrier.sql](../../../services/game-session-service/src/main/resources/db/migration/V1047__canonical_initial_account_admission_barrier.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java); [CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java); [CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountTenantAuthorityEventRepository` appends the canonical tenant authority event during demo entitlement provisioning; `AccountMembershipAuthorityEventProducer` emits the first-JOIN membership event with its billing cutoff taken from that current tenant authority event, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. The default public bootstrap discovery, direct-scope, JOIN, and connect-token receiving composition returns `AUTH_UNAVAILABLE` before bootstrap/scope or legacy authority reads. Manually configured receivers follow the [Account API composition boundaries](../../architecture/microservices/account-service/api-contracts.md); connect-token validates bootstrap identity and reads scope but remains held before replay or issuance. The numeric runtime entitlement receiver returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. The held boundary, preserved positive component obligations, and proof history are in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving). Target current-authority and postcondition revalidation remain unproved. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. Prepared JOIN component behavior retains the subscription-row lock boundary, remote scope/target/entitlement checks outside the lock-holding transaction, and atomic membership, operation-outcome, and audit-outbox persistence. These components are not reachable through the default receiving facade. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and supported text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance fails closed before these checks and does not establish target grant validation. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). The unregistered INITIAL Account prerequisite preserves one original target and does not supply abandoned-target or account-wide fenced recovery, fresh Account authority, final admission or runtime activation; see the [readiness scope and proof](#canonical-new-admission-components). | | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql); [AccountStartSessionActivationProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java); [V1006 World activation terminal digest alignment](../../../services/account-service/src/main/resources/db/migration/V1006__world_activation_terminal_digest_alignment.sql); [V1007 selected source reservations](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql); [AccountSelectedOwnerIntakeSourceReservationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java); [V1008 selected-owner intake final authorizations](../../../services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_final_authorizations.sql); [V1009 selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1009__selected_owner_intake_terminal_settlement.sql); [V1010 Entity selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql); [AccountSelectedOwnerIntakeSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java); [AccountSelectedOwnerIntakeAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java); [AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java); [AccountSelectedOwnerIntakeSettlementReceipt.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java); [AccountStartSessionAdmissionProtectionAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java); [AccountStartSessionAdmissionProtectionSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java); [AccountStartSessionAdmissionProtectionGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcService.java); [AccountStartSessionAdmissionProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java); [GrpcAccountInitialAdmissionSettlementReadClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClient.java); [EmailVerificationTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/EmailVerificationTokenRepository.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [AccountFreshEnrollmentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentRepository.java); [AccountFreshEnrollmentPolicyRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPolicyRepository.java); [AccountRecentReauthenticationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationService.java); [AccountRecentReauthenticationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationRepository.java); [V1018__account_fresh_enrollment_certification.sql](../../../services/account-service/src/main/resources/db/migration/V1018__account_fresh_enrollment_certification.sql); [V1018.1__recent_reauthentication_replay_credentials.sql](../../../services/account-service/src/main/resources/db/migration/V1018.1__recent_reauthentication_replay_credentials.sql); [V1018.2](../../../services/account-service/src/main/resources/db/migration/V1018.2__recent_reauthentication_replay_failure_budget.sql); [AccountControlUiCurrentActorVerifier.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java); [V1016__account_recent_reauthentication_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V1016__account_recent_reauthentication_evidence.sql); [V1017__account_global_control_ui_issuance_scope.sql](../../../services/account-service/src/main/resources/db/migration/V1017__account_global_control_ui_issuance_scope.sql) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java); [SelectedOwnerSourceDisclosurePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java); [AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSettlementServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java); [SelectedOwnerIntakeSettlementGrpcCodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java); [AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java); [AccountStartSessionAdmissionProtectionGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcServiceTest.java); [GrpcAccountInitialAdmissionSettlementReadClientTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java); [AccountCredentialPeerGrpcMtlsTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountCredentialPeerGrpcMtlsTest.java); [EmailVerificationHttpAuthWiringTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountFreshEnrollmentPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPostgresIntegrationTest.java); [AccountGlobalControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiIssuancePostgresIntegrationTest.java); [AccountGlobalControlUiScopePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiScopePostgresIntegrationTest.java); [AccountRecentReauthenticationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java); [AccountRecentReauthenticationReplayTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationReplayTest.java); [AccountControlUiCurrentActorVerifierTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` still fails closed with `501 NOT_IMPLEMENTED` before mutation: the internal recent-reauthentication owner is purpose-bound to self-service game creation and is not wired to factor changes. General factor-change evidence and mutation composition remain open under ADR 0045. Account-global Control-UI, fresh-enrollment certification and purpose-specific recent-reauthentication preparation are present in the sources and focused proof linked here; their receiving limits are recorded below, and they do not establish production registration or custody. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal retained numeric subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; the canonical UUID billing-owner detection gap is recorded in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving), and retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. The Account admission-protection acquisition, settlement, gRPC and repository sources are manually composed, but remain unregistered. Focused proof is recorded by the acquisition PostgreSQL, repository PostgreSQL, service unit and gRPC service unit suites linked above; this does not establish runtime registration, the downstream final-admission path, production authority or PKI, operational custody, or Entity placement and delivery. The World protected-activation consumer is also unregistered. The historical R9 report above records 13 Account PostgreSQL cases and four composed World/Account/Game Session cases, including exact authenticated World terminal settlement, with its missing tested-snapshot and original XML attribution stated explicitly. The separately source-bound receiving proof above qualifies only its named scope. These controlled upstream inputs establish no broader proof; runtime registration, genuine upstream authority, admission, Entity placement and delivery remain unproved. V1003 storage remains passive and V1004 lifecycle integrity checks do not authenticate World. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. Email confirmation atomically claims an exact unexpired token under a fresh locked Account/source transaction; equality at expiry, expired and replayed tokens refuse without Account changes. Credential RPCs require the exact same-namespace Game Session workload; only Authenticate has a separate disabled-by-default local Entity demo fixture. Unbound export/linking/Account-ID email-initiation and deferred currency adapters refuse before owner effects; supported REST and token owners remain. This containment and focused proof do not implement those deferred APIs or remove the existing recovery, audit, production and registration gaps. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [StripeWebhookIntakeService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/StripeWebhookIntakeService.java); [StripeEventInboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/StripeEventInboxRepository.java); [AccountBillingCustomerProvisioningService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingCustomerProvisioningService.java); [AccountBillingCustomerRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerRepository.java); [AccountBillingPrerequisiteConfirmationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationService.java); [AccountPaymentInstrumentAttachmentService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentService.java); [AccountPaymentInstrumentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPaymentInstrumentRepository.java); [V1026__stripe_event_inbox.sql](../../../services/account-service/src/main/resources/db/migration/V1026__stripe_event_inbox.sql); [V1027__account_billing_customer_and_instrument_owners.sql](../../../services/account-service/src/main/resources/db/migration/V1027__account_billing_customer_and_instrument_owners.sql); [V1027.1__billing_customer_first_dispatch_claim.sql](../../../services/account-service/src/main/resources/db/migration/V1027.1__billing_customer_first_dispatch_claim.sql); [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml); [StripeHostingSubscriptionProvisioner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisioner.java); [AccountHostingSubscriptionProvisioningService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java); [StripeHostingSubscriptionObserver.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserver.java); [AccountHostingSubscriptionLifecycleRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java); [AccountHostingSubscriptionLifecycleService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleService.java); [AccountSubscriptionIntentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java); [AccountHostingPlanCatalog.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalog.java) | [StripeWebhookIntakePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/StripeWebhookIntakePostgresIntegrationTest.java); [AccountBillingPrerequisitesPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingPrerequisitesPostgresIntegrationTest.java); [AccountBillingCustomerDispatchPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerDispatchPostgresIntegrationTest.java); [AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java); [AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java); [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java); [StripeHostingSubscriptionProvisionerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisionerTest.java); [AccountHostingSubscriptionProvisioningServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java); [AccountHostingSubscriptionDispatchPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java); [StripeHostingSubscriptionObserverTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserverTest.java); [AccountHostingSubscriptionLifecycleRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java); [AccountHostingSubscriptionLifecycleServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleServiceTest.java); [AccountSubscriptionIntentRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepositoryTest.java); [AccountHostingPlanCatalogTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalogTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | The first cut adds an unregistered verified Stripe event inbox (V1026), durable customer intent/first-dispatch source (V1027 and V1027.1), and exact-customer saved-method confirmation source. Controlled Stripe SDK/readback and PostgreSQL proof sources do not establish live provider calls or a public route. The unregistered hosting observer, intent, lifecycle and plan sources and their focused unit proof are present. The canonical UUID schema/lifecycle and exact focused proof are present in [canonical billing receiving](#canonical-billing-and-retention-receiving); V1028 retains the original numeric archive, and active canonical ownership uses V1029 and its forward lifecycle migrations. Existing public facade convergence and positive consumers remain in [#3390](https://github.com/benhook1013/FireMUD/pull/3390); `CreateSubscription` still fails closed before mutation. The linked receiving section owns bounded intent/lifecycle/reconciliation and terminal-cancellation proof; production registration, live provider/custody qualification, remaining lifecycle outcomes, complete consumer/runtime enforcement, transfer and replacement-before-detach remain incomplete. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION`; generic provider-mutating substrate is unsupported. Creator/player commerce, donations, fees/shares, payouts, and settlement remain deferred. Webhook intake, billing-customer and saved-method registration additionally require approved finite category schedules, guarded minimization/erasure and account-deletion/backup treatment with physical proof under [the Stripe registration prerequisites](../../architecture/microservices/account-service/stripe-integration.md#billing-owner-source-registration-prerequisites). Append-only provider payloads and card-display history do not authorize indefinite production retention or retention of the Account beyond ADR 0043’s minimum billing-evidence boundary. | -| `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The current numeric runtime entitlement endpoint returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. Current status, preserved positive receiving obligations, and proof history are recorded in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving); earlier focused storage/retry proof does not establish a live legacy-row producer. Legacy gRPC still carries unavailable outcomes in its error field, an explicit transport-classification gap. Current connect-token issuance follows the [Account API conditional bootstrap/scope validation boundary](../../architecture/microservices/account-service/api-contracts.md#rest-apis), but remains unavailable before entitlement reads, cached replay, or token issuance; older positive-issuance tests are historical. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its shared subscription-version/billing-sequence projection and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. No current gameplay or public-join eligibility is inferred from a retained numeric `past_due` row while the runtime entitlement boundary is held. | +| `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml); [bounded capacity owner](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java); [original-NEW final owner](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [Account/Game Session capacity composition](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java); [native final-admission evidence](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | Bounded reservation/final-admission source and focused proof are prepared but unregistered; [strict capacity status](#strict-tenant-capacity-owner-preparation) records the executed and unrun boundaries and remaining production qualification. The current numeric runtime entitlement endpoint returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. Current status, preserved positive receiving obligations, and proof history are recorded in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving); earlier focused storage/retry proof does not establish a live legacy-row producer. Legacy gRPC still carries unavailable outcomes in its error field, an explicit transport-classification gap. Current connect-token issuance follows the [Account API conditional bootstrap/scope validation boundary](../../architecture/microservices/account-service/api-contracts.md#rest-apis), but remains unavailable before entitlement reads, cached replay, or token issuance; older positive-issuance tests are historical. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its shared subscription-version/billing-sequence projection and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. No current gameplay or public-join eligibility is inferred from a retained numeric `past_due` row while the runtime entitlement boundary is held. | | `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [Authenticated TCP receiver](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java); [live LOGIN custody](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java); [verified TCP origin](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/VerifiedTcpProxyOrigin.java); [dedicated mTLS Gateway client](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClient.java); [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java); [CanonicalGameplayIssuerAdmissionControlRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java); [CanonicalGameplayIssuerAdmissionBarrierRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java); [CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java); [V1045__canonical_issuer_binding_local_acknowledgement.sql](../../../services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql); [V1046__canonical_issuer_live_admission_control.sql](../../../services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql); [DirectTextAuthenticatedLobbyOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java); [DirectTextAuthenticatedLobbyRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java); [V1052__direct_text_authenticated_lobby.sql](../../../services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql) | [authenticated receiver units](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java); [live custody units](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java); [Gateway mTLS client units](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClientTest.java); [TCP listener admission integration](../../../services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/filter/TcpProxyTlsListenerAdmissionIntegrationTest.java); [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java); [CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java); [CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above; [DirectTextAuthenticatedLobbyTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java); [DirectTextAuthenticatedLobbyIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Authenticated TCP receiving preserves the Gateway-verified origin over the dedicated exact-namespace mTLS hop and retains LOGIN custody on the original live backend generation. Missing protected owners or custody fail closed as `UNAVAILABLE`; malformed commands and missing local LOGIN/WORLDS/REALMS steps return bounded actionable errors. Source and controlled-component proof do not qualify a deployed authenticated LOGIN-to-PLAY chain, canonical admission, fresh-image runtime behavior, or production Redis/PKI/source custody. Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` returns `AUTH_UNAVAILABLE` before bootstrap/scope validation when canonical scope consumers are absent; when manually configured, it validates bootstrap identity and reads the connect scope before refusing cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Direct-text `CHARS` returns unavailable without legacy Entity enumeration or an accepted command event; Account HTTP/bootstrap roster discovery remains separate. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN has selectable default-off dispatch through the existing Account gRPC service and composition of its existing owner graph; genuine runtime caller authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. Issuer LIVE/OPEN/cutoff and INITIAL Account components are manually composed prerequisites, not complete original NEW or playable admission; custody, default registration, final admission and activation remain unqualified as recorded in the [readiness scope and proof](#canonical-new-admission-components). The authenticated lobby SQL companion exists but is unregistered; live REALMS/JOIN registration and admission remain open. | | `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. Current WebSocket reconnect suppresses retained private-context presentation while durable episode/generation eligibility is unqualified; rows remain stored, so this is neither deletion nor proof of logout invalidation. R1424 executed bounded suppression/redraw proof (57 WebSocket-handler units, 20 integration cases and ten LOOK cross-service cases), separately attributed in [Reconnect and Continuity](#reconnect-and-continuity); this is not a fresh current-head image result or proof of eligible-context replay. The earlier first-party post-logout replay defect is historical: current first-party `LOGIN` and `PLAY` deny before legacy effects while the genuine context consumers remain unavailable. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. See AA-2.1 for the finite namespace controller-index migration-driver prefix, its implementation and proof anchors, and the unproved physical PostgreSQL/Redis, final-image, and trusted-bootstrap/execution gates. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisMovementEffectIdempotencyService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [RedisMovementEffectIdempotencyServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java); [SessionContextSecretAndPresenceRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/SessionContextSecretAndPresenceRedisIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. The [local secret/presence containment](#session-secret-and-presence-containment) prevents new raw delegation-JWT persistence and projects legacy values without rehydration; physical retained-value cleanup remains open; scoped receiving proof is recorded at that owner. | diff --git a/dev-tools/evidence_digest.py b/dev-tools/evidence_digest.py index 19ad420d04..9020866943 100644 --- a/dev-tools/evidence_digest.py +++ b/dev-tools/evidence_digest.py @@ -7,12 +7,12 @@ from typing import Any -def canonical_evidence_digest(record: dict[str, Any]) -> str: - """Hash a record, excluding only its top-level immutableArtifactId field. +def canonical_json_bytes(value: Any) -> bytes: + """Encode the restricted RFC 8785 evidence subset as canonical UTF-8 bytes. - Nested immutableArtifactId occurrences remain part of the canonical payload. + Evidence records intentionally reject floating-point values and integers outside + the interoperable range rather than applying JavaScript number rounding. """ - payload = {key: value for key, value in record.items() if key != "immutableArtifactId"} def encode(value: Any) -> str: if value is None: @@ -38,5 +38,15 @@ def encode(value: Any) -> str: return "[" + ",".join(encode(nested) for nested in value) + "]" raise TypeError(f"unsupported evidence value type: {type(value).__name__}") - encoded = encode(payload).encode("utf-8") + return encode(value).encode("utf-8") + + +def canonical_evidence_digest(record: dict[str, Any]) -> str: + """Hash a record, excluding only its top-level immutableArtifactId field. + + Nested immutableArtifactId occurrences remain part of the canonical payload. + """ + payload = {key: value for key, value in record.items() if key != "immutableArtifactId"} + + encoded = canonical_json_bytes(payload) return f"sha256:{hashlib.sha256(encoded).hexdigest()}" diff --git a/protos/account/v1/account_service.proto b/protos/account/v1/account_service.proto index 56e6a9183f..0d5cc807cb 100644 --- a/protos/account/v1/account_service.proto +++ b/protos/account/v1/account_service.proto @@ -3,12 +3,15 @@ syntax = "proto3"; package account.v1; import "shared/v1/errors.proto"; +import "account/v1/tenant_capacity_admission.proto"; import "shared/v1/player_execution_context.proto"; option java_package = "net.firedevops.firemud.account.v1"; option java_multiple_files = true; service AccountService { + // Strict capacity owner. Available only through an explicitly composed bounded mTLS receiver. + rpc CommitTenantCapacityAdmission(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 new file mode 100644 index 0000000000..973bb17cc1 --- /dev/null +++ b/protos/account/v1/tenant_capacity_admission.proto @@ -0,0 +1,70 @@ +syntax = "proto3"; +package account.v1; +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Singleton repeated envelopes preserve multiplicity for the strict bounded codec. +message TenantCapacityShape { + repeated int64 active_sessions = 1; + repeated int64 concurrent_game_instances = 2; + repeated int64 storage_bytes = 3; +} +// Exact PlayerExecutionContext content with strict singleton multiplicity preserved on this wire. +message TenantCapacityPlayerContext { + repeated string account_id = 1; + repeated string tenant_id = 2; + repeated string playable_state_namespace_id = 3; + repeated string game_instance_id = 4; + repeated string character_id = 5; + repeated string session_id = 6; + repeated string realm_id = 7; + repeated string request_id = 8; + repeated string playable_state_scope = 9; +} +message TenantCapacityWorldContext { + repeated string tenant_id = 1; + repeated string operation_id = 2; + repeated string lifecycle_id = 3; + repeated string game_instance_id = 4; + repeated string owner_id = 5; + repeated int64 owner_fence = 6; +} +message TenantCapacityAdmissionAttempt { + 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 target_namespace = 6; + // Exactly one typed alternative, never a caller-supplied workload identity. + repeated TenantCapacityPlayerContext player_context = 7; + repeated TenantCapacityWorldContext world_context = 8; + repeated string operation = 9; + repeated TenantCapacityShape prior_shape = 10; + repeated TenantCapacityShape requested_shape = 11; + // Exact existing Account canonical bundle; content parsing cannot register its authority. + repeated bytes canonical_account_evidence = 12; + repeated string mutation_digest = 13; +} +message CommitTenantCapacityAdmissionRequest { + repeated TenantCapacityAdmissionAttempt attempt = 1; + // Mandatory presence. Proto JSON is a canonical base-10 decimal string, not a JSON number. + optional int64 capacity_delta = 2; +} +message TenantCapacityAdmissionCommitment { + 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 reservation_id = 7; + repeated int64 reservation_fence = 8; + repeated string expires_at = 9; + repeated string state = 10; + repeated string snapshot_identity = 11; + repeated string evaluation_identity = 12; +} +message CommitTenantCapacityAdmissionResponse { + repeated TenantCapacityAdmissionCommitment commitment = 1; +} 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 new file mode 100644 index 0000000000..9fdb6c982d --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java @@ -0,0 +1,262 @@ +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.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.Evidence; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Identity; +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 org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Account-local primitives only, always in the owning writable transaction. No bean or seed API. + */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Private owner transaction collaborator.") +public final class AccountTenantCapacityRepository { + private static final String FIND_RESERVATION = + "SELECT * FROM account_tenant_capacity_reservations WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?"; + private final DSLContext dsl; + + public AccountTenantCapacityRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + /** Called by the actual Account player evaluator before its final source transaction commits. */ + public void retainPlayerEvaluation(RuntimePlayerAdmissionEntitlementEvidence source) { + retain(Evidence.player(source)); + } + + private void retain(Evidence evidence) { + transaction(); + int inserted = + dsl.execute( + "INSERT INTO account_tenant_capacity_evaluations " + + "(evaluation_identity, snapshot_identity, tenant_uuid, caller_workload, owner_service, canonical_evidence, evaluated_at, expires_at) " + + "VALUES (?, ?, ?, ?, ?, ?, ?::timestamptz, ?::timestamptz) ON CONFLICT (evaluation_identity) DO NOTHING", + evidence.evaluationIdentity(), + evidence.snapshotIdentity(), + evidence.tenantId(), + evidence.callerWorkload(), + evidence.owner().service(), + evidence.canonicalBytes(), + at(evidence.evaluatedAt()), + at(evidence.expiresAt())); + if (inserted != 0 && inserted != 1) throw unavailable(); + requireRetained(evidence); + } + + public void requireRetained(Evidence evidence) { + transaction(); + Record row = + dsl.fetchOne( + "SELECT * FROM account_tenant_capacity_evaluations WHERE evaluation_identity = ? FOR SHARE", + evidence.evaluationIdentity()); + if (row == null + || !evidence.tenantId().equals(row.get("tenant_uuid", UUID.class)) + || !evidence.snapshotIdentity().equals(row.get("snapshot_identity", String.class)) + || !evidence.callerWorkload().equals(row.get("caller_workload", String.class)) + || !evidence.owner().service().equals(row.get("owner_service", String.class)) + || !Arrays.equals(evidence.canonicalBytes(), row.get("canonical_evidence", byte[].class)) + || !evidence + .evaluatedAt() + .truncatedTo(java.time.temporal.ChronoUnit.MICROS) + .equals(time(row, "evaluated_at")) + || !evidence + .expiresAt() + .truncatedTo(java.time.temporal.ChronoUnit.MICROS) + .equals(time(row, "expires_at"))) throw unavailable(); + } + + public Record find(Identity id) { + return find(id, FIND_RESERVATION + " FOR UPDATE"); + } + + /** Exact replay reads the transaction snapshot without taking a mutation lock. */ + public Record findForReplay(Identity id) { + return find(id, FIND_RESERVATION); + } + + private Record find(Identity id, String query) { + transaction(); + return dsl.fetchOne(query, id.tenantId(), id.requestId(), id.admissionId()); + } + + public Record usage(Request request) { + transaction(); + Record usage = + dsl.fetchOne( + "SELECT * FROM account_tenant_capacity_usage WHERE tenant_uuid = ? AND owner_service = ? FOR UPDATE", + request.identity().tenantId(), + request.context().owner().service()); + if (usage == null) throw unavailable(); + return usage; + } + + public Result exact(Request request, Record row) { + if (!request.mutationDigest().equals(row.get("mutation_digest", String.class)) + || !request.admissionAttemptId().equals(row.get("admission_attempt_id", UUID.class)) + || request.capacityRearmFence() != number(row, "capacity_rearm_fence") + || !Arrays.equals( + CapacityAdmissionDigest.preimage(request), row.get("canonical_payload", byte[].class)) + || !request.evidence().callerWorkload().equals(row.get("caller_workload", String.class))) + throw conflict(); + return result(row); + } + + public void requirePriorHistory(Request prior, Request next) { + transaction(); + if (!prior.identity().equals(next.identity()) + || prior.admissionAttemptId().equals(next.admissionAttemptId()) + || next.capacityRearmFence() != Math.incrementExact(prior.capacityRearmFence())) + throw conflict(); + Record history = + dsl.fetchOne( + "SELECT * FROM account_tenant_capacity_attempt_history WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND admission_attempt_id = ? FOR SHARE", + prior.identity().tenantId(), + prior.identity().requestId(), + prior.identity().admissionId(), + prior.admissionAttemptId()); + if (history == null + || number(history, "capacity_rearm_fence") != prior.capacityRearmFence() + || !prior.mutationDigest().equals(history.get("mutation_digest", String.class)) + || !Arrays.equals( + CapacityAdmissionDigest.preimage(prior), history.get("canonical_payload", byte[].class)) + || 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()); + 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); + long held = Math.addExact(number(usage, "held_units"), delta); + updateUsage(request, usage, held, number(usage, "used_units")); + int created = + 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 (?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?::timestamptz, ?::timestamptz, 'RESERVED', 'OWNER_EXECUTION_PENDING')", + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + UUID.randomUUID(), + request.context().owner().service(), + request.evidence().callerWorkload(), + request.admissionAttemptId(), + request.capacityRearmFence(), + request.mutationDigest(), + CapacityAdmissionDigest.preimage(request), + request.evidence().evaluationIdentity(), + delta, + 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); + } + } + + public void updateUsage(Request request, Record before, long held, long used) { + transaction(); + if (held < 0 || used < 0 || Math.addExact(held, used) < 0) throw unavailable(); + long revision = number(before, "usage_revision"); + int updated = + dsl.execute( + "UPDATE account_tenant_capacity_usage SET held_units = ?, used_units = ?, usage_revision = ? WHERE tenant_uuid = ? AND owner_service = ? AND usage_revision = ?", + held, + used, + Math.incrementExact(revision), + request.identity().tenantId(), + request.context().owner().service(), + revision); + if (updated != 1) throw unavailable(); + } + + public Result result(Record row) { + transaction(); + Record evaluation = + dsl.fetchOne( + "SELECT snapshot_identity FROM account_tenant_capacity_evaluations WHERE evaluation_identity = ?", + row.get("evaluation_identity", String.class)); + if (evaluation == null) throw unavailable(); + return new Result( + new Identity( + row.get("tenant_uuid", UUID.class), + row.get("request_id", UUID.class), + row.get("admission_id", UUID.class)), + row.get("admission_attempt_id", UUID.class), + number(row, "capacity_rearm_fence"), + row.get("mutation_digest", String.class), + row.get("reservation_id", UUID.class), + number(row, "reservation_fence"), + time(row, "expires_at"), + State.valueOf(row.get("state", String.class)), + evaluation.get("snapshot_identity", String.class), + row.get("evaluation_identity", String.class)); + } + + public static long number(Record row, String name) { + Long value = row.get(name, Long.class); + if (value == null || value < 0) throw unavailable(); + return value; + } + + public static Instant time(Record row, String name) { + OffsetDateTime value = row.get(name, OffsetDateTime.class); + if (value == null) throw unavailable(); + return value.toInstant(); + } + + public static OffsetDateTime at(Instant instant) { + return instant.truncatedTo(java.time.temporal.ChronoUnit.MICROS).atOffset(ZoneOffset.UTC); + } + + public static void transaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) throw unavailable(); + } + + public static CapacityException conflict() { + return new CapacityException(Failure.IDEMPOTENCY_CONFLICT); + } + + public static CapacityException unavailable() { + return new CapacityException(Failure.ENTITLEMENT_UNAVAILABLE); + } + + public static final class CapacityException extends IllegalStateException { + private final Failure code; + + public CapacityException(Failure code) { + super(code.name()); + this.code = code; + } + + public Failure code() { + return code; + } + } +} 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 new file mode 100644 index 0000000000..88e1694a6f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuard.java @@ -0,0 +1,69 @@ +package net.firedevops.firemud.accountservice.security; + +import io.grpc.Context; +import io.grpc.Contexts; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.Status; +import 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.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 Set allowed; + + public AccountTenantCapacityWorkloadGuard(String namespace) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Namespace required"); + allowed = + Set.of( + TenantCapacityAdmission.expectedWorkload(namespace, Owner.GAME_SESSION), + TenantCapacityAdmission.expectedWorkload(namespace, Owner.WORLD_MANAGEMENT)); + } + + public String requireAuthenticatedCaller() { + String value = caller.get(); + if (!allowed.contains(value == null ? "" : 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() + .getFullMethodName() + .equals(call.getMethodDescriptor().getFullMethodName())) + return deny(call, Status.PERMISSION_DENIED); + return Contexts.interceptCall( + Context.current().withValue(caller, peer.orElseThrow().uri()), call, headers, next); + } + + private static boolean ambient() { + return SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService() + || SessionContext.getServiceName() != null + || SessionContext.getServiceInstanceId() != null; + } + + private static ServerCall.Listener deny( + ServerCall call, Status status) { + call.close( + status.withDescription("Exact capacity owner workload and method required"), + new Metadata()); + return new ServerCall.Listener<>() {}; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java index 9b6ddd5dc6..e918d69b5e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java @@ -28,6 +28,8 @@ import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.FenceRejectedException; import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceSelection; +import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.CapacityException; import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier.VerifiedCaller; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff; @@ -35,6 +37,7 @@ import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector; @@ -573,7 +576,7 @@ private static void requireSupportedTarget( || !"PRESEEDED_ONLY".equals(target.characterCreationPolicy())) throw targetPrecondition(); } - private static RuntimePlayerAdmissionEntitlementEvidence capture( + private RuntimePlayerAdmissionEntitlementEvidence capture( Request request, CurrentPlayer player, PublishedRealmEvidence target, @@ -632,15 +635,25 @@ private static RuntimePlayerAdmissionEntitlementEvidence capture( RuntimePlayerAdmissionEntitlementEvidence.digestBytes(world.canonicalBytes())); sources.put("worldCaptureId", world.captureId().toString()); sources.put("worldRowVersion", Long.toString(world.rowVersion())); - return RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( - request.requestId(), - request.authenticatedCallerWorkload(), - scope.scopeTokenHash(), - player.snapshot(), - binding, - facts, - sources, - time); + var evidence = + RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( + request.requestId(), + request.authenticatedCallerWorkload(), + scope.scopeTokenHash(), + player.snapshot(), + binding, + facts, + sources, + time); + // Retain only inside this actual evaluator's final source transaction. A supplied bundle + // cannot register itself as capacity authority, and commit failure returns no evidence. + try { + new AccountTenantCapacityRepository(dsl).retainPlayerEvaluation(evidence); + } catch (CapacityException retentionFailure) { + if (retentionFailure.code() == Failure.ENTITLEMENT_UNAVAILABLE) throw unavailable(); + throw retentionFailure; + } + return evidence; } private static Map facts( 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 new file mode 100644 index 0000000000..2a00b3420c --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java @@ -0,0 +1,351 @@ +package net.firedevops.firemud.accountservice.service; + +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; +import io.grpc.Context; +import io.grpc.Deadline; +import java.sql.Connection; +import java.sql.SQLException; +import java.time.Clock; +import java.time.Instant; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +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; +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.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.grpc.GrpcPeerIdentity; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.dao.CannotSerializeTransactionException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered strict Account capacity authority. Caller identity must come from the bounded mTLS + * receiver. No caller can register a bundle, initialize usage, attest an execution result, or cause + * a final Game Session/World activation here. World capacity remains held without its current + * lifecycle/evaluation producer. The scalar shape is deliberately restricted to an exact new player + * binding; non-expanding recovery stays held until Account has authoritative prior-shape evidence. + */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Private Account owner collaborators.") +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 final DSLContext dsl; + private final AccountRepository accounts; + private final AccountCanonicalRuntimeMembershipSnapshotRepository memberships; + private final AccountGameplayDelegationIssuanceRepository issuances; + private final AccountConnectScopeRepository scopes; + private final AccountTenantCapacityRepository capacity; + private final TransactionTemplate transaction; + private final Clock clock; + private final String namespace; + + public AccountTenantCapacityOwner( + DSLContext dsl, + AccountRepository accounts, + AccountCanonicalRuntimeMembershipSnapshotRepository memberships, + AccountGameplayDelegationIssuanceRepository issuances, + AccountConnectScopeRepository scopes, + PlatformTransactionManager transactions, + Clock clock, + String namespace) { + this.dsl = Objects.requireNonNull(dsl); + this.accounts = Objects.requireNonNull(accounts); + this.memberships = Objects.requireNonNull(memberships); + this.issuances = Objects.requireNonNull(issuances); + this.scopes = Objects.requireNonNull(scopes); + this.capacity = new AccountTenantCapacityRepository(dsl); + this.clock = Objects.requireNonNull(clock); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Namespace required"); + this.namespace = namespace; + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + transaction.setTimeout(TRANSACTION_TIMEOUT_SECONDS); + } + + 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); + }); + } + + /** 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(); + next.requireCommittable(); + if (!prior.identity().equals(next.identity()) + || prior.admissionAttemptId().equals(next.admissionAttemptId()) + || next.capacityRearmFence() != Math.incrementExact(prior.capacityRearmFence()) + || !prior.context().equals(next.context()) + || prior.operation() != next.operation() + || !prior.priorShape().equals(next.priorShape()) + || !prior.requestedShape().equals(next.requestedShape()) + || !Objects.equals(prior.capacityDelta(), next.capacityDelta()) + || !Objects.equals( + prior.evidence().fields().get("authorityTuple"), + next.evidence().fields().get("authorityTuple"))) throw conflict(); + return inTransaction( + () -> { + lockPlayerAccount(next); + Record row = capacity.find(prior.identity()); + if (row == null) throw conflict(); + if (next.admissionAttemptId().equals(row.get("admission_attempt_id", UUID.class))) { + capacity.requirePriorHistory(prior, next); + return capacity.exact(next, row); + } + capacity.exact(prior, row); + requireClaim(row, recoveryOwner, claimFence, clock.instant()); + 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); + requireSupportedShape(next); + requireCurrentLifetime(next.evidence(), clock.instant()); + int history = + dsl.execute( + "INSERT INTO account_tenant_capacity_attempt_history " + + "(tenant_uuid, request_id, admission_id, admission_attempt_id, capacity_rearm_fence, mutation_digest, canonical_payload, owner_readback) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + prior.identity().tenantId(), + prior.identity().requestId(), + prior.identity().admissionId(), + prior.admissionAttemptId(), + prior.capacityRearmFence(), + prior.mutationDigest(), + CapacityAdmissionDigest.preimage(prior), + row.get("owner_readback", byte[].class)); + if (history != 1) throw unavailable(); + 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'", + next.admissionAttemptId(), + next.capacityRearmFence(), + Math.incrementExact(number(row, "reservation_fence")), + next.mutationDigest(), + CapacityAdmissionDigest.preimage(next), + next.evidence().evaluationIdentity(), + at(next.evidence().expiresAt()), + at(next.evidence().expiresAt().plusSeconds(60)), + prior.identity().tenantId(), + prior.identity().requestId(), + prior.identity().admissionId(), + prior.admissionAttemptId(), + prior.capacityRearmFence(), + prior.mutationDigest(), + recoveryOwner, + claimFence); + if (changed != 1) throw conflict(); + // Reservation identity and both usage columns are deliberately untouched. + return capacity.exact(next, Objects.requireNonNull(capacity.find(next.identity()))); + }); + } + + private void current(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 = + current + .authorityTuple() + .tenantBillingCutoff() + .map(cutoffs -> cutoffs.get(current.tenantId())) + .orElseThrow(AccountTenantCapacityRepository::unavailable); + if (Long.parseLong(billing.tenantBillingSequence()) + > Long.parseLong((String) fields.get("tenantBillingSequence"))) + 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 (!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.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(); + var scope = + qualifiedSource( + () -> + scopes.findCanonicalEvidenceByTokenHash(parsed.verifiedConnectScopeTokenHash())) + .orElseThrow(AccountTenantCapacityRepository::unavailable); + if (!scope.accountUuid().equals(player.accountId()) + || !scope.tenantUuid().equals(player.tenantId()) + || !scope.scopeDigest().equals(source.get("scopeDigest")) + || !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(); + } + + private static T qualifiedSource(Supplier read) { + try { + return read.get(); + } catch (IllegalArgumentException | IllegalStateException unqualifiedSource) { + throw unavailable(); + } + } + + private static void requireSupportedShape(Request request) { + if (request.context().owner() != TenantCapacityAdmission.Owner.GAME_SESSION + || request.operation() != TenantCapacityAdmission.Operation.CAPACITY_CREATING + || !request.priorShape().equals(new TenantCapacityAdmission.Shape(0, 0, 0)) + || !request.requestedShape().equals(new TenantCapacityAdmission.Shape(1, 0, 0)) + || !Long.valueOf(1).equals(request.capacityDelta())) throw unavailable(); + } + + private void lockPlayerAccount(Request request) { + if (!(request.context() instanceof PlayerContext player)) throw unavailable(); + accounts + .findByAccountUuidForUpdate(player.accountId()) + .orElseThrow(AccountTenantCapacityRepository::unavailable); + } + + private void requireCaller(Request request, String caller) { + if (request == null || !namespace.equals(request.targetNamespace())) + throw new CapacityException(Failure.INVALID_ARGUMENT); + if (!TenantCapacityAdmission.expectedWorkload(namespace, request.context().owner()) + .equals(caller) + || !request.evidence().callerWorkload().equals(caller)) + throw new CapacityException(Failure.PERMISSION_DENIED); + } + + static void requireClaim(Record row, UUID owner, long fence, Instant now) { + if (owner == null + || !owner.equals(row.get("recovery_owner", UUID.class)) + || fence != number(row, "recovery_claim_fence") + || !now.isBefore(AccountTenantCapacityRepository.time(row, "recovery_claim_expires_at"))) + throw conflict(); + } + + private Result 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); + 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(); + }); + } catch (RuntimeException failure) { + // 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 + || !serializationFailure(failure) + || !waitForFreshSnapshot(caller, retryDeadline, attempt)) throw failure; + } + } + } + + private static boolean waitForFreshSnapshot(Context caller, Deadline deadline, int attempt) { + long minimumDelay = INITIAL_RETRY_DELAY_MILLIS << (attempt - 1); + long delay = ThreadLocalRandom.current().nextLong(minimumDelay, 2 * minimumDelay); + if (caller.isCancelled() || deadline.timeRemaining(TimeUnit.MILLISECONDS) <= delay) { + return false; + } + try { + TimeUnit.MILLISECONDS.sleep(delay); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + return false; + } + return !caller.isCancelled() && !deadline.isExpired(); + } + + 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; + } + return false; + } + + T inTransaction(Supplier action) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) throw unavailable(); + return Objects.requireNonNull( + transaction.execute( + status -> { + AccountTenantCapacityRepository.transaction(); + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() + != Connection.TRANSACTION_SERIALIZABLE) throw unavailable(); + }); + return action.get(); + })); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityRecoveryWorker.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityRecoveryWorker.java new file mode 100644 index 0000000000..11997dbb02 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityRecoveryWorker.java @@ -0,0 +1,428 @@ +package net.firedevops.firemud.accountservice.service; + +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.unavailable; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Clock; +import java.time.Instant; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Identity; +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 org.jooq.DSLContext; +import org.jooq.Record; + +/** + * Unregistered Account reservation recovery. Only this owner mutates reservation outcomes. Its + * protected selected-owner read client is a required dependency, not an automatically registered + * source or a caller-supplied attestation. Original-NEW Game Session has a bounded exact reader; + * World lifecycle and other action families remain unsupported. No timeout synthesizes no-commit. + */ +@SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "Private owner/source collaborators.") +public final class AccountTenantCapacityRecoveryWorker { + public enum Disposition { + COMMITTED, + NOT_EXECUTED_AFTER_AUTHORIZATION, + INDETERMINATE + } + + public enum NoCommitAction { + RETAIN_FOR_REARM, + RELEASE + } + + /** + * An implementation must use the exact selected owner's authenticated mTLS readback and validate + * its current owner fence and authoritative state, including durable original-attempt rejection + * and no mutation for NOT_EXECUTED_AFTER_AUTHORIZATION. Content construction is not authority. + * FENCE_REJECTED, FAILED, pending and ambiguous responses map only to INDETERMINATE. + */ + public interface ExecutionReadClient { + Observation readExact(Request request, Result reservation, Instant deadline); + } + + public record Observation( + String authenticatedOwnerWorkload, + Result reservation, + byte[] canonicalAttemptPayload, + Disposition disposition, + UUID proofId, + long currentOwnerFence, + String authoritativeStateDigest, + byte[] canonicalOwnerReadback) { + public Observation { + Objects.requireNonNull(reservation); + Objects.requireNonNull(disposition); + TenantCapacityAdmission.uuid(proofId); + if (authenticatedOwnerWorkload == null + || currentOwnerFence <= 0 + || authoritativeStateDigest == null + || !authoritativeStateDigest.matches("sha256:[0-9a-f]{64}") + || canonicalAttemptPayload == null + || canonicalAttemptPayload.length == 0 + || canonicalAttemptPayload.length > CapacityAdmissionDigest.MAX_PREIMAGE_BYTES + || canonicalOwnerReadback == null + || canonicalOwnerReadback.length == 0 + || canonicalOwnerReadback.length > 256 * 1024) + throw new IllegalArgumentException("Complete owner readback required"); + canonicalAttemptPayload = canonicalAttemptPayload.clone(); + canonicalOwnerReadback = canonicalOwnerReadback.clone(); + } + + @Override + public byte[] canonicalAttemptPayload() { + return canonicalAttemptPayload.clone(); + } + + @Override + public byte[] canonicalOwnerReadback() { + return canonicalOwnerReadback.clone(); + } + + @Override + public String toString() { + return "CapacityOwnerObservation[redacted]"; + } + } + + private final AccountTenantCapacityOwner owner; + private final DSLContext dsl; + private final AccountTenantCapacityRepository capacity; + private final ExecutionReadClient source; + private final Clock clock; + private final UUID workerId = UUID.randomUUID(); + private final Set inFlight = ConcurrentHashMap.newKeySet(); + + public AccountTenantCapacityRecoveryWorker( + AccountTenantCapacityOwner owner, DSLContext dsl, ExecutionReadClient source, Clock clock) { + this.owner = Objects.requireNonNull(owner); + this.dsl = Objects.requireNonNull(dsl); + this.capacity = new AccountTenantCapacityRepository(dsl); + this.source = Objects.requireNonNull(source); + this.clock = Objects.requireNonNull(clock); + } + + /** Twelve bounded observations or the original deadline quarantine the same complete hold. */ + public Result reconcile(Request request, NoCommitAction noCommitAction) { + Objects.requireNonNull(noCommitAction); + request.requireCommittable(); + return withExclusiveOperation( + request.identity(), () -> reconcileClaim(request, noCommitAction)); + } + + private Result reconcileClaim(Request request, NoCommitAction noCommitAction) { + Claim claim = claim(request); + if (claim.reservation().state() != State.RESERVED) return claim.reservation(); + if (claim.noCommitProof() != null) { + if (noCommitAction == NoCommitAction.RETAIN_FOR_REARM) return claim.reservation(); + return owner.inTransaction( + () -> { + Record row = capacity.find(request.identity()); + if (row == null) throw conflict(); + Result current = capacity.exact(request, row); + AccountTenantCapacityOwner.requireClaim(row, workerId, claim.fence(), clock.instant()); + if (!current.equals(claim.reservation()) + || !"NOT_EXECUTED_AFTER_AUTHORIZATION" + .equals(row.get("execution_status", String.class)) + || !Arrays.equals(claim.noCommitProof(), row.get("owner_readback", byte[].class))) + throw conflict(); + moveUsage(request, false); + int changed = + dsl.execute( + "UPDATE account_tenant_capacity_reservations SET state = 'RELEASED', reservation_fence = ?, next_reconcile_at = NULL WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND recovery_owner = ? AND recovery_claim_fence = ? AND state = 'RESERVED' AND execution_status = 'NOT_EXECUTED_AFTER_AUTHORIZATION'", + Math.incrementExact(current.reservationFence()), + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + workerId, + claim.fence()); + if (changed != 1) throw conflict(); + return capacity.exact( + request, Objects.requireNonNull(capacity.find(request.identity()))); + }); + } + Observation candidate = null; + byte[] candidateProof = null; + if (claim.attempts() < 12) { + Instant started = clock.instant(); + boolean positiveOnly = !started.isBefore(claim.reconcileDeadline()); + Instant deadline = started.plusSeconds(5); + if (!positiveOnly && claim.reconcileDeadline().isBefore(deadline)) + deadline = claim.reconcileDeadline(); + try { + candidate = source.readExact(request, claim.reservation(), deadline); + if (!clock.instant().isBefore(deadline)) throw unavailable(); + requireExactSource(request, claim.reservation(), candidate); + // A delayed first reconciliation must still recognize an exact committed effect. The + // expired negative-evidence window never permits a late read to release the hold. + if (positiveOnly && candidate.disposition() != Disposition.COMMITTED) throw unavailable(); + candidateProof = proof(request, candidate); + } catch (RuntimeException unavailableSource) { + // Missing, malformed, late and failed reads are indeterminate, never no-commit proof. + candidate = null; + candidateProof = null; + } + } + final Observation observed = candidate; + final byte[] exactProof = candidateProof; + return owner.inTransaction( + () -> { + Record row = capacity.find(request.identity()); + if (row == null) throw conflict(); + Result current = capacity.exact(request, row); + AccountTenantCapacityOwner.requireClaim(row, workerId, claim.fence(), clock.instant()); + if (!current.equals(claim.reservation())) throw conflict(); + int attempt = Math.incrementExact(Math.toIntExact(number(row, "recovery_attempt_count"))); + if (attempt > 12) throw unavailable(); + Instant now = clock.instant(); + boolean indeterminate = + observed == null || observed.disposition() == Disposition.INDETERMINATE; + boolean quarantine = + indeterminate && (attempt == 12 || !now.isBefore(claim.reconcileDeadline())); + String outcome = + quarantine + ? State.QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION.name() + : observed == null ? "SOURCE_UNAVAILABLE" : observed.disposition().name(); + int retained = + dsl.execute( + "INSERT INTO account_tenant_capacity_recovery_evidence (tenant_uuid, request_id, admission_id, admission_attempt_id, recovery_claim_fence, recovery_policy_version, recovery_attempt_number, observed_at, outcome, canonical_readback, readback_digest) VALUES (?, ?, ?, ?, ?, 'capacity-recovery/1', ?, ?::timestamptz, ?, ?, ?)", + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + request.admissionAttemptId(), + claim.fence(), + attempt, + at(now), + outcome, + exactProof, + exactProof == null ? null : sha256(exactProof)); + if (retained != 1) throw unavailable(); + if (indeterminate) { + int updated = + dsl.execute( + "UPDATE account_tenant_capacity_reservations SET recovery_attempt_count = ?, state = ?, recovery_escalated_at = ?::timestamptz, next_reconcile_at = ?::timestamptz WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND recovery_owner = ? AND recovery_claim_fence = ? AND state = 'RESERVED' AND execution_status = 'OWNER_EXECUTION_PENDING'", + attempt, + quarantine + ? State.QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION.name() + : State.RESERVED.name(), + quarantine ? at(now) : null, + quarantine + ? null + : at( + now.plusSeconds(5).isBefore(claim.reconcileDeadline()) + ? now.plusSeconds(5) + : claim.reconcileDeadline()), + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + workerId, + claim.fence()); + if (updated != 1) throw conflict(); + return capacity.exact( + request, Objects.requireNonNull(capacity.find(request.identity()))); + } + boolean committed = observed.disposition() == Disposition.COMMITTED; + State next = + committed + ? State.FINALIZED + : noCommitAction == NoCommitAction.RELEASE ? State.RELEASED : State.RESERVED; + if (committed || next == State.RELEASED) moveUsage(request, committed); + long reservationFence = + next == State.RELEASED + ? Math.incrementExact(current.reservationFence()) + : current.reservationFence(); + int changed = + dsl.execute( + "UPDATE account_tenant_capacity_reservations SET state = ?, execution_status = ?, owner_readback = ?, owner_readback_digest = ?, reservation_fence = ?, recovery_attempt_count = ?, next_reconcile_at = NULL " + + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND admission_attempt_id = ? AND mutation_digest = ? AND reservation_fence = ? AND recovery_owner = ? AND recovery_claim_fence = ? AND state = 'RESERVED' AND execution_status = 'OWNER_EXECUTION_PENDING'", + next.name(), + committed ? "COMMITTED" : "NOT_EXECUTED_AFTER_AUTHORIZATION", + exactProof, + sha256(exactProof), + reservationFence, + attempt, + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + request.admissionAttemptId(), + request.mutationDigest(), + current.reservationFence(), + workerId, + claim.fence()); + if (changed != 1) throw conflict(); + return capacity.exact(request, Objects.requireNonNull(capacity.find(request.identity()))); + }); + } + + private void moveUsage(Request request, boolean committed) { + Record usage = capacity.usage(request); + long delta = Objects.requireNonNull(request.capacityDelta()); + capacity.updateUsage( + request, + usage, + Math.subtractExact(number(usage, "held_units"), delta), + committed + ? Math.addExact(number(usage, "used_units"), delta) + : number(usage, "used_units")); + } + + public Result rearm(Request prior, Request next) { + prior.requireCommittable(); + next.requireCommittable(); + return withExclusiveOperation(prior.identity(), () -> rearmClaim(prior, next)); + } + + private Result rearmClaim(Request prior, Request next) { + java.util.Optional replay = + owner.inTransaction( + () -> { + Record row = capacity.find(next.identity()); + if (row != null + && next.admissionAttemptId() + .equals(row.get("admission_attempt_id", UUID.class))) { + capacity.requirePriorHistory(prior, next); + return java.util.Optional.of(capacity.exact(next, row)); + } + return java.util.Optional.empty(); + }); + if (replay.isPresent()) return replay.orElseThrow(); + Claim claim = claim(prior); + return owner.rearm(prior, next, workerId, claim.fence()); + } + + private Result withExclusiveOperation(Identity identity, Supplier operation) { + // This worker can advance its own live claim for a sequential retry or rearm. + if (!inFlight.add(identity)) throw unavailable(); + try { + return operation.get(); + } finally { + inFlight.remove(identity); + } + } + + private Claim claim(Request request) { + return owner.inTransaction( + () -> { + Record row = capacity.find(request.identity()); + if (row == null) throw conflict(); + Result result = capacity.exact(request, row); + if (result.state() != State.RESERVED) + return new Claim( + result, + number(row, "recovery_claim_fence"), + Math.toIntExact(number(row, "recovery_attempt_count")), + AccountTenantCapacityRepository.time(row, "reconcile_deadline"), + row.get("owner_readback", byte[].class)); + Instant now = clock.instant(); + if (row.get("recovery_owner", UUID.class) != null + && !workerId.equals(row.get("recovery_owner", UUID.class)) + && now.isBefore( + AccountTenantCapacityRepository.time(row, "recovery_claim_expires_at"))) + throw unavailable(); + long fence = Math.incrementExact(number(row, "recovery_claim_fence")); + int changed = + dsl.execute( + "UPDATE account_tenant_capacity_reservations SET recovery_owner = ?, recovery_claim_fence = ?, recovery_claim_expires_at = ?::timestamptz, next_reconcile_at = LEAST(?::timestamptz, reconcile_deadline) " + + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND recovery_claim_fence = ?", + workerId, + fence, + at(now.plusSeconds(15)), + at(now.plusSeconds(5)), + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + number(row, "recovery_claim_fence")); + if (changed != 1) throw conflict(); + return new Claim( + result, + fence, + Math.toIntExact(number(row, "recovery_attempt_count")), + AccountTenantCapacityRepository.time(row, "reconcile_deadline"), + row.get("owner_readback", byte[].class)); + }); + } + + private static void requireExactSource(Request request, Result expected, Observation observed) { + if (observed == null + || !expected.equals(observed.reservation()) + || !TenantCapacityAdmission.expectedWorkload( + request.targetNamespace(), request.context().owner()) + .equals(observed.authenticatedOwnerWorkload()) + || !Arrays.equals( + CapacityAdmissionDigest.preimage(request), observed.canonicalAttemptPayload())) + throw unavailable(); + } + + private static byte[] proof(Request request, Observation observed) { + // Fixed content binding includes the entire attempt and exact owner readback, not a boolean. + var output = new java.io.ByteArrayOutputStream(); + for (byte[] bytes : + new byte[][] { + "account-capacity-owner-readback/v1".getBytes(java.nio.charset.StandardCharsets.US_ASCII), + CapacityAdmissionDigest.preimage(request), + observed + .reservation() + .reservationId() + .toString() + .getBytes(java.nio.charset.StandardCharsets.US_ASCII), + Long.toString(observed.reservation().reservationFence()) + .getBytes(java.nio.charset.StandardCharsets.US_ASCII), + observed + .authenticatedOwnerWorkload() + .getBytes(java.nio.charset.StandardCharsets.US_ASCII), + observed.disposition().name().getBytes(java.nio.charset.StandardCharsets.US_ASCII), + observed.proofId().toString().getBytes(java.nio.charset.StandardCharsets.US_ASCII), + Long.toString(observed.currentOwnerFence()) + .getBytes(java.nio.charset.StandardCharsets.US_ASCII), + observed.authoritativeStateDigest().getBytes(java.nio.charset.StandardCharsets.US_ASCII), + observed.canonicalOwnerReadback() + }) { + output.writeBytes( + Integer.toString(bytes.length).getBytes(java.nio.charset.StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + byte[] proof = output.toByteArray(); + if (proof.length > 1024 * 1024) throw unavailable(); + return proof; + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException(unavailable); + } + } + + private record Claim( + Result reservation, + long fence, + int attempts, + Instant reconcileDeadline, + byte[] noCommitProof) { + private Claim { + noCommitProof = noCommitProof == null ? null : noCommitProof.clone(); + } + + @Override + public byte[] noCommitProof() { + return noCommitProof == null ? null : noCommitProof.clone(); + } + } +} 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 new file mode 100644 index 0000000000..22a326f5f3 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java @@ -0,0 +1,102 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.TlsServerCredentials; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.Objects; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.TrustManagerFactory; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionRequest; +import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionResponse; +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.TenantCapacityAdmissionGrpcCodec; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; +import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; +import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit private composition only. Other Account RPCs remain UNIMPLEMENTED on this server. */ +public final class AccountTenantCapacityGrpcService + extends AccountServiceGrpc.AccountServiceImplBase { + private final AccountTenantCapacityOwner owner; + private final AccountTenantCapacityWorkloadGuard guard; + + public AccountTenantCapacityGrpcService(AccountTenantCapacityOwner owner, String namespace) { + this.owner = Objects.requireNonNull(owner); + guard = new AccountTenantCapacityWorkloadGuard(namespace); + } + + public Server createUnregisteredServer( + String address, KeyManagerFactory keys, TrustManagerFactory trust) { + var factory = + new BoundedGrpcServerFactory( + Objects.requireNonNull(address), + List.of(), + Objects.requireNonNull(keys), + Objects.requireNonNull(trust), + TlsServerCredentials.ClientAuth.REQUIRE, + GrpcRequestBytePolicy.ordinary(), + TenantCapacityAdmissionGrpcCodec.MAX_REQUEST_WIRE_BYTES); + factory.addService(ServerInterceptors.interceptForward(this, guard)); + return factory.createServer(); + } + + @Override + public void commitTenantCapacityAdmission( + CommitTenantCapacityAdmissionRequest wire, + StreamObserver observer) { + Objects.requireNonNull(observer); + final String peer; + try { + peer = guard.requireAuthenticatedCaller(); + } 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 net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.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 { + result = TenantCapacityAdmissionGrpcCodec.toResponse(request, owner.commit(request, peer)); + } catch (CapacityException denied) { + observer.onError(denied.code().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(Status.INTERNAL.asRuntimeException()); + return; + } + try { + observer.onNext(result); + observer.onCompleted(); + } catch (RuntimeException callback) { + observer.onError(Status.INTERNAL.asRuntimeException()); + } + } +} diff --git a/services/account-service/src/main/resources/db/migration/V1040__account_tenant_capacity_owner.sql b/services/account-service/src/main/resources/db/migration/V1040__account_tenant_capacity_owner.sql new file mode 100644 index 0000000000..ceec667db8 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1040__account_tenant_capacity_owner.sql @@ -0,0 +1,321 @@ +-- Existing tenants are deliberately not initialized from missing usage or eligibility snapshots. +ALTER TABLE account_fresh_tenant_identity_associations ADD COLUMN capacity_birth_transaction VARCHAR(20); +ALTER TABLE account_fresh_tenant_identity_associations ALTER COLUMN capacity_birth_transaction SET DEFAULT pg_current_xact_id()::TEXT; + +CREATE TABLE account_tenant_capacity_usage ( + tenant_uuid UUID NOT NULL REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id), + owner_service VARCHAR(40) NOT NULL CHECK (owner_service IN ('game-session-service', 'world-management-service')), + bootstrap_request_id UUID NOT NULL REFERENCES account_tenant_creation_bootstrap_operations(request_id), + creation_evidence_digest VARCHAR(71) NOT NULL CHECK (creation_evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + held_units BIGINT NOT NULL CHECK (held_units >= 0), + used_units BIGINT NOT NULL CHECK (used_units >= 0), + usage_revision BIGINT NOT NULL CHECK (usage_revision > 0), + PRIMARY KEY (tenant_uuid, owner_service), + CHECK (held_units <= 9223372036854775807 - used_units) +); + +CREATE TABLE account_tenant_capacity_evaluations ( + evaluation_identity VARCHAR(71) PRIMARY KEY CHECK (evaluation_identity ~ '^sha256:[0-9a-f]{64}$'), + snapshot_identity VARCHAR(71) NOT NULL CHECK (snapshot_identity ~ '^sha256:[0-9a-f]{64}$'), + tenant_uuid UUID NOT NULL REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id), + caller_workload VARCHAR(253) NOT NULL, + owner_service VARCHAR(40) NOT NULL CHECK (owner_service IN ('game-session-service', 'world-management-service')), + canonical_evidence BYTEA NOT NULL CHECK (octet_length(canonical_evidence) BETWEEN 1 AND 262144), + evaluated_at TIMESTAMPTZ NOT NULL, + expires_at TIMESTAMPTZ NOT NULL CHECK (expires_at > evaluated_at) +); + +CREATE TABLE account_tenant_capacity_reservations ( + tenant_uuid UUID NOT NULL, + request_id UUID NOT NULL CHECK (request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + admission_id UUID NOT NULL CHECK (admission_id <> '00000000-0000-0000-0000-000000000000'::UUID), + reservation_id UUID NOT NULL UNIQUE CHECK (reservation_id <> '00000000-0000-0000-0000-000000000000'::UUID), + owner_service VARCHAR(40) NOT NULL, + caller_workload VARCHAR(253) NOT NULL, + admission_attempt_id UUID NOT NULL UNIQUE, + capacity_rearm_fence BIGINT NOT NULL CHECK (capacity_rearm_fence > 0), + reservation_fence BIGINT NOT NULL CHECK (reservation_fence > 0), + mutation_digest CHAR(64) NOT NULL CHECK (mutation_digest ~ '^[0-9a-f]{64}$'), + canonical_payload BYTEA NOT NULL CHECK (octet_length(canonical_payload) BETWEEN 1 AND 524288), + evaluation_identity VARCHAR(71) NOT NULL REFERENCES account_tenant_capacity_evaluations(evaluation_identity), + capacity_delta BIGINT NOT NULL CHECK (capacity_delta >= 0), + expires_at TIMESTAMPTZ NOT NULL, + state VARCHAR(64) NOT NULL CHECK (state IN ('RESERVED', 'FINALIZED', 'RELEASED', 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION')), + execution_status VARCHAR(48) NOT NULL CHECK (execution_status IN ('OWNER_EXECUTION_PENDING', 'COMMITTED', 'NOT_EXECUTED_AFTER_AUTHORIZATION')), + recovery_owner UUID, + recovery_claim_fence BIGINT NOT NULL DEFAULT 0 CHECK (recovery_claim_fence >= 0), + recovery_claim_expires_at TIMESTAMPTZ, + next_reconcile_at TIMESTAMPTZ, + reconcile_deadline TIMESTAMPTZ NOT NULL, + recovery_policy_version VARCHAR(32) NOT NULL DEFAULT 'capacity-recovery/1' CHECK (recovery_policy_version = 'capacity-recovery/1'), + recovery_attempt_count INT NOT NULL DEFAULT 0 CHECK (recovery_attempt_count BETWEEN 0 AND 12), + recovery_escalated_at TIMESTAMPTZ, + owner_readback BYTEA CHECK (octet_length(owner_readback) BETWEEN 1 AND 1048576), + owner_readback_digest CHAR(64) CHECK (owner_readback_digest ~ '^[0-9a-f]{64}$'), + PRIMARY KEY (tenant_uuid, request_id, admission_id), + FOREIGN KEY (tenant_uuid, owner_service) REFERENCES account_tenant_capacity_usage(tenant_uuid, owner_service), + CHECK ((execution_status = 'OWNER_EXECUTION_PENDING') = (owner_readback IS NULL)), + CHECK ((owner_readback IS NULL) = (owner_readback_digest IS NULL)), + CHECK ((state = 'FINALIZED') = (execution_status = 'COMMITTED')), + CHECK ((state = 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION') = (recovery_escalated_at IS NOT NULL)), + CHECK (state <> 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION' OR execution_status = 'OWNER_EXECUTION_PENDING'), + CHECK (state <> 'RELEASED' OR execution_status = 'NOT_EXECUTED_AFTER_AUTHORIZATION'), + CHECK ((recovery_owner IS NULL) = (recovery_claim_expires_at IS NULL)) +); + +CREATE TABLE account_tenant_capacity_attempt_history ( + tenant_uuid UUID NOT NULL, + request_id UUID NOT NULL, + admission_id UUID NOT NULL, + admission_attempt_id UUID NOT NULL UNIQUE, + capacity_rearm_fence BIGINT NOT NULL CHECK (capacity_rearm_fence > 0), + mutation_digest CHAR(64) NOT NULL CHECK (mutation_digest ~ '^[0-9a-f]{64}$'), + canonical_payload BYTEA NOT NULL CHECK (octet_length(canonical_payload) BETWEEN 1 AND 524288), + owner_readback BYTEA NOT NULL CHECK (octet_length(owner_readback) BETWEEN 1 AND 1048576), + PRIMARY KEY (tenant_uuid, request_id, admission_id, admission_attempt_id), + FOREIGN KEY (tenant_uuid, request_id, admission_id) REFERENCES account_tenant_capacity_reservations(tenant_uuid, request_id, admission_id) +); + +CREATE TABLE account_tenant_capacity_recovery_evidence ( + tenant_uuid UUID NOT NULL, + request_id UUID NOT NULL, + admission_id UUID NOT NULL, + admission_attempt_id UUID NOT NULL, + recovery_claim_fence BIGINT NOT NULL CHECK (recovery_claim_fence > 0), + recovery_policy_version VARCHAR(32) NOT NULL CHECK (recovery_policy_version = 'capacity-recovery/1'), + recovery_attempt_number INT NOT NULL CHECK (recovery_attempt_number BETWEEN 1 AND 12), + observed_at TIMESTAMPTZ NOT NULL, + outcome VARCHAR(64) NOT NULL CHECK (outcome IN ('INDETERMINATE', 'SOURCE_UNAVAILABLE', 'COMMITTED', 'NOT_EXECUTED_AFTER_AUTHORIZATION', 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION')), + canonical_readback BYTEA CHECK (octet_length(canonical_readback) BETWEEN 1 AND 1048576), + readback_digest CHAR(64) CHECK (readback_digest ~ '^[0-9a-f]{64}$'), + PRIMARY KEY (tenant_uuid, request_id, admission_id, admission_attempt_id, recovery_claim_fence), + UNIQUE (tenant_uuid, request_id, admission_id, admission_attempt_id, recovery_attempt_number), + FOREIGN KEY (tenant_uuid, request_id, admission_id) REFERENCES account_tenant_capacity_reservations(tenant_uuid, request_id, admission_id), + CHECK ((canonical_readback IS NULL) = (readback_digest IS NULL)), + CHECK (outcome NOT IN ('COMMITTED', 'NOT_EXECUTED_AFTER_AUTHORIZATION') OR canonical_readback IS NOT NULL) +); + +-- [jooq ignore start] +-- Only a genuinely new same-transaction fresh tenant completion can establish zero usage. +-- Replaying/importing a previously committed tenant cannot turn unknown usage into zero. +CREATE FUNCTION account_tenant_capacity_bootstrap_new_tenant() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE birth account_fresh_tenant_identity_associations%ROWTYPE; +BEGIN + IF OLD.status = 'IN_PROGRESS' AND NEW.status = 'COMMITTED' THEN + SELECT * INTO birth FROM account_fresh_tenant_identity_associations + WHERE canonical_tenant_id = NEW.tenant_uuid FOR SHARE; + IF birth.capacity_birth_transaction IS DISTINCT FROM pg_current_xact_id()::TEXT THEN + RETURN NEW; + END IF; + IF birth.operation_id IS DISTINCT FROM NEW.creation_operation_id + OR birth.creation_request_id IS DISTINCT FROM NEW.creation_request_id + OR NEW.baseline_event_sequence <> 0 + OR NEW.gameplay_admission_allowed IS DISTINCT FROM FALSE + OR EXISTS (SELECT 1 FROM account_tenant_membership + WHERE tenant_uuid = NEW.tenant_uuid AND gameplay_admission_allowed IS TRUE) + OR EXISTS (SELECT 1 FROM account_tenant_capacity_usage WHERE tenant_uuid = NEW.tenant_uuid) THEN + RAISE EXCEPTION 'Fresh tenant capacity baseline is not demonstrably empty' USING ERRCODE = '23514'; + END IF; + INSERT INTO account_tenant_capacity_usage + (tenant_uuid, owner_service, bootstrap_request_id, creation_evidence_digest, held_units, used_units, usage_revision) + VALUES (NEW.tenant_uuid, 'game-session-service', NEW.request_id, birth.evidence_digest, 0, 0, 1), + (NEW.tenant_uuid, 'world-management-service', NEW.request_id, birth.evidence_digest, 0, 0, 1); + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_tenant_capacity_fresh_bootstrap AFTER UPDATE ON account_tenant_creation_bootstrap_operations + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_bootstrap_new_tenant(); + +CREATE FUNCTION account_tenant_capacity_immutable_evaluation() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Capacity evaluation and historical attempt evidence is immutable' USING ERRCODE = '23514'; +END; +$$; +CREATE TRIGGER account_tenant_capacity_evaluation_guard BEFORE UPDATE OR DELETE ON account_tenant_capacity_evaluations + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_immutable_evaluation(); +CREATE TRIGGER account_tenant_capacity_history_guard BEFORE UPDATE OR DELETE ON account_tenant_capacity_attempt_history + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_immutable_evaluation(); +CREATE TRIGGER account_tenant_capacity_recovery_evidence_guard BEFORE UPDATE OR DELETE ON account_tenant_capacity_recovery_evidence + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_immutable_evaluation(); + +CREATE FUNCTION account_tenant_capacity_usage_insert_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.held_units <> 0 OR NEW.used_units <> 0 OR NEW.usage_revision <> 1 OR NOT EXISTS ( + SELECT 1 FROM account_tenant_creation_bootstrap_operations bootstrap + JOIN account_fresh_tenant_identity_associations birth ON birth.canonical_tenant_id = bootstrap.tenant_uuid + WHERE bootstrap.request_id = NEW.bootstrap_request_id AND bootstrap.tenant_uuid = NEW.tenant_uuid + AND bootstrap.status = 'COMMITTED' AND bootstrap.gameplay_admission_allowed IS FALSE + AND bootstrap.baseline_event_sequence = 0 + AND bootstrap.creation_operation_id = birth.operation_id + AND birth.evidence_digest = NEW.creation_evidence_digest + AND birth.capacity_birth_transaction = pg_current_xact_id()::TEXT) THEN + RAISE EXCEPTION 'Capacity usage initialization requires same-transaction new-tenant bootstrap' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_tenant_capacity_usage_birth BEFORE INSERT ON account_tenant_capacity_usage + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_usage_insert_guard(); + +CREATE FUNCTION account_tenant_capacity_usage_update_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid OR NEW.owner_service IS DISTINCT FROM OLD.owner_service + OR NEW.bootstrap_request_id IS DISTINCT FROM OLD.bootstrap_request_id + OR NEW.creation_evidence_digest IS DISTINCT FROM OLD.creation_evidence_digest + OR NEW.usage_revision <> OLD.usage_revision + 1 THEN + RAISE EXCEPTION 'Capacity usage identity is immutable and revision must advance once' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_tenant_capacity_usage_revision BEFORE UPDATE ON account_tenant_capacity_usage + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_usage_update_guard(); + +CREATE FUNCTION account_tenant_capacity_reservation_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM account_tenant_capacity_evaluations evaluation + WHERE evaluation.evaluation_identity = NEW.evaluation_identity + AND evaluation.tenant_uuid = NEW.tenant_uuid AND evaluation.caller_workload = NEW.caller_workload + AND evaluation.owner_service = NEW.owner_service) THEN + RAISE EXCEPTION 'Capacity reservation lacks its exact retained Account evaluation' USING ERRCODE = '23514'; + END IF; + IF (TG_OP = 'INSERT' OR NEW.admission_attempt_id IS DISTINCT FROM OLD.admission_attempt_id) + AND EXISTS (SELECT 1 FROM account_tenant_capacity_attempt_history WHERE admission_attempt_id = NEW.admission_attempt_id) THEN + RAISE EXCEPTION 'Capacity admission attempt identity must be fresh' USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.state <> 'RESERVED' OR NEW.execution_status <> 'OWNER_EXECUTION_PENDING' + OR NEW.capacity_rearm_fence <> 1 OR NEW.reservation_fence <> 1 + OR NEW.recovery_owner IS NOT NULL OR NEW.recovery_claim_fence <> 0 OR NEW.owner_readback IS NOT NULL + OR NEW.recovery_attempt_count <> 0 OR NEW.recovery_escalated_at IS NOT NULL THEN + RAISE EXCEPTION 'Capacity reservation must begin as the original pending attempt' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.admission_id IS DISTINCT FROM OLD.admission_id OR NEW.reservation_id IS DISTINCT FROM OLD.reservation_id + OR NEW.owner_service IS DISTINCT FROM OLD.owner_service OR NEW.caller_workload IS DISTINCT FROM OLD.caller_workload + OR NEW.capacity_delta IS DISTINCT FROM OLD.capacity_delta OR NEW.recovery_claim_fence < OLD.recovery_claim_fence + OR NEW.recovery_policy_version IS DISTINCT FROM OLD.recovery_policy_version THEN + RAISE EXCEPTION 'Capacity reservation identity and hold are immutable' USING ERRCODE = '23514'; + END IF; + IF NEW.recovery_owner IS DISTINCT FROM OLD.recovery_owner + OR NEW.recovery_claim_expires_at IS DISTINCT FROM OLD.recovery_claim_expires_at + OR NEW.recovery_claim_fence <> OLD.recovery_claim_fence THEN + IF NEW.recovery_claim_fence <> OLD.recovery_claim_fence + 1 OR NEW.recovery_owner IS NULL + OR NEW.recovery_claim_expires_at <= clock_timestamp() + OR (OLD.recovery_owner IS DISTINCT FROM NEW.recovery_owner + AND OLD.recovery_claim_expires_at > clock_timestamp()) THEN + RAISE EXCEPTION 'Capacity recovery claim must monotonically fence its exact current owner' USING ERRCODE = '23514'; + END IF; + END IF; + IF NEW.admission_attempt_id IS DISTINCT FROM OLD.admission_attempt_id THEN + IF OLD.state <> 'RESERVED' OR OLD.execution_status <> 'NOT_EXECUTED_AFTER_AUTHORIZATION' + OR OLD.owner_readback IS NULL OR OLD.recovery_owner IS NULL + OR OLD.recovery_claim_expires_at <= clock_timestamp() + OR NEW.recovery_owner IS DISTINCT FROM OLD.recovery_owner + OR NEW.recovery_claim_fence <> OLD.recovery_claim_fence + OR NEW.capacity_rearm_fence <> OLD.capacity_rearm_fence + 1 + OR NEW.reservation_fence <> OLD.reservation_fence + 1 + OR NEW.state <> 'RESERVED' OR NEW.execution_status <> 'OWNER_EXECUTION_PENDING' + OR NEW.recovery_attempt_count <> 0 OR NEW.recovery_escalated_at IS NOT NULL + OR NEW.owner_readback IS NOT NULL OR NEW.owner_readback_digest IS NOT NULL + OR NOT EXISTS (SELECT 1 FROM account_tenant_capacity_attempt_history history + WHERE history.tenant_uuid = OLD.tenant_uuid AND history.request_id = OLD.request_id + AND history.admission_id = OLD.admission_id AND history.admission_attempt_id = OLD.admission_attempt_id + AND history.capacity_rearm_fence = OLD.capacity_rearm_fence + AND history.mutation_digest = OLD.mutation_digest AND history.canonical_payload = OLD.canonical_payload + AND history.owner_readback = OLD.owner_readback) THEN + RAISE EXCEPTION 'Capacity rearm requires exact durable terminal no-commit and current recovery claim' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF NEW.capacity_rearm_fence <> OLD.capacity_rearm_fence + OR NEW.mutation_digest IS DISTINCT FROM OLD.mutation_digest OR NEW.canonical_payload IS DISTINCT FROM OLD.canonical_payload + OR NEW.evaluation_identity IS DISTINCT FROM OLD.evaluation_identity OR NEW.expires_at IS DISTINCT FROM OLD.expires_at + OR NEW.reconcile_deadline IS DISTINCT FROM OLD.reconcile_deadline THEN + RAISE EXCEPTION 'Changed capacity attempt is an idempotency conflict' USING ERRCODE = '23514'; + END IF; + IF OLD.state <> 'RESERVED' THEN + IF NEW IS DISTINCT FROM OLD THEN + RAISE EXCEPTION 'Terminal capacity result is immutable' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF NEW.recovery_attempt_count <> OLD.recovery_attempt_count THEN + IF NEW.recovery_attempt_count <> OLD.recovery_attempt_count + 1 + OR NEW.recovery_owner IS NULL OR NEW.recovery_claim_expires_at <= clock_timestamp() + OR NOT EXISTS (SELECT 1 FROM account_tenant_capacity_recovery_evidence evidence + WHERE evidence.tenant_uuid = OLD.tenant_uuid AND evidence.request_id = OLD.request_id + AND evidence.admission_id = OLD.admission_id AND evidence.admission_attempt_id = OLD.admission_attempt_id + AND evidence.recovery_claim_fence = NEW.recovery_claim_fence + AND evidence.recovery_attempt_number = NEW.recovery_attempt_count) THEN + RAISE EXCEPTION 'Capacity recovery must retain each bounded observation under its current claim' USING ERRCODE = '23514'; + END IF; + END IF; + IF NEW.state = 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION' THEN + IF OLD.execution_status <> 'OWNER_EXECUTION_PENDING' + OR (NEW.recovery_attempt_count < 12 AND clock_timestamp() < OLD.reconcile_deadline) + OR NEW.recovery_escalated_at IS NULL + OR NEW.next_reconcile_at IS NOT NULL THEN + RAISE EXCEPTION 'Capacity quarantine requires exhausted bounded recovery and preserves the original hold' USING ERRCODE = '23514'; + END IF; + END IF; + IF OLD.execution_status = 'NOT_EXECUTED_AFTER_AUTHORIZATION' + AND (NEW.execution_status <> OLD.execution_status OR NEW.owner_readback IS DISTINCT FROM OLD.owner_readback + OR NEW.owner_readback_digest IS DISTINCT FROM OLD.owner_readback_digest) THEN + RAISE EXCEPTION 'Terminal capacity no-commit evidence cannot be replaced' USING ERRCODE = '23514'; + END IF; + IF NEW.state <> OLD.state OR NEW.execution_status <> OLD.execution_status THEN + IF NEW.recovery_owner IS NULL OR NEW.recovery_claim_fence = 0 + OR NEW.recovery_claim_expires_at <= clock_timestamp() + OR (NEW.state <> 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION' AND NEW.owner_readback IS NULL) THEN + RAISE EXCEPTION 'Only current Account recovery claim may transition capacity evidence' USING ERRCODE = '23514'; + END IF; + END IF; + IF (NEW.state = 'RELEASED' AND NEW.reservation_fence <> OLD.reservation_fence + 1) + OR (NEW.state <> 'RELEASED' AND NEW.reservation_fence <> OLD.reservation_fence) THEN + RAISE EXCEPTION 'Capacity release must durably fence the original reservation' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_tenant_capacity_reservation_fences BEFORE INSERT OR UPDATE ON account_tenant_capacity_reservations + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_reservation_guard(); + +-- The complete durable reservation inventory, not a local issuer counter, owns usage. +CREATE FUNCTION account_tenant_capacity_exact_usage() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE held NUMERIC; used NUMERIC; actual account_tenant_capacity_usage%ROWTYPE; +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; + RETURN NULL; +END; +$$; +CREATE CONSTRAINT TRIGGER account_tenant_capacity_usage_complete AFTER INSERT OR UPDATE ON account_tenant_capacity_usage + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_exact_usage(); +CREATE CONSTRAINT TRIGGER account_tenant_capacity_reservation_complete AFTER INSERT OR UPDATE ON account_tenant_capacity_reservations + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_exact_usage(); +CREATE TRIGGER account_tenant_capacity_usage_no_delete BEFORE DELETE ON account_tenant_capacity_usage + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_immutable_evaluation(); +CREATE TRIGGER account_tenant_capacity_reservation_no_delete BEFORE DELETE ON account_tenant_capacity_reservations + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_immutable_evaluation(); +CREATE TRIGGER account_tenant_capacity_usage_no_truncate BEFORE TRUNCATE ON account_tenant_capacity_usage + FOR EACH STATEMENT EXECUTE FUNCTION account_tenant_capacity_immutable_evaluation(); +CREATE TRIGGER account_tenant_capacity_reservation_no_truncate BEFORE TRUNCATE ON account_tenant_capacity_reservations + FOR EACH STATEMENT EXECUTE FUNCTION account_tenant_capacity_immutable_evaluation(); +CREATE TRIGGER account_tenant_capacity_evaluation_no_truncate BEFORE TRUNCATE ON account_tenant_capacity_evaluations + FOR EACH STATEMENT EXECUTE FUNCTION account_tenant_capacity_immutable_evaluation(); +CREATE TRIGGER account_tenant_capacity_history_no_truncate BEFORE TRUNCATE ON account_tenant_capacity_attempt_history + FOR EACH STATEMENT EXECUTE FUNCTION account_tenant_capacity_immutable_evaluation(); +CREATE TRIGGER account_tenant_capacity_recovery_evidence_no_truncate BEFORE TRUNCATE ON account_tenant_capacity_recovery_evidence + FOR EACH STATEMENT EXECUTE FUNCTION account_tenant_capacity_immutable_evaluation(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountRuntimeEntitlementNoWriteIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountRuntimeEntitlementNoWriteIntegrationTest.java new file mode 100644 index 0000000000..2e71e3b8ac --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountRuntimeEntitlementNoWriteIntegrationTest.java @@ -0,0 +1,332 @@ +package net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mockingDetails; + +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.stub.MetadataUtils; +import java.nio.file.Files; +import java.nio.file.Path; +import java.sql.Connection; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import javax.sql.DataSource; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeRequest; +import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; +import net.firedevops.firemud.accountservice.client.EntityManagementClient; +import net.firedevops.firemud.accountservice.client.GameSessionClient; +import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository; +import net.firedevops.firemud.accountservice.security.AccountPlayerAdmissionEntitlementWorkloadGuard; +import net.firedevops.firemud.accountservice.security.AccountTenantCapacityWorkloadGuard; +import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner; +import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner; +import net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker; +import net.firedevops.firemud.accountservice.service.impl.AccountGrpcService; +import net.firedevops.firemud.accountservice.service.impl.AccountPlayerAdmissionEntitlementGrpcService; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.accountservice.service.impl.AccountTenantCapacityGrpcService; +import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.security.GrpcAuthProperties; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import net.firedevops.firemud.test.LoopbackMtlsTestPki.IdentitySpec; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.TestContainerImages; +import net.firedevops.firemud.test.TlsTestSupport; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.context.ApplicationContext; +import org.springframework.grpc.server.GrpcServerFactory; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Full default Account application, real database/Redis and ordinary REQUIRE-mTLS listener. Empty + * capacity cohorts prove no durable creation only. Populated-family preservation, + * retention/erasure, production PKI, admission and owner activation are not qualified here. + */ +@Testcontainers(disabledWithoutDocker = true) +@SpringBootTest( + classes = AccountServiceApplication.class, + webEnvironment = WebEnvironment.RANDOM_PORT, + properties = { + "spring.config.import=classpath:account-main-application.yml", + "spring.grpc.server.port=0", + "spring.grpc.server.ssl.enabled=true", + "spring.grpc.server.ssl.bundle=firemud-grpc", + "spring.grpc.server.ssl.client-auth=REQUIRE", + "firemud.grpc.workload-namespace=test", + "firemud.mail.verification-url=https://account.test/verify-email?token=%s" + }) +class AccountRuntimeEntitlementNoWriteIntegrationTest { + private static final String METHOD = "account.v1.AccountService/GetTenantEntitlementsForRuntime"; + private static final List CAPACITY_TABLES = + List.of( + "account_tenant_capacity_evaluations", + "account_tenant_capacity_usage", + "account_tenant_capacity_reservations", + "account_tenant_capacity_attempt_history", + "account_tenant_capacity_recovery_evidence"); + private static final GetTenantEntitlementsForRuntimeRequest REQUEST = + GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("1") + .setRequestId("default-runtime-entitlement-no-write") + .build(); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + private static Path tlsDirectory; + private static LoopbackMtlsTestPki.Pki pki; + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) throws Exception { + PostgresBackedServiceTestSupport.registerPostgresService(registry, postgres, "account_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + tlsDirectory = Files.createTempDirectory("account-runtime-no-write-mtls-"); + pki = + LoopbackMtlsTestPki.create( + tlsDirectory, + "Account default runtime no-write CA", + new IdentitySpec("account", "spiffe://firemud/ns/test/sa/account-service", true), + new IdentitySpec( + "game-session", "spiffe://firemud/ns/test/sa/game-session-service", false), + new IdentitySpec( + "world", "spiffe://firemud/ns/test/sa/world-management-service", false), + new IdentitySpec( + "wrong-service", "spiffe://firemud/ns/test/sa/entity-management-service", false), + new IdentitySpec( + "cross-namespace", "spiffe://firemud/ns/other/sa/game-session-service", false)); + var server = pki.clientProperties(tlsDirectory, pki.identity("account")); + registry.add("FIREMUD_GRPC_CERT_CHAIN_PATH", server::getCertChain); + registry.add("FIREMUD_GRPC_PRIVATE_KEY_PATH", server::getPrivateKey); + registry.add("FIREMUD_GRPC_CA_CERT_PATH", server::getCaCert); + } + + @Autowired private ApplicationContext context; + @Autowired private DataSource dataSource; + @Autowired private DSLContext dsl; + @Autowired private AccountService accountService; + @Autowired private AccountServiceImpl accountFacade; + @Autowired private AccountGrpcService accountGrpcService; + @Autowired private GrpcServerLifecycle listener; + + @MockitoBean private EntityManagementClient entityManagementClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private LoggingAdminClient loggingAdminClient; + @MockitoBean private JavaMailSender mailSender; + + @BeforeEach + void assertActualDefaultRegistration() { + assertThat(listener.isRunning()).isTrue(); + assertThat(listener.getPort()).isPositive(); + assertThat(listener.getFactory()).isSameAs(context.getBean(GrpcServerFactory.class)); + assertThat(listener.getFactory()).isExactlyInstanceOf(BoundedGrpcServerFactory.class); + assertThat(accountService).isSameAs(accountFacade); + for (Object actual : + List.of( + accountService, + accountGrpcService, + dataSource, + dsl, + context.getBean(GrpcPeerIdentityInterceptor.class))) { + assertThat(mockingDetails(actual).isMock()).isFalse(); + } + assertThat(context.getBeansOfType(GrpcPeerIdentityInterceptor.class)).hasSize(1); + assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) + .contains(METHOD) + .doesNotContain("account.v1.AccountService/*"); + assertThat(context.getBeansOfType(AccountPlayerAdmissionEntitlementOwner.class)).isEmpty(); + assertThat(context.getBeansOfType(AccountPlayerAdmissionEntitlementGrpcService.class)) + .isEmpty(); + assertThat(context.getBeansOfType(AccountPlayerAdmissionEntitlementWorkloadGuard.class)) + .isEmpty(); + assertThat(context.getBeansOfType(AccountTenantCapacityRepository.class)).isEmpty(); + assertThat(context.getBeansOfType(AccountTenantCapacityOwner.class)).isEmpty(); + assertThat(context.getBeansOfType(AccountTenantCapacityGrpcService.class)).isEmpty(); + assertThat(context.getBeansOfType(AccountTenantCapacityRecoveryWorker.class)).isEmpty(); + assertThat(context.getBeansOfType(AccountTenantCapacityWorkloadGuard.class)).isEmpty(); + assertThat(dsl.fetchValue("SELECT current_schema()", String.class)) + .isEqualTo("account_service"); + } + + @ParameterizedTest + @ValueSource(strings = {"game-session", "world"}) + void authorizedNumericRefusalAndExactRetryCreateNoCapacityRows(String identity) throws Exception { + Map before = emptyCapacityImages(); + ManagedChannel channel = channel(identity); + try { + var stub = AccountServiceGrpc.newBlockingStub(channel); + for (int attempt = 0; attempt < 2; attempt++) { + assertRefusal( + stub.withDeadlineAfter(5, TimeUnit.SECONDS).getTenantEntitlementsForRuntime(REQUEST), + "ENTITLEMENT_UNAVAILABLE"); + assertThat(capacityImages()).isEqualTo(before); + } + } finally { + close(channel); + } + } + + @ParameterizedTest + @ValueSource(strings = {"wrong-service", "cross-namespace"}) + void deniedCertificateAndSpoofedMetadataCreateNoCapacityRows(String identity) throws Exception { + Map before = emptyCapacityImages(); + ManagedChannel channel = channel(identity); + try { + var stub = AccountServiceGrpc.newBlockingStub(channel); + assertRefusal( + stub.withDeadlineAfter(5, TimeUnit.SECONDS).getTenantEntitlementsForRuntime(REQUEST), + "PERMISSION_DENIED"); + assertThat(capacityImages()).isEqualTo(before); + assertRefusal( + stub.withInterceptors(MetadataUtils.newAttachHeadersInterceptor(fakePeer())) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .getTenantEntitlementsForRuntime(REQUEST), + "PERMISSION_DENIED"); + assertThat(capacityImages()).isEqualTo(before); + } finally { + close(channel); + } + } + + @Test + void missingClientCertificateIsRefusedByTlsWithoutCapacityCreation() throws Exception { + Map before = emptyCapacityImages(); + ManagedChannel channel = channel(null); + try { + assertThatThrownBy( + () -> + AccountServiceGrpc.newBlockingStub(channel) + .withInterceptors(MetadataUtils.newAttachHeadersInterceptor(fakePeer())) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .getTenantEntitlementsForRuntime(REQUEST)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)).isTrue()); + assertThat(capacityImages()).isEqualTo(before); + } finally { + close(channel); + } + } + + private static void assertRefusal(GetTenantEntitlementsForRuntimeResponse response, String code) { + assertThat(response.hasError()).isTrue(); + assertThat(response.getError().getCode()).isEqualTo(code); + assertThat(response.toBuilder().clearError().build()) + .isEqualTo(GetTenantEntitlementsForRuntimeResponse.getDefaultInstance()); + } + + private static Metadata fakePeer() { + Metadata headers = new Metadata(); + String claim = "spiffe://firemud/ns/test/sa/game-session-service"; + for (String name : + List.of("x-firemud-peer-identity", "x-spiffe-id", "x-forwarded-client-cert")) { + headers.put(Metadata.Key.of(name, Metadata.ASCII_STRING_MARSHALLER), claim); + } + return headers; + } + + private ManagedChannel channel(String identity) throws Exception { + var tls = GrpcSslContexts.forClient().trustManager(pki.trustManagerFactory()); + if (identity != null) tls.keyManager(pki.keyManagerFactory(pki.identity(identity))); + return NettyChannelBuilder.forAddress("localhost", listener.getPort()) + .sslContext(tls.build()) + .build(); + } + + private static void close(ManagedChannel channel) throws InterruptedException { + channel.shutdownNow(); + assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + + private Map emptyCapacityImages() throws Exception { + Map images = capacityImages(); + assertThat(images).hasSize(5); + images.forEach( + (table, image) -> { + assertThat(image.count()).as(table).isZero(); + assertThat(image.rows()).as(table).isEmpty(); + }); + return images; + } + + private Map capacityImages() throws Exception { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + Map images = new LinkedHashMap<>(); + // Fresh autocommit connections observe committed postimages, never a shared test rollback. + try (Connection connection = dataSource.getConnection()) { + assertThat(connection.getAutoCommit()).isTrue(); + assertThat(connection.getTransactionIsolation()) + .isEqualTo(Connection.TRANSACTION_READ_COMMITTED); + assertThat(connection.getMetaData().getDatabaseProductName()).isEqualTo("PostgreSQL"); + assertThat(connection.getCatalog()).isEqualTo(postgres.getDatabaseName()); + assertThat(connection.getSchema()).isEqualTo("account_service"); + for (String table : CAPACITY_TABLES) { + long count; + try (var statement = connection.createStatement(); + var result = statement.executeQuery("SELECT COUNT(*) FROM account_service." + table)) { + assertThat(result.next()).isTrue(); + count = result.getLong(1); + } + List rows = new ArrayList<>(); + try (var statement = connection.createStatement(); + var result = + statement.executeQuery( + "SELECT to_jsonb(t)::text, t.xmin::text FROM account_service." + + table + + " t ORDER BY 1, 2")) { + while (result.next()) rows.add(new RowImage(result.getString(1), result.getString(2))); + } + assertThat(rows).hasSize(Math.toIntExact(count)); + images.put(table, new TableImage(count, List.copyOf(rows))); + } + } + return Map.copyOf(images); + } + + @AfterAll + static void removeOwnedTlsFixture() throws Exception { + if (tlsDirectory != null) { + try (var files = Files.walk(tlsDirectory)) { + for (Path file : files.sorted(Comparator.reverseOrder()).toList()) Files.delete(file); + } + } + } + + private record RowImage(String json, String xmin) {} + + private record TableImage(long count, List rows) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java index 79c1169e9b..9ca9d6efb5 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java @@ -284,7 +284,7 @@ void migrationRetainsV1AndStoresExactV2ScopeAndPendingIntentWithoutMembershipOrE } @Test - void receivingUpgradeFromParent1036Through1038PreservesCanonicalRowsAndHistory() { + void capacityUpgradeFromParent1036Through1040PreservesCanonicalRowsAndHistory() { String schema = createSchema("canonical_join_scope_"); DriverManagerDataSource dataSource = postgres.dataSource(schema); Flyway parent = accountFlyway(dataSource, schema, "1036"); @@ -357,24 +357,28 @@ void receivingUpgradeFromParent1036Through1038PreservesCanonicalRowsAndHistory() "V1037__canonical_join_failure_and_attempt_diagnostics.sql", "V1038__canonical_join_existing_membership_terminal.sql"); - Flyway current = accountFlyway(dataSource, schema, "1038"); + Flyway current = accountFlyway(dataSource, schema, "1040"); current.migrate(); current.validate(); assertThat(current.info().current().getVersion()) - .isEqualTo(MigrationVersion.fromVersion("1038")); + .isEqualTo(MigrationVersion.fromVersion("1040")); List> upgradedHistory = flywayHistory(setupDsl); - assertThat(upgradedHistory).hasSize(parentHistory.size() + 2); + assertThat(upgradedHistory).hasSize(parentHistory.size() + 4); assertThat(upgradedHistory.subList(0, parentHistory.size())) .containsExactlyElementsOf(parentHistory); List> addedHistory = upgradedHistory.subList(parentHistory.size(), upgradedHistory.size()); - assertThat(addedHistory).extracting(row -> row.get("version")).containsExactly("1037", "1038"); + assertThat(addedHistory) + .extracting(row -> row.get("version")) + .containsExactly("1037", "1038", "1039", "1040"); assertThat(addedHistory) .extracting(row -> row.get("script")) .containsExactly( "V1037__canonical_join_failure_and_attempt_diagnostics.sql", - "V1038__canonical_join_existing_membership_terminal.sql"); + "V1038__canonical_join_existing_membership_terminal.sql", + "V1039__hosting_unclaimed_wallet_settlement.sql", + "V1040__account_tenant_capacity_owner.sql"); assertThat(addedHistory) .allSatisfy( row -> { 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 new file mode 100644 index 0000000000..7f67a85b2e --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java @@ -0,0 +1,219 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +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.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +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.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.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; + +/** Real forward migration with retained tenant provenance. No existing usage is guessed. */ +class AccountTenantCapacityMigrationPostgresIntegrationTest { + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + + @BeforeAll + static void start() { + POSTGRES.start(); + } + + @AfterAll + static void stop() { + POSTGRES.stop(); + } + + @Test + void historicalBootstrapCompletionAndPlainNewImportCannotInitializeCapacity() { + String schema = "capacity_migration_" + 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(); + 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 historical = + Objects.requireNonNull( + transaction.execute( + status -> { + repository.importVerified(existing); + return 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); + 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")) + .isNull(); + var completed = + Objects.requireNonNull( + transaction.execute( + status -> { + var operation = operations.findForUpdate(historical.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(completed.status()).isEqualTo("COMMITTED"); + assertThat(completed.tenantUuid()).isEqualTo(existing.canonicalTenantId()); + assertThat(dsl.fetchCount(DSL.table("account_tenant_capacity_usage"))).isZero(); + var later = source(); + transaction.executeWithoutResult(status -> repository.importVerified(later)); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "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(); + } finally { + new JdbcTemplate(POSTGRES.dataSource()).execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + + private static Account creator() { + String suffix = UUID.randomUUID().toString().replace("-", ""); + var account = new Account(); + account.setUsername("capacity-" + suffix); + account.setEmail(suffix + "@example.test"); + account.setPasswordHash("test-only-password-hash"); + account.setRole("player"); + 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); + String digest = GameTenantCreationDigest.requestDigest("prod", request, slug, "Capacity", null); + long row = Math.abs((long) tenant.hashCode()) + 1; + return new FreshTenantCreationEvidence( + 1, + "prod", + request, + operation, + digest, + tenant, + row, + slug, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "prod", request, operation, digest, tenant, row, slug, "NEW_GAME_ROW")); + } +} 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 6c0028a33e..32b82b90e3 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 @@ -61,6 +61,7 @@ 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.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; @@ -331,12 +332,26 @@ void actualFirstJoinRetainsItsPositiveMembershipAndExactScopeBinding() { .containsExactlyEntriesOf(Map.of(f.tenantId.toString(), "2")); assertThat(value.membershipSource().membershipAuthorityGeneration()).isEqualTo("1"); assertThat(value.membershipSource().gameplayAdmissionAllowed()).isTrue(); - assertThat(value.verifiedConnectScopeTokenHash()) - .isEqualTo(AccountJoinDigest.tokenHash(f.scope.connectScopeId())); + var retained = + f.dsl.fetchOne( + "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); assertThat( - new String(value.canonicalBytes(), StandardCharsets.UTF_8) - .contains(f.scope.connectScopeId())) + new String(retainedEvidence, StandardCharsets.UTF_8).contains(f.scope.connectScopeId())) .isFalse(); + assertThat(retainedEvidence).containsExactly(value.canonicalBytes()); + var decoded = RuntimePlayerAdmissionEntitlementEvidence.parseCanonical(retainedEvidence); + assertThat(decoded.verifiedConnectScopeTokenHash()) + .isEqualTo(AccountJoinDigest.tokenHash(f.scope.connectScopeId())); + assertThat(decoded.fields()).doesNotContainKey("verifiedConnectScopeId"); + assertThat(retained.get("snapshot_identity", String.class)) + .isEqualTo(value.fields().get("snapshotIdentity")); + assertThat(f.dsl.fetchCount(DSL.table("account_tenant_capacity_reservations"))).isZero(); + // This old fixture tenant was imported before creator completion. Eligibility evaluation + // never invents an empty capacity baseline for it. + assertThat(f.dsl.fetchCount(DSL.table("account_tenant_capacity_usage"))).isZero(); var binding = (Map) value.fields().get("target"); assertThat(binding.get("realmId")).isEqualTo(f.scope.realmId().toString()); assertThat(binding.get("playableStateNamespaceId")) @@ -419,6 +434,7 @@ public void beforeCommit(boolean readOnly) { assertThatThrownBy(() -> f.owner.evaluate(f.request(), CONTROLLED_COMPACT_TOKEN)) .hasMessageContaining("controlled final source commit refusal"); assertThat(competingWriterRefused.get()).isTrue(); + assertThat(f.dsl.fetchCount(DSL.table("account_tenant_capacity_evaluations"))).isZero(); var unlocked = f.transaction.execute( status -> f.accounts.findByAccountUuidForUpdate(f.account.getAccountUuid())); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java index 0d552450fc..0def873ad4 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 @@ -25,6 +25,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; @@ -57,11 +58,13 @@ import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountCreatorMembershipSourceReader; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; +import net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker; import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapAuthorizationSource; import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapService; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.accountservice.service.session.AccountTenantCreationAdmissionRepository.Admitted; import net.firedevops.firemud.accountservice.service.session.AccountTenantCreationIntentRepository.OriginalIntent; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; @@ -360,6 +363,559 @@ void fullStoredOwnerCompletionCommitsAllReceiptsAndExactReplayWithoutReconsumpti assertThat(c.dsl.fetchCount(DSL.table("account_audit_outbox"))).isEqualTo(2); } + @Test + void capacityOwnerPersistenceFinalizesOneOriginalReservationAndUsageExactlyOnce() { + var f = capacityPersistenceFixture(); + 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(); + 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.reservationId()).isEqualTo(f.initial.reservationId()); + assertThat(result.state()) + .isEqualTo( + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State.FINALIZED); + assertThat( + recovery.reconcile( + f.request, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .NoCommitAction.RELEASE)) + .isEqualTo(result); + assertThat(calls).hasValue(1); + assertThat( + Objects.requireNonNull( + f.context.dsl.fetchOne( + "SELECT held_units, used_units FROM account_tenant_capacity_usage WHERE tenant_uuid = ? AND owner_service = 'world-management-service'", + f.request.identity().tenantId())) + .get("held_units", Long.class)) + .isZero(); + assertThat( + Objects.requireNonNull( + f.context.dsl.fetchOne( + "SELECT used_units FROM account_tenant_capacity_usage WHERE tenant_uuid = ? AND owner_service = 'world-management-service'", + f.request.identity().tenantId())) + .get("used_units", Long.class)) + .isEqualTo(17); + } + + @Test + void overlappingRecoveryCallsCannotInvalidateTheSameWorkersLiveClaim() throws Exception { + var f = capacityPersistenceFixture(); + var next = + new TenantCapacityAdmission.Request( + f.request.identity(), + UUID.randomUUID(), + f.request.capacityRearmFence() + 1, + f.request.targetNamespace(), + f.request.context(), + f.request.operation(), + f.request.priorShape(), + f.request.requestedShape(), + f.request.evidence(), + f.request.capacityDelta(), + null) + .withDigest(); + var readStarted = new CountDownLatch(1); + var resumeRead = new CountDownLatch(1); + var calls = new AtomicInteger(); + var secondWorkerCalls = new AtomicInteger(); + var recoveryClock = Clock.fixed(f.request.evidence().evaluatedAt(), ZoneOffset.UTC); + var recovery = + new AccountTenantCapacityRecoveryWorker( + f.owner, + f.context.dsl, + (request, reservation, deadline) -> { + if (calls.incrementAndGet() == 1) { + readStarted.countDown(); + try { + assertThat(resumeRead.await(10, TimeUnit.SECONDS)).isTrue(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new AssertionError("Interrupted while waiting to resume read", interrupted); + } + } + return capacityObservation( + request, reservation, AccountTenantCapacityRecoveryWorker.Disposition.COMMITTED); + }, + recoveryClock); + var secondWorker = + new AccountTenantCapacityRecoveryWorker( + f.owner, + f.context.dsl, + (request, reservation, deadline) -> { + secondWorkerCalls.incrementAndGet(); + return capacityObservation( + request, reservation, AccountTenantCapacityRecoveryWorker.Disposition.COMMITTED); + }, + recoveryClock); + var action = AccountTenantCapacityRecoveryWorker.NoCommitAction.RELEASE; + try (var executor = Executors.newSingleThreadExecutor()) { + var pending = executor.submit(() -> recovery.reconcile(f.request, action)); + try { + assertThat(readStarted.await(10, TimeUnit.SECONDS)).isTrue(); + assertThatThrownBy(() -> recovery.reconcile(f.request, action)) + .hasMessage("ENTITLEMENT_UNAVAILABLE"); + assertThatThrownBy(() -> recovery.rearm(f.request, next)) + .hasMessage("ENTITLEMENT_UNAVAILABLE"); + assertThatThrownBy(() -> secondWorker.reconcile(f.request, action)) + .hasMessage("ENTITLEMENT_UNAVAILABLE"); + assertThatThrownBy(() -> secondWorker.rearm(f.request, next)) + .hasMessage("ENTITLEMENT_UNAVAILABLE"); + assertThat(calls).hasValue(1); + assertThat(secondWorkerCalls).hasValue(0); + } finally { + resumeRead.countDown(); + } + var result = pending.get(10, TimeUnit.SECONDS); + assertThat(result.state()).isEqualTo(TenantCapacityAdmission.State.FINALIZED); + assertThat(recovery.reconcile(f.request, action)).isEqualTo(result); + assertThat(calls).hasValue(1); + assertThat(secondWorkerCalls).hasValue(0); + } + } + + @Test + void capacityIndeterminateReadbackCannotReleaseAndTerminalNoCommitReleasesSameHold() { + var f = capacityPersistenceFixture(); + var disposition = + new java.util.concurrent.atomic.AtomicReference<>( + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .Disposition.INDETERMINATE); + var recovery = + new net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker( + f.owner, + f.context.dsl, + (request, reservation, deadline) -> + capacityObservation(request, reservation, disposition.get()), + java.time.Clock.systemUTC()); + assertThat( + recovery.reconcile( + f.request, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .NoCommitAction.RELEASE)) + .isEqualTo(f.initial); + assertThat( + Objects.requireNonNull( + f.context.dsl.fetchOne( + "SELECT held_units FROM account_tenant_capacity_usage WHERE tenant_uuid = ? AND owner_service = 'world-management-service'", + f.request.identity().tenantId())) + .get("held_units", Long.class)) + .isEqualTo(17); + // This is controlled source/claim proof, not production selected-owner CAS qualification. + disposition.set( + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .Disposition.NOT_EXECUTED_AFTER_AUTHORIZATION); + var released = + recovery.reconcile( + f.request, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .NoCommitAction.RELEASE); + assertThat(released.state()) + .isEqualTo( + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State.RELEASED); + assertThat(released.reservationId()).isEqualTo(f.initial.reservationId()); + assertThat(released.reservationFence()).isEqualTo(f.initial.reservationFence() + 1); + assertThat( + recovery.reconcile( + f.request, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .NoCommitAction.RELEASE)) + .isEqualTo(released); + assertThat( + Objects.requireNonNull( + f.context.dsl.fetchOne( + "SELECT held_units, used_units FROM account_tenant_capacity_usage WHERE tenant_uuid = ? AND owner_service = 'world-management-service'", + f.request.identity().tenantId())) + .get("held_units", Long.class)) + .isZero(); + assertThat(f.context.dsl.fetchCount(DSL.table("account_tenant_capacity_reservations"))) + .isEqualTo(1); + } + + @Test + void capacityChangedAttemptConflictsWithoutUsageMutationAndIncompleteLedgerCannotBeSeeded() { + var f = capacityPersistenceFixture(); + var changed = + new net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request( + f.request.identity(), + UUID.randomUUID(), + f.request.capacityRearmFence(), + f.request.targetNamespace(), + f.request.context(), + f.request.operation(), + f.request.priorShape(), + f.request.requestedShape(), + f.request.evidence(), + f.request.capacityDelta(), + null) + .withDigest(); + assertThatThrownBy( + () -> + f.context.transaction.execute( + status -> f.repository.exact(changed, f.repository.find(changed.identity())))) + .hasMessage("IDEMPOTENCY_CONFLICT"); + assertThatThrownBy( + () -> + f.context.transaction.executeWithoutResult( + status -> + f.context.dsl.execute( + "UPDATE account_tenant_capacity_usage SET held_units = held_units + 1, usage_revision = usage_revision + 1 WHERE tenant_uuid = ? AND owner_service = 'world-management-service'", + f.request.identity().tenantId()))) + .isInstanceOf(RuntimeException.class); + assertThat( + Objects.requireNonNull( + f.context.dsl.fetchOne( + "SELECT held_units FROM account_tenant_capacity_usage WHERE tenant_uuid = ? AND owner_service = 'world-management-service'", + f.request.identity().tenantId())) + .get("held_units", Long.class)) + .isEqualTo(17); + assertThat(f.context.dsl.fetchCount(DSL.table("account_tenant_capacity_reservations"))) + .isEqualTo(1); + } + + @Test + void boundedIndeterminateCapacityRecoveryQuarantinesTheOriginalCompleteHold() { + var f = capacityPersistenceFixture(); + 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(); + throw new IllegalStateException("Controlled selected-owner unavailability"); + }, + java.time.Clock.systemUTC()); + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result result = + f.initial; + for (int attempt = 0; attempt < 12; attempt++) { + result = + recovery.reconcile( + f.request, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .NoCommitAction.RELEASE); + assertThat(result.reservationId()).isEqualTo(f.initial.reservationId()); + assertThat(result.reservationFence()).isEqualTo(f.initial.reservationFence()); + } + assertThat(result.state()) + .isEqualTo( + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State + .QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION); + assertThat(calls).hasValue(12); + assertThat( + recovery.reconcile( + f.request, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .NoCommitAction.RELEASE)) + .isEqualTo(result); + assertThat(calls).hasValue(12); + assertThat(f.context.dsl.fetchCount(DSL.table("account_tenant_capacity_recovery_evidence"))) + .isEqualTo(12); + var usage = + Objects.requireNonNull( + f.context.dsl.fetchOne( + "SELECT held_units, used_units FROM account_tenant_capacity_usage WHERE tenant_uuid = ? AND owner_service = 'world-management-service'", + f.request.identity().tenantId()), + "Capacity usage row is absent"); + assertThat(usage.get("held_units", Long.class)).isEqualTo(17); + assertThat(usage.get("used_units", Long.class)).isZero(); + var retained = + Objects.requireNonNull( + f.context.dsl.fetchOne( + "SELECT recovery_attempt_count, recovery_escalated_at, next_reconcile_at FROM account_tenant_capacity_reservations WHERE reservation_id = ?", + result.reservationId()), + "Capacity reservation row is absent"); + assertThat(retained.get("recovery_attempt_count", Integer.class)).isEqualTo(12); + assertThat(retained.get("recovery_escalated_at")).isNotNull(); + assertThat(retained.get("next_reconcile_at")).isNull(); + } + + @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()); + 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()); + var recoveryClock = + new java.time.Clock() { + @Override + public java.time.ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public java.time.Clock withZone(java.time.ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return now.get(); + } + }; + 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).isEqualTo(now.get().plusSeconds(5)); + if (outcome.equals("unavailable")) + throw new IllegalStateException("Controlled source unavailable"); + if (outcome.equals("late")) now.set(deadline); + var disposition = + outcome.equals("negative") + ? net.firedevops.firemud.accountservice.service + .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); + if (!outcome.equals("malformed")) return observation; + return new net.firedevops.firemud.accountservice.service + .AccountTenantCapacityRecoveryWorker.Observation( + "spiffe://firemud/ns/prod/sa/wrong-owner", + observation.reservation(), + observation.canonicalAttemptPayload(), + observation.disposition(), + observation.proofId(), + observation.currentOwnerFence(), + observation.authoritativeStateDigest(), + observation.canonicalOwnerReadback()); + }, + recoveryClock); + var result = + recovery.reconcile( + f.request, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .NoCommitAction.RELEASE); + assertThat(result.state()) + .as(outcome) + .isEqualTo( + 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( + 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)).isEqualTo(17); + assertThat(usage.get("used_units", Long.class)).isZero(); + var retained = + f.context.dsl.fetchSingle( + "SELECT outcome, canonical_readback FROM account_tenant_capacity_recovery_evidence"); + 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); + } + + private static CapacityPersistenceFixture capacityPersistenceFixture(boolean expired) { + StorageContext c = storageContext(); + var fixture = storageFixture(c); + var assembled = assembleStoredOwner(c, fixture, new AccountAuditOutboxRepository(c.dsl)); + assembled.owner.complete( + fixture.intent.creationOperationId(), + assembled.terminal, + assembled.environment, + assembled.recent); + UUID tenant = assembled.terminal.evidence().receipt().orElseThrow().canonicalTenantId(); + var base = + net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture.worldRequest( + 17L); + // A retained historical reservation is inserted through the same controlled source fixture. + // No live producer accepts stale evidence, and no immutable row or database clock is changed. + var now = + java.time.Instant.now() + .minusSeconds(expired ? 120 : 0) + .truncatedTo(java.time.temporal.ChronoUnit.MICROS); + String json = + new String(base.evidence().canonicalBytes(), java.nio.charset.StandardCharsets.UTF_8) + .replace(base.identity().tenantId().toString(), tenant.toString()) + .replace( + net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture.NOW + .toString(), + now.toString()); + var evidence = + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Evidence.parse( + json.getBytes(java.nio.charset.StandardCharsets.UTF_8), + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Owner + .WORLD_MANAGEMENT); + var context = + (net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.WorldContext) + base.context(); + var request = + new net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request( + new net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Identity( + tenant, base.identity().requestId(), base.identity().admissionId()), + base.admissionAttemptId(), + base.capacityRearmFence(), + base.targetNamespace(), + new net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission + .WorldContext( + tenant, + context.operationId(), + context.lifecycleId(), + context.gameInstanceId(), + context.ownerId(), + context.ownerFence()), + base.operation(), + base.priorShape(), + base.requestedShape(), + evidence, + base.capacityDelta(), + null) + .withDigest(); + var repository = + new net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository(c.dsl); + var initial = + c.transaction.execute( + status -> { + // Controlled fixture evidence deliberately bypasses the absent World producer. + // Production + // has no route to perform this insertion and World admission remains unavailable. + c.dsl.execute( + "INSERT INTO account_tenant_capacity_evaluations (evaluation_identity, snapshot_identity, tenant_uuid, caller_workload, owner_service, canonical_evidence, evaluated_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?::timestamptz, ?::timestamptz)", + evidence.evaluationIdentity(), + evidence.snapshotIdentity(), + tenant, + evidence.callerWorkload(), + evidence.owner().service(), + evidence.canonicalBytes(), + net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository + .at(evidence.evaluatedAt()), + net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository + .at(evidence.expiresAt())); + return repository.create( + request, + evidence.expiresAt(), + Clock.fixed(evidence.evaluatedAt(), ZoneOffset.UTC)); + }); + var owner = + new net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner( + c.dsl, + c.accounts, + mock( + net.firedevops.firemud.accountservice.repository + .AccountCanonicalRuntimeMembershipSnapshotRepository.class), + mock( + net.firedevops.firemud.accountservice.repository + .AccountGameplayDelegationIssuanceRepository.class), + mock( + net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository + .class), + c.manager, + java.time.Clock.systemUTC(), + "prod"); + return new CapacityPersistenceFixture(c, request, repository, owner, initial); + } + + private static net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .Observation + capacityObservation( + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request request, + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result reservation, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .Disposition + disposition) { + return new net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .Observation( + request.evidence().callerWorkload(), + reservation, + net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest.preimage(request), + disposition, + request.admissionAttemptId(), + 7, + "sha256:" + "e".repeat(64), + "controlled-owner-readback".getBytes(java.nio.charset.StandardCharsets.US_ASCII)); + } + + private record CapacityPersistenceFixture( + StorageContext context, + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request request, + net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository repository, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner owner, + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result initial) {} + @Test void expiredCreatedSettlesSharedSourceHoldWithoutAnyAccountCreatorCompletion() { StorageContext c = storageContext(15, 0); @@ -763,6 +1319,8 @@ c.dsl, new DraftAuthorizationFenceRepository(c.dsl)), } private static void assertAtomicRowsBeforeFinal(StorageContext c) { + assertThat(c.dsl.fetchCount(DSL.table("account_tenant_capacity_usage"))).isEqualTo(2); + assertThat(c.dsl.fetchCount(DSL.table("account_tenant_capacity_reservations"))).isZero(); for (String table : List.of( "account_fresh_tenant_identity_associations", @@ -776,6 +1334,9 @@ private static void assertAtomicRowsBeforeFinal(StorageContext c) { } private static void assertAtomicRows(StorageContext c, int expected) { + assertThat(c.dsl.fetchCount(DSL.table("account_tenant_capacity_usage"))) + .isEqualTo(2 * expected); + assertThat(c.dsl.fetchCount(DSL.table("account_tenant_capacity_reservations"))).isZero(); for (String table : List.of( "account_fresh_tenant_identity_associations", 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 new file mode 100644 index 0000000000..6c8482d5ec --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java @@ -0,0 +1,128 @@ +package net.firedevops.firemud.accountservice.security; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Attributes; +import io.grpc.Context; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import javax.net.ssl.SSLSession; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +class AccountTenantCapacityWorkloadGuardTest { + private final AccountTenantCapacityWorkloadGuard guard = + new AccountTenantCapacityWorkloadGuard("firemud"); + + @AfterEach + void clear() { + SessionContext.clear(); + } + + @Test + void onlyExactTlsGameSessionAndMethodCanInstallPrivateAssertion() throws Exception { + var method = AccountServiceGrpc.getCommitTenantCapacityAdmissionMethod(); + assertThat( + invoke( + method, + tls("firemud", "game-session-service"), + "spiffe://firemud/ns/firemud/sa/game-session-service")) + .isNull(); + assertThat( + invoke( + method, + tls("firemud", "world-management-service"), + "spiffe://firemud/ns/firemud/sa/world-management-service")) + .isNull(); + assertThatThrownBy(guard::requireAuthenticatedCaller) + .isInstanceOf(StatusRuntimeException.class); + assertThat(invoke(method, tls("other", "game-session-service")).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(invoke(method, tls("firemud", "account-service")).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + invoke(AccountServiceGrpc.getGetProfileMethod(), tls("firemud", "game-session-service")) + .getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } + + @Test + void arbitraryPeerContextAndSessionClaimsNeverAuthenticate() throws Exception { + var method = AccountServiceGrpc.getCommitTenantCapacityAdmissionMethod(); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/firemud/sa/game-session-service") + .orElseThrow()) + .run( + () -> { + assertThat(invoke(method, null).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThatThrownBy(guard::requireAuthenticatedCaller) + .isInstanceOf(StatusRuntimeException.class); + }); + for (boolean internal : List.of(true, false)) { + if (internal) + SessionContext.setContext( + null, List.of(), Map.of(), true, "game-session-service", "instance"); + else SessionContext.setContext("caller", List.of(), Map.of()); + assertThat(invoke(method, tls("firemud", "game-session-service")).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + SessionContext.clear(); + } + } + + private Status invoke(MethodDescriptor method, SSLSession ssl) { + return invoke(method, ssl, null); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private Status invoke(MethodDescriptor method, SSLSession ssl, String expectedCallerUri) { + ServerCall call = mock(ServerCall.class); + when(call.getMethodDescriptor()).thenReturn(method); + when(call.getAttributes()) + .thenReturn( + ssl == null + ? Attributes.EMPTY + : Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, ssl).build()); + AtomicInteger starts = new AtomicInteger(); + ServerCallHandler next = + (ignored, headers) -> { + assertThat(guard.requireAuthenticatedCaller()).isEqualTo(expectedCallerUri); + starts.incrementAndGet(); + return new ServerCall.Listener() {}; + }; + guard.interceptCall(call, new Metadata(), next); + var captured = ArgumentCaptor.forClass(Status.class); + verify(call, org.mockito.Mockito.atMostOnce()).close(captured.capture(), any(Metadata.class)); + assertThat(starts.get()).isEqualTo(captured.getAllValues().isEmpty() ? 1 : 0); + return captured.getAllValues().isEmpty() ? null : captured.getValue(); + } + + private static SSLSession tls(String namespace, String service) throws Exception { + var leaf = mock(X509Certificate.class); + when(leaf.getSubjectAlternativeNames()) + .thenReturn(List.of(List.of(6, "spiffe://firemud/ns/" + namespace + "/sa/" + service))); + var ssl = mock(SSLSession.class); + when(ssl.getPeerCertificates()).thenReturn(new Certificate[] {leaf}); + return ssl; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java index 05a2f6e1bc..703e8bf61e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java @@ -134,10 +134,16 @@ void missingMembershipRemainsAnExplicitNonadmittingBaselineWithActualCallerAndTa assertThat(value.fields()).containsEntry("variant", "PLAYER_ADMISSION"); assertThat(value.fields().get("requestId")).isEqualTo(f.request.requestId().toString()); assertThat(value.fields().get("callerWorkload")).isEqualTo(PEER); + assertThat(f.retainedCapacity).hasSize(1); assertThat( new String(value.canonicalBytes(), java.nio.charset.StandardCharsets.UTF_8) .contains(f.scope.connectScopeId())) .isFalse(); + assertThat( + f.retainedCapacity + .get(value.fields().get("evaluationIdentity")) + .get("canonical_evidence", byte[].class)) + .containsExactly(value.canonicalBytes()); assertThat(value.membershipSource().accountId()).isEqualTo(ACCOUNT.toString()); assertThat(value.membershipSource().tenantId()).isEqualTo(TENANT.toString()); assertThat(value.membershipSource().membershipExists()).isFalse(); @@ -163,6 +169,29 @@ void missingMembershipRemainsAnExplicitNonadmittingBaselineWithActualCallerAndTa verifyNoInteractions(f.hosting, f.observer); } + @Test + void capacityRetentionFailureRollsBackSourceCaptureWithoutReturningEvidence() throws Exception { + Fixture f = new Fixture(true); + f.refuseCapacityRetention = true; + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .isInstanceOf(DataAccessException.class) + .hasMessage("Controlled capacity retention refusal"); + assertThat(f.retainedCapacity).isEmpty(); + assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "rollback"); + } + + @Test + void missingCapacityRetentionReadbackRollsBackAsSourceUnavailable() throws Exception { + Fixture f = new Fixture(true); + f.missingCapacityRetentionReadback = true; + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .isInstanceOf(AccountPlayerAdmissionEntitlementOwner.SourceUnavailableException.class) + .hasMessage("ENTITLEMENT_UNAVAILABLE: current player source evidence is unavailable") + .hasNoCause(); + assertThat(f.retainedCapacity).isEmpty(); + assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "rollback"); + } + @Test void existingMembershipCarriesItsIndependentVersionAndPositiveCheckpoint() throws Exception { Fixture f = new Fixture(true); @@ -940,6 +969,9 @@ private static final class Fixture { private final CanonicalGameplayAdmissionDecisionReadClient targets = mock(CanonicalGameplayAdmissionDecisionReadClient.class); private final RecordingTransactions transactions = new RecordingTransactions(); + private final Map retainedCapacity = new LinkedHashMap<>(); + private boolean refuseCapacityRetention; + private boolean missingCapacityRetentionReadback; private final java.util.concurrent.atomic.AtomicReference time = new java.util.concurrent.atomic.AtomicReference<>(NOW); private final FreshTenantCreationEvidence source = source(); @@ -1027,6 +1059,44 @@ private Fixture(boolean exists, String stateScope) throws Exception { PEER); controlledTarget(targets); var dsl = mock(DSLContext.class); + // Controlled retention content, not physical atomicity or Account source authentication. + when(dsl.execute(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0, String.class); + if (!sql.startsWith("INSERT INTO account_tenant_capacity_evaluations ")) + throw new AssertionError(sql); + if (refuseCapacityRetention) + throw new DataAccessException("Controlled capacity retention refusal"); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + if (missingCapacityRetentionReadback) return 0; + Object[] values = (Object[]) invocation.getRawArguments()[1]; + String id = (String) values[0]; + if (retainedCapacity.containsKey(id)) return 0; + var row = mock(org.jooq.Record.class); + when(row.get("evaluation_identity", String.class)).thenReturn(id); + when(row.get("snapshot_identity", String.class)).thenReturn((String) values[1]); + when(row.get("tenant_uuid", UUID.class)).thenReturn((UUID) values[2]); + when(row.get("caller_workload", String.class)).thenReturn((String) values[3]); + when(row.get("owner_service", String.class)).thenReturn((String) values[4]); + when(row.get("canonical_evidence", byte[].class)) + .thenReturn(((byte[]) values[5]).clone()); + when(row.get("evaluated_at", java.time.OffsetDateTime.class)) + .thenReturn((java.time.OffsetDateTime) values[6]); + when(row.get("expires_at", java.time.OffsetDateTime.class)) + .thenReturn((java.time.OffsetDateTime) values[7]); + retainedCapacity.put(id, row); + return 1; + }); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0, String.class); + if (!sql.startsWith("SELECT * FROM account_tenant_capacity_evaluations ")) + throw new AssertionError(sql); + Object[] values = (Object[]) invocation.getRawArguments()[1]; + return retainedCapacity.get((String) values[0]); + }); var connection = mock(Connection.class); when(connection.getTransactionIsolation()).thenReturn(Connection.TRANSACTION_SERIALIZABLE); doAnswer( 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 new file mode 100644 index 0000000000..0b811bf47e --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java @@ -0,0 +1,558 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.startsWith; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.sql.Connection; +import java.sql.SQLException; +import java.time.Clock; +import java.time.ZoneOffset; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +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.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository; +import net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; +import org.jooq.ConnectionRunnable; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** + * Controlled ordering/denial only. Physical transaction and positive current-source proof are + * separate. + */ +class AccountTenantCapacityOwnerTest { + @AfterEach + void clear() { + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } + + @Test + void sharedRejectedUsageVectorsReachAccountReservationGuardWithoutWrites() throws Exception { + var resource = getClass().getResourceAsStream("/capacity/capacity-admission-v1-vectors.json"); + assertThat(resource).isNotNull(); + try (resource) { + var corpus = JsonMapper.builder().build().readTree(resource); + for (var vector : corpus.path("rejectedUsage")) { + DSLContext dsl = mock(DSLContext.class); + Record usage = mock(Record.class); + when(usage.get("held_units", Long.class)) + .thenReturn(TenantCapacityAdmission.decimal(vector.path("held").asText())); + when(usage.get("used_units", Long.class)) + .thenReturn(TenantCapacityAdmission.decimal(vector.path("usage").asText())); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(usage); + var request = + CapacityAdmissionTestFixture.worldRequest( + TenantCapacityAdmission.decimal(vector.path("capacityDelta").asText())); + request.requireCommittable(); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy( + () -> + new AccountTenantCapacityRepository(dsl) + .create( + request, + request.evidence().expiresAt(), + Clock.fixed(request.evidence().evaluatedAt(), ZoneOffset.UTC))) + .as(vector.path("name").asText()) + .hasMessage(vector.path("expected").asText()); + verify(dsl, never()).execute(anyString(), any(Object[].class)); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + } + } + } + + @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); + }); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy( + () -> + new AccountTenantCapacityRepository(dsl) + .create(request, request.evidence().expiresAt(), clock)) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> assertThat(failure.code()).isEqualTo(Failure.CAPACITY_ADMISSION_STALE)); + verify(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); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void repeatedSerializationFailuresRetryAndReplayInAFreshTransaction() throws Exception { + var f = new Fixture(true); + f.existing = false; + var aborted = serializationFailure(); + var abortedAttempts = new AtomicInteger(); + when(f.accounts.findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT)) + .thenAnswer( + invocation -> { + if (abortedAttempts.incrementAndGet() == 2) f.existing = true; + throw aborted; + }); + + assertThat(f.owner.commit(f.request, f.request.evidence().callerWorkload()).reservationId()) + .isEqualTo(f.reservation); + verify(f.accounts, times(2)).findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT); + verify(f.dsl, times(3)) + .fetchOne( + startsWith("SELECT * FROM account_tenant_capacity_reservations "), any(Object[].class)); + verifyNoInteractions(f.memberships, f.issuances, f.scopes); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void repeatedSerializationFailuresStopAtTheAttemptLimit() throws Exception { + var f = new Fixture(true); + f.existing = false; + var aborted = serializationFailure(); + when(f.accounts.findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT)) + .thenThrow(aborted); + + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .isSameAs(aborted); + verify(f.accounts, times(4)).findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void cancelledCallDoesNotRetryAnAbortedTransaction() throws Exception { + var f = new Fixture(true); + f.existing = false; + var aborted = serializationFailure(); + try (var caller = Context.current().withCancellation()) { + when(f.accounts.findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT)) + .thenAnswer( + invocation -> { + caller.cancel(null); + throw aborted; + }); + + caller.run( + () -> + assertThatThrownBy( + () -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .isSameAs(aborted)); + } + verify(f.accounts).findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + private static org.jooq.exception.DataAccessException serializationFailure() { + return new org.jooq.exception.DataAccessException( + "concurrent reservation", new SQLException("serialization failure", "40001")); + } + + @Test + void changedAttemptOrPayloadOrFenceConflictsBeforeAnyCurrentSourceOrUsageMutation() + throws Exception { + var f = new Fixture(false); + for (Request changed : + java.util.List.of( + CapacityAdmissionTestFixture.playerRequest(false), + new Request( + f.request.identity(), + UUID.randomUUID(), + f.request.capacityRearmFence(), + f.request.targetNamespace(), + f.request.context(), + f.request.operation(), + f.request.priorShape(), + f.request.requestedShape(), + f.request.evidence(), + f.request.capacityDelta(), + null) + .withDigest(), + new Request( + f.request.identity(), + f.request.admissionAttemptId(), + 2, + f.request.targetNamespace(), + f.request.context(), + f.request.operation(), + f.request.priorShape(), + f.request.requestedShape(), + f.request.evidence(), + f.request.capacityDelta(), + null) + .withDigest(), + new Request( + f.request.identity(), + f.request.admissionAttemptId(), + f.request.capacityRearmFence(), + f.request.targetNamespace(), + f.request.context(), + f.request.operation(), + f.request.priorShape(), + new net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission + .Shape(2, 0, 0), + f.request.evidence(), + f.request.capacityDelta(), + null) + .withDigest())) { + assertThatThrownBy(() -> f.owner.commit(changed, changed.evidence().callerWorkload())) + .hasMessage("IDEMPOTENCY_CONFLICT"); + } + verifyNoInteractions(f.memberships, f.issuances, f.scopes); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void matchingContentWithoutAccountRetainedAuthorityCannotCreateUsage() throws Exception { + var f = new Fixture(false); + f.existing = false; + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .hasMessage("ENTITLEMENT_UNAVAILABLE"); + verifyNoInteractions(f.memberships, f.issuances, f.scopes); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void wrongPeerOrAbsentDeltaNeverStartsAccountWork() throws Exception { + var f = new Fixture(false); + assertThatThrownBy( + () -> f.owner.commit(f.request, "spiffe://firemud/ns/prod/sa/world-management-service")) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> { + assertThat(failure.code()).isEqualTo(Failure.PERMISSION_DENIED); + assertThat(failure.code().toStatusException().getStatus().getCode()) + .isEqualTo(io.grpc.Status.Code.PERMISSION_DENIED); + }); + var absent = + new Request( + f.request.identity(), + f.request.admissionAttemptId(), + 1, + f.request.targetNamespace(), + f.request.context(), + f.request.operation(), + f.request.priorShape(), + f.request.requestedShape(), + f.request.evidence(), + null, + null) + .withDigest(); + assertThatThrownBy(() -> f.owner.commit(absent, absent.evidence().callerWorkload())) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(f.accounts, f.dsl, f.memberships, f.issuances, f.scopes); + } + + @Test + void authenticatedGameSessionCannotSelectWorldOwnerBeforeAccountWork() throws Exception { + var f = new Fixture(false, CapacityAdmissionTestFixture.worldRequest(1L)); + assertThatThrownBy(() -> f.owner.commit(f.request, CapacityAdmissionTestFixture.PEER)) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> assertThat(failure.code()).isEqualTo(Failure.PERMISSION_DENIED)); + verifyNoInteractions(f.accounts, f.dsl, f.memberships, f.issuances, f.scopes); + } + + @Test + void authenticatedWorldRequestCannotReplayWhileWorldCapacityRemainsHeld() throws Exception { + var f = new Fixture(false, CapacityAdmissionTestFixture.worldRequest(1L)); + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> assertThat(failure.code()).isEqualTo(Failure.ENTITLEMENT_UNAVAILABLE)); + verifyNoInteractions(f.accounts, f.dsl, f.memberships, f.issuances, f.scopes); + } + + @Test + void wrongTargetNamespaceOrMissingRequestIsInvalidBeforeAccountWork() throws Exception { + var f = new Fixture(false, CapacityAdmissionTestFixture.playerRequest(), "staging"); + for (String peer : + java.util.List.of( + CapacityAdmissionTestFixture.PEER, + "spiffe://firemud/ns/staging/sa/game-session-service")) { + assertThatThrownBy(() -> f.owner.commit(f.request, peer)) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> { + assertThat(failure.code()).isEqualTo(Failure.INVALID_ARGUMENT); + assertThat(failure.code().toStatusException().getStatus().getCode()) + .isEqualTo(io.grpc.Status.Code.INVALID_ARGUMENT); + }); + } + assertThatThrownBy(() -> f.owner.commit(null, CapacityAdmissionTestFixture.PEER)) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> assertThat(failure.code()).isEqualTo(Failure.INVALID_ARGUMENT)); + verifyNoInteractions(f.accounts, f.dsl, f.memberships, f.issuances, f.scopes); + } + + @Test + void unretainedNonCreatingEvidenceRemainsUnavailableWithoutAnyUsageWrite() throws Exception { + var f = new Fixture(false, CapacityAdmissionTestFixture.playerRequest(false)); + f.existing = false; + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .hasMessage("ENTITLEMENT_UNAVAILABLE"); + verifyNoInteractions(f.memberships, f.issuances, f.scopes); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void exactRetainedNonCreatingEvidenceOutsideWindowIsStale() throws Exception { + var f = new Fixture(true, CapacityAdmissionTestFixture.playerRequest(false)); + f.existing = false; + f.retained = true; + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .hasMessage("CAPACITY_ADMISSION_STALE"); + verifyNoInteractions(f.memberships, f.issuances, f.scopes); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void qualifiedNewerBillingCutoffMakesExactRetainedEvaluationStale() throws Exception { + var f = new Fixture(false); + f.existing = false; + f.retained = true; + var current = mock(Snapshot.class); + var tuple = mock(AuthorityTuple.class); + var tenant = f.request.identity().tenantId().toString(); + var sequence = + Long.parseLong((String) f.request.evidence().fields().get("tenantBillingSequence")); + when(current.membershipExists()).thenReturn(true); + when(current.membershipLifecycleState()).thenReturn("ACTIVE"); + when(current.gameplayAdmissionAllowed()).thenReturn(true); + when(current.tenantId()).thenReturn(tenant); + when(current.authorityTuple()).thenReturn(tuple); + when(tuple.tenantBillingCutoff()) + .thenReturn( + Optional.of( + Map.of( + tenant, + new TenantBillingCutoff("1", Long.toString(sequence + 1), "billing", "2")))); + when(f.memberships.readCurrent( + CapacityAdmissionTestFixture.ACCOUNT, f.request.identity().tenantId())) + .thenReturn(current); + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .hasMessage("CAPACITY_ADMISSION_STALE"); + verifyNoInteractions(f.issuances, f.scopes); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void currentOwnerReadWithoutQualifiedEvidenceIsUnavailable() throws Exception { + var f = new Fixture(false); + f.existing = false; + f.retained = true; + when(f.memberships.readCurrent( + CapacityAdmissionTestFixture.ACCOUNT, f.request.identity().tenantId())) + .thenThrow(new IllegalStateException("Missing committed source")); + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .hasMessage("ENTITLEMENT_UNAVAILABLE"); + verifyNoInteractions(f.issuances, f.scopes); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void nonCreatingEvidenceCannotStartRecoveryOrRearmWork() throws Exception { + var f = new Fixture(false); + var source = + mock( + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .ExecutionReadClient.class); + var recovery = + new net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker( + f.owner, f.dsl, source, Clock.fixed(CapacityAdmissionTestFixture.NOW, ZoneOffset.UTC)); + var denied = CapacityAdmissionTestFixture.playerRequest(false); + var next = + new Request( + denied.identity(), + UUID.randomUUID(), + 2, + denied.targetNamespace(), + denied.context(), + denied.operation(), + denied.priorShape(), + denied.requestedShape(), + denied.evidence(), + denied.capacityDelta(), + null) + .withDigest(); + assertThatThrownBy(() -> recovery.rearm(f.request, next)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + recovery.reconcile( + denied, + net.firedevops.firemud.accountservice.service + .AccountTenantCapacityRecoveryWorker.NoCommitAction.RETAIN_FOR_REARM)) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(f.accounts, f.dsl, f.memberships, f.issuances, f.scopes, source); + } + + private static final class Fixture { + private final DSLContext dsl = mock(DSLContext.class); + private final AccountRepository accounts = mock(AccountRepository.class); + private final AccountCanonicalRuntimeMembershipSnapshotRepository memberships = + mock(AccountCanonicalRuntimeMembershipSnapshotRepository.class); + private final AccountGameplayDelegationIssuanceRepository issuances = + mock(AccountGameplayDelegationIssuanceRepository.class); + private final AccountConnectScopeRepository scopes = mock(AccountConnectScopeRepository.class); + private final Request request; + private final UUID reservation = UUID.randomUUID(); + private final AccountTenantCapacityOwner owner; + private boolean existing = true; + private boolean retained; + + private Fixture(boolean expired) throws Exception { + this(expired, CapacityAdmissionTestFixture.playerRequest()); + } + + private Fixture(boolean expired, Request request) throws Exception { + this(expired, request, "prod"); + } + + private Fixture(boolean expired, Request request, String namespace) throws Exception { + this.request = request; + when(accounts.findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT)) + .thenReturn(Optional.of(new Account())); + Connection connection = mock(Connection.class); + when(connection.getTransactionIsolation()).thenReturn(Connection.TRANSACTION_SERIALIZABLE); + doAnswer( + invocation -> { + invocation.getArgument(0, ConnectionRunnable.class).run(connection); + return null; + }) + .when(dsl) + .connection(any(ConnectionRunnable.class)); + Record row = mock(Record.class); + when(row.get("tenant_uuid", UUID.class)).thenReturn(request.identity().tenantId()); + when(row.get("request_id", UUID.class)).thenReturn(request.identity().requestId()); + when(row.get("admission_id", UUID.class)).thenReturn(request.identity().admissionId()); + when(row.get("admission_attempt_id", UUID.class)).thenReturn(request.admissionAttemptId()); + when(row.get("reservation_id", UUID.class)).thenReturn(reservation); + when(row.get("capacity_rearm_fence", Long.class)).thenReturn(1L); + when(row.get("reservation_fence", Long.class)).thenReturn(1L); + when(row.get("mutation_digest", String.class)).thenReturn(request.mutationDigest()); + when(row.get("canonical_payload", byte[].class)) + .thenReturn(CapacityAdmissionDigest.preimage(request)); + when(row.get("caller_workload", String.class)) + .thenReturn(request.evidence().callerWorkload()); + when(row.get("evaluation_identity", String.class)) + .thenReturn(request.evidence().evaluationIdentity()); + when(row.get("expires_at", java.time.OffsetDateTime.class)) + .thenReturn(AccountTenantCapacityRepository.at(request.evidence().expiresAt())); + when(row.get("state", String.class)).thenReturn("RESERVED"); + Record evaluation = mock(Record.class); + when(evaluation.get("snapshot_identity", String.class)) + .thenReturn(request.evidence().snapshotIdentity()); + var evidence = request.evidence(); + when(evaluation.get("tenant_uuid", UUID.class)).thenReturn(evidence.tenantId()); + when(evaluation.get("caller_workload", String.class)).thenReturn(evidence.callerWorkload()); + when(evaluation.get("owner_service", String.class)).thenReturn(evidence.owner().service()); + when(evaluation.get("canonical_evidence", byte[].class)) + .thenReturn(evidence.canonicalBytes()); + when(evaluation.get("evaluated_at", java.time.OffsetDateTime.class)) + .thenReturn(AccountTenantCapacityRepository.at(evidence.evaluatedAt())); + when(evaluation.get("expires_at", java.time.OffsetDateTime.class)) + .thenReturn(AccountTenantCapacityRepository.at(evidence.expiresAt())); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0, String.class); + if (sql.startsWith("SELECT * FROM account_tenant_capacity_reservations ")) + return existing ? row : null; + 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; + throw new AssertionError(sql); + }); + owner = + new AccountTenantCapacityOwner( + dsl, + accounts, + memberships, + issuances, + scopes, + new ControlledTransactions(), + Clock.fixed( + CapacityAdmissionTestFixture.NOW.plusSeconds(expired ? 60 : 1), ZoneOffset.UTC), + namespace); + } + } + + private static final class ControlledTransactions implements PlatformTransactionManager { + @Override + public TransactionStatus getTransaction( + @org.jspecify.annotations.Nullable TransactionDefinition definition) { + assertThat(definition).isNotNull(); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_SERIALIZABLE); + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getTimeout()).isEqualTo(5); + assertThat(definition.isReadOnly()).isFalse(); + TransactionSynchronizationManager.setActualTransactionActive(true); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + @Override + public void rollback(TransactionStatus status) { + 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 new file mode 100644 index 0000000000..0bda32761b --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java @@ -0,0 +1,123 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Status; +import io.grpc.protobuf.StatusProto; +import io.grpc.stub.StreamObserver; +import java.util.stream.Stream; +import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionRequest; +import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionResponse; +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.CapacityAdmissionTestFixture; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedConstruction; + +/** Controlled handler classification only, not authenticated transport or owner-source proof. */ +class AccountTenantCapacityGrpcServiceTest { + @Test + void malformedWireAndStructurallyInvalidRequestsRefuseBeforeOwner() { + var valid = + TenantCapacityAdmissionGrpcCodec.toRequest(CapacityAdmissionTestFixture.playerRequest()); + for (var wire : + new CommitTenantCapacityAdmissionRequest[] { + null, + CommitTenantCapacityAdmissionRequest.getDefaultInstance(), + valid.toBuilder().setCapacityDelta(0).build() + }) { + try (var guards = authenticatedCaller()) { + AccountTenantCapacityOwner owner = mock(); + StreamObserver observer = mock(); + + new AccountTenantCapacityGrpcService(owner, "prod") + .commitTenantCapacityAdmission(wire, observer); + + assertFailure(observer, Failure.INVALID_ARGUMENT); + verifyNoInteractions(owner); + } + } + } + + @ParameterizedTest + @MethodSource("ownerEvidenceFailures") + void unexpectedOwnerFailuresAreSanitizedInternal(RuntimeException cause) { + var request = CapacityAdmissionTestFixture.playerRequest(); + try (var guards = authenticatedCaller()) { + AccountTenantCapacityOwner owner = mock(); + when(owner.commit(request, CapacityAdmissionTestFixture.PEER)).thenThrow(cause); + StreamObserver observer = mock(); + + new AccountTenantCapacityGrpcService(owner, "prod") + .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(); + verify(owner).commit(request, CapacityAdmissionTestFixture.PEER); + } + } + + @Test + void typedOwnerEvidenceUnavailableKeepsItsPublicFailure() { + var request = CapacityAdmissionTestFixture.playerRequest(); + try (var guards = authenticatedCaller()) { + AccountTenantCapacityOwner owner = mock(); + when(owner.commit(request, CapacityAdmissionTestFixture.PEER)) + .thenThrow(new CapacityException(Failure.ENTITLEMENT_UNAVAILABLE)); + StreamObserver observer = mock(); + new AccountTenantCapacityGrpcService(owner, "prod") + .commitTenantCapacityAdmission( + TenantCapacityAdmissionGrpcCodec.toRequest(request), observer); + assertFailure(observer, Failure.ENTITLEMENT_UNAVAILABLE); + } + } + + private static Stream ownerEvidenceFailures() { + return Stream.of( + new NumberFormatException("Controlled retained billing parse failure"), + new IllegalArgumentException("Controlled retained enum or evidence parse failure"), + new ArithmeticException("Controlled retained arithmetic failure")); + } + + private static MockedConstruction authenticatedCaller() { + return mockConstruction( + AccountTenantCapacityWorkloadGuard.class, + (guard, context) -> + when(guard.requireAuthenticatedCaller()).thenReturn(CapacityAdmissionTestFixture.PEER)); + } + + private static void assertFailure( + StreamObserver observer, Failure expected) { + var error = ArgumentCaptor.forClass(Throwable.class); + verify(observer).onError(error.capture()); + var expectedFailure = expected.toStatusException(); + assertThat(Status.fromThrowable(error.getValue()).getCode()) + .isEqualTo(expectedFailure.getStatus().getCode()); + assertThat(StatusProto.fromThrowable(error.getValue())) + .isEqualTo(StatusProto.fromThrowable(expectedFailure)); + assertThat(error.getValue().getCause()).isNull(); + verify(observer, never()).onNext(any()); + verify(observer, never()).onCompleted(); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigest.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigest.java new file mode 100644 index 0000000000..5536f68777 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigest.java @@ -0,0 +1,188 @@ +package net.firedevops.firemud.common.account.capacity; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.text.Normalizer; +import java.util.Base64; +import java.util.HexFormat; +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.Shape; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.WorldContext; + +/** The capacity-admission/1 action-family mapping of ADR 0047 mutationDigest/v1. */ +public final class CapacityAdmissionDigest { + public static final int MAX_PREIMAGE_BYTES = 512 * 1024; + public static final int MAX_SEGMENT_BYTES = 384 * 1024; + public static final int MAX_STRING_BYTES = 352 * 1024; + + private CapacityAdmissionDigest() {} + + public static byte[] preimage(Request request) { + var output = new ByteArrayOutputStream(); + segment(output, ascii("mutationDigest/v1")); + field(output, "actionFamilySchemaId", string(TenantCapacityAdmission.SCHEMA_ID)); + field(output, "actionFamilySchemaVersion", string(TenantCapacityAdmission.SCHEMA_VERSION)); + field( + output, + "scope", + object( + "tenantId", string(request.identity().tenantId().toString()), + "requestId", string(request.identity().requestId().toString()), + "admissionId", string(request.identity().admissionId().toString()))); + byte[] context; + if (request.context() instanceof PlayerContext player) { + context = + object( + "accountId", + string(player.accountId().toString()), + "tenantId", + string(player.tenantId().toString()), + "playableStateNamespaceId", + string(player.playableStateNamespaceId().toString()), + "gameInstanceId", + string(player.gameInstanceId().toString()), + "characterId", + string(player.characterId().toString()), + "sessionId", + string(player.sessionId().toString()), + "realmId", + string(player.realmId().toString()), + "requestId", + string(player.requestId().toString()), + "playableStateScope", + string(player.playableStateScope())); + } else { + var world = (WorldContext) request.context(); + context = + object( + "tenantId", + string(world.tenantId().toString()), + "operationId", + string(world.operationId().toString()), + "lifecycleId", + string(world.lifecycleId().toString()), + "gameInstanceId", + string(world.gameInstanceId().toString()), + "ownerId", + string(world.ownerId().toString()), + "ownerFence", + number(world.ownerFence())); + } + field( + output, + "target", + object( + "ownerService", + string(request.context().owner().service()), + "targetNamespace", + string(request.targetNamespace()), + "ownerContext", + context)); + field( + output, + "expectedVersion", + object( + "admissionAttemptId", string(request.admissionAttemptId().toString()), + "capacityRearmFence", number(request.capacityRearmFence()))); + field( + output, + "mutation", + object( + "operation", + string(request.operation().name()), + "priorShape", + shape(request.priorShape()), + "requestedShape", + shape(request.requestedShape()), + "accountEvidence", + string(Base64.getEncoder().encodeToString(request.evidence().canonicalBytes())), + "capacityDelta", + request.capacityDelta() == null + ? value("absent", false, new byte[0]) + : number(request.capacityDelta()))); + field(output, "auditReason", string("capacity-admission")); + if (output.size() > MAX_PREIMAGE_BYTES) throw invalid(); + return output.toByteArray(); + } + + public static String digest(Request request) { + try { + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(preimage(request))); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException(unavailable); + } + } + + private static byte[] shape(Shape shape) { + return object( + "activeSessions", + number(shape.activeSessions()), + "concurrentGameInstances", + number(shape.concurrentGameInstances()), + "storageBytes", + number(shape.storageBytes())); + } + + private static byte[] number(long value) { + if (value < 0) throw invalid(); + return value("number", true, ascii(Long.toString(value))); + } + + private static byte[] string(String value) { + if (value == null || value.length() > MAX_STRING_BYTES) throw invalid(); + for (int index = 0; index < value.length(); index++) { + char c = value.charAt(index); + if (Character.isHighSurrogate(c)) { + if (++index >= value.length() || !Character.isLowSurrogate(value.charAt(index))) + throw invalid(); + } else if (Character.isLowSurrogate(c)) throw invalid(); + } + byte[] bytes = + Normalizer.normalize(value, Normalizer.Form.NFC).getBytes(StandardCharsets.UTF_8); + if (bytes.length > MAX_STRING_BYTES) throw invalid(); + return value("string", true, bytes); + } + + private static byte[] object(Object... fields) { + if (fields.length % 2 != 0 || fields.length > 32) throw invalid(); + var output = new ByteArrayOutputStream(); + segment(output, ascii(Integer.toString(fields.length / 2))); + for (int index = 0; index < fields.length; index += 2) { + field(output, (String) fields[index], (byte[]) fields[index + 1]); + } + return value("object", true, output.toByteArray()); + } + + private static byte[] value(String type, boolean present, byte[] payload) { + var output = new ByteArrayOutputStream(); + segment(output, ascii(type)); + output.write(present ? '1' : '0'); + segment(output, payload); + return output.toByteArray(); + } + + private static void field(ByteArrayOutputStream output, String name, byte[] value) { + segment(output, ascii(name)); + output.writeBytes(value); + if (output.size() > MAX_PREIMAGE_BYTES) throw invalid(); + } + + private static void segment(ByteArrayOutputStream output, byte[] bytes) { + if (bytes.length > MAX_SEGMENT_BYTES) throw invalid(); + output.writeBytes(ascii(Integer.toString(bytes.length))); + output.write(':'); + output.writeBytes(bytes); + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid capacity-admission/1 canonical value"); + } +} 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 new file mode 100644 index 0000000000..2632939b7d --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/OriginalNewCapacityExecution.java @@ -0,0 +1,119 @@ +package net.firedevops.firemud.common.account.capacity; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; + +/** Exact original-NEW execution binding. Content is not an Account grant or owner attestation. */ +public record OriginalNewCapacityExecution( + TenantCapacityAdmission.Request request, + TenantCapacityAdmission.Result reservation, + UUID transitionId, + String candidateDigest, + String selectedOwnerId, + long selectedOwnerFence) { + public OriginalNewCapacityExecution { + Objects.requireNonNull(request).requireCommittable(); + 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 + && reservation.state() != TenantCapacityAdmission.State.FINALIZED) + || !request.identity().admissionId().equals(transitionId) + || selectedOwnerFence <= 0 + || candidateDigest == null + || !candidateDigest.matches("sha256:[0-9a-f]{64}")) + throw new IllegalArgumentException("Exact original NEW capacity execution required"); + } + + /** All strings have closed grammars; the complete canonical attempt includes Account evidence. */ + public byte[] canonicalBytes() { + Map fields = new LinkedHashMap<>(); + fields.put("schema", "gs-original-new-capacity-execution/v1"); + fields.put("tenantId", request.identity().tenantId().toString()); + fields.put("requestId", request.identity().requestId().toString()); + fields.put("admissionId", request.identity().admissionId().toString()); + fields.put("admissionAttemptId", request.admissionAttemptId().toString()); + fields.put("capacityRearmFence", Long.toString(request.capacityRearmFence())); + fields.put("mutationDigest", request.mutationDigest()); + fields.put("reservationId", reservation.reservationId().toString()); + fields.put("reservationFence", Long.toString(reservation.reservationFence())); + // Floor milliseconds, never extend Account's microsecond expiry at Redis's TIME boundary. + fields.put("expiresAtMillis", Long.toString(reservation.expiresAt().toEpochMilli())); + fields.put("expiresAt", reservation.expiresAt().toString()); + fields.put("snapshotIdentity", reservation.snapshotIdentity()); + fields.put("evaluationIdentity", reservation.evaluationIdentity()); + fields.put("transitionId", transitionId.toString()); + fields.put("candidateDigest", candidateDigest); + fields.put("selectedOwnerId", selectedOwnerId); + fields.put("selectedOwnerFence", Long.toString(selectedOwnerFence)); + fields.put( + "canonicalAttemptPayload", + Base64.getEncoder().encodeToString(CapacityAdmissionDigest.preimage(request))); + StringBuilder json = new StringBuilder("{"); + fields.forEach( + (name, value) -> { + if (json.length() > 1) json.append(','); + json.append('"').append(name).append("\":\"").append(value).append('"'); + }); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(json.append('}').toString()); + } catch (java.io.IOException malformed) { + throw new IllegalArgumentException("Invalid capacity execution", malformed); + } + } + + public String digest() { + return "sha256:" + sha256(canonicalBytes()); + } + + public static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException(unavailable); + } + } + + public byte[] terminalEvidence(String disposition, String physicalDigest, String receiptDigest) { + if (!("COMMITTED".equals(disposition) || "NOT_EXECUTED_AFTER_AUTHORIZATION".equals(disposition)) + || physicalDigest == null + || !physicalDigest.matches("sha256:[0-9a-f]{64}") + || receiptDigest == null + || !receiptDigest.matches("sha256:[0-9a-f]{64}")) + throw new IllegalArgumentException("Exact terminal owner evidence required"); + var output = new java.io.ByteArrayOutputStream(); + for (byte[] item : + new byte[][] { + "gs-original-new-capacity-result/v1".getBytes(StandardCharsets.US_ASCII), + digest().getBytes(StandardCharsets.US_ASCII), + disposition.getBytes(StandardCharsets.US_ASCII), + physicalDigest.getBytes(StandardCharsets.US_ASCII), + receiptDigest.getBytes(StandardCharsets.US_ASCII) + }) { + output.writeBytes(Integer.toString(item.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(item); + } + return output.toByteArray(); + } + + @Override + public String toString() { + return "OriginalNewCapacityExecution[redacted]"; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmission.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmission.java new file mode 100644 index 0000000000..3376286d64 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmission.java @@ -0,0 +1,407 @@ +package net.firedevops.firemud.common.account.capacity; + +import java.time.Instant; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; +import net.firedevops.firemud.common.account.authority.RuntimeTenantOperationEntitlementEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Content contract only. Neither construction nor a digest authenticates Account or an owner. */ +public final class TenantCapacityAdmission { + public static final String SCHEMA_ID = "capacity-admission"; + public static final String SCHEMA_VERSION = "1"; + public static final int MAX_EVIDENCE_BYTES = 256 * 1024; + + private TenantCapacityAdmission() {} + + public enum Owner { + GAME_SESSION("game-session-service", "maxActiveSessions"), + WORLD_MANAGEMENT("world-management-service", "maxConcurrentGameInstances"); + + private final String service; + private final String quota; + + Owner(String service, String quota) { + this.service = service; + this.quota = quota; + } + + public String service() { + return service; + } + + public String quota() { + return quota; + } + } + + public enum Operation { + CAPACITY_CREATING, + NON_EXPANDING_RECOVERY + } + + public enum State { + RESERVED, + FINALIZED, + RELEASED, + QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION + } + + public record Identity(UUID tenantId, UUID requestId, UUID admissionId) { + public Identity { + uuid(tenantId); + uuid(requestId); + uuid(admissionId); + } + } + + /** Complete target resource shape, not the aggregate tenant usage counter. */ + public record Shape(long activeSessions, long concurrentGameInstances, long storageBytes) { + public Shape { + if (activeSessions < 0 || concurrentGameInstances < 0 || storageBytes < 0) throw invalid(); + } + + public long units(Owner owner) { + return owner == Owner.GAME_SESSION ? activeSessions : concurrentGameInstances; + } + } + + public sealed interface OwnerContext permits PlayerContext, WorldContext { + Owner owner(); + + UUID tenantId(); + + UUID gameInstanceId(); + } + + /** The exact typed PlayerExecutionContext, validated against Account's retained evaluation. */ + public record PlayerContext( + UUID accountId, + UUID tenantId, + UUID playableStateNamespaceId, + UUID gameInstanceId, + UUID characterId, + UUID sessionId, + UUID realmId, + UUID requestId, + String playableStateScope) + implements OwnerContext { + public PlayerContext { + uuid(accountId); + uuid(tenantId); + uuid(playableStateNamespaceId); + uuid(gameInstanceId); + uuid(characterId); + uuid(sessionId); + uuid(realmId); + uuid(requestId); + if (!"SHARED".equals(playableStateScope) && !"PRIVATE".equals(playableStateScope)) + throw invalid(); + } + + @Override + public Owner owner() { + return Owner.GAME_SESSION; + } + } + + /** Separate tenant/operation lifecycle context; never inferred from a player context. */ + public record WorldContext( + UUID tenantId, + UUID operationId, + UUID lifecycleId, + UUID gameInstanceId, + UUID ownerId, + long ownerFence) + implements OwnerContext { + public WorldContext { + uuid(tenantId); + uuid(operationId); + uuid(lifecycleId); + uuid(gameInstanceId); + uuid(ownerId); + if (ownerFence <= 0) throw invalid(); + } + + @Override + public Owner owner() { + return Owner.WORLD_MANAGEMENT; + } + } + + /** Exact, strictly decoded existing Account bundle. Bytes are never replaced by a subset/hash. */ + public static final class Evidence { + private final byte[] bytes; + private final Owner owner; + private final Map fields; + + private Evidence(byte[] bytes, Owner owner) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_EVIDENCE_BYTES) throw invalid(); + this.owner = Objects.requireNonNull(owner); + this.bytes = bytes.clone(); + fields = + owner == Owner.GAME_SESSION + ? RuntimePlayerAdmissionEntitlementEvidence.parseCanonical(bytes).fields() + : RuntimeTenantOperationEntitlementEvidence.parseCanonical(bytes).fields(); + } + + public static Evidence player(RuntimePlayerAdmissionEntitlementEvidence value) { + return new Evidence(Objects.requireNonNull(value).canonicalBytes(), Owner.GAME_SESSION); + } + + public static Evidence world(RuntimeTenantOperationEntitlementEvidence value) { + return new Evidence(Objects.requireNonNull(value).canonicalBytes(), Owner.WORLD_MANAGEMENT); + } + + public static Evidence parse(byte[] bytes, Owner owner) { + return new Evidence(bytes, owner); + } + + public byte[] canonicalBytes() { + return bytes.clone(); + } + + public Map fields() { + return owner == Owner.GAME_SESSION + ? RuntimePlayerAdmissionEntitlementEvidence.parseCanonical(bytes).fields() + : RuntimeTenantOperationEntitlementEvidence.parseCanonical(bytes).fields(); + } + + public Owner owner() { + return owner; + } + + public UUID tenantId() { + return UUID.fromString(text("tenantId")); + } + + public String snapshotIdentity() { + return text("snapshotIdentity"); + } + + public String evaluationIdentity() { + return text("evaluationIdentity"); + } + + public String callerWorkload() { + return text("callerWorkload"); + } + + public Instant evaluatedAt() { + return Instant.parse(text("evaluatedAt")); + } + + public Instant expiresAt() { + Instant freshness = evaluatedAt().plusSeconds(15); + if (owner == Owner.GAME_SESSION) { + Instant validity = Instant.parse(text("validUntil")); + if (validity.isBefore(freshness)) return validity; + } + return freshness; + } + + public void requireCurrent(Instant now) { + if (now.isBefore(evaluatedAt()) || !now.isBefore(expiresAt())) throw invalid(); + } + + public long quota() { + Object raw = fields.get("quotas"); + if (!(raw instanceof Map quotas) + || !(quotas.get(owner.quota()) instanceof String value)) throw invalid(); + return decimal(value); + } + + public boolean permitsCreation() { + return Boolean.TRUE.equals(fields.get("gameplayAvailable")) + && Boolean.TRUE.equals( + fields.get( + owner == Owner.GAME_SESSION + ? "allowNewGameplayBindings" + : "allowNewInstanceStarts")); + } + + private String text(String field) { + if (!(fields.get(field) instanceof String value)) throw invalid(); + return value; + } + + @Override + public boolean equals(Object other) { + return other instanceof Evidence value + && owner == value.owner + && Arrays.equals(bytes, value.bytes); + } + + @Override + public int hashCode() { + return 31 * owner.hashCode() + Arrays.hashCode(bytes); + } + + @Override + public String toString() { + return "CapacityEvidence[redacted]"; + } + } + + public record Request( + Identity identity, + UUID admissionAttemptId, + long capacityRearmFence, + String targetNamespace, + OwnerContext context, + Operation operation, + Shape priorShape, + Shape requestedShape, + Evidence evidence, + Long capacityDelta, + String mutationDigest) { + public Request { + Objects.requireNonNull(identity); + uuid(admissionAttemptId); + if (capacityRearmFence <= 0 || !GrpcPeerIdentity.isValidNamespace(targetNamespace)) + throw invalid(); + Objects.requireNonNull(context); + Objects.requireNonNull(operation); + Objects.requireNonNull(priorShape); + Objects.requireNonNull(requestedShape); + Objects.requireNonNull(evidence); + if (!identity.tenantId().equals(context.tenantId()) + || !identity.tenantId().equals(evidence.tenantId()) + || context.owner() != evidence.owner() + || !expectedWorkload(targetNamespace, context.owner()).equals(evidence.callerWorkload())) + throw invalid(); + if (capacityDelta != null && capacityDelta < 0) throw invalid(); + if (mutationDigest != null && !mutationDigest.matches("[0-9a-f]{64}")) throw invalid(); + } + + public Request withDigest() { + return new Request( + identity, + admissionAttemptId, + capacityRearmFence, + targetNamespace, + context, + operation, + priorShape, + requestedShape, + evidence, + capacityDelta, + CapacityAdmissionDigest.digest(this)); + } + + /** Strong guard for rearm and selected-owner execution; content alone grants no authority. */ + public void requireCommittable() { + requireStructurallyValid(); + if (!evidence.permitsCreation()) throw invalid(); + } + + /** Account resolves exact replay/conflict and current policy after this content check. */ + public void requireStructurallyValid() { + if (capacityDelta == null + || mutationDigest == null + || !mutationDigest.equals(CapacityAdmissionDigest.digest(this)) + || !identity.requestId().toString().equals(evidence.fields().get("requestId"))) + throw invalid(); + long net = + Math.subtractExact( + requestedShape.units(context.owner()), priorShape.units(context.owner())); + if (operation == Operation.CAPACITY_CREATING) { + if (capacityDelta <= 0 || net <= 0 || capacityDelta > net) throw invalid(); + // A scalar commitment cannot hide expansion in another resource dimension. + if (context.owner() == Owner.GAME_SESSION + ? requestedShape.concurrentGameInstances() > priorShape.concurrentGameInstances() + : requestedShape.activeSessions() > priorShape.activeSessions()) throw invalid(); + if (requestedShape.storageBytes() > priorShape.storageBytes()) throw invalid(); + } else if (capacityDelta != 0 + || requestedShape.activeSessions() > priorShape.activeSessions() + || requestedShape.concurrentGameInstances() > priorShape.concurrentGameInstances() + || requestedShape.storageBytes() > priorShape.storageBytes()) throw invalid(); + if (context instanceof PlayerContext player) { + if (!identity.requestId().equals(player.requestId())) throw invalid(); + var fields = evidence.fields(); + if (!player.accountId().toString().equals(fields.get("callerAccountId")) + || !(fields.get("target") instanceof Map target) + || !targetNamespace.equals(target.get("targetNamespace")) + || !player.realmId().toString().equals(target.get("realmId")) + || !player + .playableStateNamespaceId() + .toString() + .equals(target.get("playableStateNamespaceId")) + || !player.gameInstanceId().toString().equals(target.get("gameInstanceId")) + || !player.playableStateScope().equals(target.get("playableStateScope"))) + throw invalid(); + } else if (!identity.requestId().equals(((WorldContext) context).operationId())) + throw invalid(); + } + + @Override + public String toString() { + return "TenantCapacityRequest[redacted]"; + } + } + + public record Result( + Identity identity, + UUID admissionAttemptId, + long capacityRearmFence, + String mutationDigest, + UUID reservationId, + long reservationFence, + Instant expiresAt, + State state, + String snapshotIdentity, + String evaluationIdentity) { + public Result { + Objects.requireNonNull(identity); + uuid(admissionAttemptId); + uuid(reservationId); + if (capacityRearmFence <= 0 + || reservationFence <= 0 + || mutationDigest == null + || !mutationDigest.matches("[0-9a-f]{64}")) throw invalid(); + Objects.requireNonNull(expiresAt); + Objects.requireNonNull(state); + if (snapshotIdentity == null + || !snapshotIdentity.matches("sha256:[0-9a-f]{64}") + || evaluationIdentity == null + || !evaluationIdentity.matches("sha256:[0-9a-f]{64}")) throw invalid(); + } + + public void requireBinding(Request request) { + if (!identity.equals(request.identity()) + || !admissionAttemptId.equals(request.admissionAttemptId()) + || capacityRearmFence != request.capacityRearmFence() + || !mutationDigest.equals(request.mutationDigest()) + || !snapshotIdentity.equals(request.evidence().snapshotIdentity()) + || !evaluationIdentity.equals(request.evidence().evaluationIdentity()) + || !expiresAt.isAfter(request.evidence().evaluatedAt()) + || expiresAt.isAfter(request.evidence().expiresAt())) throw invalid(); + } + } + + public static long decimal(String value) { + if (value == null || !value.matches("0|[1-9][0-9]{0,18}")) throw invalid(); + try { + return Long.parseLong(value); + } catch (NumberFormatException overflow) { + throw invalid(); + } + } + + public static String expectedWorkload(String namespace, Owner owner) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) throw invalid(); + return "spiffe://firemud/ns/" + namespace + "/sa/" + owner.service(); + } + + public static UUID uuid(UUID value) { + if (value == null || value.equals(new UUID(0, 0))) throw invalid(); + return value; + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Exact bounded tenant capacity admission required"); + } +} diff --git a/services/common-platform-core/src/main/resources/capacity/capacity-admission-v1.schema.json b/services/common-platform-core/src/main/resources/capacity/capacity-admission-v1.schema.json new file mode 100644 index 0000000000..9048e0c312 --- /dev/null +++ b/services/common-platform-core/src/main/resources/capacity/capacity-admission-v1.schema.json @@ -0,0 +1,19 @@ +{ + "actionFamilySchemaId": "capacity-admission", + "actionFamilySchemaVersion": "1", + "encoding": "mutationDigest/v1", + "outerFieldOrder": ["actionFamilySchemaId", "actionFamilySchemaVersion", "scope", "target", "expectedVersion", "mutation", "auditReason"], + "scope": {"order": ["tenantId", "requestId", "admissionId"], "types": ["string", "string", "string"]}, + "target": {"order": ["ownerService", "targetNamespace", "ownerContext"], "types": ["string", "string", "object"]}, + "playerContext": {"order": ["accountId", "tenantId", "playableStateNamespaceId", "gameInstanceId", "characterId", "sessionId", "realmId", "requestId", "playableStateScope"], "types": ["string", "string", "string", "string", "string", "string", "string", "string", "string"]}, + "worldContext": {"order": ["tenantId", "operationId", "lifecycleId", "gameInstanceId", "ownerId", "ownerFence"], "types": ["string", "string", "string", "string", "string", "number"]}, + "expectedVersion": {"order": ["admissionAttemptId", "capacityRearmFence"], "types": ["string", "number"]}, + "mutation": {"order": ["operation", "priorShape", "requestedShape", "accountEvidence", "capacityDelta"], "types": ["string", "object", "object", "string", "number-or-absent"]}, + "shape": {"order": ["activeSessions", "concurrentGameInstances", "storageBytes"], "types": ["number", "number", "number"]}, + "accountEvidence": {"content": "RFC 4648 padded base64 of the complete strict canonical account-auth-evidence-bundle/v1 bytes", "variants": {"game-session-service": "PLAYER_ADMISSION", "world-management-service": "TENANT_OPERATION"}, "validation": "Decode with the existing closed variant codec, including canonical re-encoding equality, before framing. This member binds every byte including bundleVersion, snapshotIdentity, evaluationIdentity, entitlement fields, complete authorityTuple, tenantBillingCutoff and outboxCheckpoints. No digest/subset/loose JSON substitute is accepted."}, + "auditReason": {"type": "string", "constant": "capacity-admission"}, + "capacityDelta": {"wire": "optional int64", "json": "canonical unsigned ASCII decimal string", "minimum": "0", "maximum": "9223372036854775807", "absentEncodingOnly": true, "absentCommitment": "REJECT", "null": "REJECT", "negative": "REJECT"}, + "limits": {"requestWireBytes": 294912, "evidenceBytes": 262144, "preimageBytes": 524288, "segmentBytes": 393216, "normalizedStringBytes": 360448, "objectMembers": 16, "numericBytes": 19, "numericScale": 0, "maximumCompositeDepth": 5}, + "sourceLimits": "The existing PLAYER_ADMISSION and TENANT_OPERATION strict decoders apply their bounded raw UTF-8, duplicate-key, nesting, token, member, array and canonical-reencoding checks before this family is framed.", + "status": "Published source contract and proof definitions only. World lifecycle and authoritative zero-delta prior-shape producers are held; this schema does not activate them." +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java new file mode 100644 index 0000000000..a8f6b0e863 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java @@ -0,0 +1,438 @@ +package net.firedevops.firemud.common.account.capacity; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import java.util.UUID; +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.Operation; +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.Shape; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +/** Shared vectors prove content encoding only, never a current Account or runtime grant. */ +class CapacityAdmissionDigestTest { + @Test + void sharedCorpusFixesCompleteEvidenceAndAbsentZeroPositiveBoundaryPreimages() throws Exception { + var resource = getClass().getResourceAsStream("/capacity/capacity-admission-v1-vectors.json"); + assertThat(resource).isNotNull(); + try (resource) { + var corpus = JsonMapper.builder().build().readTree(resource); + for (var vector : corpus.path("vectors")) { + Long delta = + vector.path("capacityDelta").isNull() + ? null + : TenantCapacityAdmission.decimal(vector.path("capacityDelta").asText()); + Request base = CapacityAdmissionTestFixture.worldRequest(delta); + assertThat(Base64.getEncoder().encodeToString(base.evidence().canonicalBytes())) + .isEqualTo(corpus.path("request").path("canonicalAccountEvidenceBase64").asText()); + Request action = base; + if (vector.has("operation")) { + var prior = vector.path("priorShape"); + var requested = vector.path("requestedShape"); + action = + new Request( + base.identity(), + base.admissionAttemptId(), + base.capacityRearmFence(), + base.targetNamespace(), + base.context(), + Operation.valueOf(vector.path("operation").asText()), + new Shape( + TenantCapacityAdmission.decimal(prior.get(0).asText()), + TenantCapacityAdmission.decimal(prior.get(1).asText()), + TenantCapacityAdmission.decimal(prior.get(2).asText())), + new Shape( + TenantCapacityAdmission.decimal(requested.get(0).asText()), + TenantCapacityAdmission.decimal(requested.get(1).asText()), + TenantCapacityAdmission.decimal(requested.get(2).asText())), + base.evidence(), + delta, + null) + .withDigest(); + } + assertThat(HexFormat.of().formatHex(CapacityAdmissionDigest.preimage(action))) + .as(vector.path("name").asText()) + .isEqualTo(vector.path("preimageHex").asText()); + assertThat(CapacityAdmissionDigest.digest(action)) + .isEqualTo(vector.path("sha256").asText()); + Request exact = action; + if (vector.path("commitAllowed").asBoolean()) exact.requireCommittable(); + else + assertThatThrownBy(exact::requireCommittable) + .isInstanceOf(IllegalArgumentException.class); + } + } + assertThat(CapacityAdmissionTestFixture.worldRequest(null).mutationDigest()) + .isNotEqualTo(CapacityAdmissionTestFixture.worldRequest(0L).mutationDigest()); + } + + @Test + void sharedPlayerCorpusFixesIndependentPreimageAndDistinctCharacterAndSessionBindings() + throws Exception { + var resource = getClass().getResourceAsStream("/capacity/capacity-admission-v1-vectors.json"); + assertThat(resource).isNotNull(); + try (resource) { + var corpus = JsonMapper.builder().build().readTree(resource); + var request = corpus.path("playerRequest"); + var context = request.path("ownerContext"); + var vector = corpus.path("playerVector"); + var player = + new PlayerContext( + UUID.fromString(context.path("accountId").asText()), + UUID.fromString(context.path("tenantId").asText()), + UUID.fromString(context.path("playableStateNamespaceId").asText()), + UUID.fromString(context.path("gameInstanceId").asText()), + UUID.fromString(context.path("characterId").asText()), + UUID.fromString(context.path("sessionId").asText()), + UUID.fromString(context.path("realmId").asText()), + UUID.fromString(context.path("requestId").asText()), + context.path("playableStateScope").asText()); + assertThat( + List.of( + player.accountId(), + player.tenantId(), + player.playableStateNamespaceId(), + player.gameInstanceId(), + player.characterId(), + player.sessionId(), + player.realmId(), + player.requestId())) + .doesNotHaveDuplicates(); + assertThat(request.path("ownerService").asText()).isEqualTo(player.owner().service()); + Request action = + new Request( + new Identity( + UUID.fromString(request.path("tenantId").asText()), + UUID.fromString(request.path("requestId").asText()), + UUID.fromString(request.path("admissionId").asText())), + UUID.fromString(request.path("admissionAttemptId").asText()), + TenantCapacityAdmission.decimal(request.path("capacityRearmFence").asText()), + request.path("targetNamespace").asText(), + player, + Operation.valueOf(request.path("operation").asText()), + vectorShape(request.path("priorShape")), + vectorShape(request.path("requestedShape")), + Evidence.parse( + Base64.getDecoder() + .decode(request.path("canonicalAccountEvidenceBase64").asText()), + Owner.GAME_SESSION), + TenantCapacityAdmission.decimal(vector.path("capacityDelta").asText()), + null) + .withDigest(); + action.requireCommittable(); + assertThat(HexFormat.of().formatHex(CapacityAdmissionDigest.preimage(action))) + .isEqualTo(vector.path("preimageHex").asText()); + assertThat(CapacityAdmissionDigest.digest(action)).isEqualTo(vector.path("sha256").asText()); + UUID changed = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + for (var ids : + List.of( + List.of(changed, player.sessionId()), + List.of(player.characterId(), changed), + List.of(player.sessionId(), player.characterId()))) { + var mutation = + new PlayerContext( + player.accountId(), + player.tenantId(), + player.playableStateNamespaceId(), + player.gameInstanceId(), + ids.get(0), + ids.get(1), + player.realmId(), + player.requestId(), + player.playableStateScope()); + Request altered = + new Request( + action.identity(), + action.admissionAttemptId(), + action.capacityRearmFence(), + action.targetNamespace(), + mutation, + action.operation(), + action.priorShape(), + action.requestedShape(), + action.evidence(), + action.capacityDelta(), + null) + .withDigest(); + altered.requireCommittable(); + assertThat(altered.mutationDigest()).isNotEqualTo(action.mutationDigest()); + } + } + } + + private static Shape vectorShape(tools.jackson.databind.JsonNode shape) { + return new Shape( + TenantCapacityAdmission.decimal(shape.get(0).asText()), + TenantCapacityAdmission.decimal(shape.get(1).asText()), + TenantCapacityAdmission.decimal(shape.get(2).asText())); + } + + @Test + void sharedRejectedEvidenceAndRequestsReachCanonicalValidators() throws Exception { + var resource = getClass().getResourceAsStream("/capacity/capacity-admission-v1-vectors.json"); + assertThat(resource).isNotNull(); + try (resource) { + var corpus = JsonMapper.builder().build().readTree(resource); + for (var vector : corpus.path("rejectedEvidence")) { + byte[] bytes = + Base64.getDecoder().decode(vector.path("canonicalAccountEvidenceBase64").asText()); + assertThatThrownBy(() -> Evidence.parse(bytes, Owner.WORLD_MANAGEMENT)) + .as(vector.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class); + } + for (var vector : corpus.path("rejectedRequests")) { + Request base = CapacityAdmissionTestFixture.worldRequest(17L); + Shape requested = base.requestedShape(); + if (vector.has("requestedShape")) { + var shape = vector.path("requestedShape"); + requested = + new Shape( + TenantCapacityAdmission.decimal(shape.get(0).asText()), + TenantCapacityAdmission.decimal(shape.get(1).asText()), + TenantCapacityAdmission.decimal(shape.get(2).asText())); + } + Long delta = + vector.has("capacityDelta") + ? (vector.path("capacityDelta").isNull() + ? null + : TenantCapacityAdmission.decimal(vector.path("capacityDelta").asText())) + : base.capacityDelta(); + Request rejected = + new Request( + base.identity(), + base.admissionAttemptId(), + base.capacityRearmFence(), + base.targetNamespace(), + base.context(), + base.operation(), + base.priorShape(), + requested, + base.evidence(), + delta, + null) + .withDigest(); + assertThatThrownBy(rejected::requireStructurallyValid) + .as(vector.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class); + } + } + } + + @Test + void nonCreatingEvidenceIsValidContentButCannotAuthorizeExecution() { + Request denied = CapacityAdmissionTestFixture.playerRequest(false); + denied.requireStructurallyValid(); + assertThat(denied.evidence().permitsCreation()).isFalse(); + assertThat(CapacityAdmissionTestFixture.playerRequest().evidence().permitsCreation()).isTrue(); + assertThat(denied.mutationDigest()) + .isNotEqualTo(CapacityAdmissionTestFixture.playerRequest().mutationDigest()); + assertThatThrownBy(denied::requireCommittable).isInstanceOf(IllegalArgumentException.class); + var reservation = + new TenantCapacityAdmission.Result( + denied.identity(), + denied.admissionAttemptId(), + denied.capacityRearmFence(), + denied.mutationDigest(), + java.util.UUID.fromString("b1111111-1111-4111-8111-111111111111"), + 1, + denied.evidence().expiresAt(), + TenantCapacityAdmission.State.RESERVED, + denied.evidence().snapshotIdentity(), + denied.evidence().evaluationIdentity()); + assertThatThrownBy( + () -> + new OriginalNewCapacityExecution( + denied, + reservation, + denied.identity().admissionId(), + "sha256:" + "a".repeat(64), + "owner-1", + 1)) + .isInstanceOf(IllegalArgumentException.class); + + for (Request invalid : + List.of( + playerMutation(denied, null, denied.requestedShape(), null).withDigest(), + playerMutation(denied, 1L, denied.requestedShape(), null), + playerMutation(denied, 1L, denied.requestedShape(), "b".repeat(64)), + playerMutation(denied, 0L, denied.requestedShape(), null).withDigest(), + playerMutation(denied, 2L, denied.requestedShape(), null).withDigest(), + playerMutation(denied, 1L, denied.priorShape(), null).withDigest(), + playerMutation(denied, 1L, new Shape(1, 1, 0), null).withDigest(), + playerMutation(denied, 1L, new Shape(1, 0, 1), null).withDigest())) { + assertThatThrownBy(invalid::requireStructurallyValid) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(invalid::requireCommittable).isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void nonExpandingRecoveryStillRequiresCreationEligibleEvidence() { + Request denied = CapacityAdmissionTestFixture.playerRequest(false); + Request recovery = + new Request( + denied.identity(), + denied.admissionAttemptId(), + denied.capacityRearmFence(), + denied.targetNamespace(), + denied.context(), + Operation.NON_EXPANDING_RECOVERY, + denied.priorShape(), + denied.priorShape(), + denied.evidence(), + 0L, + null) + .withDigest(); + recovery.requireStructurallyValid(); + assertThatThrownBy(recovery::requireCommittable).isInstanceOf(IllegalArgumentException.class); + } + + @Test + void boundReleasedAndQuarantinedResultsCannotAuthorizeOriginalExecution() { + Request request = CapacityAdmissionTestFixture.playerRequest(); + for (var state : + List.of( + TenantCapacityAdmission.State.RELEASED, + TenantCapacityAdmission.State.QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION)) { + var reservation = + new TenantCapacityAdmission.Result( + request.identity(), + request.admissionAttemptId(), + request.capacityRearmFence(), + request.mutationDigest(), + UUID.fromString("b1111111-1111-4111-8111-111111111111"), + 1, + request.evidence().expiresAt(), + state, + request.evidence().snapshotIdentity(), + request.evidence().evaluationIdentity()); + reservation.requireBinding(request); + assertThatThrownBy( + () -> + new OriginalNewCapacityExecution( + request, + reservation, + request.identity().admissionId(), + "sha256:" + "a".repeat(64), + "owner-1", + 1)) + .as(state.name()) + .isInstanceOf(IllegalArgumentException.class); + } + } + + private static Request playerMutation(Request base, Long delta, Shape requested, String digest) { + return new Request( + base.identity(), + base.admissionAttemptId(), + base.capacityRearmFence(), + base.targetNamespace(), + base.context(), + base.operation(), + base.priorShape(), + requested, + base.evidence(), + delta, + digest); + } + + @Test + void decimalWireGrammarRejectsNegativesOverflowAndMalformedSpellingsBeforeHash() { + for (String value : + List.of("9223372036854775808", "-1", "+1", "01", "1e0", "1.0", " 1", "1 ")) { + assertThatThrownBy(() -> TenantCapacityAdmission.decimal(value)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThat(TenantCapacityAdmission.decimal("0")).isZero(); + assertThat(TenantCapacityAdmission.decimal("9223372036854775807")).isEqualTo(Long.MAX_VALUE); + assertThatThrownBy(() -> assertThat(Math.addExact(Long.MAX_VALUE, 1)).isPositive()) + .isInstanceOf(ArithmeticException.class); + } + + @Test + void evidenceIsStrictCanonicalAndCompleteChangedFieldsAlterDigest() { + Request original = CapacityAdmissionTestFixture.worldRequest(17L); + String json = new String(original.evidence().canonicalBytes(), StandardCharsets.UTF_8); + for (String changed : + List.of( + " " + json, + json.replaceFirst("\"outboxSequence\":\"3\"", "\"outboxSequence\":\"4\""), + "{\"bundleVersion\":\"1\"," + json.substring(1))) { + assertThatThrownBy( + () -> + Evidence.parse(changed.getBytes(StandardCharsets.UTF_8), Owner.WORLD_MANAGEMENT)) + .isInstanceOf(IllegalArgumentException.class); + } + Evidence changed = + Evidence.parse( + json.replace("\"entitlementVersion\":\"7\"", "\"entitlementVersion\":\"8\"") + .getBytes(StandardCharsets.UTF_8), + Owner.WORLD_MANAGEMENT); + Request mutation = + new Request( + original.identity(), + original.admissionAttemptId(), + original.capacityRearmFence(), + original.targetNamespace(), + original.context(), + original.operation(), + original.priorShape(), + original.requestedShape(), + changed, + original.capacityDelta(), + null) + .withDigest(); + assertThat(mutation.mutationDigest()).isNotEqualTo(original.mutationDigest()); + byte[] copy = changed.canonicalBytes(); + copy[0] = 0; + assertThat(changed.canonicalBytes()[0]).isEqualTo((byte) '{'); + } + + @Test + void zeroCannotHideAnyChangedExpandingShape() { + Request original = CapacityAdmissionTestFixture.worldRequest(0L); + Request zero = + new Request( + original.identity(), + original.admissionAttemptId(), + original.capacityRearmFence(), + original.targetNamespace(), + original.context(), + Operation.NON_EXPANDING_RECOVERY, + new Shape(0, 1, 0), + new Shape(0, 1, 0), + original.evidence(), + 0L, + null) + .withDigest(); + zero.requireCommittable(); + for (Shape shape : List.of(new Shape(1, 1, 0), new Shape(0, 2, 0), new Shape(0, 1, 1))) { + var expanding = + new Request( + zero.identity(), + zero.admissionAttemptId(), + zero.capacityRearmFence(), + zero.targetNamespace(), + zero.context(), + zero.operation(), + zero.priorShape(), + shape, + zero.evidence(), + 0L, + null) + .withDigest(); + assertThatThrownBy(expanding::requireCommittable) + .isInstanceOf(IllegalArgumentException.class); + assertThat(expanding.mutationDigest()).isNotEqualTo(zero.mutationDigest()); + } + } +} 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 new file mode 100644 index 0000000000..3dbb82c187 --- /dev/null +++ b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionTestFixture.java @@ -0,0 +1,430 @@ +package net.firedevops.firemud.common.account.capacity; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Checkpoint; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; +import net.firedevops.firemud.common.account.authority.RuntimeTenantOperationEntitlementEvidence; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; + +/** + * Controlled content only. Nothing here authenticates a source, initializes usage or admits play. + */ +public final class CapacityAdmissionTestFixture { + public static final UUID ACCOUNT = UUID.fromString("11111111-1111-4111-8111-111111111111"); + public static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + public static final UUID REQUEST = UUID.fromString("33333333-3333-4333-8333-333333333333"); + public static final UUID ADMISSION = UUID.fromString("44444444-4444-4444-8444-444444444444"); + public static final UUID ATTEMPT = UUID.fromString("55555555-5555-4555-8555-555555555555"); + public static final UUID PLAYABLE_STATE_NAMESPACE = + UUID.fromString("66666666-6666-4666-8666-666666666666"); + public static final UUID GAME_INSTANCE = UUID.fromString("77777777-7777-4777-8777-777777777777"); + 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 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); + + private CapacityAdmissionTestFixture() {} + + public static RuntimePlayerAdmissionEntitlementEvidence playerEvidence() { + return capture(target(), facts(), sources(), NOW); + } + + public static TenantCapacityAdmission.Request playerRequest() { + return playerRequest(true); + } + + /** Controlled policy content, never proof of current Account entitlement custody. */ + public static TenantCapacityAdmission.Request playerRequest(boolean permitsCreation) { + Map policyFacts = facts(); + policyFacts.put("allowNewGameplayBindings", permitsCreation); + var evidence = capture(target(), policyFacts, sources(), NOW); + return new TenantCapacityAdmission.Request( + new TenantCapacityAdmission.Identity(TENANT, REQUEST, ADMISSION), + ATTEMPT, + 1, + "prod", + new TenantCapacityAdmission.PlayerContext( + ACCOUNT, + TENANT, + PLAYABLE_STATE_NAMESPACE, + GAME_INSTANCE, + CHARACTER, + SESSION, + REALM, + REQUEST, + "SHARED"), + TenantCapacityAdmission.Operation.CAPACITY_CREATING, + new TenantCapacityAdmission.Shape(0, 0, 0), + new TenantCapacityAdmission.Shape(1, 0, 0), + TenantCapacityAdmission.Evidence.player(evidence), + 1L, + null) + .withDigest(); + } + + /** Controlled complete content for a native owner component fixture, not Account authority. */ + public static TenantCapacityAdmission.Request playerRequestFor( + TenantCapacityAdmission.PlayerContext player, + UUID admission, + UUID attempt, + String namespace, + Map target, + Instant at) { + Map source = new LinkedHashMap<>(sources()); + source.put("callerTokenExpiresAt", at.plusSeconds(90).toString()); + var evidence = + RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( + player.requestId(), + TenantCapacityAdmission.expectedWorkload( + namespace, TenantCapacityAdmission.Owner.GAME_SESSION), + RuntimePlayerAdmissionEntitlementEvidence.connectScopeTokenHash("controlled-scope"), + admittingMembership(player.accountId(), player.tenantId(), player.requestId()), + target, + facts(), + source, + at); + return new TenantCapacityAdmission.Request( + new TenantCapacityAdmission.Identity(player.tenantId(), player.requestId(), admission), + attempt, + 1, + namespace, + player, + TenantCapacityAdmission.Operation.CAPACITY_CREATING, + new TenantCapacityAdmission.Shape(0, 0, 0), + new TenantCapacityAdmission.Shape(1, 0, 0), + TenantCapacityAdmission.Evidence.player(evidence), + 1L, + null) + .withDigest(); + } + + public static TenantCapacityAdmission.Request worldRequest(Long delta) { + String tenant = TENANT.toString(); + String stream = "account:auth-authority:v1:tenant/" + tenant; + Map fields = new LinkedHashMap<>(); + fields.put("schema", "account-auth-evidence-bundle/v1"); + fields.put("variant", "TENANT_OPERATION"); + fields.put("bundleVersion", "1"); + fields.put("authorityAvailability", "AVAILABLE"); + fields.put("tenantId", tenant); + fields.put("requestId", REQUEST.toString()); + fields.put("callerWorkload", "spiffe://firemud/ns/prod/sa/world-management-service"); + fields.put("sourceKind", "PAID_HOSTING"); + fields.put("subscriptionStatus", "active"); + fields.put("provisioningStatus", null); + fields.put("gameplayAvailable", true); + fields.put("allowPublicJoin", true); + fields.put("allowNewGameplayBindings", true); + fields.put("allowNewInstanceStarts", true); + fields.put( + "quotas", + Map.of( + "maxActiveSessions", + "100", + "maxConcurrentGameInstances", + Long.toString(Long.MAX_VALUE), + "maxStorageBytes", + "1048576")); + fields.put("entitlementVersion", "7"); + fields.put("tenantBillingSequence", "11"); + fields.put("tenantAuthorityGeneration", "5"); + fields.put("evaluatedAt", NOW.toString()); + fields.put("snapshotIdentity", "sha256:" + "a".repeat(64)); + fields.put("evaluationIdentity", "sha256:" + "b".repeat(64)); + fields.put( + "authorityTuple", + Map.of( + "tenantAuthorityGeneration", + Map.of(tenant, "5"), + "tenantBillingCutoff", + Map.of( + tenant, + Map.of( + "tenantAuthorityGeneration", + "5", + "tenantBillingSequence", + "11", + "outboxStreamKey", + stream, + "outboxSequence", + "3")))); + fields.put( + "outboxCheckpoints", + List.of( + Map.of( + "outboxStreamKey", + stream, + "outboxSequence", + "3", + "sourceEventId", + ACCOUNT.toString(), + "sourceEventDigest", + "sha256:" + "a".repeat(64)))); + return new TenantCapacityAdmission.Request( + new TenantCapacityAdmission.Identity(TENANT, REQUEST, ADMISSION), + ATTEMPT, + 1, + "prod", + new TenantCapacityAdmission.WorldContext( + TENANT, REQUEST, ADMISSION, ACCOUNT, ATTEMPT, 7), + TenantCapacityAdmission.Operation.CAPACITY_CREATING, + new TenantCapacityAdmission.Shape(0, 0, 0), + new TenantCapacityAdmission.Shape(0, Long.MAX_VALUE, 0), + TenantCapacityAdmission.Evidence.world( + RuntimeTenantOperationEntitlementEvidence.fromOwnerEvaluation(fields)), + delta, + null) + .withDigest(); + } + + private static RuntimePlayerAdmissionEntitlementEvidence capture( + Map target, + Map facts, + Map source, + Instant at) { + return RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( + REQUEST, + PEER, + RuntimePlayerAdmissionEntitlementEvidence.connectScopeTokenHash("controlled-scope"), + membership(), + target, + facts, + source, + at); + } + + private static Map target() { + Map target = new LinkedHashMap<>(); + target.put("targetClass", "PUBLIC_PRODUCTION"); + target.put("characterCreationPolicy", "PRESEEDED_ONLY"); + target.put("targetNamespace", "prod"); + target.put("tenantId", TENANT.toString()); + target.put("tenantSlug", "tenant"); + target.put("worldSlug", "world"); + target.put("realmId", REALM.toString()); + target.put("realmSlug", "production"); + target.put("playableStateNamespaceId", PLAYABLE_STATE_NAMESPACE.toString()); + target.put("playableStateScope", "SHARED"); + target.put("gameInstanceId", GAME_INSTANCE.toString()); + target.put("canonicalVersionId", REQUEST.toString()); + target.put("catalogRevision", "7"); + target.put("pointerVersion", "3"); + target.put("activeWorldEpoch", "5"); + target.put("evaluatedAt", NOW.minusSeconds(20).toString()); + target.put("connectScopeExpiresAt", NOW.plusSeconds(120).toString()); + return target; + } + + private static Map facts() { + Map facts = new LinkedHashMap<>(); + facts.put("sourceKind", "NON_PAID_DEMO"); + facts.put("subscriptionStatus", null); + facts.put("provisioningStatus", null); + for (String flag : + List.of( + "gameplayAvailable", + "allowPublicJoin", + "allowNewGameplayBindings", + "allowNewInstanceStarts")) facts.put(flag, true); + facts.put( + "quotas", + Map.of( + "maxActiveSessions", + "3", + "maxConcurrentGameInstances", + "2", + "maxStorageBytes", + "4096")); + facts.put("entitlementVersion", "1"); + facts.put("tenantBillingSequence", "1"); + facts.put("tenantAuthorityGeneration", "2"); + return facts; + } + + private static Map sources() { + Map source = new LinkedHashMap<>(); + source.put("callerTokenExpiresAt", NOW.plusSeconds(90).toString()); + source.put("paidReceiptValidUntil", null); + for (String key : + List.of("callerTokenJti", "callerContextId", "callerOperationId", "worldCaptureId")) + source.put(key, REQUEST.toString()); + for (String key : + List.of( + "callerTokenSha256", + "callerRegistryRecordSha256", + "callerCommitProofSha256", + "admissionPointerSnapshotDigest")) source.put(key, HASH); + for (String key : + List.of( + "scopeDigest", + "entitlementSourceDigest", + "gameSessionOwnerProofDigest", + "publishedPolicySetDigest", + "worldLifecycleDigest")) source.put(key, "sha256:" + HASH); + source.put("worldRowVersion", "0"); + return source; + } + + private static Snapshot membership() { + return membership(ACCOUNT, TENANT, REQUEST, false); + } + + private static Snapshot admittingMembership(UUID account, UUID tenantId, UUID requestId) { + return membership(account, tenantId, requestId, true); + } + + private static Snapshot membership( + UUID account, UUID tenantId, UUID requestId, boolean admitted) { + String requestDigest = + GameTenantCreationDigest.requestDigest("prod", requestId, "world", "World", null); + var source = + new FreshTenantCreationEvidence( + 1, + "prod", + requestId, + requestId, + requestDigest, + tenantId, + 17, + "world", + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "prod", + requestId, + requestId, + requestDigest, + tenantId, + 17, + "world", + "NEW_GAME_ROW")); + var request = + new TenantAuthorityEventV1Codec.AuthorityRequest( + requestId, + "sha256:" + HASH, + tenantId, + source.creationRequestId(), + source.requestDigest()); + var billing = + new TenantAuthorityEventV1Codec.BillingReceipt( + tenantId, + requestId, + "sha256:" + HASH, + TenantAuthorityEventV1Codec.tenantBillingStreamKey(tenantId), + 1, + TenantAuthorityEventV1Codec.tenantBillingEventId(requestId), + "sha256:" + HASH); + var event = TenantAuthorityEventV1Codec.seal(request, source, 2, 2, 1, billing); + String prefix = MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX; + var tuple = + new AuthorityTuple( + "1", + "1", + Map.of(tenantId.toString(), "2"), + Map.of(tenantId.toString(), "1"), + List.of(), + Optional.empty(), + Optional.of( + Map.of( + tenantId.toString(), + new TenantBillingCutoff("2", "1", event.outboxStreamKey(), "1")))); + String membershipStream = prefix + "membership/" + account + "/" + tenantId; + var tenantSource = + new SourceEvidence( + event.outboxStreamKey(), + "1", + event.eventId().toString(), + event.eventDigest(), + new String(event.payload(), StandardCharsets.UTF_8)); + List sourceEvidence; + if (admitted) { + Map eventFields = new LinkedHashMap<>(); + eventFields.put("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION); + eventFields.put("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE); + eventFields.put("eventId", "membership-event-" + requestId); + eventFields.put("requestId", requestId.toString()); + eventFields.put("outboxStreamKey", membershipStream); + eventFields.put("outboxSequence", "1"); + eventFields.put("sourceScope", "membership/" + account + "/" + tenantId); + eventFields.put("accountId", account.toString()); + eventFields.put("tenantId", tenantId.toString()); + eventFields.put("membershipExists", true); + eventFields.put("membershipLifecycleState", "ACTIVE"); + eventFields.put("membershipVersion", Map.of(tenantId.toString(), "1")); + eventFields.put("membershipAuthorityGeneration", "1"); + eventFields.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(tenantId.toString(), "2"), + "membershipAuthorityGeneration", + Map.of(tenantId.toString(), "1"), + "privateRealmGrantVersions", + List.of(), + "tenantBillingCutoff", + Map.of( + tenantId.toString(), + Map.of( + "tenantAuthorityGeneration", + "2", + "tenantBillingSequence", + "1", + "outboxStreamKey", + event.outboxStreamKey(), + "outboxSequence", + "1")))); + eventFields.put("issuanceFence", "1"); + eventFields.put("roles", List.of("player")); + eventFields.put("gameplayAdmissionAllowed", true); + eventFields.put("callerBoundAuthorityInvalidated", false); + var membershipEvent = MembershipAuthorityEventV1Codec.seal(eventFields); + sourceEvidence = + List.of( + new SourceEvidence( + membershipStream, + "1", + membershipEvent.eventId(), + membershipEvent.eventDigest(), + membershipEvent.canonicalJson()), + tenantSource); + } else { + sourceEvidence = List.of(tenantSource); + } + return new Snapshot( + "firemud-account-service", + account.toString(), + tenantId.toString(), + admitted, + admitted ? "ACTIVE" : "MISSING", + admitted, + Map.of(tenantId.toString(), "1"), + "1", + admitted ? List.of("player") : List.of(), + tuple, + "1", + List.of( + new Checkpoint(prefix + "account/" + account, "0"), + new Checkpoint(prefix + "issuer/firemud-account-service", "0"), + new Checkpoint(membershipStream, admitted ? "1" : "0"), + new Checkpoint(event.outboxStreamKey(), "1")), + sourceEvidence); + } +} diff --git a/services/common-platform-core/src/testFixtures/resources/capacity/capacity-admission-v1-vectors.json b/services/common-platform-core/src/testFixtures/resources/capacity/capacity-admission-v1-vectors.json new file mode 100644 index 0000000000..e557b9147e --- /dev/null +++ b/services/common-platform-core/src/testFixtures/resources/capacity/capacity-admission-v1-vectors.json @@ -0,0 +1,238 @@ +{ + "schema": "capacity-admission/1", + "validation": "Encoding vectors and separate native request/Account usage rejection fixtures; not source or runtime authority", + "request": { + "tenantId": "22222222-2222-4222-8222-222222222222", + "requestId": "33333333-3333-4333-8333-333333333333", + "admissionId": "44444444-4444-4444-8444-444444444444", + "admissionAttemptId": "55555555-5555-4555-8555-555555555555", + "capacityRearmFence": "1", + "targetNamespace": "prod", + "ownerService": "world-management-service", + "ownerContext": { + "tenantId": "22222222-2222-4222-8222-222222222222", + "operationId": "33333333-3333-4333-8333-333333333333", + "lifecycleId": "44444444-4444-4444-8444-444444444444", + "gameInstanceId": "11111111-1111-4111-8111-111111111111", + "ownerId": "55555555-5555-4555-8555-555555555555", + "ownerFence": "7" + }, + "operation": "CAPACITY_CREATING", + "priorShape": [ + "0", + "0", + "0" + ], + "requestedShape": [ + "0", + "9223372036854775807", + "0" + ], + "canonicalAccountEvidenceBase64": "eyJhbGxvd05ld0dhbWVwbGF5QmluZGluZ3MiOnRydWUsImFsbG93TmV3SW5zdGFuY2VTdGFydHMiOnRydWUsImFsbG93UHVibGljSm9pbiI6dHJ1ZSwiYXV0aG9yaXR5QXZhaWxhYmlsaXR5IjoiQVZBSUxBQkxFIiwiYXV0aG9yaXR5VHVwbGUiOnsidGVuYW50QXV0aG9yaXR5R2VuZXJhdGlvbiI6eyIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiOiI1In0sInRlbmFudEJpbGxpbmdDdXRvZmYiOnsiMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIjp7Im91dGJveFNlcXVlbmNlIjoiMyIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6dGVuYW50LzIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiIsInRlbmFudEF1dGhvcml0eUdlbmVyYXRpb24iOiI1IiwidGVuYW50QmlsbGluZ1NlcXVlbmNlIjoiMTEifX19LCJidW5kbGVWZXJzaW9uIjoiMSIsImNhbGxlcldvcmtsb2FkIjoic3BpZmZlOi8vZmlyZW11ZC9ucy9wcm9kL3NhL3dvcmxkLW1hbmFnZW1lbnQtc2VydmljZSIsImVudGl0bGVtZW50VmVyc2lvbiI6IjciLCJldmFsdWF0ZWRBdCI6IjIwMjYtMTEtMDJUMDA6MDA6MDBaIiwiZXZhbHVhdGlvbklkZW50aXR5Ijoic2hhMjU2OmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmIiLCJnYW1lcGxheUF2YWlsYWJsZSI6dHJ1ZSwib3V0Ym94Q2hlY2twb2ludHMiOlt7Im91dGJveFNlcXVlbmNlIjoiMyIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6dGVuYW50LzIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiIsInNvdXJjZUV2ZW50RGlnZXN0Ijoic2hhMjU2OmFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLCJzb3VyY2VFdmVudElkIjoiMTExMTExMTEtMTExMS00MTExLTgxMTEtMTExMTExMTExMTExIn1dLCJwcm92aXNpb25pbmdTdGF0dXMiOm51bGwsInF1b3RhcyI6eyJtYXhBY3RpdmVTZXNzaW9ucyI6IjEwMCIsIm1heENvbmN1cnJlbnRHYW1lSW5zdGFuY2VzIjoiOTIyMzM3MjAzNjg1NDc3NTgwNyIsIm1heFN0b3JhZ2VCeXRlcyI6IjEwNDg1NzYifSwicmVxdWVzdElkIjoiMzMzMzMzMzMtMzMzMy00MzMzLTgzMzMtMzMzMzMzMzMzMzMzIiwic2NoZW1hIjoiYWNjb3VudC1hdXRoLWV2aWRlbmNlLWJ1bmRsZS92MSIsInNuYXBzaG90SWRlbnRpdHkiOiJzaGEyNTY6YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsInNvdXJjZUtpbmQiOiJQQUlEX0hPU1RJTkciLCJzdWJzY3JpcHRpb25TdGF0dXMiOiJhY3RpdmUiLCJ0ZW5hbnRBdXRob3JpdHlHZW5lcmF0aW9uIjoiNSIsInRlbmFudEJpbGxpbmdTZXF1ZW5jZSI6IjExIiwidGVuYW50SWQiOiIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiLCJ2YXJpYW50IjoiVEVOQU5UX09QRVJBVElPTiJ9" + }, + "vectors": [ + { + "name": "absent", + "capacityDelta": null, + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673131383a63617061636974792d61646d697373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a656374313138323a313a33383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d323232323232323232323232393a726571756573744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a61646d697373696f6e4964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d343434343434343434343434363a746172676574363a6f626a656374313434373a313a3331323a6f776e657253657276696365363a737472696e673132343a776f726c642d6d616e6167656d656e742d7365727669636531353a7461726765744e616d657370616365363a737472696e6731343a70726f6431323a6f776e6572436f6e74657874363a6f626a656374313333323a313a36383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231313a6f7065726174696f6e4964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a6c6966656379636c654964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d34343434343434343434343431343a67616d65496e7374616e63654964363a737472696e673133363a31313131313131312d313131312d343131312d383131312d313131313131313131313131373a6f776e65724964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531303a6f776e657246656e6365363a6e756d62657231313a3731353a657870656374656456657273696f6e363a6f626a656374313130353a313a3231383a61646d697373696f6e417474656d70744964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531383a6361706163697479526561726d46656e6365363a6e756d62657231313a31383a6d75746174696f6e363a6f626a65637431323431383a313a35393a6f7065726174696f6e363a737472696e673131373a43415041434954595f4352454154494e4731303a7072696f725368617065363a6f626a6563743139373a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d62657231313a3031323a73746f726167654279746573363a6e756d62657231313a3031343a7265717565737465645368617065363a6f626a656374313131363a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d6265723131393a3932323333373230333638353437373538303731323a73746f726167654279746573363a6e756d62657231313a3031353a6163636f756e7445766964656e6365363a737472696e6731323034383a65794a68624778766430356c643064686257567762474635516d6c755a476c755a334d694f6e527964575573496d467362473933546d56335357357a64474675593256546447467964484d694f6e527964575573496d4673624739335548566962476c6a536d39706269493664484a315a53776959585630614739796158523551585a6861577868596d6c7361585235496a6f6951565a4253557842516b78464969776959585630614739796158523556485677624755694f6e73696447567559573530515856306147397961585235523256755a584a6864476c7662694936657949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694f694931496e3073496e526c626d467564454a7062477870626d6444645852765a6d59694f6e73694d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a4979496a7037496d393164474a7665464e6c6358566c626d4e6c496a6f694d794973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e526c626d46756445463164476876636d6c306555646c626d567959585270623234694f694931496977696447567559573530516d6c7362476c755a314e6c6358566c626d4e6c496a6f694d544569665831394c434a696457356b624756575a584a7a61573975496a6f694d534973496d4e686247786c636c6476636d74736232466b496a6f69633342705a6d5a6c4f6938765a6d6c795a5731315a43397563793977636d396b4c334e684c336476636d786b4c573168626d466e5a57316c626e517463325679646d6c6a5a534973496d567564476c30624756745a573530566d567963326c7662694936496a63694c434a6c646d4673645746305a57524264434936496a49774d6a59744d5445744d444a554d4441364d4441364d444261496977695a585a686248566864476c76626b6c6b5a57353061585235496a6f69633268684d6a55324f6d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d49694c434a6e5957316c634778686555463259576c7359574a735a53493664484a315a53776962335630596d39345132686c5932747762326c7564484d694f6c7437496d393164474a7665464e6c6358566c626d4e6c496a6f694d794973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e4e7664584a6a5a5556325a57353052476c6e5a584e30496a6f69633268684d6a55324f6d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a7a6233567959325646646d567564456c6b496a6f694d5445784d5445784d5445744d5445784d5330304d5445784c5467784d5445744d5445784d5445784d5445784d544578496e31644c434a77636d393261584e7062323570626d64546447463064584d694f6d353162477773496e4631623352686379493665794a745958684259335270646d56545a584e7a6157397563794936496a45774d434973496d316865454e76626d4e31636e4a6c626e52485957316c5357357a644746755932567a496a6f694f5449794d7a4d334d6a417a4e6a67314e4463334e5467774e794973496d316865464e3062334a685a3256436558526c63794936496a45774e4467314e7a596966537769636d56786457567a64456c6b496a6f694d7a4d7a4d7a4d7a4d7a4d744d7a4d7a4d7930304d7a4d7a4c54677a4d7a4d744d7a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4969776963324e6f5a573168496a6f6959574e6a62335675644331686458526f4c5756326157526c626d4e6c4c574a31626d52735a5339324d534973496e4e755958427a614739305357526c626e527064486b694f694a7a614745794e54593659574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859534973496e4e7664584a6a5a557470626d51694f694a5151556c45583068505531524a546b63694c434a7a64574a7a59334a7063485270623235546447463064584d694f694a6859335270646d55694c434a305a573568626e52426458526f62334a7064486c485a57356c636d463061573975496a6f694e534973496e526c626d467564454a7062477870626d64545a5846315a57356a5a534936496a4578496977696447567559573530535751694f6949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694c434a3259584a7059573530496a6f695645564f515535555830395152564a4256456c5054694a3931333a636170616369747944656c7461363a616273656e7430303a31313a6175646974526561736f6e363a737472696e673131383a63617061636974792d61646d697373696f6e", + "sha256": "34da579bb6e881688bc1481a3d8fc910a7e4eee81bc008c5991d31fce179e845", + "commitAllowed": false + }, + { + "name": "present-zero", + "capacityDelta": "0", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673131383a63617061636974792d61646d697373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a656374313138323a313a33383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d323232323232323232323232393a726571756573744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a61646d697373696f6e4964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d343434343434343434343434363a746172676574363a6f626a656374313434373a313a3331323a6f776e657253657276696365363a737472696e673132343a776f726c642d6d616e6167656d656e742d7365727669636531353a7461726765744e616d657370616365363a737472696e6731343a70726f6431323a6f776e6572436f6e74657874363a6f626a656374313333323a313a36383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231313a6f7065726174696f6e4964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a6c6966656379636c654964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d34343434343434343434343431343a67616d65496e7374616e63654964363a737472696e673133363a31313131313131312d313131312d343131312d383131312d313131313131313131313131373a6f776e65724964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531303a6f776e657246656e6365363a6e756d62657231313a3731353a657870656374656456657273696f6e363a6f626a656374313130353a313a3231383a61646d697373696f6e417474656d70744964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531383a6361706163697479526561726d46656e6365363a6e756d62657231313a31383a6d75746174696f6e363a6f626a65637431323431393a313a35393a6f7065726174696f6e363a737472696e673131373a43415041434954595f4352454154494e4731303a7072696f725368617065363a6f626a6563743139373a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d62657231313a3031323a73746f726167654279746573363a6e756d62657231313a3031343a7265717565737465645368617065363a6f626a656374313131363a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d6265723131393a3932323333373230333638353437373538303731323a73746f726167654279746573363a6e756d62657231313a3031353a6163636f756e7445766964656e6365363a737472696e6731323034383a65794a68624778766430356c643064686257567762474635516d6c755a476c755a334d694f6e527964575573496d467362473933546d56335357357a64474675593256546447467964484d694f6e527964575573496d4673624739335548566962476c6a536d39706269493664484a315a53776959585630614739796158523551585a6861577868596d6c7361585235496a6f6951565a4253557842516b78464969776959585630614739796158523556485677624755694f6e73696447567559573530515856306147397961585235523256755a584a6864476c7662694936657949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694f694931496e3073496e526c626d467564454a7062477870626d6444645852765a6d59694f6e73694d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a4979496a7037496d393164474a7665464e6c6358566c626d4e6c496a6f694d794973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e526c626d46756445463164476876636d6c306555646c626d567959585270623234694f694931496977696447567559573530516d6c7362476c755a314e6c6358566c626d4e6c496a6f694d544569665831394c434a696457356b624756575a584a7a61573975496a6f694d534973496d4e686247786c636c6476636d74736232466b496a6f69633342705a6d5a6c4f6938765a6d6c795a5731315a43397563793977636d396b4c334e684c336476636d786b4c573168626d466e5a57316c626e517463325679646d6c6a5a534973496d567564476c30624756745a573530566d567963326c7662694936496a63694c434a6c646d4673645746305a57524264434936496a49774d6a59744d5445744d444a554d4441364d4441364d444261496977695a585a686248566864476c76626b6c6b5a57353061585235496a6f69633268684d6a55324f6d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d49694c434a6e5957316c634778686555463259576c7359574a735a53493664484a315a53776962335630596d39345132686c5932747762326c7564484d694f6c7437496d393164474a7665464e6c6358566c626d4e6c496a6f694d794973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e4e7664584a6a5a5556325a57353052476c6e5a584e30496a6f69633268684d6a55324f6d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a7a6233567959325646646d567564456c6b496a6f694d5445784d5445784d5445744d5445784d5330304d5445784c5467784d5445744d5445784d5445784d5445784d544578496e31644c434a77636d393261584e7062323570626d64546447463064584d694f6d353162477773496e4631623352686379493665794a745958684259335270646d56545a584e7a6157397563794936496a45774d434973496d316865454e76626d4e31636e4a6c626e52485957316c5357357a644746755932567a496a6f694f5449794d7a4d334d6a417a4e6a67314e4463334e5467774e794973496d316865464e3062334a685a3256436558526c63794936496a45774e4467314e7a596966537769636d56786457567a64456c6b496a6f694d7a4d7a4d7a4d7a4d7a4d744d7a4d7a4d7930304d7a4d7a4c54677a4d7a4d744d7a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4969776963324e6f5a573168496a6f6959574e6a62335675644331686458526f4c5756326157526c626d4e6c4c574a31626d52735a5339324d534973496e4e755958427a614739305357526c626e527064486b694f694a7a614745794e54593659574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859534973496e4e7664584a6a5a557470626d51694f694a5151556c45583068505531524a546b63694c434a7a64574a7a59334a7063485270623235546447463064584d694f694a6859335270646d55694c434a305a573568626e52426458526f62334a7064486c485a57356c636d463061573975496a6f694e534973496e526c626d467564454a7062477870626d64545a5846315a57356a5a534936496a4578496977696447567559573530535751694f6949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694c434a3259584a7059573530496a6f695645564f515535555830395152564a4256456c5054694a3931333a636170616369747944656c7461363a6e756d62657231313a3031313a6175646974526561736f6e363a737472696e673131383a63617061636974792d61646d697373696f6e", + "sha256": "3c80f1967fdb3d87875fc852e306681d7d8b86521f286b7f3896696ded5a9c59", + "commitAllowed": false + }, + { + "name": "present-seventeen", + "capacityDelta": "17", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673131383a63617061636974792d61646d697373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a656374313138323a313a33383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d323232323232323232323232393a726571756573744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a61646d697373696f6e4964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d343434343434343434343434363a746172676574363a6f626a656374313434373a313a3331323a6f776e657253657276696365363a737472696e673132343a776f726c642d6d616e6167656d656e742d7365727669636531353a7461726765744e616d657370616365363a737472696e6731343a70726f6431323a6f776e6572436f6e74657874363a6f626a656374313333323a313a36383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231313a6f7065726174696f6e4964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a6c6966656379636c654964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d34343434343434343434343431343a67616d65496e7374616e63654964363a737472696e673133363a31313131313131312d313131312d343131312d383131312d313131313131313131313131373a6f776e65724964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531303a6f776e657246656e6365363a6e756d62657231313a3731353a657870656374656456657273696f6e363a6f626a656374313130353a313a3231383a61646d697373696f6e417474656d70744964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531383a6361706163697479526561726d46656e6365363a6e756d62657231313a31383a6d75746174696f6e363a6f626a65637431323432303a313a35393a6f7065726174696f6e363a737472696e673131373a43415041434954595f4352454154494e4731303a7072696f725368617065363a6f626a6563743139373a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d62657231313a3031323a73746f726167654279746573363a6e756d62657231313a3031343a7265717565737465645368617065363a6f626a656374313131363a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d6265723131393a3932323333373230333638353437373538303731323a73746f726167654279746573363a6e756d62657231313a3031353a6163636f756e7445766964656e6365363a737472696e6731323034383a65794a68624778766430356c643064686257567762474635516d6c755a476c755a334d694f6e527964575573496d467362473933546d56335357357a64474675593256546447467964484d694f6e527964575573496d4673624739335548566962476c6a536d39706269493664484a315a53776959585630614739796158523551585a6861577868596d6c7361585235496a6f6951565a4253557842516b78464969776959585630614739796158523556485677624755694f6e73696447567559573530515856306147397961585235523256755a584a6864476c7662694936657949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694f694931496e3073496e526c626d467564454a7062477870626d6444645852765a6d59694f6e73694d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a4979496a7037496d393164474a7665464e6c6358566c626d4e6c496a6f694d794973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e526c626d46756445463164476876636d6c306555646c626d567959585270623234694f694931496977696447567559573530516d6c7362476c755a314e6c6358566c626d4e6c496a6f694d544569665831394c434a696457356b624756575a584a7a61573975496a6f694d534973496d4e686247786c636c6476636d74736232466b496a6f69633342705a6d5a6c4f6938765a6d6c795a5731315a43397563793977636d396b4c334e684c336476636d786b4c573168626d466e5a57316c626e517463325679646d6c6a5a534973496d567564476c30624756745a573530566d567963326c7662694936496a63694c434a6c646d4673645746305a57524264434936496a49774d6a59744d5445744d444a554d4441364d4441364d444261496977695a585a686248566864476c76626b6c6b5a57353061585235496a6f69633268684d6a55324f6d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d49694c434a6e5957316c634778686555463259576c7359574a735a53493664484a315a53776962335630596d39345132686c5932747762326c7564484d694f6c7437496d393164474a7665464e6c6358566c626d4e6c496a6f694d794973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e4e7664584a6a5a5556325a57353052476c6e5a584e30496a6f69633268684d6a55324f6d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a7a6233567959325646646d567564456c6b496a6f694d5445784d5445784d5445744d5445784d5330304d5445784c5467784d5445744d5445784d5445784d5445784d544578496e31644c434a77636d393261584e7062323570626d64546447463064584d694f6d353162477773496e4631623352686379493665794a745958684259335270646d56545a584e7a6157397563794936496a45774d434973496d316865454e76626d4e31636e4a6c626e52485957316c5357357a644746755932567a496a6f694f5449794d7a4d334d6a417a4e6a67314e4463334e5467774e794973496d316865464e3062334a685a3256436558526c63794936496a45774e4467314e7a596966537769636d56786457567a64456c6b496a6f694d7a4d7a4d7a4d7a4d7a4d744d7a4d7a4d7930304d7a4d7a4c54677a4d7a4d744d7a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4969776963324e6f5a573168496a6f6959574e6a62335675644331686458526f4c5756326157526c626d4e6c4c574a31626d52735a5339324d534973496e4e755958427a614739305357526c626e527064486b694f694a7a614745794e54593659574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859534973496e4e7664584a6a5a557470626d51694f694a5151556c45583068505531524a546b63694c434a7a64574a7a59334a7063485270623235546447463064584d694f694a6859335270646d55694c434a305a573568626e52426458526f62334a7064486c485a57356c636d463061573975496a6f694e534973496e526c626d467564454a7062477870626d64545a5846315a57356a5a534936496a4578496977696447567559573530535751694f6949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694c434a3259584a7059573530496a6f695645564f515535555830395152564a4256456c5054694a3931333a636170616369747944656c7461363a6e756d62657231323a313731313a6175646974526561736f6e363a737472696e673131383a63617061636974792d61646d697373696f6e", + "sha256": "61877a450478b0ce6b980f8d502ff027e5248c736444897c9dc536d924b1ee55", + "commitAllowed": true + }, + { + "name": "present-int64-max", + "capacityDelta": "9223372036854775807", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673131383a63617061636974792d61646d697373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a656374313138323a313a33383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d323232323232323232323232393a726571756573744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a61646d697373696f6e4964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d343434343434343434343434363a746172676574363a6f626a656374313434373a313a3331323a6f776e657253657276696365363a737472696e673132343a776f726c642d6d616e6167656d656e742d7365727669636531353a7461726765744e616d657370616365363a737472696e6731343a70726f6431323a6f776e6572436f6e74657874363a6f626a656374313333323a313a36383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231313a6f7065726174696f6e4964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a6c6966656379636c654964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d34343434343434343434343431343a67616d65496e7374616e63654964363a737472696e673133363a31313131313131312d313131312d343131312d383131312d313131313131313131313131373a6f776e65724964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531303a6f776e657246656e6365363a6e756d62657231313a3731353a657870656374656456657273696f6e363a6f626a656374313130353a313a3231383a61646d697373696f6e417474656d70744964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531383a6361706163697479526561726d46656e6365363a6e756d62657231313a31383a6d75746174696f6e363a6f626a65637431323433383a313a35393a6f7065726174696f6e363a737472696e673131373a43415041434954595f4352454154494e4731303a7072696f725368617065363a6f626a6563743139373a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d62657231313a3031323a73746f726167654279746573363a6e756d62657231313a3031343a7265717565737465645368617065363a6f626a656374313131363a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d6265723131393a3932323333373230333638353437373538303731323a73746f726167654279746573363a6e756d62657231313a3031353a6163636f756e7445766964656e6365363a737472696e6731323034383a65794a68624778766430356c643064686257567762474635516d6c755a476c755a334d694f6e527964575573496d467362473933546d56335357357a64474675593256546447467964484d694f6e527964575573496d4673624739335548566962476c6a536d39706269493664484a315a53776959585630614739796158523551585a6861577868596d6c7361585235496a6f6951565a4253557842516b78464969776959585630614739796158523556485677624755694f6e73696447567559573530515856306147397961585235523256755a584a6864476c7662694936657949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694f694931496e3073496e526c626d467564454a7062477870626d6444645852765a6d59694f6e73694d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a4979496a7037496d393164474a7665464e6c6358566c626d4e6c496a6f694d794973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e526c626d46756445463164476876636d6c306555646c626d567959585270623234694f694931496977696447567559573530516d6c7362476c755a314e6c6358566c626d4e6c496a6f694d544569665831394c434a696457356b624756575a584a7a61573975496a6f694d534973496d4e686247786c636c6476636d74736232466b496a6f69633342705a6d5a6c4f6938765a6d6c795a5731315a43397563793977636d396b4c334e684c336476636d786b4c573168626d466e5a57316c626e517463325679646d6c6a5a534973496d567564476c30624756745a573530566d567963326c7662694936496a63694c434a6c646d4673645746305a57524264434936496a49774d6a59744d5445744d444a554d4441364d4441364d444261496977695a585a686248566864476c76626b6c6b5a57353061585235496a6f69633268684d6a55324f6d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d49694c434a6e5957316c634778686555463259576c7359574a735a53493664484a315a53776962335630596d39345132686c5932747762326c7564484d694f6c7437496d393164474a7665464e6c6358566c626d4e6c496a6f694d794973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e4e7664584a6a5a5556325a57353052476c6e5a584e30496a6f69633268684d6a55324f6d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a7a6233567959325646646d567564456c6b496a6f694d5445784d5445784d5445744d5445784d5330304d5445784c5467784d5445744d5445784d5445784d5445784d544578496e31644c434a77636d393261584e7062323570626d64546447463064584d694f6d353162477773496e4631623352686379493665794a745958684259335270646d56545a584e7a6157397563794936496a45774d434973496d316865454e76626d4e31636e4a6c626e52485957316c5357357a644746755932567a496a6f694f5449794d7a4d334d6a417a4e6a67314e4463334e5467774e794973496d316865464e3062334a685a3256436558526c63794936496a45774e4467314e7a596966537769636d56786457567a64456c6b496a6f694d7a4d7a4d7a4d7a4d7a4d744d7a4d7a4d7930304d7a4d7a4c54677a4d7a4d744d7a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4969776963324e6f5a573168496a6f6959574e6a62335675644331686458526f4c5756326157526c626d4e6c4c574a31626d52735a5339324d534973496e4e755958427a614739305357526c626e527064486b694f694a7a614745794e54593659574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859534973496e4e7664584a6a5a557470626d51694f694a5151556c45583068505531524a546b63694c434a7a64574a7a59334a7063485270623235546447463064584d694f694a6859335270646d55694c434a305a573568626e52426458526f62334a7064486c485a57356c636d463061573975496a6f694e534973496e526c626d467564454a7062477870626d64545a5846315a57356a5a534936496a4578496977696447567559573530535751694f6949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694c434a3259584a7059573530496a6f695645564f515535555830395152564a4256456c5054694a3931333a636170616369747944656c7461363a6e756d6265723131393a3932323333373230333638353437373538303731313a6175646974526561736f6e363a737472696e673131383a63617061636974792d61646d697373696f6e", + "sha256": "04ba8983d5c1b5f82ed29498bbec78a6e4b8390839525112ec2c8c969f1831bc", + "commitAllowed": true + }, + { + "name": "non-expanding-zero", + "capacityDelta": "0", + "operation": "NON_EXPANDING_RECOVERY", + "priorShape": [ + "0", + "1", + "0" + ], + "requestedShape": [ + "0", + "1", + "0" + ], + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673131383a63617061636974792d61646d697373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a656374313138323a313a33383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d323232323232323232323232393a726571756573744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a61646d697373696f6e4964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d343434343434343434343434363a746172676574363a6f626a656374313434373a313a3331323a6f776e657253657276696365363a737472696e673132343a776f726c642d6d616e6167656d656e742d7365727669636531353a7461726765744e616d657370616365363a737472696e6731343a70726f6431323a6f776e6572436f6e74657874363a6f626a656374313333323a313a36383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231313a6f7065726174696f6e4964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a6c6966656379636c654964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d34343434343434343434343431343a67616d65496e7374616e63654964363a737472696e673133363a31313131313131312d313131312d343131312d383131312d313131313131313131313131373a6f776e65724964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531303a6f776e657246656e6365363a6e756d62657231313a3731353a657870656374656456657273696f6e363a6f626a656374313130353a313a3231383a61646d697373696f6e417474656d70744964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531383a6361706163697479526561726d46656e6365363a6e756d62657231313a31383a6d75746174696f6e363a6f626a65637431323430343a313a35393a6f7065726174696f6e363a737472696e673132323a4e4f4e5f455850414e44494e475f5245434f5645525931303a7072696f725368617065363a6f626a6563743139373a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d62657231313a3131323a73746f726167654279746573363a6e756d62657231313a3031343a7265717565737465645368617065363a6f626a6563743139373a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d62657231313a3131323a73746f726167654279746573363a6e756d62657231313a3031353a6163636f756e7445766964656e6365363a737472696e6731323034383a65794a68624778766430356c643064686257567762474635516d6c755a476c755a334d694f6e527964575573496d467362473933546d56335357357a64474675593256546447467964484d694f6e527964575573496d4673624739335548566962476c6a536d39706269493664484a315a53776959585630614739796158523551585a6861577868596d6c7361585235496a6f6951565a4253557842516b78464969776959585630614739796158523556485677624755694f6e73696447567559573530515856306147397961585235523256755a584a6864476c7662694936657949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694f694931496e3073496e526c626d467564454a7062477870626d6444645852765a6d59694f6e73694d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a4979496a7037496d393164474a7665464e6c6358566c626d4e6c496a6f694d794973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e526c626d46756445463164476876636d6c306555646c626d567959585270623234694f694931496977696447567559573530516d6c7362476c755a314e6c6358566c626d4e6c496a6f694d544569665831394c434a696457356b624756575a584a7a61573975496a6f694d534973496d4e686247786c636c6476636d74736232466b496a6f69633342705a6d5a6c4f6938765a6d6c795a5731315a43397563793977636d396b4c334e684c336476636d786b4c573168626d466e5a57316c626e517463325679646d6c6a5a534973496d567564476c30624756745a573530566d567963326c7662694936496a63694c434a6c646d4673645746305a57524264434936496a49774d6a59744d5445744d444a554d4441364d4441364d444261496977695a585a686248566864476c76626b6c6b5a57353061585235496a6f69633268684d6a55324f6d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d49694c434a6e5957316c634778686555463259576c7359574a735a53493664484a315a53776962335630596d39345132686c5932747762326c7564484d694f6c7437496d393164474a7665464e6c6358566c626d4e6c496a6f694d794973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e4e7664584a6a5a5556325a57353052476c6e5a584e30496a6f69633268684d6a55324f6d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a7a6233567959325646646d567564456c6b496a6f694d5445784d5445784d5445744d5445784d5330304d5445784c5467784d5445744d5445784d5445784d5445784d544578496e31644c434a77636d393261584e7062323570626d64546447463064584d694f6d353162477773496e4631623352686379493665794a745958684259335270646d56545a584e7a6157397563794936496a45774d434973496d316865454e76626d4e31636e4a6c626e52485957316c5357357a644746755932567a496a6f694f5449794d7a4d334d6a417a4e6a67314e4463334e5467774e794973496d316865464e3062334a685a3256436558526c63794936496a45774e4467314e7a596966537769636d56786457567a64456c6b496a6f694d7a4d7a4d7a4d7a4d7a4d744d7a4d7a4d7930304d7a4d7a4c54677a4d7a4d744d7a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4969776963324e6f5a573168496a6f6959574e6a62335675644331686458526f4c5756326157526c626d4e6c4c574a31626d52735a5339324d534973496e4e755958427a614739305357526c626e527064486b694f694a7a614745794e54593659574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859534973496e4e7664584a6a5a557470626d51694f694a5151556c45583068505531524a546b63694c434a7a64574a7a59334a7063485270623235546447463064584d694f694a6859335270646d55694c434a305a573568626e52426458526f62334a7064486c485a57356c636d463061573975496a6f694e534973496e526c626d467564454a7062477870626d64545a5846315a57356a5a534936496a4578496977696447567559573530535751694f6949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694c434a3259584a7059573530496a6f695645564f515535555830395152564a4256456c5054694a3931333a636170616369747944656c7461363a6e756d62657231313a3031313a6175646974526561736f6e363a737472696e673131383a63617061636974792d61646d697373696f6e", + "sha256": "c93ecc41111c5440dfa53da14b7a564a5148a5411221abe15251ad59859ee3cb", + "commitAllowed": true + } + ], + "rejected": [ + { + "name": "delta-0", + "capacityDelta": "9223372036854775808", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "delta-1", + "capacityDelta": "-1", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "delta-2", + "capacityDelta": "+1", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "delta-3", + "capacityDelta": "01", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "delta-4", + "capacityDelta": "1e0", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "delta-5", + "capacityDelta": "1.0", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "delta-6", + "capacityDelta": " 1", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "delta-7", + "capacityDelta": "1 ", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "delta-8", + "capacityDelta": 1, + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "delta-9", + "capacityDelta": 0.0, + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + } + ], + "rejectedEvidence": [ + { + "name": "changed-cutoff-without-checkpoint", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null, + "canonicalAccountEvidenceBase64": "eyJhbGxvd05ld0dhbWVwbGF5QmluZGluZ3MiOnRydWUsImFsbG93TmV3SW5zdGFuY2VTdGFydHMiOnRydWUsImFsbG93UHVibGljSm9pbiI6dHJ1ZSwiYXV0aG9yaXR5QXZhaWxhYmlsaXR5IjoiQVZBSUxBQkxFIiwiYXV0aG9yaXR5VHVwbGUiOnsidGVuYW50QXV0aG9yaXR5R2VuZXJhdGlvbiI6eyIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiOiI1In0sInRlbmFudEJpbGxpbmdDdXRvZmYiOnsiMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIjp7Im91dGJveFNlcXVlbmNlIjoiNCIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6dGVuYW50LzIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiIsInRlbmFudEF1dGhvcml0eUdlbmVyYXRpb24iOiI1IiwidGVuYW50QmlsbGluZ1NlcXVlbmNlIjoiMTEifX19LCJidW5kbGVWZXJzaW9uIjoiMSIsImNhbGxlcldvcmtsb2FkIjoic3BpZmZlOi8vZmlyZW11ZC9ucy9wcm9kL3NhL3dvcmxkLW1hbmFnZW1lbnQtc2VydmljZSIsImVudGl0bGVtZW50VmVyc2lvbiI6IjciLCJldmFsdWF0ZWRBdCI6IjIwMjYtMTEtMDJUMDA6MDA6MDBaIiwiZXZhbHVhdGlvbklkZW50aXR5Ijoic2hhMjU2OmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmIiLCJnYW1lcGxheUF2YWlsYWJsZSI6dHJ1ZSwib3V0Ym94Q2hlY2twb2ludHMiOlt7Im91dGJveFNlcXVlbmNlIjoiMyIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6dGVuYW50LzIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiIsInNvdXJjZUV2ZW50RGlnZXN0Ijoic2hhMjU2OmFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLCJzb3VyY2VFdmVudElkIjoiMTExMTExMTEtMTExMS00MTExLTgxMTEtMTExMTExMTExMTExIn1dLCJwcm92aXNpb25pbmdTdGF0dXMiOm51bGwsInF1b3RhcyI6eyJtYXhBY3RpdmVTZXNzaW9ucyI6IjEwMCIsIm1heENvbmN1cnJlbnRHYW1lSW5zdGFuY2VzIjoiOTIyMzM3MjAzNjg1NDc3NTgwNyIsIm1heFN0b3JhZ2VCeXRlcyI6IjEwNDg1NzYifSwicmVxdWVzdElkIjoiMzMzMzMzMzMtMzMzMy00MzMzLTgzMzMtMzMzMzMzMzMzMzMzIiwic2NoZW1hIjoiYWNjb3VudC1hdXRoLWV2aWRlbmNlLWJ1bmRsZS92MSIsInNuYXBzaG90SWRlbnRpdHkiOiJzaGEyNTY6YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsInNvdXJjZUtpbmQiOiJQQUlEX0hPU1RJTkciLCJzdWJzY3JpcHRpb25TdGF0dXMiOiJhY3RpdmUiLCJ0ZW5hbnRBdXRob3JpdHlHZW5lcmF0aW9uIjoiNSIsInRlbmFudEJpbGxpbmdTZXF1ZW5jZSI6IjExIiwidGVuYW50SWQiOiIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiLCJ2YXJpYW50IjoiVEVOQU5UX09QRVJBVElPTiJ9" + }, + { + "name": "noncanonical-evidence-whitespace", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null, + "canonicalAccountEvidenceBase64": "IHsiYWxsb3dOZXdHYW1lcGxheUJpbmRpbmdzIjp0cnVlLCJhbGxvd05ld0luc3RhbmNlU3RhcnRzIjp0cnVlLCJhbGxvd1B1YmxpY0pvaW4iOnRydWUsImF1dGhvcml0eUF2YWlsYWJpbGl0eSI6IkFWQUlMQUJMRSIsImF1dGhvcml0eVR1cGxlIjp7InRlbmFudEF1dGhvcml0eUdlbmVyYXRpb24iOnsiMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIjoiNSJ9LCJ0ZW5hbnRCaWxsaW5nQ3V0b2ZmIjp7IjIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiI6eyJvdXRib3hTZXF1ZW5jZSI6IjMiLCJvdXRib3hTdHJlYW1LZXkiOiJhY2NvdW50OmF1dGgtYXV0aG9yaXR5OnYxOnRlbmFudC8yMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiLCJ0ZW5hbnRBdXRob3JpdHlHZW5lcmF0aW9uIjoiNSIsInRlbmFudEJpbGxpbmdTZXF1ZW5jZSI6IjExIn19fSwiYnVuZGxlVmVyc2lvbiI6IjEiLCJjYWxsZXJXb3JrbG9hZCI6InNwaWZmZTovL2ZpcmVtdWQvbnMvcHJvZC9zYS93b3JsZC1tYW5hZ2VtZW50LXNlcnZpY2UiLCJlbnRpdGxlbWVudFZlcnNpb24iOiI3IiwiZXZhbHVhdGVkQXQiOiIyMDI2LTExLTAyVDAwOjAwOjAwWiIsImV2YWx1YXRpb25JZGVudGl0eSI6InNoYTI1NjpiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiIiwiZ2FtZXBsYXlBdmFpbGFibGUiOnRydWUsIm91dGJveENoZWNrcG9pbnRzIjpbeyJvdXRib3hTZXF1ZW5jZSI6IjMiLCJvdXRib3hTdHJlYW1LZXkiOiJhY2NvdW50OmF1dGgtYXV0aG9yaXR5OnYxOnRlbmFudC8yMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiLCJzb3VyY2VFdmVudERpZ2VzdCI6InNoYTI1NjphYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhIiwic291cmNlRXZlbnRJZCI6IjExMTExMTExLTExMTEtNDExMS04MTExLTExMTExMTExMTExMSJ9XSwicHJvdmlzaW9uaW5nU3RhdHVzIjpudWxsLCJxdW90YXMiOnsibWF4QWN0aXZlU2Vzc2lvbnMiOiIxMDAiLCJtYXhDb25jdXJyZW50R2FtZUluc3RhbmNlcyI6IjkyMjMzNzIwMzY4NTQ3NzU4MDciLCJtYXhTdG9yYWdlQnl0ZXMiOiIxMDQ4NTc2In0sInJlcXVlc3RJZCI6IjMzMzMzMzMzLTMzMzMtNDMzMy04MzMzLTMzMzMzMzMzMzMzMyIsInNjaGVtYSI6ImFjY291bnQtYXV0aC1ldmlkZW5jZS1idW5kbGUvdjEiLCJzbmFwc2hvdElkZW50aXR5Ijoic2hhMjU2OmFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLCJzb3VyY2VLaW5kIjoiUEFJRF9IT1NUSU5HIiwic3Vic2NyaXB0aW9uU3RhdHVzIjoiYWN0aXZlIiwidGVuYW50QXV0aG9yaXR5R2VuZXJhdGlvbiI6IjUiLCJ0ZW5hbnRCaWxsaW5nU2VxdWVuY2UiOiIxMSIsInRlbmFudElkIjoiMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIiwidmFyaWFudCI6IlRFTkFOVF9PUEVSQVRJT04ifQ==" + }, + { + "name": "duplicate-evidence-member", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null, + "canonicalAccountEvidenceBase64": "eyJidW5kbGVWZXJzaW9uIjoiMSIsImFsbG93TmV3R2FtZXBsYXlCaW5kaW5ncyI6dHJ1ZSwiYWxsb3dOZXdJbnN0YW5jZVN0YXJ0cyI6dHJ1ZSwiYWxsb3dQdWJsaWNKb2luIjp0cnVlLCJhdXRob3JpdHlBdmFpbGFiaWxpdHkiOiJBVkFJTEFCTEUiLCJhdXRob3JpdHlUdXBsZSI6eyJ0ZW5hbnRBdXRob3JpdHlHZW5lcmF0aW9uIjp7IjIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiI6IjUifSwidGVuYW50QmlsbGluZ0N1dG9mZiI6eyIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiOnsib3V0Ym94U2VxdWVuY2UiOiIzIiwib3V0Ym94U3RyZWFtS2V5IjoiYWNjb3VudDphdXRoLWF1dGhvcml0eTp2MTp0ZW5hbnQvMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIiwidGVuYW50QXV0aG9yaXR5R2VuZXJhdGlvbiI6IjUiLCJ0ZW5hbnRCaWxsaW5nU2VxdWVuY2UiOiIxMSJ9fX0sImJ1bmRsZVZlcnNpb24iOiIxIiwiY2FsbGVyV29ya2xvYWQiOiJzcGlmZmU6Ly9maXJlbXVkL25zL3Byb2Qvc2Evd29ybGQtbWFuYWdlbWVudC1zZXJ2aWNlIiwiZW50aXRsZW1lbnRWZXJzaW9uIjoiNyIsImV2YWx1YXRlZEF0IjoiMjAyNi0xMS0wMlQwMDowMDowMFoiLCJldmFsdWF0aW9uSWRlbnRpdHkiOiJzaGEyNTY6YmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYiIsImdhbWVwbGF5QXZhaWxhYmxlIjp0cnVlLCJvdXRib3hDaGVja3BvaW50cyI6W3sib3V0Ym94U2VxdWVuY2UiOiIzIiwib3V0Ym94U3RyZWFtS2V5IjoiYWNjb3VudDphdXRoLWF1dGhvcml0eTp2MTp0ZW5hbnQvMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIiwic291cmNlRXZlbnREaWdlc3QiOiJzaGEyNTY6YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsInNvdXJjZUV2ZW50SWQiOiIxMTExMTExMS0xMTExLTQxMTEtODExMS0xMTExMTExMTExMTEifV0sInByb3Zpc2lvbmluZ1N0YXR1cyI6bnVsbCwicXVvdGFzIjp7Im1heEFjdGl2ZVNlc3Npb25zIjoiMTAwIiwibWF4Q29uY3VycmVudEdhbWVJbnN0YW5jZXMiOiI5MjIzMzcyMDM2ODU0Nzc1ODA3IiwibWF4U3RvcmFnZUJ5dGVzIjoiMTA0ODU3NiJ9LCJyZXF1ZXN0SWQiOiIzMzMzMzMzMy0zMzMzLTQzMzMtODMzMy0zMzMzMzMzMzMzMzMiLCJzY2hlbWEiOiJhY2NvdW50LWF1dGgtZXZpZGVuY2UtYnVuZGxlL3YxIiwic25hcHNob3RJZGVudGl0eSI6InNoYTI1NjphYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhIiwic291cmNlS2luZCI6IlBBSURfSE9TVElORyIsInN1YnNjcmlwdGlvblN0YXR1cyI6ImFjdGl2ZSIsInRlbmFudEF1dGhvcml0eUdlbmVyYXRpb24iOiI1IiwidGVuYW50QmlsbGluZ1NlcXVlbmNlIjoiMTEiLCJ0ZW5hbnRJZCI6IjIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiIsInZhcmlhbnQiOiJURU5BTlRfT1BFUkFUSU9OIn0=" + } + ], + "rejectedRequests": [ + { + "name": "delta-10", + "capacityDelta": null, + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "changed-shape", + "requestedShape": [ + "1", + "9223372036854775807", + "0" + ], + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + } + ], + "rejectedUsage": [ + { + "name": "usage-addition-overflow", + "usage": "9223372036854775807", + "held": "0", + "capacityDelta": "1", + "expected": "CAPACITY_QUOTA_EXCEEDED", + "acceptedDigest": null + }, + { + "name": "held-addition-overflow", + "usage": "0", + "held": "9223372036854775807", + "capacityDelta": "1", + "expected": "CAPACITY_QUOTA_EXCEEDED", + "acceptedDigest": null + } + ], + "playerRequest": { + "tenantId": "22222222-2222-4222-8222-222222222222", + "requestId": "33333333-3333-4333-8333-333333333333", + "admissionId": "44444444-4444-4444-8444-444444444444", + "ownerService": "game-session-service", + "targetNamespace": "prod", + "ownerContext": { + "accountId": "11111111-1111-4111-8111-111111111111", + "tenantId": "22222222-2222-4222-8222-222222222222", + "playableStateNamespaceId": "66666666-6666-4666-8666-666666666666", + "gameInstanceId": "77777777-7777-4777-8777-777777777777", + "characterId": "88888888-8888-4888-8888-888888888888", + "sessionId": "99999999-9999-4999-8999-999999999999", + "realmId": "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + "requestId": "33333333-3333-4333-8333-333333333333", + "playableStateScope": "SHARED" + }, + "admissionAttemptId": "55555555-5555-4555-8555-555555555555", + "capacityRearmFence": "1", + "operation": "CAPACITY_CREATING", + "priorShape": [ + "0", + "0", + "0" + ], + "requestedShape": [ + "1", + "0", + "0" + ], + "canonicalAccountEvidenceBase64": "eyJhbGxvd05ld0dhbWVwbGF5QmluZGluZ3MiOnRydWUsImFsbG93TmV3SW5zdGFuY2VTdGFydHMiOnRydWUsImFsbG93UHVibGljSm9pbiI6dHJ1ZSwiYXV0aG9yaXR5QXZhaWxhYmlsaXR5IjoiQVZBSUxBQkxFIiwiYXV0aG9yaXR5U291cmNlRXZpZGVuY2UiOlt7ImNhbm9uaWNhbEV2ZW50SnNvbiI6IntcImV2ZW50RGlnZXN0XCI6XCJzaGEyNTY6MGU4NDI5OTgzM2Q4NTc1NGZhNTgzZTQxNTBmYTdkOTEzNzQ2YjgzYWVlYzM0YTA1NmM0Y2NiNTY2YTE1MGMyNFwiLFwiZXZlbnRJZFwiOlwiZWRiM2JkMzMtODZlMS0zYmZkLTllYjItZjY3ZmZkYzNjOTZiXCIsXCJldmVudFR5cGVcIjpcIlRFTkFOVF9BVVRIT1JJVFlfQ0hBTkdFRFwiLFwib3V0Ym94U2VxdWVuY2VcIjpcIjFcIixcIm91dGJveFN0cmVhbUtleVwiOlwiYWNjb3VudDphdXRoLWF1dGhvcml0eTp2MTp0ZW5hbnQvMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyXCIsXCJyZXF1ZXN0RGlnZXN0XCI6XCJzaGEyNTY6YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYVwiLFwicmVxdWVzdElkXCI6XCIzMzMzMzMzMy0zMzMzLTQzMzMtODMzMy0zMzMzMzMzMzMzMzNcIixcInNjaGVtYVZlcnNpb25cIjpcImFjY291bnQtdGVuYW50LWF1dGhvcml0eS1ldmVudC92MVwiLFwic291cmNlRXZpZGVuY2VcIjp7XCJjYW5vbmljYWxUZW5hbnRJZFwiOlwiMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyXCIsXCJjcmVhdGlvblJlcXVlc3RJZFwiOlwiMzMzMzMzMzMtMzMzMy00MzMzLTgzMzMtMzMzMzMzMzMzMzMzXCIsXCJldmlkZW5jZURpZ2VzdFwiOlwic2hhMjU2OjcxNzQwZWZmNTcxNzI0ZDY3ZmJiMjVjMGY4NzQ1MjYyMzY1NzRmNzI0MjlhODg1OTI2ODljMWFjNDdlODAzY2VcIixcIm9wZXJhdGlvbklkXCI6XCIzMzMzMzMzMy0zMzMzLTQzMzMtODMzMy0zMzMzMzMzMzMzMzNcIixcInByb3ZlbmFuY2VLaW5kXCI6XCJORVdfR0FNRV9ST1dcIixcInJlcXVlc3REaWdlc3RcIjpcInNoYTI1NjpmMDZlNWU1MGJiZGE5OTE3YjNmZGFkOGUyNzczNzA2OTNmNDlhZmMzMzllZWM3Zjc1NDhiMWU1NDEyNTQ2NjkwXCIsXCJzY2hlbWFWZXJzaW9uXCI6MSxcInNvdXJjZUdhbWVSb3dJZFwiOlwiMTdcIixcInNvdXJjZUdhbWVUZW5hbnRLZXlcIjpcIndvcmxkXCIsXCJ0YXJnZXROYW1lc3BhY2VcIjpcInByb2RcIn0sXCJ0ZW5hbnRBdXRob3JpdHlHZW5lcmF0aW9uXCI6XCIyXCIsXCJ0ZW5hbnRBdXRob3JpdHlTb3VyY2VWZXJzaW9uXCI6XCIyXCIsXCJ0ZW5hbnRCaWxsaW5nUmVjZWlwdFwiOntcImV2ZW50RGlnZXN0XCI6XCJzaGEyNTY6YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYVwiLFwiZXZlbnRJZFwiOlwiNWFjMTU4MmItYTQwZC0zNTA1LWFiNDItZjc3NjY1N2I0YjYwXCIsXCJvdXRib3hTdHJlYW1LZXlcIjpcImFjY291bnQ6dGVuYW50LWVudGl0bGVtZW50OnYxOnRlbmFudC8yMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjJcIixcInRlbmFudEJpbGxpbmdTZXF1ZW5jZVwiOlwiMVwifSxcInRlbmFudElkXCI6XCIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjJcIn0iLCJldmVudERpZ2VzdCI6InNoYTI1NjowZTg0Mjk5ODMzZDg1NzU0ZmE1ODNlNDE1MGZhN2Q5MTM3NDZiODNhZWVjMzRhMDU2YzRjY2I1NjZhMTUwYzI0IiwiZXZlbnRJZCI6ImVkYjNiZDMzLTg2ZTEtM2JmZC05ZWIyLWY2N2ZmZGMzYzk2YiIsIm91dGJveFNlcXVlbmNlIjoiMSIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6dGVuYW50LzIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiJ9XSwiYXV0aG9yaXR5VHVwbGUiOnsiYWNjb3VudEF1dGhvcml0eUdlbmVyYXRpb24iOiIxIiwiaXNzdWVyQXV0aEdlbmVyYXRpb24iOiIxIiwibWVtYmVyc2hpcEF1dGhvcml0eUdlbmVyYXRpb24iOnsiMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIjoiMSJ9LCJwcml2YXRlUmVhbG1HcmFudFZlcnNpb25zIjpbXSwidGVuYW50QXV0aG9yaXR5R2VuZXJhdGlvbiI6eyIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiOiIyIn0sInRlbmFudEJpbGxpbmdDdXRvZmYiOnsiMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIjp7Im91dGJveFNlcXVlbmNlIjoiMSIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6dGVuYW50LzIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiIsInRlbmFudEF1dGhvcml0eUdlbmVyYXRpb24iOiIyIiwidGVuYW50QmlsbGluZ1NlcXVlbmNlIjoiMSJ9fX0sImJ1bmRsZVZlcnNpb24iOiIyIiwiY2FsbGVyQWNjb3VudElkIjoiMTExMTExMTEtMTExMS00MTExLTgxMTEtMTExMTExMTExMTExIiwiY2FsbGVyV29ya2xvYWQiOiJzcGlmZmU6Ly9maXJlbXVkL25zL3Byb2Qvc2EvZ2FtZS1zZXNzaW9uLXNlcnZpY2UiLCJlbnRpdGxlbWVudFZlcnNpb24iOiIxIiwiZXZhbHVhdGVkQXQiOiIyMDI2LTExLTAyVDAwOjAwOjAwWiIsImV2YWx1YXRpb25JZGVudGl0eSI6InNoYTI1NjpkYWY2MTU0MjQwNWE1MmMwOTY5OTRiNWRiODk5NmRhNGJhOWJiNWFhOGI4ZjU2YjY4YjY4NWJjNTU4NTdjYjM4IiwiZ2FtZXBsYXlBZG1pc3Npb25BbGxvd2VkIjpmYWxzZSwiZ2FtZXBsYXlBdmFpbGFibGUiOnRydWUsImlzc3VhbmNlRmVuY2UiOiIxIiwiaXNzdWVyIjoiZmlyZW11ZC1hY2NvdW50LXNlcnZpY2UiLCJtZW1iZXJzaGlwQXV0aG9yaXR5R2VuZXJhdGlvbiI6IjEiLCJtZW1iZXJzaGlwRXhpc3RzIjpmYWxzZSwibWVtYmVyc2hpcExpZmVjeWNsZVN0YXRlIjoiTUlTU0lORyIsIm1lbWJlcnNoaXBWZXJzaW9uIjp7IjIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiI6IjEifSwib3V0Ym94Q2hlY2twb2ludHMiOlt7Im91dGJveFNlcXVlbmNlIjoiMCIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6YWNjb3VudC8xMTExMTExMS0xMTExLTQxMTEtODExMS0xMTExMTExMTExMTEifSx7Im91dGJveFNlcXVlbmNlIjoiMCIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6aXNzdWVyL2ZpcmVtdWQtYWNjb3VudC1zZXJ2aWNlIn0seyJvdXRib3hTZXF1ZW5jZSI6IjAiLCJvdXRib3hTdHJlYW1LZXkiOiJhY2NvdW50OmF1dGgtYXV0aG9yaXR5OnYxOm1lbWJlcnNoaXAvMTExMTExMTEtMTExMS00MTExLTgxMTEtMTExMTExMTExMTExLzIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiJ9LHsib3V0Ym94U2VxdWVuY2UiOiIxIiwib3V0Ym94U3RyZWFtS2V5IjoiYWNjb3VudDphdXRoLWF1dGhvcml0eTp2MTp0ZW5hbnQvMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIiwic291cmNlRXZlbnREaWdlc3QiOiJzaGEyNTY6MGU4NDI5OTgzM2Q4NTc1NGZhNTgzZTQxNTBmYTdkOTEzNzQ2YjgzYWVlYzM0YTA1NmM0Y2NiNTY2YTE1MGMyNCIsInNvdXJjZUV2ZW50SWQiOiJlZGIzYmQzMy04NmUxLTNiZmQtOWViMi1mNjdmZmRjM2M5NmIifV0sInByb3Zpc2lvbmluZ1N0YXR1cyI6bnVsbCwicXVvdGFzIjp7Im1heEFjdGl2ZVNlc3Npb25zIjoiMyIsIm1heENvbmN1cnJlbnRHYW1lSW5zdGFuY2VzIjoiMiIsIm1heFN0b3JhZ2VCeXRlcyI6IjQwOTYifSwicmVxdWVzdElkIjoiMzMzMzMzMzMtMzMzMy00MzMzLTgzMzMtMzMzMzMzMzMzMzMzIiwicm9sZXMiOltdLCJzY2hlbWEiOiJhY2NvdW50LWF1dGgtZXZpZGVuY2UtYnVuZGxlL3YxIiwic25hcHNob3RJZGVudGl0eSI6InNoYTI1NjphNmQ4ZjBjOTU3NTFjMDdkNzExOTlmZGE2ZjFjYjU4MzgyY2ZkODM0NWM2MTllYWIxM2E3MWE1M2MyMmU5YTVjIiwic291cmNlS2luZCI6Ik5PTl9QQUlEX0RFTU8iLCJzb3VyY2VSZWZlcmVuY2VzIjp7ImFkbWlzc2lvblBvaW50ZXJTbmFwc2hvdERpZ2VzdCI6ImFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLCJjYWxsZXJDb21taXRQcm9vZlNoYTI1NiI6ImFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLCJjYWxsZXJDb250ZXh0SWQiOiIzMzMzMzMzMy0zMzMzLTQzMzMtODMzMy0zMzMzMzMzMzMzMzMiLCJjYWxsZXJPcGVyYXRpb25JZCI6IjMzMzMzMzMzLTMzMzMtNDMzMy04MzMzLTMzMzMzMzMzMzMzMyIsImNhbGxlclJlZ2lzdHJ5UmVjb3JkU2hhMjU2IjoiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsImNhbGxlclRva2VuRXhwaXJlc0F0IjoiMjAyNi0xMS0wMlQwMDowMTozMFoiLCJjYWxsZXJUb2tlbkp0aSI6IjMzMzMzMzMzLTMzMzMtNDMzMy04MzMzLTMzMzMzMzMzMzMzMyIsImNhbGxlclRva2VuU2hhMjU2IjoiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsImVudGl0bGVtZW50U291cmNlRGlnZXN0Ijoic2hhMjU2OmFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLCJnYW1lU2Vzc2lvbk93bmVyUHJvb2ZEaWdlc3QiOiJzaGEyNTY6YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsInBhaWRSZWNlaXB0VmFsaWRVbnRpbCI6bnVsbCwicHVibGlzaGVkUG9saWN5U2V0RGlnZXN0Ijoic2hhMjU2OmFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLCJzY29wZURpZ2VzdCI6InNoYTI1NjphYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhIiwid29ybGRDYXB0dXJlSWQiOiIzMzMzMzMzMy0zMzMzLTQzMzMtODMzMy0zMzMzMzMzMzMzMzMiLCJ3b3JsZExpZmVjeWNsZURpZ2VzdCI6InNoYTI1NjphYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhIiwid29ybGRSb3dWZXJzaW9uIjoiMCJ9LCJzdWJzY3JpcHRpb25TdGF0dXMiOm51bGwsInRhcmdldCI6eyJhY3RpdmVXb3JsZEVwb2NoIjoiNSIsImNhbm9uaWNhbFZlcnNpb25JZCI6IjMzMzMzMzMzLTMzMzMtNDMzMy04MzMzLTMzMzMzMzMzMzMzMyIsImNhdGFsb2dSZXZpc2lvbiI6IjciLCJjaGFyYWN0ZXJDcmVhdGlvblBvbGljeSI6IlBSRVNFRURFRF9PTkxZIiwiY29ubmVjdFNjb3BlRXhwaXJlc0F0IjoiMjAyNi0xMS0wMlQwMDowMjowMFoiLCJldmFsdWF0ZWRBdCI6IjIwMjYtMTEtMDFUMjM6NTk6NDBaIiwiZ2FtZUluc3RhbmNlSWQiOiI3Nzc3Nzc3Ny03Nzc3LTQ3NzctODc3Ny03Nzc3Nzc3Nzc3NzciLCJwbGF5YWJsZVN0YXRlTmFtZXNwYWNlSWQiOiI2NjY2NjY2Ni02NjY2LTQ2NjYtODY2Ni02NjY2NjY2NjY2NjYiLCJwbGF5YWJsZVN0YXRlU2NvcGUiOiJTSEFSRUQiLCJwb2ludGVyVmVyc2lvbiI6IjMiLCJyZWFsbUlkIjoiYWFhYWFhYWEtYWFhYS00YWFhLThhYWEtYWFhYWFhYWFhYWFhIiwicmVhbG1TbHVnIjoicHJvZHVjdGlvbiIsInRhcmdldENsYXNzIjoiUFVCTElDX1BST0RVQ1RJT04iLCJ0YXJnZXROYW1lc3BhY2UiOiJwcm9kIiwidGVuYW50SWQiOiIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiLCJ0ZW5hbnRTbHVnIjoidGVuYW50Iiwid29ybGRTbHVnIjoid29ybGQifSwidGVuYW50QXV0aG9yaXR5R2VuZXJhdGlvbiI6IjIiLCJ0ZW5hbnRCaWxsaW5nU2VxdWVuY2UiOiIxIiwidGVuYW50SWQiOiIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiLCJ2YWxpZFVudGlsIjoiMjAyNi0xMS0wMlQwMDowMTozMFoiLCJ2YXJpYW50IjoiUExBWUVSX0FETUlTU0lPTiIsInZlcmlmaWVkQ29ubmVjdFNjb3BlVG9rZW5IYXNoIjoic2hhMjU2OjIyZjhhNGExOTIzNTMzNGVmZDAzNThjOTM2M2MyZTkzYzc5OWJkNWQ4NDkzODkxODk5MmExM2E3MDRiMDUzNjIifQ==" + }, + "playerVector": { + "name": "distinct-player-admission-positive", + "capacityDelta": "1", + "commitAllowed": true, + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673131383a63617061636974792d61646d697373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a656374313138323a313a33383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d323232323232323232323232393a726571756573744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a61646d697373696f6e4964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d343434343434343434343434363a746172676574363a6f626a656374313634363a313a3331323a6f776e657253657276696365363a737472696e673132303a67616d652d73657373696f6e2d7365727669636531353a7461726765744e616d657370616365363a737472696e6731343a70726f6431323a6f776e6572436f6e74657874363a6f626a656374313533353a313a39393a6163636f756e744964363a737472696e673133363a31313131313131312d313131312d343131312d383131312d313131313131313131313131383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323232343a706c617961626c6553746174654e616d6573706163654964363a737472696e673133363a36363636363636362d363636362d343636362d383636362d36363636363636363636363631343a67616d65496e7374616e63654964363a737472696e673133363a37373737373737372d373737372d343737372d383737372d37373737373737373737373731313a6368617261637465724964363a737472696e673133363a38383838383838382d383838382d343838382d383838382d383838383838383838383838393a73657373696f6e4964363a737472696e673133363a39393939393939392d393939392d343939392d383939392d393939393939393939393939373a7265616c6d4964363a737472696e673133363a61616161616161612d616161612d346161612d386161612d616161616161616161616161393a726571756573744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331383a706c617961626c65537461746553636f7065363a737472696e6731363a53484152454431353a657870656374656456657273696f6e363a6f626a656374313130353a313a3231383a61646d697373696f6e417474656d70744964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531383a6361706163697479526561726d46656e6365363a6e756d62657231313a31383a6d75746174696f6e363a6f626a65637431383533393a313a35393a6f7065726174696f6e363a737472696e673131373a43415041434954595f4352454154494e4731303a7072696f725368617065363a6f626a6563743139373a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d62657231313a3031323a73746f726167654279746573363a6e756d62657231313a3031343a7265717565737465645368617065363a6f626a6563743139373a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3132333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d62657231313a3031323a73746f726167654279746573363a6e756d62657231313a3031353a6163636f756e7445766964656e6365363a737472696e6731383138383a65794a68624778766430356c643064686257567762474635516d6c755a476c755a334d694f6e527964575573496d467362473933546d56335357357a64474675593256546447467964484d694f6e527964575573496d4673624739335548566962476c6a536d39706269493664484a315a53776959585630614739796158523551585a6861577868596d6c7361585235496a6f6951565a4253557842516b78464969776959585630614739796158523555323931636d4e6c52585a705a475675593255694f6c7437496d4e68626d397561574e68624556325a573530536e4e7662694936496e7463496d56325a57353052476c6e5a584e305843493658434a7a614745794e5459364d4755344e4449354f54677a4d3251344e5463314e475a684e54677a5a5451784e54426d5954646b4f54457a4e7a5132596a677a5957566c597a4d30595441314e6d4d3059324e694e545932595445314d474d794e4677694c4677695a585a6c626e524a5a4677694f6c77695a5752694d324a6b4d7a4d744f445a6c4d53307a596d5a6b4c546c6c596a49745a6a59335a6d5a6b597a4e6a4f545a695843497358434a6c646d56756446523563475663496a7063496c5246546b464f564639425656524954314a4a56466c6651306842546b6446524677694c46776962335630596d3934553256786457567559325663496a7063496a466349697863496d393164474a7665464e30636d56686255746c655677694f6c776959574e6a62335675644470686458526f4c57463164476876636d6c30655470324d5470305a573568626e51764d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a49795843497358434a795a5846315a584e3052476c6e5a584e305843493658434a7a614745794e545936595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595677694c467769636d56786457567a64456c6b584349365843497a4d7a4d7a4d7a4d7a4d79307a4d7a4d7a4c54517a4d7a4d744f444d7a4d79307a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4e6349697863496e4e6a6147567459565a6c636e4e7062323563496a7063496d466a59323931626e517464475675595735304c57463164476876636d6c306553316c646d5675644339324d5677694c46776963323931636d4e6c52585a705a47567559325663496a703758434a6a59573576626d6c6a595778555a573568626e524a5a4677694f6c77694d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a49795843497358434a6a636d566864476c76626c4a6c6358566c6333524a5a4677694f6c77694d7a4d7a4d7a4d7a4d7a4d744d7a4d7a4d7930304d7a4d7a4c54677a4d7a4d744d7a4d7a4d7a4d7a4d7a4d7a4d7a4d7a5843497358434a6c646d6c6b5a57356a5a5552705a32567a644677694f6c7769633268684d6a55324f6a63784e7a51775a575a6d4e5463784e7a49305a4459335a6d4a694d6a566a4d4759344e7a51314d6a59794d7a59314e7a526d4e7a49304d6a6c684f4467314f5449324f446c6a4d57466a4e44646c4f44417a5932566349697863496d39775a584a6864476c76626b6c6b584349365843497a4d7a4d7a4d7a4d7a4d79307a4d7a4d7a4c54517a4d7a4d744f444d7a4d79307a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4e6349697863496e427962335a6c626d46755932564c6157356b5843493658434a4f525664665230464e525639535431646349697863496e4a6c6358566c633352456157646c63335263496a7063496e4e6f595449314e6a706d4d445a6c4e5755314d474a695a4745354f544533596a4e6d5a47466b4f4755794e7a637a4e7a41324f544e6d4e446c685a6d4d7a4d7a6c6c5a574d335a6a63314e4468694d5755314e4445794e5451324e6a6b775843497358434a7a5932686c625746575a584a7a61573975584349364d537863496e4e7664584a6a5a556468625756536233644a5a4677694f6c77694d54646349697863496e4e7664584a6a5a556468625756555a573568626e524c5a586c63496a7063496e6476636d786b5843497358434a3059584a6e5a58524f5957316c6333426859325663496a7063496e427962325263496e307358434a305a573568626e52426458526f62334a7064486c485a57356c636d46306157397558434936584349795843497358434a305a573568626e52426458526f62334a7064486c5462335679593256575a584a7a6157397558434936584349795843497358434a305a573568626e5243615778736157356e556d566a5a576c77644677694f6e7463496d56325a57353052476c6e5a584e305843493658434a7a614745794e545936595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595677694c4677695a585a6c626e524a5a4677694f6c77694e57466a4d5455344d6d4974595451775a43307a4e5441314c5746694e4449745a6a63334e6a59314e324930596a59775843497358434a76645852696233685464484a6c5957314c5a586c63496a7063496d466a59323931626e513664475675595735304c57567564476c30624756745a5735304f6e59784f6e526c626d4675644338794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a4a6349697863496e526c626d467564454a7062477870626d64545a5846315a57356a5a5677694f6c77694d56776966537863496e526c626d467564456c6b58434936584349794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a4a63496e30694c434a6c646d5675644552705a32567a64434936496e4e6f595449314e6a6f775a5467304d6a6b354f444d7a5a4467314e7a55305a6d45314f444e6c4e4445314d475a684e3251354d544d334e445a694f444e685a57566a4d7a52684d445532597a526a593249314e6a5a684d545577597a4930496977695a585a6c626e524a5a434936496d566b596a4e695a444d7a4c5467325a5445744d324a6d5a4330355a5749794c5759324e325a6d5a474d7a597a6b3259694973496d393164474a7665464e6c6358566c626d4e6c496a6f694d534973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694a395853776959585630614739796158523556485677624755694f6e736959574e6a623356756445463164476876636d6c306555646c626d567959585270623234694f6949784969776961584e7a64575679515856306145646c626d567959585270623234694f6949784969776962575674596d5679633268706345463164476876636d6c306555646c626d567959585270623234694f6e73694d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a4979496a6f694d534a394c434a77636d6c325958526c556d566862473148636d467564465a6c636e4e706232357a496a7062585377696447567559573530515856306147397961585235523256755a584a6864476c7662694936657949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694f694979496e3073496e526c626d467564454a7062477870626d6444645852765a6d59694f6e73694d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a4979496a7037496d393164474a7665464e6c6358566c626d4e6c496a6f694d534973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e526c626d46756445463164476876636d6c306555646c626d567959585270623234694f694979496977696447567559573530516d6c7362476c755a314e6c6358566c626d4e6c496a6f694d534a3966583073496d4a31626d52735a565a6c636e4e70623234694f69497949697769593246736247567951574e6a6233567564456c6b496a6f694d5445784d5445784d5445744d5445784d5330304d5445784c5467784d5445744d5445784d5445784d5445784d5445784969776959324673624756795632397961327876595751694f694a7a63476c6d5a6d55364c79396d61584a6c6258566b4c32357a4c33427962325176633245765a3246745a53317a5a584e7a615739754c584e6c636e5a70593255694c434a6c626e52706447786c6257567564465a6c636e4e70623234694f694978496977695a585a68624856686447566b515851694f6949794d4449324c5445784c544179564441774f6a41774f6a417757694973496d563259577831595852706232354a5a47567564476c3065534936496e4e6f595449314e6a706b595759324d5455304d6a51774e5745314d6d4d774f5459354f5452694e5752694f446b354e6d52684e474a684f574a694e5746684f4749345a6a5532596a5934596a59344e574a6a4e5455344e54646a596a4d34496977695a3246745a58427359586c425a47317063334e7062323542624778766432566b496a706d5957787a5a5377695a3246745a58427359586c42646d467062474669624755694f6e527964575573496d6c7a63335668626d4e6c526d5675593255694f6949784969776961584e7a64575679496a6f695a6d6c795a5731315a43316859324e76645735304c584e6c636e5a70593255694c434a745a5731695a584a7a61476c77515856306147397961585235523256755a584a6864476c7662694936496a45694c434a745a5731695a584a7a61476c77525868706333527a496a706d5957787a5a53776962575674596d567963326870634578705a6d566a65574e735a564e305958526c496a6f6954556c5455306c4f52794973496d316c62574a6c636e4e6f615842575a584a7a61573975496a7037496a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694936496a45696653776962335630596d39345132686c5932747762326c7564484d694f6c7437496d393164474a7665464e6c6358566c626d4e6c496a6f694d434973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453659574e6a62335675644338784d5445784d5445784d5330784d5445784c5451784d5445744f4445784d5330784d5445784d5445784d5445784d54456966537837496d393164474a7665464e6c6358566c626d4e6c496a6f694d434973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453661584e7a645756794c325a70636d56746457517459574e6a623356756443317a5a584a3261574e6c496e307365794a7664585269623368545a5846315a57356a5a534936496a41694c434a76645852696233685464484a6c5957314c5a586b694f694a6859324e76645735304f6d4631644767745958563061473979615852354f6e59784f6d316c62574a6c636e4e6f615841764d5445784d5445784d5445744d5445784d5330304d5445784c5467784d5445744d5445784d5445784d5445784d5445784c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694a394c48736962335630596d39345532567864575675593255694f6949784969776962335630596d3934553352795a57467453325635496a6f6959574e6a62335675644470686458526f4c57463164476876636d6c30655470324d5470305a573568626e51764d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a49794969776963323931636d4e6c52585a6c626e52456157646c633351694f694a7a614745794e5459364d4755344e4449354f54677a4d3251344e5463314e475a684e54677a5a5451784e54426d5954646b4f54457a4e7a5132596a677a5957566c597a4d30595441314e6d4d3059324e694e545932595445314d474d794e434973496e4e7664584a6a5a5556325a573530535751694f694a6c5a47497a596d517a4d7930344e6d55784c544e695a6d51744f5756694d69316d4e6a646d5a6d526a4d324d354e6d496966563073496e427962335a7063326c76626d6c755a314e305958523163794936626e567362437769635856766447467a496a7037496d31686545466a64476c325a564e6c63334e706232357a496a6f694d794973496d316865454e76626d4e31636e4a6c626e52485957316c5357357a644746755932567a496a6f694d694973496d316865464e3062334a685a3256436558526c63794936496a51774f54596966537769636d56786457567a64456c6b496a6f694d7a4d7a4d7a4d7a4d7a4d744d7a4d7a4d7930304d7a4d7a4c54677a4d7a4d744d7a4d7a4d7a4d7a4d7a4d7a4d7a4d7a49697769636d39735a584d694f6c74644c434a7a5932686c625745694f694a6859324e76645735304c574631644767745a585a705a47567559325574596e56755a47786c4c335978496977696332356863484e6f6233524a5a47567564476c3065534936496e4e6f595449314e6a70684e6d51345a6a426a4f5455334e54466a4d44646b4e7a45784f546c6d5a4745325a6a466a596a55344d7a677959325a6b4f444d304e574d324d546c6c595749784d3245334d5745314d324d794d6d55355954566a4969776963323931636d4e6c53326c755a434936496b3550546c395151556c4558305246545538694c434a7a62335679593256535a575a6c636d56755932567a496a7037496d466b62576c7a63326c76626c4276615735305a584a54626d467763326876644552705a32567a64434936496d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a6a595778735a584a446232317461585251636d39765a6c4e6f595449314e694936496d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a6a595778735a584a44623235305a586830535751694f69497a4d7a4d7a4d7a4d7a4d79307a4d7a4d7a4c54517a4d7a4d744f444d7a4d79307a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4d694c434a6a595778735a584a5063475679595852706232354a5a434936496a4d7a4d7a4d7a4d7a4d7a4c544d7a4d7a4d744e444d7a4d7930344d7a4d7a4c544d7a4d7a4d7a4d7a4d7a4d7a4d7a4d794973496d4e686247786c636c4a6c5a326c7a64484a35556d566a62334a6b553268684d6a5532496a6f6959574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859534973496d4e686247786c636c5276613256755258687761584a6c63304630496a6f694d6a41794e6930784d5330774d6c51774d446f774d546f7a4d466f694c434a6a595778735a584a556232746c626b703061534936496a4d7a4d7a4d7a4d7a4d7a4c544d7a4d7a4d744e444d7a4d7930344d7a4d7a4c544d7a4d7a4d7a4d7a4d7a4d7a4d7a4d794973496d4e686247786c636c527661325675553268684d6a5532496a6f6959574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859534973496d567564476c30624756745a57353055323931636d4e6c52476c6e5a584e30496a6f69633268684d6a55324f6d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a6e5957316c5532567a63326c76626b3933626d567955484a7662325a456157646c633351694f694a7a614745794e54593659574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859534973496e4268615752535a574e6c61584230566d467361575256626e527062434936626e5673624377696348566962476c7a6147566b5547397361574e355532563052476c6e5a584e30496a6f69633268684d6a55324f6d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a7a593239775a5552705a32567a64434936496e4e6f595449314e6a70685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746684969776964323979624752445958423064584a6c535751694f69497a4d7a4d7a4d7a4d7a4d79307a4d7a4d7a4c54517a4d7a4d744f444d7a4d79307a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4d694c434a3362334a735a4578705a6d566a65574e735a5552705a32567a64434936496e4e6f595449314e6a7068595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668496977696432397962475253623364575a584a7a61573975496a6f694d434a394c434a7a64574a7a59334a7063485270623235546447463064584d694f6d353162477773496e5268636d646c6443493665794a6859335270646d565862334a735a45567762324e6f496a6f694e534973496d4e68626d397561574e6862465a6c636e4e706232354a5a434936496a4d7a4d7a4d7a4d7a4d7a4c544d7a4d7a4d744e444d7a4d7930344d7a4d7a4c544d7a4d7a4d7a4d7a4d7a4d7a4d7a4d794973496d4e6864474673623264535a585a7063326c7662694936496a63694c434a6a6147467959574e305a584a44636d566864476c76626c427662476c6a65534936496c425352564e465255524652463950546b785a4969776959323975626d566a64464e6a6233426c5258687761584a6c63304630496a6f694d6a41794e6930784d5330774d6c51774d446f774d6a6f774d466f694c434a6c646d4673645746305a57524264434936496a49774d6a59744d5445744d4446554d6a4d364e546b364e444261496977695a3246745a556c7563335268626d4e6c535751694f6949334e7a63334e7a63334e7930334e7a63334c5451334e7a63744f4463334e7930334e7a63334e7a63334e7a63334e7a63694c434a776247463559574a735a564e305958526c546d46745a584e7759574e6c535751694f6949324e6a59324e6a59324e6930324e6a59324c5451324e6a59744f4459324e6930324e6a59324e6a59324e6a59324e6a59694c434a776247463559574a735a564e305958526c55324e76634755694f694a5453454653525551694c434a7762326c7564475679566d567963326c7662694936496a4d694c434a795a57467362556c6b496a6f695957466859574668595745745957466859533030595746684c546868595745745957466859574668595746685957466849697769636d5668624731546248566e496a6f6963484a765a48566a64476c7662694973496e5268636d646c64454e7359584e7a496a6f695546564354456c4458314253543052565131524a543034694c434a3059584a6e5a58524f5957316c63334268593255694f694a77636d396b496977696447567559573530535751694f6949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694c434a305a573568626e52546248566e496a6f6964475675595735304969776964323979624752546248566e496a6f696432397962475169665377696447567559573530515856306147397961585235523256755a584a6864476c7662694936496a49694c434a305a573568626e5243615778736157356e5532567864575675593255694f694978496977696447567559573530535751694f6949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694c434a32595778705a46567564476c73496a6f694d6a41794e6930784d5330774d6c51774d446f774d546f7a4d466f694c434a3259584a7059573530496a6f6955457842575556535830464554556c5455306c5054694973496e5a6c636d6c6d6157566b51323975626d566a64464e6a6233426c564739725a57354959584e6f496a6f69633268684d6a55324f6a49795a6a68684e4745784f54497a4e544d7a4e47566d5a44417a4e54686a4f544d324d324d795a546b7a597a63354f574a6b4e5751344e446b7a4f446b784f446b354d6d45784d3245334d4452694d44557a4e6a496966513d3d31333a636170616369747944656c7461363a6e756d62657231313a3131313a6175646974526561736f6e363a737472696e673131383a63617061636974792d61646d697373696f6e", + "sha256": "a78250cc70a4da7ce2933e504d1ab4d773746ff4b5a21acd18510d24b412c735" + } +} diff --git a/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py b/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py new file mode 100644 index 0000000000..4adf3aa94a --- /dev/null +++ b/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py @@ -0,0 +1,252 @@ +"""Independent capacity-admission/1 corpus consumer. Encoding proof, not runtime authority.""" +import base64 +import copy +import hashlib +import json +import re +import sys +import unicodedata +import unittest +from pathlib import Path + +MAX = 9223372036854775807 +REPOSITORY = Path(__file__).resolve().parents[6] +sys.path.insert(0, str(REPOSITORY / "dev-tools")) + +from evidence_digest import canonical_json_bytes + + +def decimal(value): + if not isinstance(value, str) or not re.fullmatch(r"0|[1-9][0-9]{0,18}", value): + raise ValueError("canonical int64 decimal string required") + result = int(value) + if result > MAX: + raise ValueError("int64 overflow") + return result + + +def segment(value): + if len(value) > 393216: + raise ValueError("segment bound") + return str(len(value)).encode("ascii") + b":" + value + + +def value(kind, payload, present=True): + return segment(kind.encode("ascii")) + (b"1" if present else b"0") + segment(payload) + + +def string(text): + encoded = unicodedata.normalize("NFC", text).encode("utf-8", "strict") + if len(encoded) > 360448: + raise ValueError("string bound") + return value("string", encoded) + + +def number(text): + return value("number", str(decimal(text)).encode("ascii")) + + +def obj(fields): + return value("object", segment(str(len(fields)).encode("ascii")) + b"".join( + segment(key.encode("ascii")) + item for key, item in fields)) + + +def shape(values): + return obj(list(zip(("activeSessions", "concurrentGameInstances", "storageBytes"), + (number(v) for v in values)))) + + +def reject_duplicates(pairs): + result = {} + for key, item in pairs: + if key in result: + raise ValueError("duplicate member") + result[key] = item + return result + + +def reject_nonfinite(token): + raise ValueError("non-finite JSON constant") + + +def evidence(encoded, variant="TENANT_OPERATION"): + raw = base64.b64decode(encoded, validate=True) + if base64.b64encode(raw).decode("ascii") != encoded: + raise ValueError("canonical padded base64 required") + if not 0 < len(raw) <= 262144: + raise ValueError("evidence bound") + parsed = json.loads(raw.decode("utf-8", "strict"), object_pairs_hook=reject_duplicates, + parse_constant=reject_nonfinite) + try: + canonical = canonical_json_bytes(parsed) + except TypeError as error: + raise ValueError("canonical evidence values required") from error + if raw != canonical or parsed["schema"] != "account-auth-evidence-bundle/v1" or parsed["variant"] != variant: + raise ValueError("exact canonical variant required") + tenant = parsed["tenantId"] + cutoff = parsed["authorityTuple"]["tenantBillingCutoff"][tenant] + points = parsed["outboxCheckpoints"] + matching = [point for point in points if point["outboxStreamKey"] == cutoff["outboxStreamKey"]] + if (variant == "TENANT_OPERATION" and len(points) != 1) or len(matching) != 1 or any( + cutoff[k] != matching[0][k] for k in ("outboxStreamKey", "outboxSequence")): + raise ValueError("cutoff checkpoint mismatch") + return encoded + + +def preimage(request, candidate): + context = request["ownerContext"] + if request["ownerService"] == "game-session-service": + variant = "PLAYER_ADMISSION" + owner_fields = [(key, string(context[key])) for key in + ("accountId", "tenantId", "playableStateNamespaceId", "gameInstanceId", + "characterId", "sessionId", "realmId", "requestId", "playableStateScope")] + elif request["ownerService"] == "world-management-service": + variant = "TENANT_OPERATION" + owner_fields = [(key, string(context[key])) for key in + ("tenantId", "operationId", "lifecycleId", "gameInstanceId", "ownerId")] + owner_fields.append(("ownerFence", number(context["ownerFence"]))) + else: + raise ValueError("known owner service required") + fields = [ + ("actionFamilySchemaId", string("capacity-admission")), + ("actionFamilySchemaVersion", string("1")), + ("scope", obj([(key, string(request[key])) for key in ("tenantId", "requestId", "admissionId")])), + ("target", obj([("ownerService", string(request["ownerService"])), + ("targetNamespace", string(request["targetNamespace"])), + ("ownerContext", obj(owner_fields))])), + ("expectedVersion", obj([("admissionAttemptId", string(request["admissionAttemptId"])), + ("capacityRearmFence", number(request["capacityRearmFence"]))])), + ("mutation", obj([("operation", string(candidate.get("operation", request["operation"]))), + ("priorShape", shape(candidate.get("priorShape", request["priorShape"]))), + ("requestedShape", shape(candidate.get("requestedShape", request["requestedShape"]))), + ("accountEvidence", string(evidence(request["canonicalAccountEvidenceBase64"], variant))), + ("capacityDelta", value("absent", b"", False) if candidate["capacityDelta"] is None + else number(candidate["capacityDelta"]))])), + ("auditReason", string("capacity-admission"))] + result = segment(b"mutationDigest/v1") + b"".join(segment(key.encode("ascii")) + item for key, item in fields) + if len(result) > 524288: + raise ValueError("preimage bound") + return result + + +class CapacityAdmissionVectors(unittest.TestCase): + def test_evidence_uses_restricted_jcs_bytes(self): + # UTF-16 ordering places the supplementary key before U+E000, unlike code-point sorting. + value = {"\ue000": "bmp", "\U00010000": "supplementary"} + self.assertEqual(canonical_json_bytes(value), + '{"\U00010000":"supplementary","\ue000":"bmp"}'.encode("utf-8")) + + corpus = json.loads(Path(__file__).with_name("capacity-admission-v1-vectors.json").read_text()) + parsed = json.loads(base64.b64decode(corpus["request"]["canonicalAccountEvidenceBase64"])) + parsed["fractional"] = 1.0 + noncanonical_numeric = json.dumps(parsed, sort_keys=True, ensure_ascii=False, + separators=(",", ":")).encode("utf-8") + encoded = base64.b64encode(noncanonical_numeric).decode("ascii") + with self.assertRaisesRegex(ValueError, "canonical evidence values"): + evidence(encoded) + + parsed.pop("fractional") + parsed["\ue000"] = "bmp" + parsed["\U00010000"] = "supplementary" + codepoint_ordered = json.dumps(parsed, sort_keys=True, ensure_ascii=False, + separators=(",", ":")).encode("utf-8") + encoded = base64.b64encode(codepoint_ordered).decode("ascii") + with self.assertRaisesRegex(ValueError, "exact canonical variant"): + evidence(encoded) + + def test_shared_golden_preimages_and_digests(self): + corpus = json.loads(Path(__file__).with_name("capacity-admission-v1-vectors.json").read_text()) + digests = [] + for candidate in corpus["vectors"]: + with self.subTest(candidate["name"]): + encoded = preimage(corpus["request"], candidate) + self.assertEqual(encoded.hex(), candidate["preimageHex"]) + digest = hashlib.sha256(encoded).hexdigest() + self.assertEqual(digest, candidate["sha256"]) + digests.append(digest) + self.assertNotEqual(digests[0], digests[1]) + + def test_player_golden_preimage_and_each_player_identity(self): + corpus = json.loads(Path(__file__).with_name("capacity-admission-v1-vectors.json").read_text()) + request, candidate = corpus["playerRequest"], corpus["playerVector"] + encoded_evidence = request["canonicalAccountEvidenceBase64"] + decoded_evidence = json.loads( + base64.b64decode(evidence(encoded_evidence, "PLAYER_ADMISSION"))) + self.assertEqual(decoded_evidence["bundleVersion"], "2") + self.assertNotIn("verifiedConnectScopeId", decoded_evidence) + scope_hash = "sha256:" + hashlib.sha256(b"controlled-scope").hexdigest() + self.assertEqual(decoded_evidence["verifiedConnectScopeTokenHash"], scope_hash) + snapshot = copy.deepcopy(decoded_evidence) + for key in ("snapshotIdentity", "requestId", "evaluatedAt", "evaluationIdentity"): + snapshot.pop(key) + snapshot_identity = "sha256:" + hashlib.sha256( + canonical_json_bytes(snapshot)).hexdigest() + self.assertEqual(decoded_evidence["snapshotIdentity"], snapshot_identity) + evaluation = { + "snapshotIdentity": snapshot_identity, + "requestId": decoded_evidence["requestId"], + "callerWorkload": decoded_evidence["callerWorkload"], + "evaluatedAt": decoded_evidence["evaluatedAt"], + } + evaluation_identity = "sha256:" + hashlib.sha256( + canonical_json_bytes(evaluation)).hexdigest() + self.assertEqual(decoded_evidence["evaluationIdentity"], evaluation_identity) + context_ids = [item for key, item in request["ownerContext"].items() if key.endswith("Id")] + self.assertEqual(len(context_ids), len(set(context_ids))) + encoded = preimage(request, candidate) + self.assertEqual(encoded.hex(), candidate["preimageHex"]) + self.assertEqual(hashlib.sha256(encoded).hexdigest(), candidate["sha256"]) + for key in ("characterId", "sessionId"): + with self.subTest(key): + changed = copy.deepcopy(request) + changed["ownerContext"][key] = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb" + self.assertNotEqual(hashlib.sha256(preimage(changed, candidate)).hexdigest(), candidate["sha256"]) + swapped = copy.deepcopy(request) + context = swapped["ownerContext"] + context["characterId"], context["sessionId"] = context["sessionId"], context["characterId"] + self.assertNotEqual(hashlib.sha256(preimage(swapped, candidate)).hexdigest(), candidate["sha256"]) + + def test_rejects_nonzero_unused_base64_pad_bits(self): + corpus = json.loads(Path(__file__).with_name("capacity-admission-v1-vectors.json").read_text()) + parsed = json.loads(base64.b64decode(corpus["request"]["canonicalAccountEvidenceBase64"])) + alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" + for padding in (1, 2): + # Valid JSON evidence with each padding width isolates the base64 spelling check. + for width in range(3): + parsed["padBitTest"] = "x" * width + raw = json.dumps(parsed, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + canonical = base64.b64encode(raw).decode("ascii") + if canonical.endswith("=" * padding) and not canonical.endswith("=" * (padding + 1)): + break + self.assertEqual(evidence(canonical), canonical) + index = len(canonical) - padding - 1 + alternate = canonical[:index] + alphabet[alphabet.index(canonical[index]) + 1] + canonical[index + 1:] + self.assertEqual(base64.b64decode(alternate, validate=True), raw) + with self.subTest(padding=padding), self.assertRaisesRegex(ValueError, "canonical padded base64"): + evidence(alternate) + + def test_rejected_decimal_candidates(self): + corpus = json.loads(Path(__file__).with_name("capacity-admission-v1-vectors.json").read_text()) + for candidate in corpus["rejected"]: + with self.subTest(candidate["name"]), self.assertRaises(ValueError): + decimal(candidate["capacityDelta"]) + + def test_rejected_evidence_candidates(self): + corpus = json.loads(Path(__file__).with_name("capacity-admission-v1-vectors.json").read_text()) + for candidate in corpus["rejectedEvidence"]: + with self.subTest(candidate["name"]), self.assertRaises(ValueError): + evidence(candidate["canonicalAccountEvidenceBase64"]) + parsed = json.loads(base64.b64decode(corpus["request"]["canonicalAccountEvidenceBase64"])) + for token, constant in (("NaN", float("nan")), ("Infinity", float("inf")), + ("-Infinity", float("-inf"))): + with self.subTest(token), self.assertRaisesRegex(ValueError, "non-finite JSON constant"): + parsed["nonFinite"] = constant + raw = json.dumps(parsed, sort_keys=True, ensure_ascii=False, + separators=(",", ":")).encode("utf-8") + evidence(base64.b64encode(raw).decode("ascii")) + # Shape/absence and usage expectations are separate from this encoding corpus: + # CapacityAdmissionDigestTest and AccountTenantCapacityOwnerTest invoke their real owners. + + +if __name__ == "__main__": + unittest.main() 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 new file mode 100644 index 0000000000..537c57c303 --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java @@ -0,0 +1,298 @@ +package net.firedevops.firemud.common.account.capacity; + +import com.google.protobuf.Any; +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.Message; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.protobuf.StatusProto; +import java.time.Instant; +import java.util.List; +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.TenantCapacityPlayerContext; +import net.firedevops.firemud.account.v1.TenantCapacityShape; +import net.firedevops.firemud.account.v1.TenantCapacityWorldContext; +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.Operation; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.OwnerContext; +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.TenantCapacityAdmission.Shape; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.WorldContext; +import net.firedevops.firemud.shared.v1.ErrorDetail; + +/** Strict bounded content mapping. TLS identity and source authority are never codec inputs. */ +public final class TenantCapacityAdmissionGrpcCodec { + public static final int MAX_REQUEST_WIRE_BYTES = 288 * 1024; + public static final int MAX_RESPONSE_WIRE_BYTES = 4096; + public static final long CALL_DEADLINE_SECONDS = 5; + + private static final String FAILURE_MESSAGE = "Tenant capacity commitment did not complete"; + + private TenantCapacityAdmissionGrpcCodec() {} + + public enum Failure { + INVALID_ARGUMENT(Status.Code.INVALID_ARGUMENT), + AUTH_UNAVAILABLE(Status.Code.UNAUTHENTICATED), + PERMISSION_DENIED(Status.Code.PERMISSION_DENIED), + IDEMPOTENCY_CONFLICT(Status.Code.ALREADY_EXISTS), + 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); + + private final Status.Code code; + + Failure(Status.Code code) { + this.code = code; + } + + public StatusRuntimeException toStatusException() { + return toStatusException(code); + } + + public StatusRuntimeException toStatusException(Status.Code status) { + if (!matches(status)) throw invalid(); + return StatusProto.toStatusRuntimeException( + com.google.rpc.Status.newBuilder() + .setCode(status.value()) + .setMessage(FAILURE_MESSAGE) + .addDetails(Any.pack(detail())) + .build()); + } + + private ErrorDetail detail() { + return ErrorDetail.newBuilder().setCode(name()).setMessage(FAILURE_MESSAGE).build(); + } + + private boolean matches(Status.Code status) { + return status == code + || (this == ENTITLEMENT_UNAVAILABLE && status == Status.Code.FAILED_PRECONDITION); + } + } + + /** Preserve the transport outcome. Accept semantic details only in the closed owner format. */ + public static StatusRuntimeException validateFailure(StatusRuntimeException failure) { + try { + var status = StatusProto.fromThrowable(failure); + if (status == null || status.getDetailsCount() == 0) return failure; + if (status.getDetailsCount() == 1 && status.getSerializedSize() <= MAX_RESPONSE_WIRE_BYTES) { + var detail = status.getDetails(0).unpack(ErrorDetail.class); + var error = Failure.valueOf(detail.getCode()); + if (error.matches(failure.getStatus().getCode()) && error.detail().equals(detail)) + return failure; + } + } catch (InvalidProtocolBufferException | IllegalArgumentException invalidDetail) { + // A malformed detail supplies no owner decision or execution proof. + } + return failure.getStatus().asRuntimeException(); + } + + public static CommitTenantCapacityAdmissionRequest toRequest(Request value) { + value.requireStructurallyValid(); + var attempt = + TenantCapacityAdmissionAttempt.newBuilder() + .addTenantId(value.identity().tenantId().toString()) + .addRequestId(value.identity().requestId().toString()) + .addAdmissionId(value.identity().admissionId().toString()) + .addAdmissionAttemptId(value.admissionAttemptId().toString()) + .addCapacityRearmFence(value.capacityRearmFence()) + .addTargetNamespace(value.targetNamespace()) + .addOperation(value.operation().name()) + .addPriorShape(shape(value.priorShape())) + .addRequestedShape(shape(value.requestedShape())) + .addCanonicalAccountEvidence(ByteString.copyFrom(value.evidence().canonicalBytes())) + .addMutationDigest(value.mutationDigest()); + if (value.context() instanceof PlayerContext player) attempt.addPlayerContext(player(player)); + else attempt.addWorldContext(world((WorldContext) value.context())); + var wire = + CommitTenantCapacityAdmissionRequest.newBuilder() + .addAttempt(attempt) + .setCapacityDelta(value.capacityDelta()) + .build(); + clean(wire, MAX_REQUEST_WIRE_BYTES); + return wire; + } + + public static Request parseRequest(CommitTenantCapacityAdmissionRequest wire) { + clean(wire, MAX_REQUEST_WIRE_BYTES); + if (!wire.hasCapacityDelta() || wire.getCapacityDelta() < 0) throw invalid(); + var attempt = one(wire.getAttemptList()); + clean(attempt, MAX_REQUEST_WIRE_BYTES); + OwnerContext context; + if (attempt.getPlayerContextCount() == 1 && attempt.getWorldContextCount() == 0) + context = player(one(attempt.getPlayerContextList())); + else if (attempt.getWorldContextCount() == 1 && attempt.getPlayerContextCount() == 0) + context = world(one(attempt.getWorldContextList())); + else throw invalid(); + var request = + new Request( + new Identity( + uuid(one(attempt.getTenantIdList())), + uuid(one(attempt.getRequestIdList())), + uuid(one(attempt.getAdmissionIdList()))), + uuid(one(attempt.getAdmissionAttemptIdList())), + one(attempt.getCapacityRearmFenceList()), + one(attempt.getTargetNamespaceList()), + context, + Operation.valueOf(one(attempt.getOperationList())), + shape(one(attempt.getPriorShapeList())), + shape(one(attempt.getRequestedShapeList())), + Evidence.parse( + one(attempt.getCanonicalAccountEvidenceList()).toByteArray(), context.owner()), + wire.getCapacityDelta(), + one(attempt.getMutationDigestList())); + request.requireStructurallyValid(); + return request; + } + + public static CommitTenantCapacityAdmissionResponse toResponse(Request request, Result result) { + result.requireBinding(request); + var wire = + CommitTenantCapacityAdmissionResponse.newBuilder() + .addCommitment( + TenantCapacityAdmissionCommitment.newBuilder() + .addTenantId(result.identity().tenantId().toString()) + .addRequestId(result.identity().requestId().toString()) + .addAdmissionId(result.identity().admissionId().toString()) + .addAdmissionAttemptId(result.admissionAttemptId().toString()) + .addCapacityRearmFence(result.capacityRearmFence()) + .addMutationDigest(result.mutationDigest()) + .addReservationId(result.reservationId().toString()) + .addReservationFence(result.reservationFence()) + .addExpiresAt(result.expiresAt().toString()) + .addState(result.state().name()) + .addSnapshotIdentity(result.snapshotIdentity()) + .addEvaluationIdentity(result.evaluationIdentity())) + .build(); + clean(wire, MAX_RESPONSE_WIRE_BYTES); + return wire; + } + + public static Result requireResponse( + Request request, CommitTenantCapacityAdmissionResponse wire) { + clean(wire, MAX_RESPONSE_WIRE_BYTES); + var result = one(wire.getCommitmentList()); + clean(result, MAX_RESPONSE_WIRE_BYTES); + String expires = one(result.getExpiresAtList()); + Instant instant; + try { + instant = Instant.parse(expires); + } catch (java.time.format.DateTimeParseException malformed) { + throw invalid(); + } + if (!instant.toString().equals(expires)) throw invalid(); + var parsed = + new Result( + new Identity( + uuid(one(result.getTenantIdList())), + uuid(one(result.getRequestIdList())), + uuid(one(result.getAdmissionIdList()))), + uuid(one(result.getAdmissionAttemptIdList())), + one(result.getCapacityRearmFenceList()), + one(result.getMutationDigestList()), + uuid(one(result.getReservationIdList())), + one(result.getReservationFenceList()), + instant, + State.valueOf(one(result.getStateList())), + one(result.getSnapshotIdentityList()), + one(result.getEvaluationIdentityList())); + parsed.requireBinding(request); + return parsed; + } + + private static TenantCapacityShape shape(Shape value) { + return TenantCapacityShape.newBuilder() + .addActiveSessions(value.activeSessions()) + .addConcurrentGameInstances(value.concurrentGameInstances()) + .addStorageBytes(value.storageBytes()) + .build(); + } + + private static Shape shape(TenantCapacityShape wire) { + clean(wire, 128); + return new Shape( + one(wire.getActiveSessionsList()), + one(wire.getConcurrentGameInstancesList()), + one(wire.getStorageBytesList())); + } + + private static TenantCapacityPlayerContext player(PlayerContext player) { + return TenantCapacityPlayerContext.newBuilder() + .addAccountId(player.accountId().toString()) + .addTenantId(player.tenantId().toString()) + .addPlayableStateNamespaceId(player.playableStateNamespaceId().toString()) + .addGameInstanceId(player.gameInstanceId().toString()) + .addCharacterId(player.characterId().toString()) + .addSessionId(player.sessionId().toString()) + .addRealmId(player.realmId().toString()) + .addRequestId(player.requestId().toString()) + .addPlayableStateScope(player.playableStateScope()) + .build(); + } + + private static PlayerContext player(TenantCapacityPlayerContext wire) { + clean(wire, 1024); + return new PlayerContext( + uuid(one(wire.getAccountIdList())), + uuid(one(wire.getTenantIdList())), + uuid(one(wire.getPlayableStateNamespaceIdList())), + uuid(one(wire.getGameInstanceIdList())), + uuid(one(wire.getCharacterIdList())), + uuid(one(wire.getSessionIdList())), + uuid(one(wire.getRealmIdList())), + uuid(one(wire.getRequestIdList())), + one(wire.getPlayableStateScopeList())); + } + + private static TenantCapacityWorldContext world(WorldContext value) { + return TenantCapacityWorldContext.newBuilder() + .addTenantId(value.tenantId().toString()) + .addOperationId(value.operationId().toString()) + .addLifecycleId(value.lifecycleId().toString()) + .addGameInstanceId(value.gameInstanceId().toString()) + .addOwnerId(value.ownerId().toString()) + .addOwnerFence(value.ownerFence()) + .build(); + } + + private static WorldContext world(TenantCapacityWorldContext wire) { + clean(wire, 1024); + return new WorldContext( + uuid(one(wire.getTenantIdList())), + uuid(one(wire.getOperationIdList())), + uuid(one(wire.getLifecycleIdList())), + uuid(one(wire.getGameInstanceIdList())), + uuid(one(wire.getOwnerIdList())), + one(wire.getOwnerFenceList())); + } + + private static UUID uuid(String raw) { + UUID parsed = UUID.fromString(raw); + if (!parsed.toString().equals(raw)) throw invalid(); + return TenantCapacityAdmission.uuid(parsed); + } + + private static T one(List values) { + if (values.size() != 1) throw invalid(); + return values.getFirst(); + } + + private static void clean(Message message, int maximum) { + if (message == null + || message.getSerializedSize() > maximum + || !message.getUnknownFields().asMap().isEmpty()) throw invalid(); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Exact bounded capacity protobuf required"); + } +} 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 new file mode 100644 index 0000000000..bea9dda822 --- /dev/null +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java @@ -0,0 +1,205 @@ +package net.firedevops.firemud.common.account.capacity; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.Any; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Status; +import io.grpc.protobuf.StatusProto; +import java.util.List; +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.shared.v1.ErrorDetail; +import org.junit.jupiter.api.Test; + +class TenantCapacityAdmissionGrpcCodecTest { + @Test + void onlyCanonicalFailureDetailsSurviveWithoutChangingTransportStatus() { + for (var failure : Failure.values()) { + var canonical = failure.toStatusException(); + assertThat(TenantCapacityAdmissionGrpcCodec.validateFailure(canonical)).isSameAs(canonical); + } + var deadline = Status.DEADLINE_EXCEEDED.asRuntimeException(); + assertThat(TenantCapacityAdmissionGrpcCodec.validateFailure(deadline)).isSameAs(deadline); + var claimedFence = + StatusProto.toStatusRuntimeException( + com.google.rpc.Status.newBuilder() + .setCode(Status.Code.UNAVAILABLE.value()) + .addDetails(Any.pack(ErrorDetail.newBuilder().setCode("FENCE_REJECTED").build())) + .build()); + var verified = TenantCapacityAdmissionGrpcCodec.validateFailure(claimedFence); + assertThat(verified.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(StatusProto.fromThrowable(verified).getDetailsList()).isEmpty(); + } + + @Test + void exactBothAlternativesRoundTripWithCompleteBundleAndReservationBinding() { + for (Request request : + List.of( + CapacityAdmissionTestFixture.playerRequest(), + CapacityAdmissionTestFixture.worldRequest(17L))) { + var wire = TenantCapacityAdmissionGrpcCodec.toRequest(request); + assertThat(wire.hasCapacityDelta()).isTrue(); + assertThat(TenantCapacityAdmissionGrpcCodec.parseRequest(wire)).isEqualTo(request); + Result result = result(request); + assertThat( + TenantCapacityAdmissionGrpcCodec.requireResponse( + request, TenantCapacityAdmissionGrpcCodec.toResponse(request, result))) + .isEqualTo(result); + } + } + + @Test + void nonCreatingEvidenceRoundTripsWithoutChangingAnyCanonicalBytes() { + Request request = CapacityAdmissionTestFixture.playerRequest(false); + var wire = TenantCapacityAdmissionGrpcCodec.toRequest(request); + var parsed = TenantCapacityAdmissionGrpcCodec.parseRequest(wire); + assertThat(wire.getAttempt(0).getCanonicalAccountEvidence(0).toByteArray()) + .containsExactly(request.evidence().canonicalBytes()); + assertThat(parsed).isEqualTo(request); + assertThat(parsed.evidence().canonicalBytes()) + .containsExactly(request.evidence().canonicalBytes()); + assertThat(parsed.evidence().permitsCreation()).isFalse(); + assertThat(TenantCapacityAdmissionGrpcCodec.toRequest(parsed).toByteArray()) + .containsExactly(wire.toByteArray()); + parsed.requireStructurallyValid(); + assertThatThrownBy(parsed::requireCommittable).isInstanceOf(IllegalArgumentException.class); + } + + @Test + void absentNegativeDuplicateUnknownAndMixedCallerContextFailBeforeCommit() { + Request request = CapacityAdmissionTestFixture.playerRequest(); + var wire = TenantCapacityAdmissionGrpcCodec.toRequest(request); + var unknown = + UnknownFieldSet.newBuilder() + .addField(999, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + var world = + TenantCapacityAdmissionGrpcCodec.toRequest(CapacityAdmissionTestFixture.worldRequest(17L)); + for (var bad : + List.of( + wire.toBuilder().clearCapacityDelta().build(), + wire.toBuilder().setCapacityDelta(-1).build(), + wire.toBuilder().addAttempt(wire.getAttempt(0)).build(), + wire.toBuilder().setUnknownFields(unknown).build(), + wire.toBuilder() + .setAttempt( + 0, + wire.getAttempt(0).toBuilder() + .addWorldContext(world.getAttempt(0).getWorldContext(0))) + .build(), + wire.toBuilder() + .setAttempt(0, wire.getAttempt(0).toBuilder().addCapacityRearmFence(1)) + .build(), + wire.toBuilder() + .setAttempt( + 0, + wire.getAttempt(0).toBuilder() + .setPlayerContext( + 0, + wire.getAttempt(0).getPlayerContext(0).toBuilder() + .addSessionId( + wire.getAttempt(0).getPlayerContext(0).getSessionId(0)))) + .build(), + wire.toBuilder() + .setAttempt( + 0, + wire.getAttempt(0).toBuilder() + .setPlayerContext( + 0, + wire.getAttempt(0).getPlayerContext(0).toBuilder() + .setUnknownFields(unknown))) + .build())) { + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.parseRequest(bad)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void presentZeroSurvivesOnlyExplicitNonExpandingClassification() { + Request base = CapacityAdmissionTestFixture.worldRequest(0L); + Request zero = + new Request( + base.identity(), + base.admissionAttemptId(), + base.capacityRearmFence(), + base.targetNamespace(), + base.context(), + TenantCapacityAdmission.Operation.NON_EXPANDING_RECOVERY, + new TenantCapacityAdmission.Shape(0, 1, 0), + new TenantCapacityAdmission.Shape(0, 1, 0), + base.evidence(), + 0L, + null) + .withDigest(); + var wire = TenantCapacityAdmissionGrpcCodec.toRequest(zero); + assertThat(wire.hasCapacityDelta()).isTrue(); + assertThat(TenantCapacityAdmissionGrpcCodec.parseRequest(wire).capacityDelta()).isZero(); + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.toRequest(base)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void responseCannotSubstituteAttemptDigestFenceOrEvidenceIdentity() { + var request = CapacityAdmissionTestFixture.playerRequest(); + var wire = TenantCapacityAdmissionGrpcCodec.toResponse(request, result(request)); + for (var bad : + List.of( + wire.toBuilder().addCommitment(wire.getCommitment(0)).build(), + wire.toBuilder() + .setCommitment(0, wire.getCommitment(0).toBuilder().setCapacityRearmFence(0, 2)) + .build(), + wire.toBuilder() + .setCommitment( + 0, wire.getCommitment(0).toBuilder().setMutationDigest(0, "b".repeat(64))) + .build(), + wire.toBuilder() + .setCommitment( + 0, + wire.getCommitment(0).toBuilder() + .setEvaluationIdentity(0, "sha256:" + "b".repeat(64))) + .build(), + wire.toBuilder() + .setCommitment( + 0, + wire.getCommitment(0).toBuilder() + .setExpiresAt(0, request.evidence().expiresAt().plusSeconds(1).toString())) + .build())) { + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.requireResponse(request, bad)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void malformedAndOutOfRangeResponseExpiryUseTheInvalidResponseException() { + var request = CapacityAdmissionTestFixture.playerRequest(); + var wire = TenantCapacityAdmissionGrpcCodec.toResponse(request, result(request)); + for (String expires : + List.of("not-an-instant", "2026-99-02T00:00:00Z", "+1000000001-01-01T00:00:00Z")) { + var malformed = + wire.toBuilder() + .setCommitment(0, wire.getCommitment(0).toBuilder().setExpiresAt(0, expires)) + .build(); + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.requireResponse(request, malformed)) + .isExactlyInstanceOf(IllegalArgumentException.class); + } + } + + private static Result result(Request request) { + return new Result( + request.identity(), + request.admissionAttemptId(), + request.capacityRearmFence(), + request.mutationDigest(), + UUID.fromString("b2222222-2222-4222-8222-222222222222"), + 1, + CapacityAdmissionTestFixture.NOW.plusSeconds(15), + State.RESERVED, + request.evidence().snapshotIdentity(), + request.evidence().evaluationIdentity()); + } +} 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 359dea0f2b..e7cbb9b5b3 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 @@ -1,17 +1,21 @@ package net.firedevops.firemud.test; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.FieldDescriptor; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; import java.util.List; import java.util.Set; import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionRequest; import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeRequest; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeRequest; import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeRequest; @@ -43,6 +47,9 @@ class AccountRuntimeStubServerCompatibilityTest { "RequestEmailVerification", "VerifyEmail", "VerifyEmailLoginOtp"); + // Private runtime mutations require their actual bounded mTLS owner, never fake authority. + private static final Set UNIMPLEMENTED_RUNTIME_METHODS = + Set.of("CommitTenantCapacityAdmission"); @Test void accountServiceMethodSetIsFullyCategorized() { @@ -53,15 +60,40 @@ void accountServiceMethodSetIsFullyCategorized() { assertThat(actualMethods) .containsExactlyInAnyOrderElementsOf( - java.util.stream.Stream.concat( + java.util.stream.Stream.of( AccountRuntimeStubServer.implementedRuntimeMethodNames().stream(), - NON_RUNTIME_METHODS.stream()) + NON_RUNTIME_METHODS.stream(), + UNIMPLEMENTED_RUNTIME_METHODS.stream()) + .flatMap(java.util.function.Function.identity()) .collect(java.util.stream.Collectors.toSet())); assertThat(AccountRuntimeStubServer.implementedRuntimeMethodNames()) .contains("IssueDirectTextConnectScope", "JoinPublicProductionMembership"); } + @Test + void privateCapacityMutationRemainsUnimplementedOnSharedFakeRuntimeServer() throws Exception { + assertThat(AccountRuntimeStubServer.implementedRuntimeMethodNames()) + .doesNotContain("CommitTenantCapacityAdmission"); + try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { + ManagedChannel channel = + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); + try { + var stub = AccountServiceGrpc.newBlockingStub(channel); + assertThatThrownBy( + () -> + stub.commitTenantCapacityAdmission( + CommitTenantCapacityAdmissionRequest.getDefaultInstance())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNIMPLEMENTED)); + } finally { + channel.shutdownNow(); + } + } + } + @Test void joinMembershipVersionsRemainUnsignedOnTheirExistingFieldNumbers() { Descriptor descriptor =