diff --git a/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md b/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md index 60d0b6db7e..3e398afaee 100644 --- a/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md +++ b/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md @@ -97,6 +97,12 @@ Both issuance paths use the same bounded typed-mutation admission contract befor For the tenant-scoped `tenantAdmin` branch of `firemud.game-session.start-session/v1`, the human evidence uses the closed `evidenceType: "HumanAuthorityEvidence/v1"` arm with Account-derived `actorAccountId`, `controlUiTokenJti`, `role`, `accountGeneration`, and `tenantGeneration`. This branch explicitly declares `assurance` absent: issuance, exact decoding, forwarding, and redemption reject an added assurance member, including `null` or a sentinel, and never invent an elevation or a JWT assurance claim. This absence is role applicability, not permission to omit unavailable evidence. Global `platformAdmin` and cross-tenant `billingAdmin` branches still require genuine current Account-owned `privileged_control` evidence; they cannot substitute this tenant branch or obtain authority from its copied role or generation values. +#### Redeemed StartSession Projection Read + +After Game Session has redeemed the original human StartSession reference and allocated its owner attempt and fence, Account may serve `ReadRedeemedOperationProjection` to the exact same-namespace `game-design-service` peer only to read the immutable template-selected source/descriptor for the same original tenant, template, and `controlPlaneRequestId`. The request is bound to the exact canonical pre-authorization tuple, Account-returned authorization-reference fingerprint, original reservation owner/fence, and actual Game Session `ownerAttemptId`/`ownerFence`; Account independently revalidates the original actor and `control-ui` token `jti`, current Account source and reference expiry, and the stored original reservation and redeemed Game Session attempt/fence before returning that projection. No forwarded JWT or opaque reference is sent on this read, and neither workload identity, fingerprint, nor authority-bundle integrity alone establishes authority. The read is credential-free and read-only: it does not renew or extend a reservation/reference, issue or redeem a credential, mutate source state, select a different template or policy, create another owner attempt, commit the owner mutation, or bootstrap/activate a runtime. Exact retries repeat the same binding and return the same operation projection without policy reselection; changed, stale, or ambiguous bindings fail closed. This read is not a commit-spanning CAS proof; owner commit and runtime activation remain separately fenced by their owners. + +The separately bounded original Game Session read/pin continuation is governed by the [Game Session owner contract](../microservices/game-session-service/api-contracts.md#restricted-original-claim-evidence-continuation); it is not a broader template-selection or mutation permission. + `authorityTuple` is copied without scalarization or field renaming from the complete canonical shape in the [JWT and token contracts](../system-architecture-jwt-and-token-contracts.md#canonical-authority-tuple). `membershipVersion` is the independently applicable Account membership-version map, including `{}` when no membership applies. `HumanAuthorityEvidence/v1` carries the Account-derived actor account, `control-ui` token `jti`, role, assurance only when applicable to that role, account generation, and applicable tenant or target-tenant generation. `AutomationAuthorityEvidence/v1` carries the exact authenticated workload, automation-policy identity/version, and applicable tenant generation. The tagged `issuanceEvidence` arm must agree with Account-derived `issuanceKind`; the inapplicable arm and inapplicable authority-scope identifiers are omitted rather than serialized as `null`, empty objects, or sentinels. `sourceEvidenceId` identifies the one Account authority snapshot and its linearization evidence, while `sourceEvidenceVersion` is the corresponding Account-issued source version; together they are the canonical source fence for the bundle and are carried unchanged with the existing `{bundleVersion, sourceVersion, sourceFence, linearization}` reference. Account derives every authority, generation, membership, freshness, and branch-decision member from that one atomic snapshot and stores the source pair with the issuance record. During redemption, Account exact-compares `sourceEvidenceId`, `sourceEvidenceVersion`, the bundle reference, and every snapshot-bound field against the stored issuance record and the current applicable authority evidence; a missing, changed, or mixed-version value rejects redemption. Consumers reject missing, extra, contradictory, separately sourced, stale, expired, wrongly tagged, or non-canonical bundle fields and must redeem the original reference with Account; a copied bundle never becomes a second authority. For every forwarded owner-mutation family, ADR 0048's canonical complete `postAuthorizationExecutionTuple` is the required post-authorization identity. It explicitly contains ADR 0048's stable `controlPlaneRequestId` for orchestration, reservation, lookup, and correlation across forwarding, `mutationDigest`, `issuanceKind`, Account-returned `authorizationReferenceFingerprint`, exact authenticated workload and actor/policy binding, exact typed `scope`, normalized `actionFamily`, `actionFamilySchemaId`, `actionFamilySchemaVersion`, typed `target`, immutable typed `targetOwner`, typed `expectedVersion`, typed `mutation`, typed `auditReason`, the exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, the exact canonical `authorityEvidenceBundle/v1` defined above (whose issuance identity carries the tagged `actionFamilyRequestIdentity` for domain action/idempotency), and every schema-bound typed presence/absence value. `targetOwner` is distinct from `target`, immutable after reservation, and is never inferred from current routing or owner state. Reservation and pre-authorization Account issuance/recovery compare `preAuthorizationReservationTuple`; post-authorization tuple completion, owner idempotency, terminal/no-commit proof, result lookup, conflict handling, and any later fresh owner attempt carries and compares its own exact tuple; no participant may omit a required identity because it is unavailable locally. diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index d4f3df054c..cb49906801 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -211,7 +211,7 @@ For the redeemed StartSession projection, `ReadRedeemedOperationProjection` acce | `GET` | `/auth/bootstrap/worlds` | List caller-visible worlds for first-party gameplay bootstrap | | `GET` | `/auth/bootstrap/worlds/{world}/realms` | List caller-visible realms for a selected world during first-party gameplay bootstrap | | `GET` | `/auth/bootstrap/worlds/{world}/realms/{realm}/characters?connectScopeId={scope}` | List caller-visible characters for the signed realm-discovery target during first-party gameplay bootstrap. The REST producer applies the canonical realm-snapshot mapping to `playableStateScope` before passing it to Entity Management; callers cannot select or provide it. | -| `POST` | `/auth/bootstrap/worlds/{world}/realms/{realm}/characters` | **Target; not currently routable or implemented.** Account-owned player-bootstrap facade for scoped character creation; retains the target delegation contract to Entity Management `CreateCharacter` after signed-scope and membership/grant checks. The REST producer applies the same canonical mapping, and `playableStateScope` is server-derived rather than an accepted request field. | +| `POST` | `/auth/bootstrap/worlds/{world}/realms/{realm}/characters` | **Target; not currently routable or implemented.** Account-owned player-bootstrap facade for scoped character creation; retains the target delegation contract to Entity Management `CreateCharacter` after signed-scope and membership/grant checks. The REST producer applies the same canonical mapping, and `playableStateScope` is server-derived rather than an accepted request field. Account's local creation protection covers the current authenticated player's membership, applicable realm grant, and entitlement authority; see Entity's [character creation owner protection](../entity-management-service/api-contracts.md#character-creation-owner-protection) for the cross-owner terminal boundary. | | `POST` | `/internal/runtime/public-production-join` | **Target REST adapter; not currently routable.** The local Account `JoinPublicProductionMembership` RPC implements explicit public-production membership creation; Game Session text `JOIN` dispatch to this RPC remains pending under #2898. No implicit membership-writer route is exposed. | | `GET` | `/internal/runtime/realm-access-grants/{tenantId}/{worldSlug}/{realmSlug}/{playtestLifecycleId}/{accountId}` | Internal-only authoritative lookup for one non-public realm-access grant; the lifecycle ID is part of the exact target | | `GET` | `/internal/runtime/accounts/{accountId}/realm-access-grants/{tenantId}/{worldSlug}/{realmSlug}/{playtestLifecycleId}` | Internal-only authoritative lookup/list for the account's exact non-public world/realm/lifecycle target used by discovery/admission filtering | diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index b7d846528f..9074f4cc9d 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,6 +8,8 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ## Implementation Status +Account's unregistered original-ACK storage seam requires PostgreSQL 18 for fresh operations: the original executor performs a writable SERIALIZABLE physical COMMIT on its enlisted connection and returns an opaque acknowledgement only after observing the database clock before unchanged expiry; a separate transaction commits the exact receipt. Receiving V146 changes only the fresh receipt-insert guard, preserving the donor V122 SQL unchanged as receiving V144. Its historical durable reader remains PostgreSQL 16-only, so lost-acknowledgement recovery and retained-receipt retries remain denied on PostgreSQL 18. This storage evidence does not authenticate a caller, establish current Account ownership or admission, authorize gameplay, or register runtime behavior. Migration provenance and pending receiving proof are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-fresh-original-ack-storage-preparation). + Account V40 adds owner-proven sequence-zero source baselines to the inherited V30–V39 authority-storage and retention-safety foundation; V74–V89 preserve that baseline and add source/global-role guards, draft-source writer exclusions and fences, immutable reset/logout/security-operation receipts, creator and tenant-bootstrap provenance, individual Creator Party and hosted-terms/environment-binding persistence, and source-change journals. V90–V97 add persistence relations and guards for source-currentness work across Account, control-UI issuance, selected-publication authorization/settlement, and Game Logic. V98 adds durable hosted-terms disclosure handoff and immutable source-evidence relations with database transition guards. These DDL stages establish persistence and source-writer fence relationships; they do not activate owner writers, legal authority verification, dispatch, or consumers. New repository-created Accounts receive the V40 source baseline; retained pre-V40 rows are neither backfilled nor admitted. Password-reset completion atomically claims and consumes its token, updates the Account, appends the canonical event and receipt, and reads back current source evidence in the owner transaction. If an earlier source intent remains `WAITING`, the request returns retryable `AUTH_UNAVAILABLE`; it does not wait on a thread for settlement, and an exact retry retains the original operation identity. A `WAITING` reset intent retains the Argon2 password verifier needed by that retry; terminal source commit or abort clears the verifier while preserving its digest and immutable source binding and receipt. Finite receipt retention remains unresolved under the owning retention policy; no lifetime is selected here. Logout-all production remains unregistered and unwired. These persistence primitives do not provide public JOIN, target-currentness protection, or runtime activation. Exact physical and local proof limits are recorded in the [Player Access and Session implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). Hard deletion remains denied, revoked grants remain tombstones, and this stage does not enable signer provisioning, LOGIN, PLAY, or activation. Proof qualification: the earlier `7a665c83e81f5cec85fcd7ec9a205c291bc0eba2` run is historical. Later physical CI executed the inspection-lock, TRUNCATE and disclosure-source regressions successfully but failed a trigger-catalog fixture. That fixture and the final optional-inventory settlement and malformed source-vector corrections require replacement physical CI. See the [player-access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#current-status) for the canonical proof inventory and exact limits. These results do not establish activation or playable closure. diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index d8eaca7da2..c693fd89e8 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -39,7 +39,7 @@ curl http://localhost:8080/ping ## gRPC - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in `entity_management_service.proto`. -- `CreateCharacter(CreateCharacterRequest) returns (CreateCharacterResponse)` – Entity-owned allocation and persistence of a primary controllable actor after the caller has passed Account membership/grant/realm admission. The target request carries the resolved `{accountId, tenantId, worldSlug, realmSlug}`, stable `playableStateNamespaceId`, the `playableStateScope` supplied only as authoritative realm-snapshot/attestation evidence, active `gameInstanceId`, explicit `entryPolicy=PLAYER_CREATED`, exact published descriptor identity/version, player creation input, and proof of the catalog/admission-pointer snapshot. Entity rejects a missing or mismatched policy before allocation or replay, and cross-checks the policy against the canonical snapshot and the applicable descriptor identity/version. It also carries caller-stable `createCharacterRequestId` and canonical `mutationDigest`; Entity recomputes the digest over the immutable trusted target, `entryPolicy`, exact descriptor/version, and creation input. The durable operation guard key is `{tenantId, playableStateNamespaceId, accountId, createCharacterRequestId}`. Within one local transaction, Entity admits and locks that guard plus digest, serializes the `PLAYER_CREATED` zero-roster boundary on `{tenantId, playableStateNamespaceId, accountId}`, and rereads the roster against the unchanged policy and descriptor/version before allocation. Only a still-empty roster may allocate; concurrent distinct request identities cannot both cross a stale zero-roster observation. Entity then atomically persists the allocated `{accountId, tenantId, playableStateNamespaceId, characterId}` association and replayable response. The same guard and digest exact-replay the original response; the same guard with a different digest returns `IDEMPOTENCY_CONFLICT` before allocation. Callers cannot choose or derive `playableStateScope`; Entity must reject caller-derived evidence and validate the exact immutable namespace/scope pair. A scope change under one namespace is rejected and never creates a second or split actor record. Entity allocates `characterId` only after the operation guard, validates the namespace/scope and active-instance fence, and never derives identity from account/name/hash or delegates character ownership to Account. Durable persistence/keying remains `{tenantId, playableStateNamespaceId, characterId}`; `playableStateScope` remains separately validated immutable routing/authorization evidence, `gameInstanceId` is only the replaceable active-runtime fence, and neither is a durable character-identity dimension. Entity Management does not expose a direct player REST route. The current request path and enforcement do not yet prove this complete target boundary, so it remains an implementation/proof gap rather than a claim about live enforcement. +- `CreateCharacter(CreateCharacterRequest) returns (CreateCharacterResponse)` – Current behavior: the scalar-only request validates tenant, account, and scope, then Entity returns an application `FAILED_PRECONDITION` before `CharacterService` allocation because the request cannot carry the authenticated owner proof and durable operation binding. Target behavior remains Entity-owned allocation and persistence of a primary controllable actor after the caller has passed Account membership/grant/realm admission. The target request carries the resolved `{accountId, tenantId, worldSlug, realmSlug}`, stable `playableStateNamespaceId`, the `playableStateScope` supplied only as authoritative realm-snapshot/attestation evidence, active `gameInstanceId`, explicit `entryPolicy=PLAYER_CREATED`, exact published descriptor identity/version, player creation input, and proof of the catalog/admission-pointer snapshot. Entity rejects a missing or mismatched policy before allocation or replay, and cross-checks the policy against the canonical snapshot and the applicable descriptor identity/version. It also carries caller-stable `createCharacterRequestId` and canonical `mutationDigest`; Entity recomputes the digest over the immutable trusted target, `entryPolicy`, exact descriptor/version, and creation input. The durable operation guard key is `{tenantId, playableStateNamespaceId, accountId, createCharacterRequestId}`. Within one local transaction, Entity admits and locks that guard plus digest, serializes the `PLAYER_CREATED` zero-roster boundary on `{tenantId, playableStateNamespaceId, accountId}`, and rereads the roster against the unchanged policy and descriptor/version before allocation. Only a still-empty roster may allocate; concurrent distinct request identities cannot both cross a stale zero-roster observation. Entity then atomically persists the allocated `{accountId, tenantId, playableStateNamespaceId, characterId}` association and replayable response. The same guard and digest exact-replay the original response; the same guard with a different digest returns `IDEMPOTENCY_CONFLICT` before allocation. Callers cannot choose or derive `playableStateScope`; Entity must reject caller-derived evidence and validate the exact immutable namespace/scope pair. A scope change under one namespace is rejected and never creates a second or split actor record. Entity allocates `characterId` only after the operation guard, validates the namespace/scope and active-instance fence, and never derives identity from account/name/hash or delegates character ownership to Account. Durable persistence/keying remains `{tenantId, playableStateNamespaceId, characterId}`; `playableStateScope` remains separately validated immutable routing/authorization evidence, `gameInstanceId` is only the replaceable active-runtime fence, and neither is a durable character-identity dimension. Entity Management does not expose a direct player REST route. This allocation and replay contract remains target state; current implementation proves denial only. - `UpdateEntity(UpdateEntityRequest) returns (UpdateEntityResponse)` – updates mutable character state for the requested `{tenantId, playableStateNamespaceId, gameInstanceId, playableStateScope, characterId}` target. `playableStateScope` must be the authoritative realm-snapshot/attestation result; callers cannot choose or derive it, and Entity validates the exact immutable namespace/scope pair before mutation. A caller-selected or changed scope, missing/mismatched namespace or scope, stale snapshot, caller-asserted instance, or global `characterId` is rejected rather than updating or splitting records. Target state also requires a fresh, server-resolved active-instance authorization fence for that exact namespace/scope and instance, checked atomically immediately before mutation. The current request path does not yet carry and prove the complete fresh fence, so it remains an implementation/proof gap and must not be treated as target enforcement. - `QueryInventory(QueryInventoryRequest) returns (QueryInventoryResponse)` – the current response is an unpaged repeated `InventoryItem items[]` projection. The live handler emits `item_id`, `item_name`, `item_description`, and `quantity`, and conditionally emits `container_instance_id`, `item_instance_id`, and `visible_ref` when those values are present. This projection does not establish complete instance-aware identity or stack/concurrency safety: rich pagination, complete holder-local stack uniqueness, find-then-create concurrency, and explicit-family duplicate handling remain target/proof gaps documented in [Runtime and Data](./runtime-and-data.md#implementation-status). - `ListCharactersByAccount` (target-state policy/descriptor/template/namespace fields) – returns only persisted actors valid for the trusted account selector and resolved `{tenantId, playableStateNamespaceId, playableStateScope}` target. Entity validates the account-to-character association before returning any roster or visibility result; an account identifier is ownership evidence, not controller identity. The target response includes exactly one published v1 entry policy (`PLAYER_CREATED`, `PRESEEDED_ONLY`, or `AUTO_PROVISIONED`) plus only its policy-applicable versioned identity: a descriptor identity/version for `PLAYER_CREATED`, a template identity/version for `AUTO_PROVISIONED`, and neither descriptor nor template fields for `PRESEEDED_ONLY`; it echoes the resolved namespace/scope. It also returns one immutable roster snapshot identity and digest for the exact target, policy/version, and ordered roster; an exact unchanged snapshot reuses both values, while a roster or policy/version change advances the identity or digest. Callers bind that snapshot for selection and retry and reject a changed snapshot rather than silently selecting a different actor. `gameInstanceId` is a fresh active-runtime fence, not durable lookup identity. Zero, one, and many results are explicit: policy determines the zero-result next action, one may be selected automatically, and many require explicit selection. A roster is discovery evidence, not admission authority. The current proto surface has none of the target policy, descriptor/template, namespace, or roster-snapshot fields and does not prove this boundary. @@ -61,7 +61,7 @@ grpcurl -plaintext localhost:6565 entity_management.v1.EntityManagementService/P ## Character creation owner protection -The fixed ordered family and raw/normalized limits are owned by the [CHARACTER_CREATE/1 action schema](./character-create-action-schema.md), using ADR 0047's unchanged byte grammar. The passive common-platform-core codec has now been proved locally, but that does not establish an authenticated producer, owner protections, or Entity terminal composition. +The approved passive common-platform-core `CHARACTER_CREATE/1` model, codec, and bounded authored-source projection are present. The standalone parent check completed 233 tasks and 372 common-platform-core tests with zero failures, errors, or skips; this does not establish an authenticated producer, owner protections, or Entity terminal composition. The fixed ordered family and raw/normalized limits are owned by the [CHARACTER_CREATE/1 action schema](./character-create-action-schema.md), using ADR 0047's unchanged byte grammar. `CreateCharacter` is explicitly tagged as a `CHARACTER_CREATE` mutation, distinct from `StartSession` and gameplay-admission operations in purpose, durable identity, encoded operation identity, and replay. Before acquiring any owner protection, the producer durably records that purpose, caller-stable `createCharacterRequestId`, canonical `mutationDigest`, and exact creation intent. The operation binds the authenticated account and immutable resolved target `{tenantId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, versionId, activeLifecycleEpoch}`, the exact catalog and admission-pointer snapshot, `entryPolicy=PLAYER_CREATED`, published descriptor identity/version, and canonical creation input. The approved action family uses the existing canonical `mutationDigest/v1` byte grammar without revising that grammar or StartSession's schema. A changed digest, target, source identity, or descriptor is a conflict and cannot select substitute authority. @@ -69,7 +69,7 @@ The operation acquires three independent owner-local protections: Account protec All three protections remain effective while Entity performs the guarded `PLAYER_CREATED` zero-roster check and, if eligible, atomically commits the character, association, and replayable `COMMITTED` result. They may be released only after that committed result is established, or after an authenticated, fenced, definitive `ABORTED` result proves the same operation can never commit in the future. Partial acquisitions are durably recorded and reconciled against the same operation identity and digest across retry and restart. Absence, timeout, `PENDING`, unavailable reads, or diagnostic expiry never prove abort and never release protection. Authority expiry permits no new allocation; an ambiguous Entity commit remains protected for reconciliation. A changed request cannot borrow an existing hold or result. -The producer, all three owner protections, and Entity's terminal cross-owner composition remain unimplemented or unproved; in this prerequisite, the legacy scalar-only `CreateCharacter` RPC remains the existing allocating implementation. The required denial belongs to subsequent receiving work tracked by #3122, which must reject that RPC with `FAILED_PRECONDITION` before allocation because it cannot carry the required authenticated owner proof, catalog/pointer snapshot, lifecycle protection, or durable terminal operation. Focused proof must cover owner-writer exclusion, partial acquisition and crash recovery, finite authority expiry, commit/abort races, and changed identity/digest/target/source conflicts. This target contract does not activate a route or claim live enforcement. +The producer, all three owner protections, and Entity's terminal cross-owner composition remain unimplemented or unproved; the legacy scalar-only `CreateCharacter` RPC is now denied with `FAILED_PRECONDITION` before allocation because it cannot carry the required authenticated owner proof, catalog/pointer snapshot, lifecycle protection, or durable terminal operation. Focused proof must cover owner-writer exclusion, partial acquisition and crash recovery, finite authority expiry, commit/abort races, and changed identity/digest/target/source conflicts. This target contract does not activate a route or claim live enforcement. ## Design-Time APIs diff --git a/design/architecture/microservices/entity-management-service/character-create-action-schema.md b/design/architecture/microservices/entity-management-service/character-create-action-schema.md index 3c0081bcec..4d6d9f89d1 100644 --- a/design/architecture/microservices/entity-management-service/character-create-action-schema.md +++ b/design/architecture/microservices/entity-management-service/character-create-action-schema.md @@ -4,7 +4,7 @@ This document owns the fixed action-family schema for `firemud.entity.create-cha ## Implementation Status -The fixed ordered `CHARACTER_CREATE/1` map below is approved. The four offline typed-preimage vectors remain unchanged, and the shared resource now includes the required negative vectors. A passive common-platform-core action model, strict ordered raw JSON encoder/decoder and digest path, and bounded authored-source projection parser are present with focused production-decoder tests. Current local proof and its limits are recorded in the [gameplay implementation tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#validation-and-proof). This remains local-only receiving support: it does not provide an authenticated producer, owner protections, Entity terminal composition, or route activation. The legacy scalar-only `CreateCharacter` RPC remains the existing allocating implementation. A subsequent Entity receiving change must enforce fail-closed denial with `FAILED_PRECONDITION` before allocation because this RPC cannot carry the required owner proof and operation binding; see the [Entity character-creation owner-protection contract](./api-contracts.md#character-creation-owner-protection). This schema does not activate a route or claim live creation support. +The fixed ordered `CHARACTER_CREATE/1` map below is approved. The four offline typed-preimage vectors remain unchanged, and the shared resource now includes the required negative vectors. A passive common-platform-core action model, strict ordered raw JSON encoder/decoder and digest path, and bounded authored-source projection parser are present with focused production-decoder tests. Current local proof and its limits are recorded in the [gameplay implementation tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#validation-and-proof). This remains local-only receiving support: it does not provide an authenticated producer, owner protections, Entity terminal composition, or route activation. The legacy scalar-only `CreateCharacter` RPC remains denied with `FAILED_PRECONDITION` before allocation because it cannot carry the required owner proof and operation binding; see the [Entity character-creation owner-protection contract](./api-contracts.md#character-creation-owner-protection). This schema does not activate a route or claim live creation support. The current owner carriers and protection contracts establish only the initial public-production boundary. Private/playtest creation remains unsupported and denied until the genuine catalog, pointer, lifecycle, and protection carriers exist. Conditional tuple slots define exact presence for a complete future owner proof; their presence in this schema does not enable that boundary. diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index ab88d5c0f0..eeb134c8a9 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -46,6 +46,8 @@ The World Management database row and monotonic lifecycle epoch are the admissio Multi-Tenancy owns the realm catalog, the canonical durable `{tenantId, realmId}` pointer identity and its routing/admission semantics, while Game Session is the sole runtime resolver, persister, and compare-and-set orchestrator for that resolved catalog and admission-pointer state; neither service owns World lifecycle state. Replacement preparation and pointer swap carry the catalog-bound `worldSlug`/`realmSlug` selectors, stable `playableStateNamespaceId`/`playableStateScope`, and, for private/playtest targets, the canonical lifecycle proof tuple `{playtestLifecycleId, playtestStateGeneration}` from [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); changing `gameInstanceId` does not authorize a new realm identity, namespace, or durable-state copy. Cutover remains closed unless every owner reports fresh compatible state and the fenced pointer CAS succeeds. After a source swap, Game Session drains and closes source bindings, then asks World to progress termination; it reports a stopped runtime only after authoritative `TERMINATED` readback. Public-production requests omit both playtest fields and reject supplied values. +For `CHARACTER_CREATE`, Game Session's owner-local protection covers only the exact catalog/admission-pointer snapshot and resolved runtime target, revalidated against its current rows when acquired. It does not establish Account membership, grant, or entitlement authority and does not replace World-owned lifecycle protection; see Entity's [character creation owner protection](../entity-management-service/api-contracts.md#character-creation-owner-protection). + The prepared compatibility proof captures the target `gameInstanceId` at exact World lifecycle state `PREPARING` and its exact epoch as the activation precondition, together with the applicable canonical lifecycle proof tuple. Game Session then asks World to perform the owner-database `PREPARING -> ACTIVE` lifecycle CAS against that precondition; World returns the resulting exact `ACTIVE` state/epoch and the same tuple, which Game Session persists in the durable cutover execution/result. Before the admission-pointer CAS, Game Session rereads World authority and requires that same `ACTIVE` state/epoch and exact tuple. A changed state/epoch or tuple invalidates execution and preserves the prior pointer. The pointer CAS binds that durable `ACTIVE` proof and expected pointer version without making Game Session a lifecycle owner. The existing ordering remains: register source cleanup and its binding in the pointer-CAS transaction, then obtain authoritative post-swap pointer/readback confirmation of that registration and source binding before asking World to finalize the cutover hold and request the source `TERMINATING` transition. This confirmation is not the all-owner terminal cleanup acknowledgement; World obtains those owner acknowledgements during its `TERMINATING` workflow before the final `TERMINATED` CAS. ### World-owned cutover hold binding @@ -89,6 +91,7 @@ The internal front-end to lease-owner path is a **target-state** fenced gameplay - `Ping` – basic connectivity check. - `StartSession` – spins up a game instance from a template-driven launch descriptor. Despite the name, this operates on game instances, not player gameplay sessions; gameplay sessions are per-player contexts backed by `session:game:*` keys. +- `AuthorizeStartSession` – accepts the exact canonical Logging & Admin post-authorization handoff and returns only the durable owner-attempt/progress echo; it does not start or create a game instance. - `StopSession` – stops a running game instance. - `RestartSession` – restarts a stopped game instance. - `EnqueueCommand` – adds a player action to the next tick's queue. @@ -129,6 +132,12 @@ The internal front-end to lease-owner path is a **target-state** fenced gameplay ### ADR-0048 operator-write contract +The typed `firemud.game-session.start-session/v1` action schema currently prepares only the human, tenant-scoped `tenantAdmin` authorization branch. Its Account-issued human evidence explicitly omits `assurance`, rejects extra assurance or a substituted global/automation branch, and retains current actor, role, tenant generation, membership and source checks. The normative evidence shape and role-required assurance rules remain owned by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#bounded-owner-delegation). This schema preparation does not make the external route or owner execution complete. + +Source-level Game Session code now contains the StartSession claim, Account redemption, and prepared-action binding. Game Design's consumer of Account's [redeemed-operation projection](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#redeemed-startsession-projection-read) remains unwired; the Game Session owner transaction that commits the selected descriptor and runtime bootstrap/activation also remain unwired. This source-level work does not establish service boot, a routable external StartSession path, or end-to-end execution. + +The typed `AuthorizeStartSession` gRPC transport now carries the exact canonical post-authorization tuple and transient Account reference to the existing owner-attempt coordinator. This method has a narrow JWT-interceptor exemption alongside `Ping`; before tuple decoding, the receiver requires the certificate-derived Logging & Admin peer, and the coordinator binds that peer to the same-namespace tuple and Account redemption. It returns only the durable owner attempt identity, fence, pending phase, and redemption progress. The coordinator is supplied only by `firemud.start-session-operator-authorization` configuration, disabled by default and requiring an explicit owner-claim lease, workload namespace, database/transaction owners, and Account peer/mTLS client inputs; otherwise the receiver fails closed. Contextual configuration proof does not establish full-service runtime. This boundary does not call the legacy instance launcher, create an instance, select a descriptor, or activate World. The numeric `StartSession` RPC remains the existing instance-start path and its legacy validation is unchanged; neither RPC is a routable Logging operator workflow yet. + **Target state:** every mutating operator RPC listed above (`StartSession`, `StopSession`, `RestartSession`, `ToggleFeatureFlag`, `PauseTicksForScope`, `ResumeTicksForScope`, `SetAdmissionPointer`, `ExecutePreparedVersionCutover`, and `PrepareVersionUpgrade`) requires the same durable request identity: `controlPlaneRequestId` plus the canonical `mutationDigest`. Account binds both values into the bounded operator authorization reference, and Game Session recomputes and validates the digest before execution. The owner durably records the request before execution and records a terminal result only after owner-specific commit proof; PostgreSQL-owned mutations commit domain state and result atomically, while Redis-backed projections use the durable claim, fenced mutation marker, and reconciliation contract in ADR 0048. A duplicate request carrying the same digest returns the previously committed result, while the same request identifier with a different digest returns `IDEMPOTENCY_CONFLICT` without applying either payload. A timeout must not create a new request identifier; Logging & Admin may use that identifier only for owner result lookup until the exact operation is reconciled. `FENCE_REJECTED` is non-rearmable and prohibits mutation redelivery. A retry against a current owner or fence is permitted only after the owner has durably recorded terminal `NOT_EXECUTED` proof for the original attempt; it uses a new `ownerMutationId` and a newly fenced attempt while retaining the external request tuple. After authorization expiry, reconciliation is read-only. The current proto and admission-pointer mutation flow remain incomplete against this target. `SetAdmissionPointerRequest` and `ExecutePreparedVersionCutoverRequest` still identify routes by `worldSlug`/`realmSlug` and do not carry durable `realmId`; the persisted/read models and callers have not proved migration to `{tenantId, realmId}`. `StartSessionRequest`, `PauseTicksForScopeRequest`, `ResumeTicksForScopeRequest`, and `GameplayAdmissionPointerMutation` for `SetAdmissionPointer` carry `controlPlaneRequestId` but not `mutationDigest`; those operations must not be reported as ADR-0048-complete until the missing request-field propagation, authorization binding, owner-side digest verification, replay persistence, and focused proof converge together. @@ -141,6 +150,8 @@ The continuation may read and exactly replay the existing immutable association Historical original-operation reconciliation is separate from that live continuation. The local, unregistered historical read returns the exact retained StartSession tuple, actual original attempt/fence, attached Account projection, immutable first selection, and existing descriptor/release association after lease or reference expiry. Its producer accepts only exact same-namespace World or Account workload callers without end-user context. The read creates no claim, renewal, redemption, reselection, pointer/audit mutation, admission authority, current-hold proof, or terminal outcome; missing, conflicting, or malformed retained evidence fails closed. The separate current STARTING association read still requires an unexpired pending lease and is not an after-expiry endpoint. Cross-owner recovery composition and deployed recovery remain open. +The separate local, unregistered `ReadOriginalStartSessionCurrentAttempt` RPC is an Account-facing reconciliation observation. It returns the exact original pending attempt only while both its database-clock owner lease and original Account reference remain unexpired; the owner claim credential never leaves the repository. Account continues to own authorization under its [operator-authorization-reference contract](../account-service/api-contracts.md#operator-authorization-references). The read does not renew the attempt or admit a player and is not registered for production use. + ### gRPC Outcome Handling Game Session follows the [canonical gRPC outcome and transport classification](../../system-architecture-grpc.md#outcome-and-transport-classification). A successfully produced command, control-plane, or read outcome uses its typed response contract; a failure that prevents producing that domain result uses canonical non-OK status with bounded structured details. Game Session preserves stable mutation request identities and reconciles ambiguous timeouts or transport failures before replaying work. Current handlers use a mixture of response-level `ErrorDetail` and transport failures, so exact per-RPC classifications and focused migration proof remain implementation gaps rather than a new service contract. diff --git a/design/architecture/microservices/game-session-service/configuration.md b/design/architecture/microservices/game-session-service/configuration.md index 00b02cf1d3..4100672b7a 100644 --- a/design/architecture/microservices/game-session-service/configuration.md +++ b/design/architecture/microservices/game-session-service/configuration.md @@ -6,6 +6,8 @@ Live pin/convergence reads now expose the authoritative `{scriptPatchVersion, scriptPinEpoch, controlPlaneRequestId}` observation, and instance-bound Automation admission carries and validates the positive epoch. The current-pin/request-result ledger commits atomically with the owner tuple; complete append-only rollout history, bounded authoritative history readback, complete history fields and focused history proof, complete source/target command identity, and remote final-effect fencing remain implementation/proof gaps. See the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps). +The StartSession owner-redemption composition is separately conditional and disabled by default at `firemud.start-session-operator-authorization.enabled`. Enabling it requires an explicit `owner-claim-lease`, the workload namespace, the existing database/transaction owners, and configured Account peer/mTLS client material. Missing startup inputs fail composition; enabling this preparation boundary does not launch an instance, activate gameplay, or expose an external operator ingress. The contextual configuration test is not full-service runtime proof. + ## Environment Variables Game Session follows the configuration scheme from [Environment Variables & Secrets Management](../../infrastructure/environment-and-secrets.md). It requires the [PostgreSQL credentials](../../infrastructure/environment-and-secrets.md#postgresql-credentials) and [Redis connection](../../infrastructure/environment-and-secrets.md#redis-connection) variables. diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index df28765195..81b87a0f2d 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -20,6 +20,7 @@ The sections below define the target-state runtime contract. Current implementat - Hidden same-type Game Session recovery within ADR 0013's qualifying conditions remains an implementation or proof gap; the target is to preserve the session through upstream rebind rather than require a player-visible re-`LOGIN` / re-`PLAY` cycle. - The live `startSession` path keeps the Game Session row and runtime projection `STARTING` until World confirms its fenced `PREPARING -> ACTIVE` transition, then records `RUNNING`; failures before an activation attempt use the existing pre-activation cleanup. Once activation may have been issued or committed, an activation error or ambiguous result, or a later local runtime-state save/finalization failure, retains both the runtime projection and local owner row as `STARTING`, and never calls stale-epoch `failPrepared` or deletes either record. A failure proven before any World termination request is issued may restore the prior `RUNNING` row and runtime state while the World remains `ACTIVE`; once a termination request may have been issued, an error or ambiguous result leaves the local row `STOPPING` and runtime projection absent. Confirmed World termination retries local `STOPPED` finalization and never restores `RUNNING`. Durable stable lifecycle-operation identity and lifecycle readback/reconciliation remain unimplemented, so these local fail-closed quarantines are not a replacement for the target durable lifecycle cleanup workflow. - Current `onCommand` ingress uses the live `{tenantId, gameInstanceId}` boundary as a region surrogate until true region partitioning is shipped; it carries the current `regionEpoch` and a producer-supplied `readSnapshotToken` derived from the command and ownership fence. That token is retained only as an owner-specific manifest input or correlation value, not universal evaluation authority. The target handler-scoped input manifest is owned by the [DSL lifecycle contract](../../system-architecture-scripting-dsl-reference-and-lifecycle.md#read-consistency-contract); current producer/storage behavior is narrower and does not yet seal the complete manifest. +- Canonical region-bootstrap preparation consumes the exact World-owned operational region assignment through the existing workload-pinned lifecycle read, requiring an `ACTIVE` response bound to the complete requested target. This read-only preparation is unregistered and is not assignment allocation, a lifecycle reservation, tick authority, or proof that the current instance-scoped executor consumes the assignment. Game Session must still create a truly absent qualified timeline with `regionEpoch=1` and `lastCommittedTickId=-1` (first tick `0`), install its actual acquired executor fence atomically, and revalidate the same lease before staging. Handoff and restart must preserve an existing timeline; decimal instance-derived region IDs and lease possession do not establish World assignment authority. - Durable command/effect execution currently covers movement and `PUT`, `TAKE`, `WEAR`, and `REMOVE` fully at the existing boundary. Current `GET` is the command spelling for the target `PICKUP`/`PickupVisibleRoomItem` family, and `GET` plus `DROP` also enqueue and execute on that durable command path, but their ADR 0054 spatial correctness remains incomplete until World `TargetingFactSnapshot` attestation/location-version propagation, the shared actor-lock/executor-fence critical section and durable barrier/handoff path, and stale-race proof are implemented. Current movement/item replay rows do not yet prove the ADR 0054 participant guard bound to root `EffectId`, typed operation, target, and request digest, or fail-closed changed reuse. - The target spatial/ambient reconciliation contract is not a current Game Session surface: the typed `EffectReconciliationAuthority`, durable `effect_reconciliation_backlog`/authority schema, immutable effect guards, durable action ledger/results, and list/retry/acknowledgement APIs remain unimplemented. Current persistence is limited to `tick_batch`/`tick_effect` and narrower domain/remote-follow-up reconciliation; see [Game Session API status](./api-contracts.md#implementation-status) and the normative [transaction reconciliation owner](../../system-architecture-transactions.md#reconciliation-owner-of-record-spatialambient-effects). - The target remote-follow-up contract makes terminal timeout/late outcomes immutable under the original identity: exact retries return the stored terminal outcome, and a late-applied result requires a separately documented feature-specific compensation flow. The current `scheduleFollowup` replay path returns an existing retryable-timeout pair or valid terminal pair without mutation, with focused unit proof for terminal-pair replay. This does not establish exact serialized timeout/result arbitration under concurrency, complete terminal-failure mirroring, missing-coordinator recovery, or late-result compensation. The live `late_result_requires_reconciliation` path also writes `LATE_RESULT_RECONCILED`/`PARTIAL` and mirrors `APPLIED`/`PARTIAL` to the origin without a separately identified compensation/saga flow; post-abandon re-drive and compensation ownership remain unproved. diff --git a/design/architecture/microservices/game-session-service/start-session-action-schema.md b/design/architecture/microservices/game-session-service/start-session-action-schema.md index f852fb1e4c..65bbfe575b 100644 --- a/design/architecture/microservices/game-session-service/start-session-action-schema.md +++ b/design/architecture/microservices/game-session-service/start-session-action-schema.md @@ -2,7 +2,7 @@ ## Implementation status -The shared StartSession action, mutation-digest codec, pre-authorization reservation tuple, post-authorization execution tuple, and Account authority-evidence bundle are present as common-platform-core value and codec contracts with focused Java tests and shared Java/Python digest vectors. Logging & Admin also implements durable StartSession pre-authorization reservation persistence and the read-only `ReadCurrentClaimEvidence` transport for Account claim-evidence handoff. Production reservation construction is write-denied and passive/read-only; mutation-capable construction is isolated to test-only fixtures. These implementations do not establish current Account authority. Account issuance and redemption are not wired; Game Session and Game Design runtime registration and owner execution integration are not implemented. External routing and end-to-end launch proof remain unproved. No external route or runtime activation is enabled by this boundary. +The shared typed action, digest codec, pre-/post-authorization tuples and Account authority-evidence bundle are implemented with focused Java tests and shared Java/Python vectors. Source-level StartSession slices now include Logging & Admin durable reservation and authorization handoff, Account ISSUE/RECOVER/REDEEM plus the current-original-operation projection, and Game Session claim/redemption transport and prepared-action binding. Logging production service/repository mutation is mechanically denied pending its approved lifecycle and exact-family retention policy; authenticated evidence reads remain available, and isolated run-owned fixtures do not enable production writing. These slices are not yet an executable runtime: the Account receiving adapter remains disabled by default, its production hosted-terms environment producer and pinned trusted-provider/key-custody composition are absent, and Game Design's prepared selector/current-Account-projection consumer remains unwired. No full physical cross-service smoke has established boot or execution; source-level and component tests do not claim that proof. No external route or runtime activation is enabled by this boundary. ## Normative contract @@ -49,6 +49,6 @@ The SHA-256 preimage follows ADR 0047's exact `mutationDigest/v1` framing. The s The target owner is fixed to `game-session-service` for this schema and is carried separately in the ADR 0048 execution tuple; it is not a digest field. `controlPlaneRequestId`, any separately tagged action-family request identity, reservation owner and claim fence, transport credentials, opaque authorization references, actor assertions, and Account authority evidence are outside these seven grammar fields and are compared at their respective boundaries under [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#bounded-owner-delegation) and [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md#one-correlated-execution). -The action contains no runtime version or patch input. It does not assert current ownership or authority. Owner-domain checks, source selection and execution remain separate runtime prerequisites outside this shared-contract slice. +The action contains no runtime version or patch input. It does not assert current ownership or authority. Game Design selects a launch descriptor under its independently authorized [original-operation read boundary](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#redeemed-startsession-projection-read); the Game Session owner performs its separate domain and execution checks. The shared Java implementation exposes `StartSessionOperatorActionCodec.decode(byte[])`, `canonicalPreimage(...)`, and `mutationDigest(...)`, plus the immutable typed action accessors. Shared Java and Python conformance vectors are stored in [the common vector fixture](../../../../services/common-platform-core/src/test/resources/operator/start-session-mutation-digest-v1-vectors.json). diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index 05d8fcf0a9..6b20fe6bbe 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -2,6 +2,16 @@ This document defines the Logging & Admin Service REST and gRPC surfaces, authentication classes, and endpoint availability expectations. +## StartSession Reservation Claim Evidence + +`logging_admin.v1.StartSessionReservationEvidenceService/ReadCurrentClaimEvidence` is a read-only internal Account handoff for [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md)'s current pre-authorization reservation. It requires the exact certificate-derived `account-service` peer in the configured workload namespace and rejects caller JWT context before reading the reservation. It is not an external operator route, authorization-reference issuance, claim renewal, ownership transfer, or commit-spanning CAS proof. + +The request binds the canonical non-nil `controlPlaneRequestId`, exact bounded canonical UTF-8 `preAuthorizationReservationTuple/v1`, original reservation owner/fence, current claim owner/fence, and an explicit `ISSUE` or `RECOVER` purpose. `ISSUE` accepts only an exact, unexpired, active `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` claim for the original owner or a fresh claim recovered from `RESERVED`. `RECOVER` accepts an exact, unexpired, active `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` or `ACCOUNT_AUTHORIZATION/AUTHORIZED` claim under a distinct recovery owner and later fence; recovery from `AUTHORIZED` is lookup-only. The response echoes the exact tuple, mutation digest, both owner/fence pairs, purpose, claim expiry, and observation time. Missing, changed, expired, or unavailable evidence fails closed; unknown fields and malformed or non-canonical input are rejected. Account validates all returned bindings and freshness before using this snapshot as an issuance or recovery precondition; it must still establish its own current authority and durable operation boundary. + +Implementation status: the claim-evidence receiver and Account read client exist with focused proof. The source-level Logging coordinator and typed Account client now have a Spring composition, but it is available only through the disabled-by-default configuration described in [Configuration](./configuration.md#conditional-startsession-coordinator-composition). This does not register an external operator ingress or establish that an operator command can execute. + +When enabled, the Spring composition requires the configured canonical workload namespace and readable file-backed client mTLS inputs, initializes the typed Account client through the managed bean lifecycle, and connects it to the existing durable reservation service. The configuration supplies no reservation or authority source and exposes no external route. Its context test uses a controlled channel factory and test-only placeholder TLS files; it does not prove physical mTLS, production service startup, remote Account availability, or execution through Game Session launch selection and World activation. The target authorization and owner-forwarding rules remain owned by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md) and [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md). + ## Account Audit Ingress and Receipt The canonical Account-to-Logging & Admin audit ingress is the existing `logging_admin.v1.LoggingAdminService/CreateLogEvent` RPC, converged in place rather than duplicated as a parallel ingress. It is a non-destructive internal service RPC, not an operator/admin mutation. Account is the producer and source authority for account state; Logging & Admin owns the receiver-side audit envelope, durable receipt/readback, deduplication, and audit projection. The audit ingress follows only shared envelope fundamentals (stable identity, event type/schema, producer occurrence time, and at-least-once/idempotent delivery) from [Session Behavior](../../system-architecture-session-behavior.md); it does **not** inherit that document's membership-specific field set or `eventDigest` grammar. Internal workload identity and method authorization follow [Authentication](../../system-architecture-authentication.md) and [gRPC](../../system-architecture-grpc.md#tls-requirements). @@ -101,6 +111,8 @@ The implementation gap is fail-closed: the HTTP controller and Gateway route are - Game instance session lifecycle remains a current Game Session owner-local route family (`/sessions*`), not current Logging & Admin ingress. Its target external operator path is Logging & Admin to Game Session owner RPCs with Account-issued authorization references; no complete current Logging & Admin `/sessions*` route family exists. - Recovery actions beyond pause/resume are hypothetical target coverage until a named typed authoritative-owner contract exists. Do not add `/tick-remediation/remediate`, an open-ended payload language, or a direct Redis mutation path. +The source-level `StartSessionAuthorizationCoordinator` now offers separate `issueHumanAndDispatch` and `recoverAndDispatch` methods that compose its existing authorization/recovery flow with `GameSessionClient`. They call the owner once only when that invocation wins the durable `OWNER_EXECUTION_PENDING` transition; exact/in-progress and recovery-unavailable results do not dispatch, and ambiguous owner outcomes propagate without automatic retry or rearming. The existing `issueHuman` and `recover` methods remain prepare-only. The typed `GameSessionClient` call sends the transient post-authorization tuple/reference and validates Game Session's secret-free durable attempt/progress echo; it requires readable file-backed workload mTLS and pins both request and response to the exact same-namespace Game Session SPIFFE URI derived from the tuple. Ping and stop keep their existing client behavior. These methods are not wired to a routable Logging & Admin StartSession ingress. Mocked tests do not establish physical mTLS, production ingress, prepared launch selection, or instance activation. + **Target ADR 0047/0048 owner-forwarding path:** [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md) owns the Logging & Admin ingress and Account-reference issuance boundary; [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md) owns the phase-qualified execution, redemption, and reconciliation contract. Supported executable operator mutations use Account's canonical [`IssueHumanOperatorAuthorizationReference`](../account-service/api-contracts.md#operator-authorization-references) issuance RPC after Logging & Admin authenticates the current `control-ui` actor and records durable intent. Logging & Admin forwards the opaque bounded reference and unchanged request/generation binding; the authoritative receiving owner recomputes the canonical digest and is the only service that calls Account's `RedeemOperatorAuthorization` RPC. Unattended automation uses Account's `IssueAutomationOperatorAuthorizationReference` with `exact_mtls_workload_plus_versioned_automation_policy`, bound to the exact Logging and Admin workload mTLS identity and current `automation_policy_id`/`automation_policy_version`; the currently supported automation branch is tenant-scoped only and carries the exact target `tenant_generation` through issuance, forwarding, redemption, and owner commit. It carries no human identity, end-user token, or `privileged_control` authority. For each owner contract, predicate evidence comes exclusively from Account's redemption response; any copy forwarded by Logging & Admin is unchanged audit/context evidence, not authority. The local `/moderation/actions` policy-input/audit mutation is a separate receiving-service path: after its gate exists, Logging & Admin redeems its one Account reference exactly once for local persistence and never forwards or reuses that reference. Any future moderation owner-enforcement command uses a separately issued command-bound reference redeemed exactly once by the receiving owner. The moderation route is currently gated/unavailable; it hard fails closed without dispatch or persistence and performs no target fixed-category policy/audit persistence or forwarding. `EvaluateModerationPolicy` is a live read and carries no mutation authorization reference. For non-moderation action families, the request identity is the exact `controlPlaneRequestId` plus digest pair. Moderation and appeal transports instead use dedicated `policyIntentRequestId`, `ownerEnforcementRequestId`, and stable appeal-submission request identities end-to-end; `controlPlaneRequestId` remains a separate correlation-only field and must not carry, replace, alias, or serve as any of those mutation identities. The dedicated identities are never shared or reused. Logging & Admin never becomes a second authorization authority. Current feature-flag and tick forwarding paths, plus internal admission control-plane implementations, are not evidence that this ADR 0048 target contract is complete. For every forwarded owner mutation, excluding the separate local `/moderation/actions` policy-input/audit path, the authoritative owner calls Account's `RedeemOperatorAuthorization` with the separately issued opaque reference and its independently derived request binding. Authorization predicates and generation authority come exclusively from that Account response. Any predicate, generation, checkpoint, or assurance copies forwarded by Logging & Admin are unchanged audit/context evidence only; the owner must not authorize or mutate from those copies, and they are excluded from the canonical `mutationDigest/v1`, which covers the normalized action request rather than ingress assertions. The local moderation route is gated/unavailable; it hard fails closed without dispatch or persistence and does not persist target fixed-category policy/audit evidence, redeem, forward, or enforce. diff --git a/design/architecture/microservices/logging-admin-service/configuration.md b/design/architecture/microservices/logging-admin-service/configuration.md index addecea4c4..288d081343 100644 --- a/design/architecture/microservices/logging-admin-service/configuration.md +++ b/design/architecture/microservices/logging-admin-service/configuration.md @@ -23,10 +23,19 @@ The Logging & Admin Service does **not** connect to Redis at runtime. It consume | `FIREMUD_AUTH_JWT_SECRET` | Legacy HMAC JWT validation secret (transitional only; not for player-facing environments) | *(none)* | | `FIREMUD_AUTH_JWT_SECRET_PATH` | Legacy file path for HMAC JWT validation secret (transitional only; not for player-facing environments) | *(none)* | | `FIREMUD_AUTH_JWT_EXPIRATION_MS` | Lifetime of issued JWTs in milliseconds | `3600000` | -| `FIREMUD_GRPC_WORKLOAD_NAMESPACE` | Namespace required for the exact Account workload identity on the StartSession reservation evidence RPC; blank configuration denies that method | *(none)* | +| `FIREMUD_GRPC_WORKLOAD_NAMESPACE` | Canonical namespace for internal gRPC workload identity checks, including the exact Account identity on the StartSession reservation evidence RPC and enabled StartSession coordinator composition; blank configuration denies that method | *(none)* | | `FIREMUD_GRPC_ACCOUNT_RESERVATION_EVIDENCE_APPROVED_LEAF_FILE` | Absolute path to the protected, method-scoped Account leaf-approval file for `ReadCurrentClaimEvidence`; blank, unreadable, or invalid policy denies the method | *(none)* | | `FIREMUD_SERVICES_ACCOUNT_SERVICE` | gRPC endpoint (host:port) for the Account Service | *(none)* | | `FIREMUD_SERVICES_GAME_SESSION_SERVICE` | gRPC endpoint (host:port) for the Game Session Service | *(none)* | +| `FIREMUD_LOGGING_ADMIN_START_SESSION_OPERATOR_AUTHORIZATION_ENABLED` | Explicitly enables the local StartSession authorization coordinator composition | `false` | + +## Conditional StartSession Coordinator Composition + +The `FIREMUD_LOGGING_ADMIN_START_SESSION_OPERATOR_AUTHORIZATION_ENABLED` opt-in defaults to `false`. When explicitly enabled, Spring composes the existing durable reservation service with `StartSessionAuthorizationCoordinator` and an Account `StartSessionOperatorAuthorizationClient`; the client is initialized and closed through the managed Spring bean lifecycle. + +Enabled composition requires a canonical `firemud.grpc.workload-namespace` and readable file-backed gRPC client certificate-chain, private-key, and CA inputs. These use the existing common gRPC TLS resolver and the `FIREMUD_GRPC_CERT_CHAIN_PATH`, `FIREMUD_GRPC_PRIVATE_KEY_PATH`, and `FIREMUD_GRPC_CA_CERT_PATH` inputs above. Missing, plaintext, incomplete, or non-file-backed TLS inputs fail composition rather than selecting defaults. The canonical operator contracts remain in [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md), [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md), and the [StartSession reservation evidence contract](./api-contracts.md#startsession-reservation-claim-evidence). + +This configuration creates no external operator route, trusted caller context, reservation provider, or gameplay activation. The focused configuration test uses a controlled channel factory and test-only placeholder files; it is wiring proof only, not physical mTLS, production startup, external-ingress, Game Session launch-selection, or World activation proof. `logging_admin.v1.StartSessionReservationEvidenceService/ReadCurrentClaimEvidence` is the only method exempted from the shared Bearer-JWT interceptor. The server's required client-certificate handshake and verified TLS peer interceptor remain enabled. The receiver requires both the exact Account SPIFFE identity in `FIREMUD_GRPC_WORKLOAD_NAMESPACE` and approval of the SHA-256 fingerprint derived from the presented TLS leaf. It reads the configured file for each request; a missing path, read failure, malformed file, or unapproved leaf denies the request before reservation access. The JWT header is not an identity source for this method. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 75c31b168a..3cb60a7cd6 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -135,8 +135,26 @@ Entry format: - Admission-history latency observation: after the merged #3173 runtime promotion, the next measured request took 35.2 seconds with 86 history entries, improved from the recorded 55.2 seconds and 170 entries. Selected-target status still required substantial history work. Further optimization is deliberately deferred to the controller owner to preserve admission identity and quota checks. Reconsideration trigger: the owner evaluates these measured traces at its next controller performance checkpoint. - Readiness-projection observation: Gameplay has not independently verified final capped-readiness recovery on a new candidate; the reported #3171 inconsistency remains owned by Overseer controller work. Reconsideration trigger: an exact candidate with exhausted human caps, resolved findings, current required checks and a current native guard establishes the final projection, allowing stewardship to retain only any remaining discrepancy. +- `2026-10-12`: Group physical PostgreSQL proof after transient CI infrastructure failures + - Context: Local full-check selected PostgreSQL cases but skipped them because Docker was unavailable. Recent CI also failed resolving Kotlin 2.4.10 POM dependencies from the Gradle Plugin Portal, although the redirected POM URL now returns HTTP 200, and one Redis image pull from ECR returned `toomanyrequests: Rate exceeded`. + - Observation: Physical PostgreSQL proof remains pending; the CI logs establish these failures but not a common root cause or a global artifact outage. + - Expected pattern: Group affected physical PostgreSQL proof with fresh-source CI and retry only the current failed job when transient evidence supports it. Do not claim missing global artifacts or count metadata-deferred callbacks as cases. Existing maintenance-board diagnostics own follow-up; no registry, cache, pipeline, or infrastructure rollout is established. + - Reconsideration trigger: revisit after fresh-source CI completes the affected physical PostgreSQL suites, or another dependency/image-fetch failure changes the evidence. Retain while physical proof is pending or the maintenance owner still needs runner diagnostics; close the observation through authorized stewardship once both are resolved. + +- `2026-10-12`: Hosted admission during a parent merge left CLI overlap unavailable + - Context: #3122's final Hosted request posted on unchanged head `24ee463534999c79e89947d72da9bd98215d500f` while parent #3172 merged during admission. The controller retained the actual reviewed base and trigger [6121614014](https://github.com/benhook1013/FireMUD/pull/3122#issuecomment-6121614014). + - Observation: POST succeeded but reported `SQLite Hosted terminal capture failed (HostedCaptureError)`. Subsequent CLI admission refused overlap because it could not attribute the active Hosted request to the exact published head. The child head and actual base were unchanged, and the native wait observed Hosted as active. Overseer subsequently traced the comparison to the configured queue parent instead of the unchanged actual PR base. Terminal Hosted sync recovered the attributable result; the comparison repair and verified overlap recovery remain pending. + - Expected pattern: preserve the active review and its base, consume terminal evidence, and investigate native capture/overlap diagnostics through the controller maintenance owner. Do not post another trigger or bypass admission; an opaque capture warning should expose enough context for bounded recovery. + - Reconsideration trigger: revisit when this exact Hosted trigger completes and native capture/CLI overlap recovery is verified, or when the controller maintenance owner establishes the capture cause. Retain while attribution or recovery diagnostics remain unresolved. + - `2026-10-12`: Retire the bounded external PostgreSQL test modes - Context: Follow-up to the `2026-10-06` remote test infrastructure authorization observation. The Overseer selected removal after the User permitted retiring the partial service-specific external modes. - Disposition: Account and Game Design test fixtures now retain only the disposable Testcontainers backend. External URL, credential, and tunnel-specific configuration hooks are removed; missing Docker leaves physical PostgreSQL proof unavailable. - Historical limits: Original provisioning authorization remains unverified. Removing the source hooks does not establish that the remote fixture or forwarding infrastructure has been deleted; resource ownership and any authorized cleanup remain separate responsibilities. - Reconsideration trigger: A future external test backend requires an explicitly supported isolation, lifecycle, credential, version, and proof contract plus any necessary infrastructure authorization. + +- `2026-10-12`: Verify the live base branch after concurrent maintenance merges + - Context: #3122 at `b71ff6875c3949266b269876707394be3c25f553` conflicted with the newly merged #3177. GitHub PR metadata still reported base `750626108b233fa96f9fa0177d682342b86a0171`, while a Git fetch showed develop at `5769a353bb222ae22428b5104f4037fb79a8a8bb`; the User noticed the conflict before the worker did. + - Observation: A saved head/base tuple and prior proof did not establish current mergeability. The normal merge exposed one documentation conflict; the maintenance fixture changes merged cleanly. + - Expected pattern: At publication and closeout, verify the actual base branch tip and current mergeability through the bounded canonical topology/status checks. Treat a stale PR base OID or missing new-head source CI as unresolved state, and reconcile before claiming readiness. + - Reconsideration trigger: Verify the next published front against its actual remote base and current required CI; retain any remaining stale-base diagnostic gap for controller maintenance. diff --git a/design/project-management/design-alignment/design-capability-allocation-microservices.md b/design/project-management/design-alignment/design-capability-allocation-microservices.md index d98d1dea9f..8672c5e9b6 100644 --- a/design/project-management/design-alignment/design-capability-allocation-microservices.md +++ b/design/project-management/design-alignment/design-capability-allocation-microservices.md @@ -73,10 +73,10 @@ This ledger maps every Markdown source under [`design/architecture/microservices | --- | --- | --- | --- | --- | --- | | `design/architecture/microservices/entity-management-service/README.md` | `GR-3` | `AA-3`, `AR-1`, `EA-1`, `GR-1`, `GR-2`, `SF-1`, `SF-2` | Whole file. Character discovery scope -> `AA-3`; template authoring -> `AR-1`; authoritative location exclusion -> `GR-2`; LOOK presentation handoff -> `EA-1`. | Service overview | World owns location and occupancy; Entity owns actor/item state and containment. | | `design/architecture/microservices/entity-management-service/api-contracts.md` | `GR-3` | `AR-1`, `EA-1`, `GR-2`, `GR-4`, `SF-1`, `SF-2`, `PO-4` | Overrides: **Design-Time APIs** and **Digest Input Manifest** -> `AR-1`; **LOOK Entity Listing Contract** -> `EA-1`/`GR-2`; **Actor State Query** -> `GR-4`; **Implementation Status (LOOK Slice)** -> `PO-4`. | API contract | LOOK returns structured entity facts; it does not own transcript rendering. | -| `design/architecture/microservices/entity-management-service/character-create-action-schema.md` | `GR-3` | `AA-3`, `AR-1`, `SF-1`, `SF-2` | Whole file. Authored-source and policy handoffs -> `AR-1`; admission/account authority -> `AA-3`; authenticated owner and protocol boundaries -> `SF-1`; durable mutation workflow -> `SF-2`. | Character-creation action schema | Canonical Entity-owned CHARACTER_CREATE/1 preimage contract; allocation records ownership without duplicating its schema. | | `design/architecture/microservices/entity-management-service/configuration.md` | `PO-3` | `GR-3`, `SF-1`, `SF-2` | Whole file. Cache variables -> `SF-2`; TLS/proto details -> `SF-1`. | Configuration contract | No unresolved ambiguity. | | `design/architecture/microservices/entity-management-service/operations.md` | `PO-4` | `GR-1`, `GR-3`, `SF-2` | Overrides: **Tick Locking** and **Tick Idempotency** -> `GR-1`/`SF-2`. | Operations contract | No unresolved ambiguity. | | `design/architecture/microservices/entity-management-service/runtime-and-data.md` | `GR-3` | `AR-1`, `AR-3`, `GR-1`, `GR-2`, `GR-4`, `SF-1`, `SF-2`, `PO-1` | Overrides: design/version portions of **Data Model and Versioning** -> `AR-1`; **Replacement-Instance State Classification** -> `AR-3`; **Inventory Transfer Audit** -> `PO-1`; **Instance Termination Cleanup Contract**, **Workflow Participation**, **Redis Role and Prefixes**, and **Version Sources for Entity Caches** -> `SF-2`; location/spatial boundaries -> `GR-2`. | Runtime/data contract | Character location remains explicitly World-owned. | +| `design/architecture/microservices/entity-management-service/character-create-action-schema.md` | `GR-3` | `AA-1`, `AA-2`, `AA-3`, `AR-1`, `GR-1`, `GR-2`, `SF-1`, `SF-2` | Whole file. Account authority -> `AA-1`; gameplay admission -> `AA-2`; realm admission and playable-state policy -> `AA-3`; authored inputs -> `AR-1`; runtime coordination -> `GR-1`; location boundaries -> `GR-2`; action schema -> `SF-1`; durable mutation workflow -> `SF-2`. | Character-creation action schema | Entity owns character mutation; account, admission, authoring, runtime, location, schema, and workflow concerns remain handoffs. | ## Game Design Service diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index e7fa2dd989..aa95dc8423 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -14,10 +14,12 @@ Focused unit tests cover immutable replay, descriptor comparison, certificate-pi This tracker consolidates the live Game Session execution substrate by capability. The recorded boundaries describe current implementation status and bounded follow-up work. -Local Game Session producer code includes an unregistered historical original-StartSession evidence read for exact same-namespace World or Account workloads and an unregistered World-only initial-admission owner-proof read bound to the configured namespace and full hold tuple. The latter returns a point-in-time `PENDING` snapshot or a terminal result backed by a positive `COMMITTED` pointer with matching audit or a durable `ABORTED` outcome. Exact-head [Validation run 38049505627](https://github.com/benhook1013/FireMUD/actions/runs/38049505627) on `efcd23e428393e71d10eb406838cee030d283cf6` executed 2,054 unit, 234 integration, and 39 cross-service Game Session cases; all 2,327 cases passed with zero skips, failures, or errors. Its JUnit artifact includes the owner-proof and original-owner tests plus the PostgreSQL-backed owner-attempt, association, descriptor, and initial-admission fixtures. Neither endpoint is deployed; these results do not establish continuous hold protection through cross-owner commit, terminal composition, restart recovery, production activation, or playable-state closure. +Local Game Session producer code includes an unregistered historical original-StartSession evidence read for exact same-namespace World or Account workloads, an unregistered World-only initial-admission owner-proof read bound to the configured namespace and full hold tuple, and a separate source-only Account-facing current-attempt read. The latter returns the exact original pending attempt only while its owner lease and Account reference are live. Its composed Common/Game Session checks, generated SQL model, migration-version and documentation checks passed locally; PostgreSQL execution remains pending because the local database-dependent cases skipped. The RPC is not registered or deployed. The initial-admission owner-proof read returns a point-in-time `PENDING` snapshot or a terminal result backed by a positive `COMMITTED` pointer with matching audit or a durable `ABORTED` outcome. Exact-head [Validation run 38049505627](https://github.com/benhook1013/FireMUD/actions/runs/38049505627) on `efcd23e428393e71d10eb406838cee030d283cf6` executed 2,054 unit, 234 integration, and 39 cross-service Game Session cases; all 2,327 cases passed with zero skips, failures, or errors. Its JUnit artifact includes the owner-proof and original-owner tests plus the PostgreSQL-backed owner-attempt, association, descriptor, and initial-admission fixtures. Neither existing endpoint is deployed; those results do not establish continuous hold protection through cross-owner commit, terminal composition, restart recovery, production activation, or playable-state closure. Gameplay-session context remains on the implementation-local `sessionctx:*` keys and per-instance binding identity. The target authenticated `session:game:{tenantGameplayTag}:...` family, persisted tenant-tag allocation, and namespace-qualified controller uniqueness are not implemented or end-to-end proved; the canonical tenancy and focused-isolation requirements remain in [Multi-Tenancy](../../architecture/system-architecture-multi-tenancy.md#data-separation-per-service). +Canonical region-bootstrap receiving preparation resolves the exact World operational UUID from a workload-pinned `ACTIVE` lifecycle read bound to the complete target request; it has no runtime registration or mutation path. Focused resolver proof does not establish real owner composition or protected currentness through a later commit. Qualified timeline persistence, the actual Redis lease/durable executor-fence handshake, same-lease staging revalidation, takeover/restart preservation, and physical composition remain open under the [Game Session runtime/data contract](../../architecture/microservices/game-session-service/runtime-and-data.md#implementation-status). The legacy instance-scoped runtime row and its decimal region surrogate are unchanged; neither supplies canonical initialization or playable proof. + Retained bootstrap correction: V8 recognizes only the unchanged, provenance-backed historical demo/sandbox pair that was seeded with two public-production realms. It changes sandbox's public flag and advances only its catalog revision, retains runtime pointer and durable realm/namespace identity, and appends an immutable repair event in the same transaction. Unknown, operator-edited, incomplete, extra-public, or conflicting-history catalogs remain untouched and fail closed. This is not World-owner lifecycle or initial-bind proof. PostgreSQL execution remains a required separate check; the local environment has no Docker or PostgreSQL runtime. Admission-catalog foundation status: Game Session pointer and audit rows now persist a separate positive `catalogRevision` and stable UUID `realmId`/`playableStateNamespaceId`; repository updates check both pointer version and catalog revision, and player-facing catalog/read projections fail closed on ambiguous tenant catalogs or incomplete identity. Runtime control-plane reads also reject persisted pointers with nonpositive `catalogRevision` or missing `realmId`/`playableStateNamespaceId` before constructing `GameInstanceRuntimeState`, returning `ADMISSION_POINTER_AUTHORITY_UNAVAILABLE` without partial pin/version metadata or pointer entries. Same-tenant world and realm selectors that collide under case-folding now fail closed in authority-backed catalogs and fixture catalogs while preserving the canonical routing tuple and revision. No-caller text `WORLDS`/`REALMS` and gRPC `ListGameplayWorlds`/`ListGameplayRealms` now share a public-production-only projection that retains the existing catalog health and public-realm cardinality checks; internal pointer health reads and explicit private admission/grant checks still see private realm authority. Caller-authorized private discovery remains unavailable until Account/caller integration. Focused regressions cover mixed-case collisions, single-selector resolution, private-only world omission, and private realm omission; validation remains pending. This is implemented whole-response fail-closed behavior, not successful migration or runtime proof. This does not implement a World-owner-validated initial bind, strict `JOIN`, or production activation. The configuration-driven pointer initializer validates configured seed shape without inserting pointer rows, and GS/WMS raw runtime seeding has been removed. Neither configured seeds nor legacy seed configuration provides World lifecycle proof. The extracted 35-path foundation passed a serialized `run-locked-gradle.sh` invocation of `:game-session-service:spotlessJavaApply :game-session-service:test :game-session-service:compileIntegrationTestJava linkCheck lintMarkdown --no-configuration-cache` on 2026-10-02. This executed unit proof and compiled PostgreSQL migration tests; no PostgreSQL/runtime execution proof is claimed. 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 77dde5715f..fd6ba3cc32 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +### Entity character-creation denial + +The existing scalar-only Entity `CreateCharacter` RPC now returns `FAILED_PRECONDITION` before allocation for valid requests in shared and isolated scopes; the focused service test also confirms the malformed zero-account case remains `INVALID_ARGUMENT`. This is denial-only implementation and unit proof. The canonical Account producer, authenticated owner proof, exact catalog/admission-pointer evidence, Game Session and World protections, and Entity durable terminal composition remain missing, so character creation is unavailable under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Entity owner-protection contract](../../architecture/microservices/entity-management-service/api-contracts.md#character-creation-owner-protection). + Restricted original-claim evidence continuation remains inactive and preparation-only; its bounded preparation and proof limits are recorded under [restricted original-claim continuation preparation](#restricted-original-claim-evidence-continuation-preparation). ### Account signer/currentness storage evidence preparation @@ -24,6 +28,14 @@ The direct expiry-erasure correction adds [V126.1](../../../services/account-ser The current Account cut adds V126 operator-authorization storage, default-inactive StartSession authorization sources, Control-UI issuance and Redis coordination, Account-owned JWKS and signer-materialization adapters, and readiness-probe sources. This preparation is tracked under AA-1.3, whose state remains `partial` / `drift-found`. StartSession composition is disabled by default. Materializer trust is disabled by default, and absent trust denies every materializer RPC. Missing bootstrap-coordinator composition denies enrollment and promotion operations; trusted generation requests, observations, and result reads remain available. No runtime issuer, signer-promotion coordinator, or consumer coordinator is registered. Production anchors include [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java), [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java), and [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql). Focused test anchors include [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java), [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java), [AccountControlUiOwnerWorkflowPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerWorkflowPostgresIntegrationTest.java), [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java), and [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql). At pinned head `22a6c39e3f1754acebf95477d6968c69edde66fd`, Validation run `38096949593` and Account artifact `11686863341` record the nine changed PostgreSQL/Redis integration suites executing 35 cases with zero failures, errors, or skips, plus 23 RestoredInventory unit cases. That proof remains historical and applies only to its recorded head and fixtures. Later hosted Validation run `38113324723` succeeded at head `f6d34031221a3337e7a958ac4b085554460668c9`; Account job `114394304424` and artifact `11693535744` record four owner-workflow PostgreSQL tests physically executed, including signer quarantine. This is bounded physical fixture proof, not deployment or runtime activation. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, Validation run `38117703529`, Account job `114405941820`, and artifact `11693819544` tested merge commit `9ca30839c8a46446f01d0a441e6e830fab8bca86` with ordered parents `4ab98ba1f0a2464349ed21ce59e7ef44ecd79e8c` and `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`; the Control-UI issuance PostgreSQL suite passed 5/5 and the StartSession authorization repository PostgreSQL suite passed 15/15 with zero skips, failures, or errors. This is bounded exact-head fixture proof, not deployment or runtime activation, and aggregate validation remains red on the unrelated Gateway fixture. The Account-owned [reservation-evidence client](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java) uses the existing Logging & Admin proto contract; completing the flow also depends on the out-of-cut Logging & Admin authorization coordinator/client and Game Session redemption composition. mTLS execution, the complete Logging & Admin/Game Session/World flow, player-facing JWT readiness, and activation remain unproved. V126/V126.1/V126.2 remain passive storage/source preparation; bounded cleanup and late revocation remain incomplete. Canonical JWT and signer behavior remains in [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md), with Account-local consequences in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). +### Account fresh original-ACK storage preparation + +This preparation is owned by AA-1.3 in [Capability Status](#capability-status), whose state remains `partial` / `drift-found`; it adds passive original-ACK storage preparation only and does not change the capability state or close an activation gate. + +The receiving Account cut imports the preserved original-ACK storage preparation from `codex/gameplay-game-design-publication-storage-foundation-20261009` at `d66d36951d3df780641e0ef04819f15df52ddc39` plus its uncommitted PostgreSQL 18 fresh-path changes. Only the receiving migration filenames are allocated anew: V140 ← source V118 (lease operations), V141 ← V119 (unknown-decision abort), V142 ← V120 (original-finalization stamp and experimental confirmation storage), V143 ← V121 (global pending fences), V144 ← V122 (original-ACK receipt), V145 ← V136 (experimental confirmation write retirement), and V146 ← V139 (PostgreSQL 18 fresh-insert guard). Their SQL bytes, including historical version comments, are preserved. Source V122 retains SHA-256 `c4f66ce16c77514717cbc9d2e0d65bc8c8ee0882239371d8518f587a0ef53490`, matching the historical `2cb445617f584d25c805f5c08e9dde67fff4efc4` migration; no donor renumbering or external migration application is performed. + +The unregistered executors and receipt repository preserve the exact original operation, source identity, finalization XID, unchanged expiry and original clock bound. Fresh original and independent receipt COMMITs are explicitly PostgreSQL 18-only; retained COMMITTED retries cannot mint another acknowledgement, and the unchanged historical durable reader still denies PostgreSQL 18 recovery or retained-receipt retries. The `AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest` PostgreSQL prototype contains 18 `@Test` cases and uses the receiving canonical `AccountPostgresIntegrationFixture(true)` without importing another fixture or build dependencies. The copied unit proof sources are separate mocked-JDBC cases. Full-check selected the PostgreSQL cases, but they skipped because local Docker was unavailable; physical PostgreSQL proof remains pending the consolidated gate. No donor or earlier receiving result proves this new intake. Authentication, current ownership/admission, runtime registration, activation and playable capability status remain unchanged. Account-local storage consequences remain in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). + ### Restricted original-claim evidence continuation preparation This inactive owner continuation may read or replay the exact immutable association pin and create at most one immutable descriptor evidence pin under that same association and original `PENDING` claim, attempt, and fence. Authenticated Account and Game Design reads occur outside SQL; owner and association state is locked and rechecked before descriptor pinning. Initial association creation also requires the exact original Account authorization reference to remain unexpired at the PostgreSQL write, independently of the owner-claim lease. Existing association replay and historical reads retain their reconciliation semantics; this preparation does not renew or reissue authorization or create a replacement claim. Its classes remain unregistered; added proto/schema support does not activate a runtime route or grant mutation authorization or player admission. Descriptor evidence does not complete canonical launch, initial World-backed admission, or historical owner reconciliation. The canonical boundary is [Game Session restricted original-claim evidence continuation](../../architecture/microservices/game-session-service/api-contracts.md#restricted-original-claim-evidence-continuation) and [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md). @@ -92,7 +104,7 @@ These links add decision provenance only; they do not upgrade player-access or s | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [RuntimeAccountIdentityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [RuntimeAccountIdentityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The focused unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped because Docker is unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. Authentication results and JWT subjects remain unchanged; profile/export profile identity fields and tenant IDs remain numeric and full portable export is not implemented. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. `RuntimeAccountIdentityGrpcService` implements the authenticated Account-owner UUID/provenance read; its 31 focused unit cases, integration-source compilation, and formatting/documentation checks do not prove PostgreSQL execution or a live mTLS handshake, and do not enable UUID authentication or gameplay admission. Lifecycle-state retention remains tracked under AA-1.3. | | `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql) | [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) | [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. On fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance does not yet validate that grant. 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). | -| `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) | [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) | [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) | [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` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. | +| `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) | [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) | [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) | [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` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. | | `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) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `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) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. 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 row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | | `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [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) | [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) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current text `PLAY` checks membership and entitlement before persisted actor selection, but fresh connect-token issuance does not validate the applicable non-public realm grant; final Account admission and complete private/playtest grant and entitlement authority remain open under [Game Session admission](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary). 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. | diff --git a/dev-tools/tests/compose-grpc-mtls-contract.sh b/dev-tools/tests/compose-grpc-mtls-contract.sh index d05c79c135..7adbef898c 100644 --- a/dev-tools/tests/compose-grpc-mtls-contract.sh +++ b/dev-tools/tests/compose-grpc-mtls-contract.sh @@ -296,7 +296,12 @@ import re import sys lines = pathlib.Path(sys.argv[1]).read_text(encoding="utf-8").splitlines() -for service in ("entity-management-service", "game-design-service", "world-management-service", "game-session-service"): +for service in ( + "entity-management-service", + "world-management-service", + "game-session-service", + "game-design-service", +): headers = [index for index, line in enumerate(lines) if line == f" {service}:"] assert len(headers) == 1, service start = headers[0] diff --git a/dev-tools/validation/test_design_capability_allocation.py b/dev-tools/validation/test_design_capability_allocation.py index dff95b88fa..61180fdd9c 100644 --- a/dev-tools/validation/test_design_capability_allocation.py +++ b/dev-tools/validation/test_design_capability_allocation.py @@ -251,6 +251,22 @@ def test_microservice_primary_drift(self) -> None: "unexpected primary capability", ) + def test_start_session_action_schema_appendix_allocation(self) -> None: + self.assertEqual( + self.validator.expected_microservice_allocation( + "design/architecture/microservices/game-session-service/start-session-action-schema.md" + ), + ("AR-3", "Operator action schema"), + ) + + def test_character_create_action_schema_appendix_allocation(self) -> None: + self.assertEqual( + self.validator.expected_microservice_allocation( + "design/architecture/microservices/entity-management-service/character-create-action-schema.md" + ), + ("GR-3", "Character-creation action schema"), + ) + def test_adr_primary_allocation_drift_with_adjusted_counts(self) -> None: with fixture_root() as directory: root = Path(directory) diff --git a/protos/game-session/v1/game_session_service.proto b/protos/game-session/v1/game_session_service.proto index 36af762c63..010eec9f8a 100644 --- a/protos/game-session/v1/game_session_service.proto +++ b/protos/game-session/v1/game_session_service.proto @@ -13,6 +13,8 @@ option java_multiple_files = true; service GameSessionService { rpc Ping(PingRequest) returns (PingResponse); rpc StartSession(StartSessionRequest) returns (StartSessionResponse); + rpc AuthorizeStartSession(AuthorizeStartSessionRequest) + returns (AuthorizeStartSessionResponse); rpc StopSession(StopSessionRequest) returns (StopSessionResponse); rpc RestartSession(RestartSessionRequest) returns (RestartSessionResponse); rpc EnqueueCommand(EnqueueCommandRequest) returns (EnqueueCommandResponse); @@ -109,6 +111,32 @@ message StartSessionResponse { shared.v1.ErrorDetail error = 2; } +// Typed non-activating operator handoff. This transport only records Account redemption progress; +// it does not create or start a game instance and does not return a session identifier. +message AuthorizeStartSessionRequest { + bytes canonical_post_authorization_execution_tuple_bytes = 1; + string operator_authorization_reference = 2; +} + +enum StartSessionOwnerAuthorizationProgress { + START_SESSION_OWNER_AUTHORIZATION_PROGRESS_UNSPECIFIED = 0; + START_SESSION_OWNER_AUTHORIZATION_PROGRESS_EXACT_REPLAY = 1; + START_SESSION_OWNER_AUTHORIZATION_PROGRESS_ACCOUNT_OUTCOME_AMBIGUOUS = 2; + START_SESSION_OWNER_AUTHORIZATION_PROGRESS_ACCOUNT_PROJECTION_ATTACHED = 3; +} + +message AuthorizeStartSessionResponse { + string target_namespace = 1; + string control_plane_request_id = 2; + string mutation_digest = 3; + string owner_attempt_id = 4; + string owner_mutation_id = 5; + int64 owner_fence = 6; + string owner_phase_state = 7; + StartSessionOwnerAuthorizationProgress progress = 8; + shared.v1.ErrorDetail error = 9; +} + message StopSessionRequest { string session_id = 1; } diff --git a/protos/game-session/v1/original_start_session_current_attempt_read.proto b/protos/game-session/v1/original_start_session_current_attempt_read.proto new file mode 100644 index 0000000000..bfb4f8893d --- /dev/null +++ b/protos/game-session/v1/original_start_session_current_attempt_read.proto @@ -0,0 +1,36 @@ +syntax = "proto3"; + +package game_session.v1; + +import "google/protobuf/timestamp.proto"; + +option java_package = "net.firedevops.firemud.gamesession.v1"; +option java_multiple_files = true; + +// Unregistered, observation-only read of one exact live original StartSession owner attempt. +// It exposes no claimant credential and grants no mutation, renewal, redemption, or admission authority. +service OriginalStartSessionCurrentAttemptReadService { + rpc ReadOriginalStartSessionCurrentAttempt( + ReadOriginalStartSessionCurrentAttemptRequest) + returns (ReadOriginalStartSessionCurrentAttemptResponse); +} + +message ReadOriginalStartSessionCurrentAttemptRequest { + int32 schema_version = 1; + // Fresh correlation UUID for this observation; it is not a durable mutation identity. + string read_request_id = 2; + string target_namespace = 3; + bytes canonical_post_authorization_tuple = 4; + string expected_owner_attempt_id = 5; + string expected_owner_mutation_id = 6; + int64 expected_owner_fence = 7; +} + +message ReadOriginalStartSessionCurrentAttemptResponse { + ReadOriginalStartSessionCurrentAttemptRequest request = 1; + string phase_state = 2; + google.protobuf.Timestamp original_lease_expires_at = 3; + bytes account_redemption_projection = 4; + // Raw lowercase SHA-256 of account_redemption_projection. + string account_redemption_projection_digest = 5; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionLeaseOperation.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionLeaseOperation.java new file mode 100644 index 0000000000..11805e3eef --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionLeaseOperation.java @@ -0,0 +1,47 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; + +/** Durable Account storage readback only; even COMMITTED is not authenticated admission proof. */ +public record AccountGameplayAdmissionLeaseOperation( + AccountGameplayAdmissionLeaseEvidence evidence, + State state, + UUID bindingDecisionId, + UUID orphanCleanupId) { + public AccountGameplayAdmissionLeaseOperation { + Objects.requireNonNull(evidence); + Objects.requireNonNull(state); + if ((bindingDecisionId != null + && (bindingDecisionId.version() != 4 || bindingDecisionId.variant() != 2)) + || (orphanCleanupId != null + && (orphanCleanupId.version() != 4 || orphanCleanupId.variant() != 2))) { + throw new IllegalArgumentException("Canonical non-nil UUIDv4 terminal identity required"); + } + if ((state == State.PENDING && (bindingDecisionId != null || orphanCleanupId != null)) + || (state == State.COMMITTED && (bindingDecisionId == null || orphanCleanupId != null)) + || (state == State.ABORTED && orphanCleanupId == null)) { + throw new IllegalArgumentException("Incomplete admission operation storage state"); + } + } + + public enum State { + PENDING, + COMMITTED, + ABORTED + } + + /** + * ABORTED retains exact binding/token evidence as pending work, never completed cleanup. A null + * decision is unknown or unobserved, never authoritative proof that no decision exists. + */ + public boolean hasPendingOrphanCleanup() { + return state == State.ABORTED; + } + + @Override + public String toString() { + return "AccountGameplayAdmissionLeaseOperation[state=" + state + "]"; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionOriginalAckReceipt.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionOriginalAckReceipt.java new file mode 100644 index 0000000000..70dc704b18 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionOriginalAckReceipt.java @@ -0,0 +1,97 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.math.BigInteger; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; + +/** + * Immutable storage readback of a trusted-JVM original COMMIT acknowledgement. + * + *

{@code committedBeforeMs} is opaque in-process capability evidence produced after the original + * physical COMMIT. SQL checks its shape and exact operation binding; SQL does not derive, + * authenticate, or independently prove that clock value. This receipt grants no current authority, + * Game Session installation, cleanup, or gameplay admission. + */ +public record AccountGameplayAdmissionOriginalAckReceipt( + AccountGameplayAdmissionLeaseOperation operation, + short schemaVersion, + UUID requestId, + UUID accountId, + UUID leaseId, + long leaseFence, + String evidenceSha256, + UUID bindingDecisionId, + long expiresAtMs, + String finalizationXid, + long committedBeforeMs, + String receiptXid) { + private static final BigInteger UINT64_MAX = + BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE); + + public AccountGameplayAdmissionOriginalAckReceipt { + Objects.requireNonNull(operation, "original committed lease operation is required"); + Objects.requireNonNull(requestId, "request ID is required"); + Objects.requireNonNull(accountId, "Account ID is required"); + Objects.requireNonNull(leaseId, "lease ID is required"); + Objects.requireNonNull(evidenceSha256, "evidence digest is required"); + Objects.requireNonNull(bindingDecisionId, "binding decision ID is required"); + Objects.requireNonNull(finalizationXid, "finalization transaction ID is required"); + Objects.requireNonNull(receiptXid, "receipt transaction ID is required"); + + var evidence = operation.evidence(); + var carrier = evidence.carrier(); + var scope = (java.util.Map) carrier.get("bindingScope"); + UUID expectedRequest = UUID.fromString((String) carrier.get("requestId")); + UUID expectedLease = UUID.fromString((String) carrier.get("leaseId")); + UUID expectedAccount = UUID.fromString((String) scope.get("accountId")); + long expectedFence = evidence.leaseFence().longValueExact(); + long expectedExpiry = Long.parseLong((String) carrier.get("expiresAt")); + + if (operation.state() != State.COMMITTED + || operation.bindingDecisionId() == null + || schemaVersion != 1 + || !requestId.equals(expectedRequest) + || !accountId.equals(expectedAccount) + || !leaseId.equals(expectedLease) + || leaseFence <= 0L + || leaseFence != expectedFence + || !evidenceSha256.matches("[0-9a-f]{64}") + || !evidenceSha256.equals(evidence.sha256()) + || !bindingDecisionId.equals(operation.bindingDecisionId()) + || expiresAtMs <= 0L + || expiresAtMs != expectedExpiry + || committedBeforeMs <= 0L + || committedBeforeMs >= expiresAtMs) { + throw invalid(); + } + + requireCanonicalFullXid(finalizationXid); + requireCanonicalFullXid(receiptXid); + if (finalizationXid.equals(receiptXid)) throw invalid(); + } + + private static void requireCanonicalFullXid(String value) { + if (value.isEmpty() || !value.matches("[1-9][0-9]*")) throw invalid(); + try { + BigInteger xid = new BigInteger(value); + if (xid.signum() <= 0 || xid.compareTo(UINT64_MAX) > 0) throw invalid(); + } catch (NumberFormatException failure) { + throw invalid(); + } + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException( + "Invalid original Account admission acknowledgement receipt"); + } + + @Override + public String toString() { + return "AccountGameplayAdmissionOriginalAckReceipt[requestId=" + + requestId + + ", schemaVersion=" + + schemaVersion + + "]"; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java new file mode 100644 index 0000000000..72d774ff1c --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java @@ -0,0 +1,320 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered, non-admitting Account-owned storage foundation. No production caller exists. + * + *

Owner-internal seams require a writable SERIALIZABLE Account transaction and lock Account + * before allocation or operation rows. They compare storage identity, not current lifecycle, + * billing, security, source checkpoints or authenticated workload. An eventual authenticated owner + * must compose every current predicate before using these seams. COMMITTED here records a decision + * identity only; it is never source authorization or a public finalization result. + * + *

SQL statement time guards expiry; this does not prove expiry at physical transaction COMMIT. + * ABORTED atomically retains the original full lease and exact orphan decision as pending cleanup; + * Account neither deletes Game Session state nor claims token retirement or cleanup delivery. + */ +public final class AccountGameplayAdmissionLeaseRepository { + private static final String OPERATIONS = "account_gameplay_admission_lease_operations"; + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Private injected persistence context; the repository never exposes it") + public AccountGameplayAdmissionLeaseRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + /** Fence domain is independent of issuance/token fences; retries retain the first allocation. */ + Allocation allocate(UUID accountId, UUID requestId, UUID leaseId) { + lockAccount(accountId); + requireUuidV4(requestId); + requireUuidV4(leaseId); + Record existing = + dsl.fetchOne( + "SELECT * FROM account_gameplay_admission_lease_allocations WHERE request_id = ?", + requestId); + if (existing != null) { + Allocation prior = allocation(existing); + if (!prior.accountId().equals(accountId) + || !prior.requestId().equals(requestId) + || !prior.leaseId().equals(leaseId)) throw conflict(); + return prior; + } + dsl.execute( + "INSERT INTO account_gameplay_admission_lease_fences(account_uuid, last_fence) VALUES (?, 1) " + + "ON CONFLICT (account_uuid) DO UPDATE SET last_fence = " + + "account_gameplay_admission_lease_fences.last_fence + 1", + accountId); + Record counter = + dsl.fetchOne( + "SELECT last_fence FROM account_gameplay_admission_lease_fences WHERE account_uuid = ?", + accountId); + if (counter == null) { + throw new IllegalStateException("Account admission lease counter readback unavailable"); + } + Long fence = counter.get("last_fence", Long.class); + if (fence == null || fence <= 0L) { + throw new IllegalStateException("Account admission lease counter readback invalid"); + } + int inserted = + dsl.execute( + "INSERT INTO account_gameplay_admission_lease_allocations " + + "(account_uuid, request_id, lease_id, lease_fence) VALUES (?, ?, ?, ?)", + accountId, + requestId, + leaseId, + fence); + if (inserted != 1) { + throw new IllegalStateException("Account admission lease allocation insert unavailable"); + } + Allocation expected = new Allocation(accountId, requestId, leaseId, fence); + Record readback = + dsl.fetchOne( + "SELECT * FROM account_gameplay_admission_lease_allocations WHERE request_id = ?", + requestId); + if (readback == null) { + throw new IllegalStateException("Account admission lease allocation readback unavailable"); + } + Allocation stored = allocation(readback); + if (!expected.equals(stored)) throw conflict(); + return stored; + } + + /** + * Recovers the original allocation after a lost response using only the original request. An + * empty result is storage absence only, never authoritative absence or no-token proof. + */ + Optional findAllocation(UUID accountId, UUID requestId) { + lockAccount(accountId); + requireUuidV4(requestId); + Record row = + dsl.fetchOne( + "SELECT * FROM account_gameplay_admission_lease_allocations WHERE request_id = ?", + requestId); + if (row == null) return Optional.empty(); + Allocation stored = allocation(row); + if (!accountId.equals(stored.accountId()) || !requestId.equals(stored.requestId())) + throw conflict(); + return Optional.of(stored); + } + + /** + * Recovers validated original operation storage after a lost response. Workload equality is + * storage correlation only. An eventual facade must supply its concretely verified peer and + * compare current authorization and immutable client inputs before any externally usable retry. + * Empty storage is never admission, authoritative absence or no-token evidence. + */ + Optional findByRequest( + UUID accountId, UUID requestId, String expectedCallerWorkload) { + lockAccount(accountId); + requireUuidV4(requestId); + if (expectedCallerWorkload == null || expectedCallerWorkload.isBlank()) { + throw new IllegalArgumentException("Exact stored caller workload correlation required"); + } + Record row = select(requestId); + if (row == null) return Optional.empty(); + AccountGameplayAdmissionLeaseEvidence evidence = + AccountGameplayAdmissionLeaseEvidence.parseCanonical( + row.get("evidence_json", String.class)); + AccountGameplayAdmissionLeaseOperation stored = exact(row, evidence); + if (!accountId.equals(accountId(stored.evidence())) + || !requestId.equals(id(stored.evidence(), "requestId")) + || !expectedCallerWorkload.equals(stored.evidence().carrier().get("callerWorkload"))) { + throw conflict(); + } + return Optional.of(stored); + } + + /** Stores only the exact carrier for an already retained Account-owned allocation. */ + AccountGameplayAdmissionLeaseOperation beginPending( + AccountGameplayAdmissionLeaseEvidence evidence) { + Objects.requireNonNull(evidence); + UUID accountId = accountId(evidence); + lockAccount(accountId); + Allocation expected = + new Allocation( + accountId, + id(evidence, "requestId"), + id(evidence, "leaseId"), + evidence.leaseFence().longValueExact()); + Record allocated = + dsl.fetchOne( + "SELECT * FROM account_gameplay_admission_lease_allocations WHERE request_id = ?", + expected.requestId()); + if (allocated == null || !expected.equals(allocation(allocated))) throw conflict(); + Record prior = select(expected.requestId()); + if (prior != null) return exact(prior, evidence); + int inserted = + dsl.execute( + "INSERT INTO " + + OPERATIONS + + " (account_uuid, request_id, lease_id, lease_fence, caller_workload, evidence_json, " + + "evidence_sha256, evaluated_at_ms, expires_at_ms, status) " + + "SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, 'PENDING' " + + "WHERE ? <= floor(extract(epoch FROM clock_timestamp()) * 1000) " + + "AND ? > floor(extract(epoch FROM clock_timestamp()) * 1000)", + accountId, + expected.requestId(), + expected.leaseId(), + expected.leaseFence(), + evidence.carrier().get("callerWorkload"), + evidence.canonicalJson(), + evidence.sha256(), + time(evidence, "evaluatedAt"), + time(evidence, "expiresAt"), + time(evidence, "evaluatedAt"), + time(evidence, "expiresAt")); + if (inserted != 1) throw new IllegalStateException("Admission lease storage deadline expired"); + return exact(select(expected.requestId()), evidence); + } + + /** Exact retry/readback retains the original state and deadline, including expired evidence. */ + Optional readExact( + AccountGameplayAdmissionLeaseEvidence evidence) { + Objects.requireNonNull(evidence); + lockAccount(accountId(evidence)); + Record stored = select(id(evidence, "requestId")); + return stored == null ? Optional.empty() : Optional.of(exact(stored, evidence)); + } + + AccountGameplayAdmissionLeaseOperation recordCommitted( + AccountGameplayAdmissionLeaseEvidence evidence, UUID bindingDecisionId) { + return terminal(evidence, State.COMMITTED, bindingDecisionId, null); + } + + /** A missing decision remains unknown; the original cleanup identity is always required. */ + AccountGameplayAdmissionLeaseOperation recordAborted( + AccountGameplayAdmissionLeaseEvidence evidence, + UUID bindingDecisionId, + UUID orphanCleanupId) { + requireUuidV4(orphanCleanupId); + return terminal(evidence, State.ABORTED, bindingDecisionId, orphanCleanupId); + } + + private AccountGameplayAdmissionLeaseOperation terminal( + AccountGameplayAdmissionLeaseEvidence evidence, State state, UUID decision, UUID cleanup) { + if (state == State.COMMITTED || decision != null) requireUuidV4(decision); + AccountGameplayAdmissionLeaseOperation prior = + readExact(evidence) + .orElseThrow( + () -> new IllegalStateException("Exact admission lease operation missing")); + if (prior.state() != State.PENDING) { + if (prior.state() != state + || !Objects.equals(prior.bindingDecisionId(), decision) + || !Objects.equals(prior.orphanCleanupId(), cleanup)) throw conflict(); + return prior; + } + int updated = + dsl.execute( + "UPDATE " + + OPERATIONS + + " SET status = ?, binding_decision_id = ?, orphan_cleanup_id = ? " + + "WHERE request_id = ? AND status = 'PENDING' " + + "AND (? = 'ABORTED' OR expires_at_ms > floor(extract(epoch FROM clock_timestamp()) * 1000))", + state.name(), + decision, + cleanup, + id(evidence, "requestId"), + state.name()); + if (updated != 1) throw new IllegalStateException("Admission lease storage deadline expired"); + return exact(select(id(evidence, "requestId")), evidence); + } + + private void lockAccount(UUID accountId) { + requireUuidV4(accountId); + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_SERIALIZABLE) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException("Writable SERIALIZABLE Account transaction required"); + } + if (dsl.fetchOne( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", accountId) + == null) throw new IllegalStateException("Account admission storage owner missing"); + } + + private Record select(UUID requestId) { + return dsl.fetchOne( + "SELECT * FROM " + OPERATIONS + " WHERE request_id = ? FOR UPDATE", requestId); + } + + private static AccountGameplayAdmissionLeaseOperation exact( + Record row, AccountGameplayAdmissionLeaseEvidence expected) { + if (row == null) throw new IllegalStateException("Admission lease storage readback missing"); + AccountGameplayAdmissionLeaseEvidence stored = + AccountGameplayAdmissionLeaseEvidence.parseCanonical( + row.get("evidence_json", String.class)); + if (!stored.sha256().equals(row.get("evidence_sha256", String.class)) + || !stored.hasSameIdentity(expected) + || !accountId(stored).equals(row.get("account_uuid", UUID.class)) + || !id(stored, "requestId").equals(row.get("request_id", UUID.class)) + || !id(stored, "leaseId").equals(row.get("lease_id", UUID.class)) + || !Long.valueOf(stored.leaseFence().longValueExact()) + .equals(row.get("lease_fence", Long.class)) + || !stored.carrier().get("callerWorkload").equals(row.get("caller_workload", String.class)) + || !Long.valueOf(time(stored, "evaluatedAt")).equals(row.get("evaluated_at_ms", Long.class)) + || !Long.valueOf(time(stored, "expiresAt")).equals(row.get("expires_at_ms", Long.class))) + throw conflict(); + return new AccountGameplayAdmissionLeaseOperation( + stored, + State.valueOf(row.get("status", String.class)), + row.get("binding_decision_id", UUID.class), + row.get("orphan_cleanup_id", UUID.class)); + } + + private static Allocation allocation(Record row) { + UUID account = row.get("account_uuid", UUID.class); + UUID request = row.get("request_id", UUID.class); + UUID lease = row.get("lease_id", UUID.class); + Long fence = row.get("lease_fence", Long.class); + requireUuidV4(account); + requireUuidV4(request); + requireUuidV4(lease); + if (fence == null || fence <= 0L) throw conflict(); + return new Allocation(account, request, lease, fence); + } + + private static UUID accountId(AccountGameplayAdmissionLeaseEvidence evidence) { + return UUID.fromString( + (String) ((java.util.Map) evidence.carrier().get("bindingScope")).get("accountId")); + } + + private static UUID id(AccountGameplayAdmissionLeaseEvidence evidence, String key) { + return UUID.fromString((String) evidence.carrier().get(key)); + } + + private static long time(AccountGameplayAdmissionLeaseEvidence evidence, String key) { + return Long.parseLong((String) evidence.carrier().get(key)); + } + + private static void requireUuidV4(UUID value) { + if (value == null || value.version() != 4 || value.variant() != 2) + throw new IllegalArgumentException("Canonical non-nil UUIDv4 identity required"); + } + + private static IdentityConflictException conflict() { + return new IdentityConflictException(); + } + + static final class IdentityConflictException extends IllegalStateException { + private static final long serialVersionUID = 1L; + + IdentityConflictException() { + super("Exact admission operation identity conflict"); + } + } + + record Allocation(UUID accountId, UUID requestId, UUID leaseId, long leaseFence) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java new file mode 100644 index 0000000000..a3c6e2569a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java @@ -0,0 +1,187 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Objects; +import java.util.UUID; +import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionOriginalAckReceipt; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionOriginalCommitExecutor.OriginalCommitAcknowledgement; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.springframework.jdbc.datasource.ConnectionHolder; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionSystemException; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Unregistered opaque original-ACK receipt executor; supplies no authentication or admission. */ +final class AccountGameplayAdmissionOriginalAckReceiptCommitExecutor { + private final DataSource dataSource; + + AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(DataSource dataSource) { + this.dataSource = Objects.requireNonNull(dataSource); + } + + AccountGameplayAdmissionOriginalAckReceipt confirm( + OriginalCommitAcknowledgement acknowledgement) { + Objects.requireNonNull(acknowledgement); + if (!acknowledgement.belongsTo(dataSource)) throw denied(); + rejectAmbient(); + var creation = + execute( + new ReceiptTransactionManager(dataSource), + repository -> { + var result = Objects.requireNonNull(repository.create(acknowledgement)); + var receipt = Objects.requireNonNull(result.receipt()); + validate(receipt, acknowledgement.evidence(), acknowledgement.decisionId()); + if (!receipt.finalizationXid().equals(acknowledgement.finalizationXid()) + || receipt.committedBeforeMs() != acknowledgement.committedBeforeMs()) + throw denied(); + return result; + }); + var created = Objects.requireNonNull(creation.receipt()); + // A fresh insert is proved by its actual receipt COMMIT; a retry COMMIT cannot prove an old + // row. + rejectAmbient(); + var read = + execute( + new ReceiptTransactionManager(dataSource), + repository -> + creation.inserted() + ? repository.readExact(acknowledgement.evidence(), acknowledgement.decisionId()) + : repository.readDurably( + acknowledgement.evidence(), acknowledgement.decisionId())); + validate(read, acknowledgement.evidence(), acknowledgement.decisionId()); + if (!created.equals(read)) throw denied(); + return read; + } + + AccountGameplayAdmissionOriginalAckReceipt read( + AccountGameplayAdmissionLeaseEvidence evidence, UUID decisionId) { + Objects.requireNonNull(evidence); + Objects.requireNonNull(decisionId); + rejectAmbient(); + var receipt = + execute( + new ReceiptTransactionManager(dataSource), + repository -> repository.readDurably(evidence, decisionId)); + validate(receipt, evidence, decisionId); + return receipt; + } + + private static void validate( + AccountGameplayAdmissionOriginalAckReceipt receipt, + AccountGameplayAdmissionLeaseEvidence evidence, + UUID decisionId) { + if (!receipt.operation().evidence().canonicalJson().equals(evidence.canonicalJson()) + || !receipt.operation().evidence().sha256().equals(evidence.sha256()) + || !receipt.bindingDecisionId().equals(decisionId)) throw denied(); + } + + private static T execute( + ReceiptTransactionManager manager, + java.util.function.Function + operation) { + var transaction = new TransactionTemplate(manager); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + transaction.setReadOnly(false); + var result = + transaction.execute( + status -> { + if (!status.isNewTransaction()) throw denied(); + Connection connection = manager.bindConnection(); + var dsl = DSL.using(connection, SQLDialect.POSTGRES); + var repository = + new AccountGameplayAdmissionOriginalAckReceiptRepository( + dsl, new AccountGameplayAdmissionLeaseRepository(dsl)); + return Objects.requireNonNull(operation.apply(repository)); + }); + if (!manager.committed) throw denied(); + return Objects.requireNonNull(result); + } + + private void rejectAmbient() { + // Spring unwraps a TransactionAwareDataSourceProxy; reject a binding on either identity. + DataSource enlistedSource = + Objects.requireNonNull(new ReceiptTransactionManager(dataSource).getDataSource()); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive() + || TransactionSynchronizationManager.hasResource(dataSource) + || TransactionSynchronizationManager.hasResource(enlistedSource)) throw denied(); + } + + private static final class ReceiptTransactionManager extends DataSourceTransactionManager { + private static final long serialVersionUID = 1L; + private transient Connection connection; + private transient boolean committed; + + private ReceiptTransactionManager(DataSource dataSource) { + super(dataSource); + // A failed guard or uncertain COMMIT must roll back before restoring auto-commit. + setRollbackOnCommitFailure(true); + } + + private Connection enlistedConnection() { + Object resource = + TransactionSynchronizationManager.getResource(Objects.requireNonNull(getDataSource())); + if (!(resource instanceof ConnectionHolder holder)) throw denied(); + return holder.getConnection(); + } + + private Connection bindConnection() { + if (connection != null) throw denied(); + connection = enlistedConnection(); + return connection; + } + + @Override + protected void doCommit(DefaultTransactionStatus status) { + if (!status.isNewTransaction() + || connection == null + || connection != enlistedConnection() + || committed) throw denied(); + try { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_SERIALIZABLE + || !"PostgreSQL".equals(connection.getMetaData().getDatabaseProductName())) + throw denied(); + try (Statement statement = connection.createStatement()) { + statement.execute("SET LOCAL synchronous_commit = on"); + try (ResultSet settings = + statement.executeQuery( + "SELECT current_setting('server_version_num')::integer, pg_is_in_recovery(), " + + "current_setting('fsync'), current_setting('synchronous_commit'), " + + "current_setting('transaction_isolation'), current_setting('transaction_read_only')")) { + if (!settings.next()) throw denied(); + int version = settings.getInt(1); + if (version < 180000 + || version >= 190000 + || settings.getBoolean(2) + || !"on".equals(settings.getString(3)) + || !"on".equals(settings.getString(4)) + || !"serializable".equals(settings.getString(5)) + || !"off".equals(settings.getString(6)) + || settings.next()) throw denied(); + } + } + connection.commit(); + committed = true; + } catch (SQLException failure) { + throw new TransactionSystemException( + "Account receipt physical COMMIT unavailable", failure); + } + } + } + + private static IllegalStateException denied() { + return new IllegalStateException("Fresh owned Account receipt COMMIT required"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java new file mode 100644 index 0000000000..ea0df8aeb8 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java @@ -0,0 +1,172 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.sql.Connection; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionOriginalAckReceipt; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionOriginalCommitExecutor.OriginalCommitAcknowledgement; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered storage for an opaque trusted-JVM acknowledgement of an original Account COMMIT. + * + *

The receipt preserves the exact original operation and post-COMMIT clock bound. SQL checks + * shape and binding but does not authenticate the acknowledgement or derive its clock value. A + * receipt is not current authority, installation, cleanup, or gameplay admission. + */ +final class AccountGameplayAdmissionOriginalAckReceiptRepository { + private static final String RECEIPTS = "account_gameplay_admission_original_commit_ack_receipts"; + private static final String READ_DURABLY_SQL = + "SELECT * FROM account_gameplay_admission_read_original_ack_receipt_durably(?, ?, ?)"; + + private final DSLContext dsl; + private final AccountGameplayAdmissionLeaseRepository leaseRepository; + + AccountGameplayAdmissionOriginalAckReceiptRepository( + DSLContext dsl, AccountGameplayAdmissionLeaseRepository leaseRepository) { + this.dsl = Objects.requireNonNull(dsl); + this.leaseRepository = Objects.requireNonNull(leaseRepository); + } + + /** Stores an exact typed ACK or returns its unchanged retained receipt. */ + Creation create(OriginalCommitAcknowledgement acknowledgement) { + requireWritableSerializableTransaction(); + Objects.requireNonNull(acknowledgement); + AccountGameplayAdmissionLeaseEvidence evidence = + Objects.requireNonNull(acknowledgement.evidence()); + UUID decisionId = Objects.requireNonNull(acknowledgement.decisionId()); + UUID requestId = validateRequest(evidence, decisionId); + + Record inserted = + dsl.fetchOne( + "INSERT INTO " + + RECEIPTS + + " (request_id, evidence_sha256, binding_decision_id, finalization_xid, committed_before_ms) " + + "VALUES (?, ?, ?, ?, ?) ON CONFLICT (request_id) DO NOTHING RETURNING *", + requestId, + evidence.sha256(), + decisionId, + acknowledgement.finalizationXid(), + acknowledgement.committedBeforeMs()); + AccountGameplayAdmissionLeaseOperation operation = exactCommitted(evidence, decisionId); + AccountGameplayAdmissionOriginalAckReceipt receipt; + boolean wasInserted; + if (inserted != null) { + receipt = decode(inserted, operation); + wasInserted = true; + } else { + Record retained = selectReceipt(requestId); + if (retained == null) throw unavailable(); + receipt = decode(retained, operation); + wasInserted = false; + } + if (!receipt.finalizationXid().equals(acknowledgement.finalizationXid()) + || receipt.committedBeforeMs() != acknowledgement.committedBeforeMs()) { + throw unavailable(); + } + return new Creation(receipt, wasInserted); + } + + /** Exact storage-only read for the sibling owner after it observed successful receipt COMMIT. */ + AccountGameplayAdmissionOriginalAckReceipt readExact( + AccountGameplayAdmissionLeaseEvidence evidence, UUID decisionId) { + requireWritableSerializableTransaction(); + UUID requestId = validateRequest(evidence, decisionId); + Record row = selectReceipt(requestId); + if (row == null) throw unavailable(); + return decode(row, exactCommitted(evidence, decisionId)); + } + + /** Proves historical independent receipt durability without changing its original evidence. */ + AccountGameplayAdmissionOriginalAckReceipt readDurably( + AccountGameplayAdmissionLeaseEvidence evidence, UUID decisionId) { + requireWritableSerializableTransaction(); + UUID requestId = validateRequest(evidence, decisionId); + Record row = dsl.fetchOne(READ_DURABLY_SQL, requestId, evidence.sha256(), decisionId); + if (row == null) throw unavailable(); + return decode(row, exactCommitted(evidence, decisionId)); + } + + private Record selectReceipt(UUID requestId) { + return dsl.fetchOne("SELECT * FROM " + RECEIPTS + " WHERE request_id = ?", requestId); + } + + private AccountGameplayAdmissionLeaseOperation exactCommitted( + AccountGameplayAdmissionLeaseEvidence evidence, UUID decisionId) { + AccountGameplayAdmissionLeaseOperation operation = + leaseRepository + .readExact(evidence) + .orElseThrow(AccountGameplayAdmissionOriginalAckReceiptRepository::unavailable); + if (operation.state() != State.COMMITTED || !decisionId.equals(operation.bindingDecisionId())) + throw unavailable(); + return operation; + } + + private static AccountGameplayAdmissionOriginalAckReceipt decode( + Record row, AccountGameplayAdmissionLeaseOperation operation) { + try { + return new AccountGameplayAdmissionOriginalAckReceipt( + operation, + required(row, "schema_version", Short.class), + required(row, "request_id", UUID.class), + required(row, "account_uuid", UUID.class), + required(row, "lease_id", UUID.class), + required(row, "lease_fence", Long.class), + required(row, "evidence_sha256", String.class), + required(row, "binding_decision_id", UUID.class), + required(row, "expires_at_ms", Long.class), + required(row, "finalization_xid", String.class), + required(row, "committed_before_ms", Long.class), + required(row, "receipt_xid", String.class)); + } catch (RuntimeException failure) { + throw unavailable(); + } + } + + private static T required(Record row, String field, Class type) { + if (row == null) throw unavailable(); + T value = row.get(field, type); + if (value == null) throw unavailable(); + return value; + } + + private static UUID validateRequest( + AccountGameplayAdmissionLeaseEvidence evidence, UUID decisionId) { + Objects.requireNonNull(evidence); + UUID requestId = UUID.fromString((String) evidence.carrier().get("requestId")); + requireUuidV4(requestId); + requireUuidV4(decisionId); + return requestId; + } + + private static void requireWritableSerializableTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_SERIALIZABLE) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException("Writable SERIALIZABLE Account transaction required"); + } + } + + private static void requireUuidV4(UUID value) { + if (value == null || value.version() != 4 || value.variant() != 2) { + throw new IllegalArgumentException("Canonical non-nil UUIDv4 identity required"); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException( + "Original Account admission acknowledgement receipt unavailable"); + } + + record Creation(AccountGameplayAdmissionOriginalAckReceipt receipt, boolean inserted) { + Creation { + Objects.requireNonNull(receipt); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java new file mode 100644 index 0000000000..f0a2786a79 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java @@ -0,0 +1,255 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.math.BigDecimal; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Objects; +import java.util.UUID; +import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.springframework.jdbc.datasource.ConnectionHolder; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionSystemException; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered original storage-COMMIT executor; supplies no authentication or admission authority. + * + *

The opaque acknowledgement binds successful synchronous COMMIT of this fresh transition to a + * subsequent database-clock upper bound strictly before unchanged expiry, on the same connection. + * It is not a persisted temporal confirmation or durable receipt. The protected owner must + * separately persist its exact confirmation and prove the receipt's own durability. Lost + * acknowledgement or unavailable/late clock evidence cannot be reconstructed by retrying this + * executor: a retained COMMITTED operation is rejected. + */ +final class AccountGameplayAdmissionOriginalCommitExecutor { + private final DataSource dataSource; + + AccountGameplayAdmissionOriginalCommitExecutor(DataSource dataSource) { + this.dataSource = Objects.requireNonNull(dataSource); + } + + OriginalCommitAcknowledgement execute( + AccountGameplayAdmissionLeaseEvidence evidence, UUID decisionId) { + Objects.requireNonNull(evidence); + Objects.requireNonNull(decisionId); + var manager = new OriginalCommitTransactionManager(dataSource); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive() + || TransactionSynchronizationManager.hasResource( + Objects.requireNonNull(manager.getDataSource()))) { + throw denied(); + } + // Each invocation owns its manager, enlisted connection and acknowledgement slot. + var transaction = new TransactionTemplate(manager); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + transaction.setReadOnly(false); + transaction.executeWithoutResult( + ignored -> { + if (!ignored.isNewTransaction()) throw denied(); + Connection connection = manager.enlistedConnection(); + // The repository cannot acquire another connection: its DSL uses this connection itself. + var repository = + new AccountGameplayAdmissionLeaseRepository( + DSL.using(connection, SQLDialect.POSTGRES)); + var prior = + repository + .readExact(evidence) + .orElseThrow(AccountGameplayAdmissionOriginalCommitExecutor::denied); + if (prior.state() != State.PENDING) throw denied(); + var committed = repository.recordCommitted(evidence, decisionId); + if (committed.state() != State.COMMITTED + || !decisionId.equals(committed.bindingDecisionId()) + || !evidence.canonicalJson().equals(committed.evidence().canonicalJson()) + || !evidence.sha256().equals(committed.evidence().sha256())) throw denied(); + manager.bindOriginal(connection, evidence, decisionId); + }); + return Objects.requireNonNull(manager.acknowledgement); + } + + /** + * Non-serializable, immutable in-process capability; only the physical COMMIT path constructs it. + */ + static final class OriginalCommitAcknowledgement { + private final DataSource originatingSource; + private final AccountGameplayAdmissionLeaseEvidence evidence; + private final UUID decisionId; + private final String finalizationXid; + private final long committedBeforeMs; + + private OriginalCommitAcknowledgement( + DataSource originatingSource, OriginalBinding binding, long committedBeforeMs) { + this.originatingSource = originatingSource; + evidence = binding.evidence(); + decisionId = binding.decisionId(); + finalizationXid = binding.finalizationXid(); + this.committedBeforeMs = committedBeforeMs; + } + + boolean belongsTo(DataSource source) { + return originatingSource == source; + } + + AccountGameplayAdmissionLeaseEvidence evidence() { + return evidence; + } + + UUID decisionId() { + return decisionId; + } + + String finalizationXid() { + return finalizationXid; + } + + long committedBeforeMs() { + return committedBeforeMs; + } + + @Override + public String toString() { + return "OriginalCommitAcknowledgement[not a temporal confirmation]"; + } + } + + private record OriginalBinding( + AccountGameplayAdmissionLeaseEvidence evidence, UUID decisionId, String finalizationXid) {} + + private static final class OriginalCommitTransactionManager extends DataSourceTransactionManager { + private static final long serialVersionUID = 1L; + private final transient DataSource originatingSource; + private transient Connection originalConnection; + private transient OriginalBinding binding; + private transient OriginalCommitAcknowledgement acknowledgement; + + private OriginalCommitTransactionManager(DataSource dataSource) { + super(dataSource); + originatingSource = dataSource; + // A rejected pre-COMMIT durability check must roll back before cleanup restores auto-commit. + // A failed/ambiguous physical COMMIT still never produces an acknowledgement. + setRollbackOnCommitFailure(true); + } + + private Connection enlistedConnection() { + DataSource source = Objects.requireNonNull(getDataSource()); + Object resource = TransactionSynchronizationManager.getResource(source); + if (!(resource instanceof ConnectionHolder holder)) throw denied(); + return holder.getConnection(); + } + + private void bindOriginal( + Connection connection, AccountGameplayAdmissionLeaseEvidence evidence, UUID decisionId) { + if (originalConnection != null || binding != null || connection != enlistedConnection()) + throw denied(); + String sql = + "SELECT finalization_xid, pg_current_xact_id_if_assigned()::text " + + "FROM account_gameplay_admission_lease_operations " + + "WHERE request_id = ? AND lease_id = ? AND evidence_sha256 = ? " + + "AND binding_decision_id = ? AND status = 'COMMITTED' FOR UPDATE"; + try (PreparedStatement statement = connection.prepareStatement(sql)) { + statement.setObject(1, UUID.fromString((String) evidence.carrier().get("requestId"))); + statement.setObject(2, UUID.fromString((String) evidence.carrier().get("leaseId"))); + statement.setString(3, evidence.sha256()); + statement.setObject(4, decisionId); + try (ResultSet row = statement.executeQuery()) { + if (!row.next()) throw denied(); + String finalizationXid = row.getString(1); + if (finalizationXid == null + || !finalizationXid.matches("[1-9][0-9]{0,19}") + || !finalizationXid.equals(row.getString(2)) + || row.next()) throw denied(); + originalConnection = connection; + binding = new OriginalBinding(evidence, decisionId, finalizationXid); + } + } catch (SQLException failure) { + throw new TransactionSystemException( + "Original Account finalization identity unavailable", failure); + } + } + + @Override + protected void doCommit(DefaultTransactionStatus status) { + if (!status.isNewTransaction() + || binding == null + || originalConnection == null + || originalConnection != enlistedConnection() + || acknowledgement != null) throw denied(); + try { + Connection connection = originalConnection; + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_SERIALIZABLE + || !"PostgreSQL".equals(connection.getMetaData().getDatabaseProductName())) + throw denied(); + try (Statement statement = connection.createStatement()) { + statement.execute("SET LOCAL synchronous_commit = on"); + try (ResultSet settings = + statement.executeQuery( + "SELECT current_setting('server_version_num')::integer, pg_is_in_recovery(), " + + "current_setting('fsync'), current_setting('synchronous_commit'), " + + "current_setting('transaction_isolation'), current_setting('transaction_read_only')")) { + if (!settings.next()) throw denied(); + int version = settings.getInt(1); + if (version < 180000 + || version >= 190000 + || settings.getBoolean(2) + || !"on".equals(settings.getString(3)) + || !"on".equals(settings.getString(4)) + || !"serializable".equals(settings.getString(5)) + || !"off".equals(settings.getString(6)) + || settings.next()) throw denied(); + } + } + // No callback or caller flag can mint this capability. An ambiguous JDBC outcome throws. + connection.commit(); + long committedBeforeMs = observeCommitBound(connection, binding.evidence()); + acknowledgement = + new OriginalCommitAcknowledgement(originatingSource, binding, committedBeforeMs); + } catch (SQLException failure) { + throw new TransactionSystemException( + "Original Account physical COMMIT unavailable", failure); + } + } + + private static long observeCommitBound( + Connection connection, AccountGameplayAdmissionLeaseEvidence evidence) { + // This statement follows the actual successful COMMIT, before cleanup or any reconnect. + // A failure here cannot undo that original COMMIT, and must never mint a capability. + try (Statement statement = connection.createStatement(); + ResultSet row = + statement.executeQuery( + "SELECT ceil(extract(epoch FROM clock_timestamp()) * 1000)::bigint")) { + if (!row.next()) throw unavailableClock(); + BigDecimal value = row.getBigDecimal(1); + if (value == null) throw unavailableClock(); + long observed = value.longValueExact(); + long expiry = Long.parseLong((String) evidence.carrier().get("expiresAt")); + if (observed <= 0 || observed >= expiry || row.next()) throw unavailableClock(); + return observed; + } catch (SQLException failure) { + throw new TransactionSystemException( + "Original Account post-COMMIT clock unavailable", failure); + } catch (ArithmeticException failure) { + throw unavailableClock(); + } + } + } + + private static IllegalStateException unavailableClock() { + return new IllegalStateException("Original Account post-COMMIT clock bound unavailable"); + } + + private static IllegalStateException denied() { + return new IllegalStateException("Fresh owned Account original COMMIT required"); + } +} diff --git a/services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql b/services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql new file mode 100644 index 0000000000..c2675aded2 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql @@ -0,0 +1,113 @@ +-- Storage foundation only. No row, fence or terminal status establishes authenticated admission. +-- The lease fence is an independent per-Account domain, never an issuance/token fence. +CREATE TABLE account_gameplay_admission_lease_fences ( + account_uuid UUID PRIMARY KEY REFERENCES accounts(account_uuid) + CHECK (account_uuid::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + last_fence BIGINT NOT NULL CHECK (last_fence > 0) +); + +CREATE TABLE account_gameplay_admission_lease_allocations ( + account_uuid UUID NOT NULL REFERENCES accounts(account_uuid) + CHECK (account_uuid::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + request_id UUID PRIMARY KEY CHECK (request_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + lease_id UUID NOT NULL UNIQUE CHECK (lease_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + lease_fence BIGINT NOT NULL CHECK (lease_fence > 0), + UNIQUE (account_uuid, lease_fence), + UNIQUE (account_uuid, request_id, lease_id, lease_fence) +); + +CREATE TABLE account_gameplay_admission_lease_operations ( + account_uuid UUID NOT NULL, + request_id UUID PRIMARY KEY, + lease_id UUID NOT NULL UNIQUE, + lease_fence BIGINT NOT NULL, + caller_workload TEXT NOT NULL, + evidence_json TEXT NOT NULL CHECK (octet_length(evidence_json) BETWEEN 1 AND 65536), + evidence_sha256 VARCHAR(64) NOT NULL CHECK (evidence_sha256 ~ '^[0-9a-f]{64}$'), + evaluated_at_ms BIGINT NOT NULL CHECK (evaluated_at_ms > 0), + expires_at_ms BIGINT NOT NULL, + status VARCHAR(16) NOT NULL CHECK (status IN ('PENDING', 'COMMITTED', 'ABORTED')), + binding_decision_id UUID CHECK (binding_decision_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + orphan_cleanup_id UUID UNIQUE CHECK (orphan_cleanup_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + FOREIGN KEY (account_uuid, request_id, lease_id, lease_fence) + REFERENCES account_gameplay_admission_lease_allocations(account_uuid, request_id, lease_id, lease_fence), + CHECK (expires_at_ms > evaluated_at_ms AND expires_at_ms - evaluated_at_ms <= 15000), + CHECK ((status = 'PENDING' AND binding_decision_id IS NULL AND orphan_cleanup_id IS NULL) + OR (status = 'COMMITTED' AND binding_decision_id IS NOT NULL AND orphan_cleanup_id IS NULL) + OR (status = 'ABORTED' AND binding_decision_id IS NOT NULL AND orphan_cleanup_id IS NOT NULL)) +); + +-- PostgreSQL executes these exact digest and JSON identity constraints. The jOOQ/H2 schema +-- simulation cannot interpret their PostgreSQL expressions; omission from that simulation +-- does not replace physical PostgreSQL migration and negative-case proof. +-- [jooq ignore start] +ALTER TABLE account_gameplay_admission_lease_operations + ADD CONSTRAINT account_admission_lease_evidence_digest_check + CHECK (evidence_sha256 = encode(sha256(convert_to(evidence_json, 'UTF8')), 'hex')); +ALTER TABLE account_gameplay_admission_lease_operations + ADD CONSTRAINT account_admission_lease_evidence_identity_check + CHECK (COALESCE((evidence_json::jsonb ->> 'requestId') = request_id::text + AND (evidence_json::jsonb ->> 'leaseId') = lease_id::text + AND (evidence_json::jsonb ->> 'leaseFence') = lease_fence::text + AND (evidence_json::jsonb ->> 'callerWorkload') = caller_workload + AND (evidence_json::jsonb -> 'bindingScope' ->> 'accountId') = account_uuid::text + AND (evidence_json::jsonb ->> 'evaluatedAt') = evaluated_at_ms::text + AND (evidence_json::jsonb ->> 'expiresAt') = expires_at_ms::text, FALSE)); +-- [jooq ignore stop] + +-- ABORTED's immutable original evidence_json includes every exact orphan binding and token +-- coordinate. orphan_cleanup_id identifies durable PENDING work, not delivery/retirement success. +-- [jooq ignore start] +CREATE FUNCTION account_gameplay_admission_storage_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Account admission storage evidence cannot be removed' USING ERRCODE = '23514'; + END IF; + IF TG_TABLE_NAME = 'account_gameplay_admission_lease_fences' THEN + PERFORM 1 FROM accounts WHERE account_uuid = NEW.account_uuid FOR UPDATE; + IF TG_OP = 'INSERT' THEN + IF NEW.last_fence <> 1 THEN RAISE EXCEPTION 'Lease fence must start at one' USING ERRCODE = '23514'; END IF; + ELSIF NEW.account_uuid IS DISTINCT FROM OLD.account_uuid OR NEW.last_fence <> OLD.last_fence + 1 THEN + RAISE EXCEPTION 'Lease fence must advance exactly once' USING ERRCODE = '23514'; + END IF; + ELSIF TG_TABLE_NAME = 'account_gameplay_admission_lease_allocations' THEN + IF TG_OP = 'UPDATE' THEN + RAISE EXCEPTION 'Lease allocation is immutable' USING ERRCODE = '23514'; + END IF; + PERFORM 1 FROM accounts WHERE account_uuid = NEW.account_uuid FOR UPDATE; + IF NOT EXISTS (SELECT 1 FROM account_gameplay_admission_lease_fences + WHERE account_uuid = NEW.account_uuid AND last_fence = NEW.lease_fence) THEN + RAISE EXCEPTION 'Lease allocation must bind current Account allocator' USING ERRCODE = '23514'; + END IF; + ELSE + IF TG_OP = 'INSERT' AND NEW.status <> 'PENDING' THEN + RAISE EXCEPTION 'Lease operation must start pending' USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'UPDATE' AND (OLD.status <> 'PENDING' + OR (to_jsonb(NEW) - ARRAY['status', 'binding_decision_id', 'orphan_cleanup_id']) + IS DISTINCT FROM (to_jsonb(OLD) - ARRAY['status', 'binding_decision_id', 'orphan_cleanup_id'])) THEN + RAISE EXCEPTION 'Exact lease evidence and terminal decisions are immutable' USING ERRCODE = '23514'; + END IF; + IF (TG_OP = 'INSERT' OR NEW.status = 'COMMITTED') + AND (NEW.evaluated_at_ms > floor(extract(epoch FROM clock_timestamp()) * 1000) + OR NEW.expires_at_ms <= floor(extract(epoch FROM clock_timestamp()) * 1000)) THEN + RAISE EXCEPTION 'Lease operation storage deadline expired' USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_admission_fence_guard BEFORE INSERT OR UPDATE OR DELETE + ON account_gameplay_admission_lease_fences FOR EACH ROW EXECUTE FUNCTION account_gameplay_admission_storage_guard(); +CREATE TRIGGER account_admission_allocation_guard BEFORE INSERT OR UPDATE OR DELETE + ON account_gameplay_admission_lease_allocations FOR EACH ROW EXECUTE FUNCTION account_gameplay_admission_storage_guard(); +CREATE TRIGGER account_admission_operation_guard BEFORE INSERT OR UPDATE OR DELETE + ON account_gameplay_admission_lease_operations FOR EACH ROW EXECUTE FUNCTION account_gameplay_admission_storage_guard(); +CREATE TRIGGER account_admission_fence_truncate_guard BEFORE TRUNCATE + ON account_gameplay_admission_lease_fences FOR EACH STATEMENT EXECUTE FUNCTION account_gameplay_admission_storage_guard(); +CREATE TRIGGER account_admission_allocation_truncate_guard BEFORE TRUNCATE + ON account_gameplay_admission_lease_allocations FOR EACH STATEMENT EXECUTE FUNCTION account_gameplay_admission_storage_guard(); +CREATE TRIGGER account_admission_operation_truncate_guard BEFORE TRUNCATE + ON account_gameplay_admission_lease_operations FOR EACH STATEMENT EXECUTE FUNCTION account_gameplay_admission_storage_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql b/services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql new file mode 100644 index 0000000000..20ed2b8443 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql @@ -0,0 +1,31 @@ +-- An aborted attempt may have an unknown binding decision. Its exact cleanup identity remains +-- mandatory pending work, never proof of decision absence, cleanup delivery or token retirement. +-- V87's existing rows, immutable evidence, deadline, digest and allocation guards are unchanged. + +-- V87 declared this table-level CHECK without an explicit name. Resolve only its exact three +-- constrained columns; fail rather than removing an unrelated or ambiguous constraint. +-- PostgreSQL catalog lookup is excluded only from jOOQ's schema simulation, not runtime proof. +-- [jooq ignore start] +DO $$ +DECLARE + original_shape_constraint TEXT; +BEGIN + SELECT c.conname INTO STRICT original_shape_constraint + FROM pg_constraint c + WHERE c.conrelid = 'account_gameplay_admission_lease_operations'::regclass + AND c.contype = 'c' + AND ARRAY(SELECT a.attname::text + FROM pg_attribute a + WHERE a.attrelid = c.conrelid AND a.attnum = ANY(c.conkey) + ORDER BY a.attname) = ARRAY['binding_decision_id', 'orphan_cleanup_id', 'status']; + EXECUTE format('ALTER TABLE account_gameplay_admission_lease_operations DROP CONSTRAINT %I', + original_shape_constraint); +END; +$$; +-- [jooq ignore stop] + +ALTER TABLE account_gameplay_admission_lease_operations + ADD CONSTRAINT account_admission_lease_operation_shape_check + CHECK ((status = 'PENDING' AND binding_decision_id IS NULL AND orphan_cleanup_id IS NULL) + OR (status = 'COMMITTED' AND binding_decision_id IS NOT NULL AND orphan_cleanup_id IS NULL) + OR (status = 'ABORTED' AND orphan_cleanup_id IS NOT NULL)); diff --git a/services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql b/services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql new file mode 100644 index 0000000000..579800746a --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql @@ -0,0 +1,404 @@ +-- Temporal storage durability only: neither COMMITTED nor this confirmation grants admission. +-- Retained terminal rows are deliberately not backfilled from xmin or inferred transaction time. +ALTER TABLE account_gameplay_admission_lease_operations ADD COLUMN finalization_xid VARCHAR(20); + +-- [jooq ignore start] +ALTER TABLE account_gameplay_admission_lease_operations + ADD CONSTRAINT account_admission_finalization_xid_check CHECK ( + CASE WHEN finalization_xid IS NULL THEN TRUE + WHEN finalization_xid ~ '^[1-9][0-9]{0,19}$' THEN + status = 'COMMITTED' AND finalization_xid::numeric <= 18446744073709551615 + ELSE FALSE END); +-- [jooq ignore stop] + +ALTER TABLE account_gameplay_admission_lease_operations + ADD CONSTRAINT account_admission_confirmation_binding_unique + UNIQUE (request_id, account_uuid, lease_id, lease_fence, evidence_sha256, + binding_decision_id, expires_at_ms, finalization_xid); + +CREATE TABLE account_gameplay_admission_commit_confirmations ( + confirmation_version SMALLINT NOT NULL DEFAULT 1 CHECK (confirmation_version = 1), + request_id UUID PRIMARY KEY, + account_uuid UUID NOT NULL, + lease_id UUID NOT NULL, + lease_fence BIGINT NOT NULL CHECK (lease_fence > 0), + evidence_sha256 VARCHAR(64) NOT NULL CHECK (evidence_sha256 ~ '^[0-9a-f]{64}$'), + binding_decision_id UUID NOT NULL, + expires_at_ms BIGINT NOT NULL CHECK (expires_at_ms > 0), + finalization_xid VARCHAR(20) NOT NULL, + wal_insert_lsn TEXT NOT NULL, + wal_flush_lsn TEXT NOT NULL, + committed_before_ms BIGINT NOT NULL CHECK (committed_before_ms > 0 AND committed_before_ms < expires_at_ms), + confirmation_xid VARCHAR(20) NOT NULL, + FOREIGN KEY (request_id, account_uuid, lease_id, lease_fence, evidence_sha256, + binding_decision_id, expires_at_ms, finalization_xid) + REFERENCES account_gameplay_admission_lease_operations + (request_id, account_uuid, lease_id, lease_fence, evidence_sha256, + binding_decision_id, expires_at_ms, finalization_xid) +); + +-- Only PostgreSQL-specific expressions and procedural enforcement are omitted from simulation. +-- All receipt columns and the exact original-operation foreign key remain visible to jOOQ. +-- [jooq ignore start] +ALTER TABLE account_gameplay_admission_commit_confirmations + ADD CONSTRAINT account_admission_confirmation_proof_shape_check CHECK ( + CASE WHEN finalization_xid ~ '^[1-9][0-9]{0,19}$' + AND confirmation_xid ~ '^[1-9][0-9]{0,19}$' + AND wal_insert_lsn ~ '^(0|[1-9A-F][0-9A-F]{0,7})/(0|[1-9A-F][0-9A-F]{0,7})$' + AND wal_flush_lsn ~ '^(0|[1-9A-F][0-9A-F]{0,7})/(0|[1-9A-F][0-9A-F]{0,7})$' THEN + finalization_xid::numeric <= 18446744073709551615 + AND confirmation_xid::numeric <= 18446744073709551615 + AND finalization_xid <> confirmation_xid + AND wal_insert_lsn::pg_lsn > '0/0'::pg_lsn + AND wal_flush_lsn::pg_lsn >= wal_insert_lsn::pg_lsn + ELSE FALSE END); + +-- Preserve every V87 guard and the V89 terminal shape; stamp only the original transition. +CREATE OR REPLACE FUNCTION account_gameplay_admission_storage_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Account admission storage evidence cannot be removed' USING ERRCODE = '23514'; + END IF; + IF TG_TABLE_NAME = 'account_gameplay_admission_lease_fences' THEN + PERFORM 1 FROM accounts WHERE account_uuid = NEW.account_uuid FOR UPDATE; + IF TG_OP = 'INSERT' THEN + IF NEW.last_fence <> 1 THEN RAISE EXCEPTION 'Lease fence must start at one' USING ERRCODE = '23514'; END IF; + ELSIF NEW.account_uuid IS DISTINCT FROM OLD.account_uuid OR NEW.last_fence <> OLD.last_fence + 1 THEN + RAISE EXCEPTION 'Lease fence must advance exactly once' USING ERRCODE = '23514'; + END IF; + ELSIF TG_TABLE_NAME = 'account_gameplay_admission_lease_allocations' THEN + IF TG_OP = 'UPDATE' THEN + RAISE EXCEPTION 'Lease allocation is immutable' USING ERRCODE = '23514'; + END IF; + PERFORM 1 FROM accounts WHERE account_uuid = NEW.account_uuid FOR UPDATE; + IF NOT EXISTS (SELECT 1 FROM account_gameplay_admission_lease_fences + WHERE account_uuid = NEW.account_uuid AND last_fence = NEW.lease_fence) THEN + RAISE EXCEPTION 'Lease allocation must bind current Account allocator' USING ERRCODE = '23514'; + END IF; + ELSE + IF TG_OP = 'INSERT' AND NEW.status <> 'PENDING' THEN + RAISE EXCEPTION 'Lease operation must start pending' USING ERRCODE = '23514'; + END IF; + IF (TG_OP = 'INSERT' AND NEW.finalization_xid IS NOT NULL) + OR (TG_OP = 'UPDATE' AND NEW.finalization_xid IS DISTINCT FROM OLD.finalization_xid) THEN + RAISE EXCEPTION 'Account admission finalization transaction is database stamped' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_finalization_xid_db_stamp'; + END IF; + IF TG_OP = 'UPDATE' AND (OLD.status <> 'PENDING' + OR (to_jsonb(NEW) - ARRAY['status', 'binding_decision_id', 'orphan_cleanup_id', 'finalization_xid']) + IS DISTINCT FROM (to_jsonb(OLD) - ARRAY['status', 'binding_decision_id', 'orphan_cleanup_id', 'finalization_xid'])) THEN + RAISE EXCEPTION 'Exact lease evidence and terminal decisions are immutable' USING ERRCODE = '23514'; + END IF; + IF (TG_OP = 'INSERT' OR NEW.status = 'COMMITTED') + AND (NEW.evaluated_at_ms > floor(extract(epoch FROM clock_timestamp()) * 1000) + OR NEW.expires_at_ms <= floor(extract(epoch FROM clock_timestamp()) * 1000)) THEN + RAISE EXCEPTION 'Lease operation storage deadline expired' USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'UPDATE' AND NEW.status = 'COMMITTED' THEN + NEW.finalization_xid := pg_current_xact_id()::text; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_gameplay_admission_confirmation_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + operation account_gameplay_admission_lease_operations%ROWTYPE; + locked_operation account_gameplay_admission_lease_operations%ROWTYPE; + receipt account_gameplay_admission_commit_confirmations%ROWTYPE; + locked_receipt account_gameplay_admission_commit_confirmations%ROWTYPE; + own_xid TEXT; + finalization_status TEXT; + fixed_snapshot pg_snapshot; + insert_fence pg_lsn; + initial_flush_fence pg_lsn; + flush_fence pg_lsn; + observed_before_ms BIGINT; + observation INTEGER; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Account admission confirmation is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_immutable'; + END IF; + IF NEW.confirmation_version IS DISTINCT FROM 1 OR NEW.account_uuid IS NOT NULL + OR NEW.lease_id IS NOT NULL OR NEW.lease_fence IS NOT NULL OR NEW.expires_at_ms IS NOT NULL + OR NEW.finalization_xid IS NOT NULL OR NEW.wal_insert_lsn IS NOT NULL + OR NEW.wal_flush_lsn IS NOT NULL OR NEW.committed_before_ms IS NOT NULL + OR NEW.confirmation_xid IS NOT NULL THEN + RAISE EXCEPTION 'Account admission confirmation proof is database derived' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_db_proof'; + END IF; + IF current_setting('transaction_isolation') IS DISTINCT FROM 'serializable' + OR current_setting('transaction_read_only') IS DISTINCT FROM 'off' THEN + RAISE EXCEPTION 'Account admission confirmation writable SERIALIZABLE transaction required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_transaction_required'; + END IF; + IF pg_is_in_recovery() OR current_setting('fsync') IS DISTINCT FROM 'on' THEN + RAISE EXCEPTION 'Account admission confirmation durable primary required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_durable_primary'; + END IF; + -- Establish the fixed transaction snapshot before the fence and before any heap read. + -- A subsequently visible independent row committed before this snapshot, hence before + -- this WAL upper bound. Even a SELECT can emit heap-pruning WAL; capture must precede it. + fixed_snapshot := pg_current_snapshot(); + own_xid := pg_current_xact_id_if_assigned()::text; + insert_fence := pg_current_wal_insert_lsn(); + initial_flush_fence := pg_current_wal_flush_lsn(); + IF insert_fence IS NULL OR insert_fence <= '0/0'::pg_lsn THEN + RAISE EXCEPTION 'Account admission confirmation WAL coverage unavailable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_wal_coverage'; + END IF; + SELECT * INTO operation FROM account_gameplay_admission_lease_operations WHERE request_id = NEW.request_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account admission confirmation operation missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_operation_required'; + END IF; + IF operation.status <> 'COMMITTED' OR operation.finalization_xid IS NULL + OR NEW.evidence_sha256 IS DISTINCT FROM operation.evidence_sha256 + OR NEW.binding_decision_id IS DISTINCT FROM operation.binding_decision_id THEN + RAISE EXCEPTION 'Account admission confirmation exact committed binding required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_binding_required'; + END IF; + -- The stamp is top-level even when finalization ran in a released subtransaction. + IF operation.finalization_xid = own_xid THEN + RAISE EXCEPTION 'Account admission confirmation requires independent finalization commit' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_finalization_independent'; + END IF; + SELECT * INTO receipt FROM account_gameplay_admission_commit_confirmations WHERE request_id = NEW.request_id; + PERFORM 1 FROM accounts WHERE account_uuid = operation.account_uuid FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account admission confirmation owner missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_owner_required'; + END IF; + SELECT * INTO locked_operation FROM account_gameplay_admission_lease_operations + WHERE request_id = NEW.request_id FOR UPDATE; + IF NOT FOUND OR locked_operation IS DISTINCT FROM operation THEN + RAISE EXCEPTION 'Account admission confirmation exact committed binding required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_binding_required'; + END IF; + IF receipt.request_id IS NOT NULL THEN + SELECT * INTO locked_receipt FROM account_gameplay_admission_commit_confirmations + WHERE request_id = NEW.request_id FOR UPDATE; + IF NOT FOUND OR locked_receipt IS DISTINCT FROM receipt + OR receipt.account_uuid IS DISTINCT FROM operation.account_uuid + OR receipt.lease_id IS DISTINCT FROM operation.lease_id + OR receipt.lease_fence IS DISTINCT FROM operation.lease_fence + OR receipt.evidence_sha256 IS DISTINCT FROM operation.evidence_sha256 + OR receipt.binding_decision_id IS DISTINCT FROM operation.binding_decision_id + OR receipt.expires_at_ms IS DISTINCT FROM operation.expires_at_ms + OR receipt.finalization_xid IS DISTINCT FROM operation.finalization_xid THEN + RAISE EXCEPTION 'Account admission confirmation immutable binding conflict' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_binding_conflict'; + END IF; + -- Suppress an exact replay INSERT, including after expiry. The caller reads the retained + -- receipt; no new proof, XID, deadline or timing bound replaces its original evidence. + RETURN NULL; + END IF; + BEGIN + finalization_status := pg_xact_status(operation.finalization_xid::xid8); + EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Account admission confirmation finalization proof unavailable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_finalization_unavailable'; + END; + IF finalization_status IS DISTINCT FROM 'committed' THEN + RAISE EXCEPTION 'Account admission confirmation requires independent finalization commit' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_finalization_independent'; + END IF; + -- Account-first locking serializes first receipt creation, and exact locked revalidation + -- preserves the independently observed immutable operation. Only the pre-lock fence needs + -- coverage; this bounded polling creates no marker, forces no flush and renews no deadline. + FOR observation IN 1..50 LOOP + flush_fence := pg_current_wal_flush_lsn(); + -- A separate statement AFTER each flush observation is essential: SQL expression order + -- is not a temporal guarantee. CEIL supplies a conservative DB wall-clock upper bound. + observed_before_ms := ceil(extract(epoch FROM clock_timestamp()) * 1000)::bigint; + IF observed_before_ms <= 0 OR observed_before_ms >= operation.expires_at_ms THEN + RAISE EXCEPTION 'Account admission confirmation original deadline expired' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_original_deadline'; + END IF; + EXIT WHEN flush_fence IS NOT NULL AND flush_fence >= insert_fence; + IF observation = 50 THEN + RAISE EXCEPTION 'Account admission confirmation WAL coverage unavailable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_wal_coverage', + DETAIL = format('phase=create snapshot=%s own_xid_if_assigned=%s finalization_xid=%s receipt_xid=%s insert_fence=%s initial_flush=%s final_flush=%s observed_db_ms=%s unchanged_expiry_ms=%s', + fixed_snapshot, own_xid, operation.finalization_xid, receipt.confirmation_xid, + insert_fence, initial_flush_fence, flush_fence, observed_before_ms, operation.expires_at_ms); + END IF; + PERFORM pg_sleep(0.01); + END LOOP; + NEW.account_uuid := operation.account_uuid; + NEW.lease_id := operation.lease_id; + NEW.lease_fence := operation.lease_fence; + NEW.expires_at_ms := operation.expires_at_ms; + NEW.finalization_xid := operation.finalization_xid; + NEW.wal_insert_lsn := insert_fence::text; + NEW.wal_flush_lsn := flush_fence::text; + NEW.committed_before_ms := observed_before_ms; + NEW.confirmation_xid := pg_current_xact_id()::text; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_admission_confirmation_guard BEFORE INSERT OR UPDATE OR DELETE + ON account_gameplay_admission_commit_confirmations FOR EACH ROW + EXECUTE FUNCTION account_gameplay_admission_confirmation_guard(); +CREATE TRIGGER account_admission_confirmation_truncate_guard BEFORE TRUNCATE + ON account_gameplay_admission_commit_confirmations FOR EACH STATEMENT + EXECUTE FUNCTION account_gameplay_admission_confirmation_guard(); + +CREATE FUNCTION account_gameplay_admission_confirm_committed( + requested_request_id UUID, expected_sha TEXT, expected_decision UUID) +RETURNS SETOF account_gameplay_admission_commit_confirmations LANGUAGE plpgsql AS $$ +DECLARE + operation account_gameplay_admission_lease_operations%ROWTYPE; + receipt account_gameplay_admission_commit_confirmations%ROWTYPE; +BEGIN + -- Enter the guard before either operation/receipt heap read. It owns the snapshot/fence + -- and suppresses exact retained replay without renewing proof. A stale SERIALIZABLE + -- conflict must surface as 40001 rather than a raw uniqueness failure. + INSERT INTO account_gameplay_admission_commit_confirmations(request_id, evidence_sha256, binding_decision_id) + VALUES (requested_request_id, expected_sha, expected_decision) + ON CONFLICT (request_id) DO NOTHING RETURNING * INTO receipt; + IF FOUND THEN + RETURN NEXT receipt; + RETURN; + END IF; + SELECT * INTO operation FROM account_gameplay_admission_lease_operations WHERE request_id = requested_request_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account admission confirmation operation missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_operation_required'; + END IF; + IF operation.status <> 'COMMITTED' OR operation.finalization_xid IS NULL + OR expected_sha IS DISTINCT FROM operation.evidence_sha256 + OR expected_decision IS DISTINCT FROM operation.binding_decision_id THEN + RAISE EXCEPTION 'Account admission confirmation exact committed binding required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_binding_required'; + END IF; + -- Exact retained replay may occur after expiry. It locks Account first and revalidates the + -- immutable original decision, but neither re-proves nor replaces the receipt's timing bound. + PERFORM 1 FROM accounts WHERE account_uuid = operation.account_uuid FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account admission confirmation owner missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_owner_required'; + END IF; + SELECT * INTO operation FROM account_gameplay_admission_lease_operations + WHERE request_id = requested_request_id FOR UPDATE; + IF NOT FOUND OR operation.status <> 'COMMITTED' OR operation.finalization_xid IS NULL + OR expected_sha IS DISTINCT FROM operation.evidence_sha256 + OR expected_decision IS DISTINCT FROM operation.binding_decision_id THEN + RAISE EXCEPTION 'Account admission confirmation exact committed binding required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_binding_required'; + END IF; + SELECT * INTO receipt FROM account_gameplay_admission_commit_confirmations + WHERE request_id = requested_request_id FOR UPDATE; + IF NOT FOUND OR receipt.account_uuid IS DISTINCT FROM operation.account_uuid + OR receipt.lease_id IS DISTINCT FROM operation.lease_id + OR receipt.lease_fence IS DISTINCT FROM operation.lease_fence + OR receipt.evidence_sha256 IS DISTINCT FROM operation.evidence_sha256 + OR receipt.binding_decision_id IS DISTINCT FROM operation.binding_decision_id + OR receipt.expires_at_ms IS DISTINCT FROM operation.expires_at_ms + OR receipt.finalization_xid IS DISTINCT FROM operation.finalization_xid THEN + RAISE EXCEPTION 'Account admission confirmation immutable binding conflict' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_binding_conflict'; + END IF; + RETURN NEXT receipt; +END; +$$; + +CREATE FUNCTION account_gameplay_admission_read_commit_confirmation( + requested_request_id UUID, expected_sha TEXT, expected_decision UUID) +RETURNS SETOF account_gameplay_admission_commit_confirmations LANGUAGE plpgsql AS $$ +DECLARE + operation account_gameplay_admission_lease_operations%ROWTYPE; + receipt account_gameplay_admission_commit_confirmations%ROWTYPE; + locked_operation account_gameplay_admission_lease_operations%ROWTYPE; + locked_receipt account_gameplay_admission_commit_confirmations%ROWTYPE; + own_xid TEXT; + fixed_snapshot pg_snapshot; + insert_fence pg_lsn; + initial_flush_fence pg_lsn; + flush_fence pg_lsn; + observed_before_ms BIGINT; + observation INTEGER; +BEGIN + IF current_setting('transaction_isolation') IS DISTINCT FROM 'serializable' + OR current_setting('transaction_read_only') IS DISTINCT FROM 'off' THEN + RAISE EXCEPTION 'Account admission confirmation writable SERIALIZABLE transaction required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_transaction_required'; + END IF; + IF pg_is_in_recovery() OR current_setting('fsync') IS DISTINCT FROM 'on' THEN + RAISE EXCEPTION 'Account admission confirmation durable primary required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_durable_primary'; + END IF; + -- Fix the snapshot and WAL upper bound before heap reads or assigning our own XID. + -- Independent receipt visibility in that same snapshot covers its prior COMMIT. + fixed_snapshot := pg_current_snapshot(); + own_xid := pg_current_xact_id_if_assigned()::text; + insert_fence := pg_current_wal_insert_lsn(); + initial_flush_fence := pg_current_wal_flush_lsn(); + IF insert_fence IS NULL OR insert_fence <= '0/0'::pg_lsn THEN + RAISE EXCEPTION 'Account admission confirmation WAL coverage unavailable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_wal_coverage'; + END IF; + SELECT * INTO operation FROM account_gameplay_admission_lease_operations WHERE request_id = requested_request_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account admission confirmation operation missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_operation_required'; + END IF; + SELECT * INTO receipt FROM account_gameplay_admission_commit_confirmations WHERE request_id = requested_request_id; + IF NOT FOUND OR operation.status IS DISTINCT FROM 'COMMITTED' + OR expected_sha IS DISTINCT FROM operation.evidence_sha256 + OR expected_decision IS DISTINCT FROM operation.binding_decision_id + OR receipt.account_uuid IS DISTINCT FROM operation.account_uuid + OR receipt.lease_id IS DISTINCT FROM operation.lease_id + OR receipt.lease_fence IS DISTINCT FROM operation.lease_fence + OR receipt.evidence_sha256 IS DISTINCT FROM operation.evidence_sha256 + OR receipt.binding_decision_id IS DISTINCT FROM operation.binding_decision_id + OR receipt.expires_at_ms IS DISTINCT FROM operation.expires_at_ms + OR receipt.finalization_xid IS DISTINCT FROM operation.finalization_xid THEN + RAISE EXCEPTION 'Account admission confirmation exact durable receipt required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_receipt_required'; + END IF; + -- MVCC visibility plus exclusion of our own top-level XID also excludes our subtransactions. + -- Historical receipts need not retain pg_xact_status data forever: fresh WAL coverage below + -- covers their independently visible original COMMIT without consulting vacuum-pruned status. + IF receipt.confirmation_xid = own_xid THEN + RAISE EXCEPTION 'Account admission confirmation requires independent receipt commit' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_receipt_independent'; + END IF; + PERFORM 1 FROM accounts WHERE account_uuid = operation.account_uuid FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account admission confirmation owner missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_owner_required'; + END IF; + SELECT * INTO locked_operation FROM account_gameplay_admission_lease_operations + WHERE request_id = requested_request_id FOR UPDATE; + IF NOT FOUND OR locked_operation IS DISTINCT FROM operation THEN + RAISE EXCEPTION 'Account admission confirmation exact durable receipt required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_receipt_required'; + END IF; + SELECT * INTO locked_receipt FROM account_gameplay_admission_commit_confirmations + WHERE request_id = requested_request_id FOR UPDATE; + IF NOT FOUND OR locked_receipt IS DISTINCT FROM receipt THEN + RAISE EXCEPTION 'Account admission confirmation exact durable receipt required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_receipt_required'; + END IF; + FOR observation IN 1..50 LOOP + flush_fence := pg_current_wal_flush_lsn(); + EXIT WHEN flush_fence IS NOT NULL AND flush_fence >= insert_fence; + IF observation = 50 THEN + observed_before_ms := ceil(extract(epoch FROM clock_timestamp()) * 1000)::bigint; + RAISE EXCEPTION 'Account admission confirmation WAL coverage unavailable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_wal_coverage', + DETAIL = format('phase=receipt-read snapshot=%s own_xid_if_assigned=%s finalization_xid=%s receipt_xid=%s insert_fence=%s initial_flush=%s final_flush=%s observed_db_ms=%s unchanged_expiry_ms=%s', + fixed_snapshot, own_xid, operation.finalization_xid, receipt.confirmation_xid, + insert_fence, initial_flush_fence, flush_fence, observed_before_ms, operation.expires_at_ms); + END IF; + PERFORM pg_sleep(0.01); + END LOOP; + -- Return immutable historical timing evidence even after expiry; never restamp or renew it. + RETURN NEXT receipt; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql b/services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql new file mode 100644 index 0000000000..007bf4ea03 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql @@ -0,0 +1,89 @@ +-- Account-wide negative pending-intent protection only. Unchanged tuple versions fence stale +-- REPEATABLE_READ/SERIALIZABLE snapshots; no logical source, restriction or authority is created. +-- Retained WAITING evidence is preserved, including unmatched or contradictory historical rows. +-- [jooq ignore start] +CREATE FUNCTION account_security_state_account_row_version_fence() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + touched_rows INTEGER; +BEGIN + IF NEW.status = 'WAITING' THEN + UPDATE accounts SET id = id + WHERE account_uuid = NEW.account_uuid + AND id = NEW.account_id + AND account_uuid_source_numeric_id = NEW.account_id + AND account_uuid_provenance = NEW.account_provenance; + GET DIAGNOSTICS touched_rows = ROW_COUNT; + IF touched_rows <> 1 THEN + RAISE EXCEPTION 'Security-state intent requires the exact persisted Account row' + USING ERRCODE = '23514', + CONSTRAINT = 'account_security_state_account_row_version_fence'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_security_state_account_row_version_fence + BEFORE INSERT ON account_security_state_operations + FOR EACH ROW EXECUTE FUNCTION account_security_state_account_row_version_fence(); + +CREATE FUNCTION account_draft_authorization_account_row_version_fence() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + account_key TEXT; + touched_rows INTEGER; +BEGIN + IF split_part(NEW.source_key, ':', 1) IN ('ACCOUNT', 'GLOBAL_ROLES') THEN + IF NEW.source_key !~ '^(ACCOUNT|GLOBAL_ROLES):[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' THEN + RAISE EXCEPTION 'Account source scope must use the exact canonical UUID key' + USING ERRCODE = '23514', + CONSTRAINT = 'account_draft_authorization_account_row_version_fence'; + END IF; + account_key := split_part(NEW.source_key, ':', 2); + UPDATE accounts SET id = id + WHERE account_uuid = account_key::UUID + AND account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND id > 0 AND account_uuid_source_numeric_id = id + AND account_uuid_provenance IN ( + 'ACCOUNT_V29_MIGRATION', 'ACCOUNT_REPOSITORY_INSERT', 'ACCOUNT_DATABASE_INSERT'); + GET DIAGNOSTICS touched_rows = ROW_COUNT; + IF touched_rows <> 1 THEN + RAISE EXCEPTION 'Account source scope requires the exact persisted Account row' + USING ERRCODE = '23514', + CONSTRAINT = 'account_draft_authorization_account_row_version_fence'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +-- Alphabetically earlier than V76's scope_insert_phase: Account is touched before parent locking. +CREATE TRIGGER account_draft_authorization_account_row_version_fence + BEFORE INSERT ON account_draft_authorization_changed_scopes + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_account_row_version_fence(); + +-- Protect snapshots predating installation without asserting retained intent provenance or +-- enrolling an Account. Exact UUID/key matching supplies negative protection only. +DO $$ +DECLARE + pending_account UUID; +BEGIN + FOR pending_account IN + SELECT a.account_uuid FROM accounts a + WHERE EXISTS ( + SELECT 1 FROM account_security_state_operations security + WHERE security.account_uuid = a.account_uuid AND security.status = 'WAITING') + OR EXISTS ( + SELECT 1 FROM account_draft_authorization_source_changes change + JOIN account_draft_authorization_changed_scopes changed USING (change_id) + WHERE change.status = 'WAITING' + AND changed.source_key IN ( + 'ACCOUNT:' || a.account_uuid::TEXT, 'GLOBAL_ROLES:' || a.account_uuid::TEXT)) + ORDER BY a.account_uuid::TEXT + LOOP + UPDATE accounts SET id = id WHERE account_uuid = pending_account; + END LOOP; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql b/services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql new file mode 100644 index 0000000000..431fcc9a56 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql @@ -0,0 +1,259 @@ +-- Persist only an opaque trusted-JVM acknowledgement of the original physical COMMIT and its +-- subsequent database-clock bound. The bound is not SQL-derived or authenticated by this schema. +-- This receipt supplies no current authority or gameplay-admission result. +CREATE TABLE account_gameplay_admission_original_commit_ack_receipts ( + schema_version SMALLINT NOT NULL DEFAULT 1 CHECK (schema_version = 1), + request_id UUID PRIMARY KEY, + account_uuid UUID NOT NULL, + lease_id UUID NOT NULL, + lease_fence BIGINT NOT NULL CHECK (lease_fence > 0), + evidence_sha256 VARCHAR(64) NOT NULL CHECK (evidence_sha256 ~ '^[0-9a-f]{64}$'), + binding_decision_id UUID NOT NULL, + expires_at_ms BIGINT NOT NULL CHECK (expires_at_ms > 0), + finalization_xid VARCHAR(20) NOT NULL, + committed_before_ms BIGINT NOT NULL CHECK ( + committed_before_ms > 0 AND committed_before_ms < expires_at_ms), + receipt_xid VARCHAR(20) NOT NULL, + FOREIGN KEY (request_id, account_uuid, lease_id, lease_fence, evidence_sha256, + binding_decision_id, expires_at_ms, finalization_xid) + REFERENCES account_gameplay_admission_lease_operations + (request_id, account_uuid, lease_id, lease_fence, evidence_sha256, + binding_decision_id, expires_at_ms, finalization_xid) +); + +-- The typed JVM acknowledgement supplies committed_before_ms. SQL validates its shape and exact +-- immutable operation binding, but cannot authenticate that opaque capability or prove its clock. +-- [jooq ignore start] +ALTER TABLE account_gameplay_admission_original_commit_ack_receipts + ADD CONSTRAINT account_admission_original_ack_receipt_xid_check CHECK ( + CASE WHEN finalization_xid ~ '^[1-9][0-9]{0,19}$' + AND receipt_xid ~ '^[1-9][0-9]{0,19}$' THEN + finalization_xid::numeric <= 18446744073709551615 + AND receipt_xid::numeric <= 18446744073709551615 + AND finalization_xid <> receipt_xid + ELSE FALSE END); + +CREATE FUNCTION account_gameplay_admission_original_ack_receipt_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + operation account_gameplay_admission_lease_operations%ROWTYPE; + locked_operation account_gameplay_admission_lease_operations%ROWTYPE; + receipt account_gameplay_admission_original_commit_ack_receipts%ROWTYPE; + locked_receipt account_gameplay_admission_original_commit_ack_receipts%ROWTYPE; + own_xid TEXT; + finalization_status TEXT; + version_num INTEGER; +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Original Account COMMIT acknowledgement receipt is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_immutable'; + END IF; + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Original Account COMMIT acknowledgement receipt is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_immutable'; + END IF; + IF NEW.schema_version IS DISTINCT FROM 1 + OR NEW.account_uuid IS NOT NULL OR NEW.lease_id IS NOT NULL + OR NEW.lease_fence IS NOT NULL OR NEW.expires_at_ms IS NOT NULL + OR NEW.receipt_xid IS NOT NULL THEN + RAISE EXCEPTION 'Original Account COMMIT acknowledgement receipt binding is database derived' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_db_binding'; + END IF; + IF current_setting('transaction_isolation') IS DISTINCT FROM 'serializable' + OR current_setting('transaction_read_only') IS DISTINCT FROM 'off' THEN + RAISE EXCEPTION 'Writable SERIALIZABLE Account acknowledgement receipt transaction required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_transaction_required'; + END IF; + version_num := current_setting('server_version_num')::integer; + IF version_num < 160000 OR version_num >= 170000 + OR pg_is_in_recovery() OR current_setting('fsync') IS DISTINCT FROM 'on' THEN + RAISE EXCEPTION 'Supported durable PostgreSQL 16 primary required for Account acknowledgement receipt' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_durable_primary'; + END IF; + + -- The request lookup only discovers the owning Account. All locked reads follow Account first. + SELECT * INTO operation FROM account_gameplay_admission_lease_operations + WHERE request_id = NEW.request_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Original Account COMMIT acknowledgement operation missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_operation_required'; + END IF; + PERFORM 1 FROM accounts WHERE account_uuid = operation.account_uuid FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Original Account COMMIT acknowledgement owner missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_owner_required'; + END IF; + SELECT * INTO locked_operation FROM account_gameplay_admission_lease_operations + WHERE request_id = NEW.request_id FOR UPDATE; + IF NOT FOUND OR locked_operation IS DISTINCT FROM operation + OR locked_operation.status IS DISTINCT FROM 'COMMITTED' + OR locked_operation.finalization_xid IS NULL + OR NEW.evidence_sha256 IS DISTINCT FROM locked_operation.evidence_sha256 + OR NEW.binding_decision_id IS DISTINCT FROM locked_operation.binding_decision_id + OR NEW.finalization_xid IS DISTINCT FROM locked_operation.finalization_xid + OR NEW.committed_before_ms <= 0 + OR NEW.committed_before_ms >= locked_operation.expires_at_ms THEN + RAISE EXCEPTION 'Exact original Account COMMIT acknowledgement required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_binding_required'; + END IF; + + SELECT * INTO receipt FROM account_gameplay_admission_original_commit_ack_receipts + WHERE request_id = NEW.request_id; + IF FOUND THEN + SELECT * INTO locked_receipt FROM account_gameplay_admission_original_commit_ack_receipts + WHERE request_id = NEW.request_id FOR UPDATE; + IF NOT FOUND OR locked_receipt IS DISTINCT FROM receipt + OR receipt.schema_version IS DISTINCT FROM 1 + OR receipt.account_uuid IS DISTINCT FROM locked_operation.account_uuid + OR receipt.lease_id IS DISTINCT FROM locked_operation.lease_id + OR receipt.lease_fence IS DISTINCT FROM locked_operation.lease_fence + OR receipt.evidence_sha256 IS DISTINCT FROM locked_operation.evidence_sha256 + OR receipt.binding_decision_id IS DISTINCT FROM locked_operation.binding_decision_id + OR receipt.expires_at_ms IS DISTINCT FROM locked_operation.expires_at_ms + OR receipt.finalization_xid IS DISTINCT FROM locked_operation.finalization_xid + OR receipt.committed_before_ms IS DISTINCT FROM NEW.committed_before_ms THEN + RAISE EXCEPTION 'Original Account COMMIT acknowledgement receipt retry conflicts' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_conflict'; + END IF; + -- An exact retained ACK retry never rewrites or restamps the original receipt. + RETURN NULL; + END IF; + + own_xid := pg_current_xact_id()::text; + IF own_xid = locked_operation.finalization_xid THEN + RAISE EXCEPTION 'Original Account COMMIT acknowledgement receipt requires independent transaction' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_independent'; + END IF; + BEGIN + finalization_status := pg_xact_status(locked_operation.finalization_xid::xid8); + EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Original Account finalization status unavailable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_finalization_unavailable'; + END; + IF finalization_status IS DISTINCT FROM 'committed' THEN + RAISE EXCEPTION 'Original Account finalization is not independently committed' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_independent'; + END IF; + + NEW.account_uuid := locked_operation.account_uuid; + NEW.lease_id := locked_operation.lease_id; + NEW.lease_fence := locked_operation.lease_fence; + NEW.expires_at_ms := locked_operation.expires_at_ms; + NEW.receipt_xid := own_xid; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_admission_original_ack_receipt_guard + BEFORE INSERT OR UPDATE OR DELETE + ON account_gameplay_admission_original_commit_ack_receipts FOR EACH ROW + EXECUTE FUNCTION account_gameplay_admission_original_ack_receipt_guard(); +CREATE TRIGGER account_admission_original_ack_receipt_truncate_guard + BEFORE TRUNCATE ON account_gameplay_admission_original_commit_ack_receipts FOR EACH STATEMENT + EXECUTE FUNCTION account_gameplay_admission_original_ack_receipt_guard(); + +CREATE FUNCTION account_gameplay_admission_read_original_ack_receipt_durably( + requested_request_id UUID, expected_sha TEXT, expected_decision UUID) +RETURNS SETOF account_gameplay_admission_original_commit_ack_receipts LANGUAGE plpgsql AS $$ +DECLARE + operation account_gameplay_admission_lease_operations%ROWTYPE; + receipt account_gameplay_admission_original_commit_ack_receipts%ROWTYPE; + locked_operation account_gameplay_admission_lease_operations%ROWTYPE; + locked_receipt account_gameplay_admission_original_commit_ack_receipts%ROWTYPE; + own_xid TEXT; + fixed_snapshot pg_snapshot; + insert_fence pg_lsn; + initial_flush_fence pg_lsn; + flush_fence pg_lsn; + observation INTEGER; +BEGIN + IF current_setting('transaction_isolation') IS DISTINCT FROM 'serializable' + OR current_setting('transaction_read_only') IS DISTINCT FROM 'off' THEN + RAISE EXCEPTION 'Writable SERIALIZABLE Account acknowledgement receipt read required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_transaction_required'; + END IF; + IF current_setting('server_version_num')::integer < 160000 + OR current_setting('server_version_num')::integer >= 170000 + OR pg_is_in_recovery() OR current_setting('fsync') IS DISTINCT FROM 'on' THEN + RAISE EXCEPTION 'Supported durable PostgreSQL 16 primary required for Account acknowledgement receipt read' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_durable_primary'; + END IF; + -- Establish one fixed snapshot and its WAL upper fence before any heap read or row lock. + -- A receipt visible in this snapshot committed independently before this fence. + fixed_snapshot := pg_current_snapshot(); + own_xid := pg_current_xact_id_if_assigned()::text; + insert_fence := pg_current_wal_insert_lsn(); + initial_flush_fence := pg_current_wal_flush_lsn(); + IF insert_fence IS NULL OR insert_fence <= '0/0'::pg_lsn THEN + RAISE EXCEPTION 'Original Account acknowledgement receipt WAL coverage unavailable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_wal_coverage'; + END IF; + + SELECT * INTO operation FROM account_gameplay_admission_lease_operations + WHERE request_id = requested_request_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Original Account acknowledgement operation missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_operation_required'; + END IF; + SELECT * INTO receipt FROM account_gameplay_admission_original_commit_ack_receipts + WHERE request_id = requested_request_id; + IF NOT FOUND OR operation.status IS DISTINCT FROM 'COMMITTED' + OR operation.finalization_xid IS NULL + OR expected_sha IS DISTINCT FROM operation.evidence_sha256 + OR expected_decision IS DISTINCT FROM operation.binding_decision_id + OR receipt.schema_version IS DISTINCT FROM 1 + OR receipt.account_uuid IS DISTINCT FROM operation.account_uuid + OR receipt.lease_id IS DISTINCT FROM operation.lease_id + OR receipt.lease_fence IS DISTINCT FROM operation.lease_fence + OR receipt.evidence_sha256 IS DISTINCT FROM operation.evidence_sha256 + OR receipt.binding_decision_id IS DISTINCT FROM operation.binding_decision_id + OR receipt.expires_at_ms IS DISTINCT FROM operation.expires_at_ms + OR receipt.finalization_xid IS DISTINCT FROM operation.finalization_xid + OR receipt.committed_before_ms <= 0 + OR receipt.committed_before_ms >= operation.expires_at_ms THEN + RAISE EXCEPTION 'Exact durable original Account acknowledgement receipt required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_required'; + END IF; + -- receipt_xid is the database-stamped top-level XID, so this excludes the current transaction + -- and any released subtransaction while retaining an independently committed historical row. + IF receipt.receipt_xid = own_xid THEN + RAISE EXCEPTION 'Original Account acknowledgement receipt requires independent commit' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_independent'; + END IF; + + PERFORM 1 FROM accounts WHERE account_uuid = operation.account_uuid FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Original Account acknowledgement owner missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_owner_required'; + END IF; + SELECT * INTO locked_operation FROM account_gameplay_admission_lease_operations + WHERE request_id = requested_request_id FOR UPDATE; + IF NOT FOUND OR locked_operation IS DISTINCT FROM operation THEN + RAISE EXCEPTION 'Exact durable original Account acknowledgement receipt required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_required'; + END IF; + SELECT * INTO locked_receipt FROM account_gameplay_admission_original_commit_ack_receipts + WHERE request_id = requested_request_id FOR UPDATE; + IF NOT FOUND OR locked_receipt IS DISTINCT FROM receipt THEN + RAISE EXCEPTION 'Exact durable original Account acknowledgement receipt required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_required'; + END IF; + + -- Bounded observation checks current WAL coverage only. It creates no marker, forces no flush, + -- consults no new clock, and never changes the original committed_before_ms or expiry. + FOR observation IN 1..50 LOOP + flush_fence := pg_current_wal_flush_lsn(); + EXIT WHEN flush_fence IS NOT NULL AND flush_fence >= insert_fence; + IF observation = 50 THEN + RAISE EXCEPTION 'Original Account acknowledgement receipt WAL coverage unavailable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_wal_coverage', + DETAIL = format('snapshot=%s own_xid_if_assigned=%s finalization_xid=%s receipt_xid=%s insert_fence=%s initial_flush=%s final_flush=%s unchanged_expiry_ms=%s', + fixed_snapshot, own_xid, operation.finalization_xid, receipt.receipt_xid, + insert_fence, initial_flush_fence, flush_fence, operation.expires_at_ms); + END IF; + PERFORM pg_sleep(0.01); + END LOOP; + RETURN NEXT receipt; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql b/services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql new file mode 100644 index 0000000000..ae140c93e9 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql @@ -0,0 +1,26 @@ +-- Retire only the unwired V120 fresh temporal-confirmation writer. Retained rows, its historical +-- independent durability reader and immutable guards remain unchanged. V120 original-finalizer +-- XID/binding stamps and V121 pending fences are still required by genuine V122 ACK receipts. +-- [jooq ignore start] +CREATE FUNCTION account_gameplay_admission_confirmation_writes_retired() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Experimental Account admission confirmation writes are retired' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_writes_retired'; +END; +$$; + +-- PostgreSQL executes same-event triggers by name: deny before the old INSERT proof guard. +CREATE TRIGGER account_admission_confirmation_00_retired_insert + BEFORE INSERT ON account_gameplay_admission_commit_confirmations FOR EACH ROW + EXECUTE FUNCTION account_gameplay_admission_confirmation_writes_retired(); + +CREATE OR REPLACE FUNCTION account_gameplay_admission_confirm_committed( + requested_request_id UUID, expected_sha TEXT, expected_decision UUID) +RETURNS SETOF account_gameplay_admission_commit_confirmations LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Experimental Account admission confirmation writes are retired' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_writes_retired'; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql b/services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql new file mode 100644 index 0000000000..437e9ba23b --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql @@ -0,0 +1,152 @@ +-- Converge only the fresh original-ACK receipt insertion guard to PostgreSQL 18. Historical +-- readDurably recovery remains fenced to its existing PostgreSQL 16 contract and is not widened. +-- [jooq ignore start] +DO $migration$ +DECLARE + guard_definition TEXT; + reader_definition TEXT; + guard_oid REGPROCEDURE := to_regprocedure( + 'account_gameplay_admission_original_ack_receipt_guard()'); +BEGIN + IF current_setting('server_version_num')::integer < 180000 + OR current_setting('server_version_num')::integer >= 190000 THEN + RAISE EXCEPTION 'PostgreSQL 18 required for Account fresh original-ACK insert convergence'; + END IF; + IF guard_oid IS NULL THEN + RAISE EXCEPTION 'Account original-ACK insert guard missing before V139'; + END IF; + SELECT pg_get_functiondef(guard_oid) INTO guard_definition; + IF guard_definition IS NULL + OR position('version_num < 160000 OR version_num >= 170000' IN guard_definition) = 0 + OR position('account_admission_original_ack_receipt_durable_primary' IN guard_definition) = 0 + OR position('pg_xact_status(locked_operation.finalization_xid::xid8)' IN guard_definition) = 0 + OR position('account_gameplay_admission_original_commit_ack_receipts' IN guard_definition) = 0 + OR NOT EXISTS ( + SELECT 1 FROM pg_trigger + WHERE tgname = 'account_admission_original_ack_receipt_guard' + AND tgfoid = guard_oid AND NOT tgisinternal) THEN + RAISE EXCEPTION 'Account V122 original-ACK insert guard drifted before V139'; + END IF; + SELECT pg_get_functiondef( + to_regprocedure('account_gameplay_admission_read_original_ack_receipt_durably(uuid,text,uuid)')) + INTO reader_definition; + IF reader_definition IS NULL + OR position('current_setting(''server_version_num'')::integer < 160000' IN reader_definition) = 0 + OR position('current_setting(''server_version_num'')::integer >= 170000' IN reader_definition) = 0 + OR position('Supported durable PostgreSQL 16 primary required for Account acknowledgement receipt read' IN reader_definition) = 0 THEN + RAISE EXCEPTION 'Account V122 historical original-ACK reader drifted before V139'; + END IF; +END; +$migration$; + +CREATE OR REPLACE FUNCTION account_gameplay_admission_original_ack_receipt_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + operation account_gameplay_admission_lease_operations%ROWTYPE; + locked_operation account_gameplay_admission_lease_operations%ROWTYPE; + receipt account_gameplay_admission_original_commit_ack_receipts%ROWTYPE; + locked_receipt account_gameplay_admission_original_commit_ack_receipts%ROWTYPE; + own_xid TEXT; + finalization_status TEXT; + version_num INTEGER; +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Original Account COMMIT acknowledgement receipt is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_immutable'; + END IF; + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Original Account COMMIT acknowledgement receipt is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_immutable'; + END IF; + IF NEW.schema_version IS DISTINCT FROM 1 + OR NEW.account_uuid IS NOT NULL OR NEW.lease_id IS NOT NULL + OR NEW.lease_fence IS NOT NULL OR NEW.expires_at_ms IS NOT NULL + OR NEW.receipt_xid IS NOT NULL THEN + RAISE EXCEPTION 'Original Account COMMIT acknowledgement receipt binding is database derived' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_db_binding'; + END IF; + IF current_setting('transaction_isolation') IS DISTINCT FROM 'serializable' + OR current_setting('transaction_read_only') IS DISTINCT FROM 'off' THEN + RAISE EXCEPTION 'Writable SERIALIZABLE Account acknowledgement receipt transaction required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_transaction_required'; + END IF; + version_num := current_setting('server_version_num')::integer; + IF version_num < 180000 OR version_num >= 190000 + OR pg_is_in_recovery() OR current_setting('fsync') IS DISTINCT FROM 'on' THEN + RAISE EXCEPTION 'Supported durable PostgreSQL 18 primary required for Account acknowledgement receipt' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_durable_primary'; + END IF; + + -- The request lookup only discovers the owning Account. All locked reads follow Account first. + SELECT * INTO operation FROM account_gameplay_admission_lease_operations + WHERE request_id = NEW.request_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Original Account COMMIT acknowledgement operation missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_operation_required'; + END IF; + PERFORM 1 FROM accounts WHERE account_uuid = operation.account_uuid FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Original Account COMMIT acknowledgement owner missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_owner_required'; + END IF; + SELECT * INTO locked_operation FROM account_gameplay_admission_lease_operations + WHERE request_id = NEW.request_id FOR UPDATE; + IF NOT FOUND OR locked_operation IS DISTINCT FROM operation + OR locked_operation.status IS DISTINCT FROM 'COMMITTED' + OR locked_operation.finalization_xid IS NULL + OR NEW.evidence_sha256 IS DISTINCT FROM locked_operation.evidence_sha256 + OR NEW.binding_decision_id IS DISTINCT FROM locked_operation.binding_decision_id + OR NEW.finalization_xid IS DISTINCT FROM locked_operation.finalization_xid + OR NEW.committed_before_ms <= 0 + OR NEW.committed_before_ms >= locked_operation.expires_at_ms THEN + RAISE EXCEPTION 'Exact original Account COMMIT acknowledgement required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_binding_required'; + END IF; + + SELECT * INTO receipt FROM account_gameplay_admission_original_commit_ack_receipts + WHERE request_id = NEW.request_id; + IF FOUND THEN + SELECT * INTO locked_receipt FROM account_gameplay_admission_original_commit_ack_receipts + WHERE request_id = NEW.request_id FOR UPDATE; + IF NOT FOUND OR locked_receipt IS DISTINCT FROM receipt + OR receipt.schema_version IS DISTINCT FROM 1 + OR receipt.account_uuid IS DISTINCT FROM locked_operation.account_uuid + OR receipt.lease_id IS DISTINCT FROM locked_operation.lease_id + OR receipt.lease_fence IS DISTINCT FROM locked_operation.lease_fence + OR receipt.evidence_sha256 IS DISTINCT FROM locked_operation.evidence_sha256 + OR receipt.binding_decision_id IS DISTINCT FROM locked_operation.binding_decision_id + OR receipt.expires_at_ms IS DISTINCT FROM locked_operation.expires_at_ms + OR receipt.finalization_xid IS DISTINCT FROM locked_operation.finalization_xid + OR receipt.committed_before_ms IS DISTINCT FROM NEW.committed_before_ms THEN + RAISE EXCEPTION 'Original Account COMMIT acknowledgement receipt retry conflicts' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_conflict'; + END IF; + -- An exact retained ACK retry never rewrites or restamps the original receipt. + RETURN NULL; + END IF; + + own_xid := pg_current_xact_id()::text; + IF own_xid = locked_operation.finalization_xid THEN + RAISE EXCEPTION 'Original Account COMMIT acknowledgement receipt requires independent transaction' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_independent'; + END IF; + BEGIN + finalization_status := pg_xact_status(locked_operation.finalization_xid::xid8); + EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Original Account finalization status unavailable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_finalization_unavailable'; + END; + IF finalization_status IS DISTINCT FROM 'committed' THEN + RAISE EXCEPTION 'Original Account finalization is not independently committed' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_independent'; + END IF; + + NEW.account_uuid := locked_operation.account_uuid; + NEW.lease_id := locked_operation.lease_id; + NEW.lease_fence := locked_operation.lease_fence; + NEW.expires_at_ms := locked_operation.expires_at_ms; + NEW.receipt_xid := own_xid; + RETURN NEW; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java new file mode 100644 index 0000000000..3f9823683d --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java @@ -0,0 +1,1065 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import java.sql.Connection; +import java.sql.SQLException; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionOriginalCommitExecutor.OriginalCommitAcknowledgement; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * PostgreSQL 18 proof for fresh original-ACK storage only. + * + *

Tests exercise the original operation's physical COMMIT, its opaque pre-expiry + * acknowledgement, and a separate physical receipt COMMIT. PostgreSQL 18 does not enable the + * retained historical durability reader or lost-acknowledgement recovery. SQL and JVM storage proof + * establish no authentication, current ownership, admission, production privilege adoption, or + * gameplay. + */ +@Execution(ExecutionMode.SAME_THREAD) +class AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest { + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(true); + + @BeforeAll + static void startPostgres() { + POSTGRES.start(); + } + + @AfterAll + static void stopPostgres() { + POSTGRES.stop(); + } + + private static final String TENANT = "22222222-2222-4222-8222-222222222222"; + private static final String OTHER = "33333333-3333-4333-8333-333333333333"; + private static final String RECEIPTS = "account_gameplay_admission_original_commit_ack_receipts"; + + @Test + void coldGenuineAcknowledgedFinalizationPersistsExactProofWithoutAuxiliaryWrites() { + var context = context(); + var ack = finalized(context, 15000); + var receipt = + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()).confirm(ack); + var scope = (Map) ack.evidence().carrier().get("bindingScope"); + assertThat(receipt.schemaVersion()).isEqualTo((short) 1); + assertThat(receipt.requestId()).isEqualTo(request(ack.evidence())); + assertThat(receipt.accountId()).isEqualTo(UUID.fromString((String) scope.get("accountId"))); + assertThat(receipt.leaseId()) + .isEqualTo(UUID.fromString((String) ack.evidence().carrier().get("leaseId"))); + assertThat(receipt.leaseFence()).isEqualTo(ack.evidence().leaseFence().longValueExact()); + assertThat(receipt.evidenceSha256()).isEqualTo(ack.evidence().sha256()); + assertThat(receipt.bindingDecisionId()).isEqualTo(ack.decisionId()); + assertThat(receipt.finalizationXid()).isEqualTo(ack.finalizationXid()); + assertThat(receipt.committedBeforeMs()).isEqualTo(ack.committedBeforeMs()); + assertThat(ack.committedBeforeMs()).isLessThan(expiry(ack)); + assertThat(receipt.expiresAtMs()).isEqualTo(expiry(ack)); + assertThat(receipt.receiptXid()).isNotEqualTo(ack.finalizationXid()); + assertThat(receipt.operation().evidence()).isEqualTo(ack.evidence()); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isOne(); + assertThatThrownBy( + () -> + context + .dsl() + .fetch( + "SELECT * FROM account_gameplay_admission_confirm_committed(?, ?, ?)", + request(ack.evidence()), + ack.evidence().sha256(), + ack.decisionId())) + .hasMessageContaining("Experimental Account admission confirmation writes are retired"); + assertThat( + context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) + .isZero(); + } + + @Test + void catalogChurnBeforeOriginalCommitPreservesGenuineAcknowledgedFinalization() { + var context = context(); + for (int index = 0; index < 30; index++) { + context.dsl().execute("CREATE TABLE retired_entry_catalog_" + index + "(id integer)"); + context.dsl().execute("DROP TABLE retired_entry_catalog_" + index); + } + var ack = finalized(context, 15000); + var receipt = + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()).confirm(ack); + assertThat(receipt.finalizationXid()).isEqualTo(ack.finalizationXid()); + assertThat(receipt.committedBeforeMs()).isEqualTo(ack.committedBeforeMs()); + assertThat(receipt.expiresAtMs()).isEqualTo(expiry(ack)); + } + + @Test + void concurrentGenuineAckCreatorsRetainOneExactWinnerWithoutRestamping() throws Exception { + var context = context(); + var ack = finalized(context, 15000); + var original = operation(context, ack.evidence()); + var sources = sourceSnapshot(context); + var start = new CountDownLatch(1); + java.util.concurrent.Callable duplicate = + () -> { + if (!start.await(10, TimeUnit.SECONDS)) throw new IllegalStateException("start timeout"); + return retrySerialization( + () -> + context + .transaction() + .execute(status -> repository(context).create(ack).receipt())); + }; + try (var executor = Executors.newFixedThreadPool(2)) { + var left = executor.submit(duplicate); + var right = executor.submit(duplicate); + start.countDown(); + assertThat(left.get(30, TimeUnit.SECONDS)).isEqualTo(right.get(30, TimeUnit.SECONDS)); + } + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isOne(); + assertThat(operation(context, ack.evidence())).isEqualTo(original); + assertThat(sourceSnapshot(context)).isEqualTo(sources); + var before = receipt(context); + waitPastExpiry(context, ack); + var replay = context.transaction().execute(status -> repository(context).create(ack)); + assertThat(replay.inserted()).isFalse(); + assertThat(replay.receipt().committedBeforeMs()).isEqualTo(ack.committedBeforeMs()); + assertThat(receipt(context)).isEqualTo(before); + // This asserts exact storage replay. A retry COMMIT is not historical durability proof. + } + + @Test + void staleSerializableGenuineAckCreatorRetriesAndRetainsOneExactWinner() throws Exception { + var context = context(); + var ack = finalized(context, 15000); + try (var stale = context.admin().getConnection()) { + stale.setAutoCommit(false); + stale.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); + DSL.using(stale).fetchSingle("SELECT pg_current_snapshot()"); + var winner = + context.transaction().execute(status -> repository(context).create(ack).receipt()); + assertThatThrownBy(() -> insertAck(DSL.using(stale), ack)) + .satisfies(failure -> assertThat(sqlState(failure)).isEqualTo("40001")); + stale.rollback(); + var retry = context.transaction().execute(status -> repository(context).create(ack)); + assertThat(retry.inserted()).isFalse(); + assertThat(retry.receipt()).isEqualTo(winner); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isOne(); + } + } + + @Test + void restrictedCallerCannotForgeProofWriteTablesInvokeGuardOrEscalate() throws Exception { + var context = context(); + var ack = finalized(context, 15000); + String role = context.schema() + "_caller"; + context + .dsl() + .execute( + "CREATE ROLE " + + role + + " NOLOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOREPLICATION"); + context.dsl().execute("GRANT USAGE ON SCHEMA " + context.schema() + " TO " + role); + var administratorRow = + java.util.Objects.requireNonNull( + context.dsl().fetchOne("SELECT quote_ident(session_user)"), + "Restricted-caller proof requires the actual administrator role row"); + String administratorRole = administratorRow.get(0, String.class); + var denied = + List.of( + "INSERT INTO " + RECEIPTS + "(request_id) VALUES ('" + request(ack.evidence()) + "')", + "UPDATE " + RECEIPTS + " SET committed_before_ms = 1", + "DELETE FROM " + RECEIPTS, + "TRUNCATE " + RECEIPTS, + "INSERT INTO account_gameplay_admission_commit_confirmations(request_id) VALUES ('" + + request(ack.evidence()) + + "')", + "SELECT account_gameplay_admission_original_ack_receipt_guard()", + "SELECT account_gameplay_admission_confirmation_guard()", + "SET ROLE " + administratorRole, + "ALTER FUNCTION account_gameplay_admission_original_ack_receipt_guard() RESET ALL", + "ALTER TABLE " + RECEIPTS + " DISABLE TRIGGER ALL", + "CREATE TABLE " + context.schema() + ".shadow(id integer)", + "SET session_replication_role = replica"); + try { + for (String sql : denied) { + try (var connection = context.admin().getConnection()) { + DSL.using(connection, SQLDialect.POSTGRES).execute("SET SESSION AUTHORIZATION " + role); + assertThatThrownBy(() -> DSL.using(connection, SQLDialect.POSTGRES).execute(sql)) + .isInstanceOf(RuntimeException.class); + } + } + } finally { + context.dsl().execute("REVOKE USAGE ON SCHEMA " + context.schema() + " FROM " + role); + context.dsl().execute("DROP ROLE " + role); + } + // The genuine trusted owner remains usable after all denied caller attempts. + var receipt = + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()).confirm(ack); + assertThat(receipt.finalizationXid()).isEqualTo(ack.finalizationXid()); + assertThat(receipt.committedBeforeMs()).isEqualTo(ack.committedBeforeMs()); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isOne(); + } + + @Test + void ownFinalizationAndReleasedSubtransactionCannotSupplyIndependentOriginal() { + for (boolean subtransaction : List.of(false, true)) { + var context = context(); + var evidence = pending(context, 15000); + UUID decision = UUID.randomUUID(); + assertThatThrownBy( + () -> + context + .transaction() + .executeWithoutResult( + status -> { + if (subtransaction) + context.dsl().execute("SAVEPOINT original_finalization"); + new AccountGameplayAdmissionLeaseRepository(context.dsl()) + .recordCommitted(evidence, decision); + if (subtransaction) + context.dsl().execute("RELEASE SAVEPOINT original_finalization"); + context + .dsl() + .execute( + "INSERT INTO " + + RECEIPTS + + "(request_id, evidence_sha256, binding_decision_id, finalization_xid, committed_before_ms) VALUES (?, ?, ?, pg_current_xact_id()::text, ?)", + request(evidence), + evidence.sha256(), + decision, + Long.parseLong((String) evidence.carrier().get("evaluatedAt"))); + })) + .hasMessageContaining("requires independent transaction"); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); + } + } + + @Test + void historicalDurableReadRemainsDeniedOnPostgres18AfterReceiptInsert() { + for (boolean subtransaction : List.of(false, true)) { + var context = context(); + var ack = finalized(context, 15000); + assertThatThrownBy( + () -> + context + .transaction() + .executeWithoutResult( + status -> { + if (subtransaction) context.dsl().execute("SAVEPOINT receipt_creation"); + repository(context).create(ack); + if (subtransaction) + context.dsl().execute("RELEASE SAVEPOINT receipt_creation"); + repository(context).readDurably(ack.evidence(), ack.decisionId()); + })) + .hasMessageContaining("Supported durable PostgreSQL 16 primary required"); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); + } + } + + @Test + void staleSnapshotBeforeOriginalCommitCannotCreateAcknowledgementReceipt() throws Exception { + var context = context(); + var evidence = pending(context, 15000); + try (var stale = context.admin().getConnection()) { + stale.setAutoCommit(false); + stale.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); + DSL.using(stale).fetchSingle("SELECT pg_current_snapshot()"); + var ack = + new AccountGameplayAdmissionOriginalCommitExecutor(context.admin()) + .execute(evidence, UUID.randomUUID()); + assertThatThrownBy(() -> insertAck(DSL.using(stale), ack)) + .satisfies(failure -> assertThat(sqlState(failure)).isIn("23514", "40001")); + stale.rollback(); + } + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); + } + + @Test + void changedCallerProofAndBindingsDenyAndRetainedReceiptRemainsImmutable() { + var context = context(); + var ack = finalized(context, 15000); + for (String field : + List.of("account_uuid", "lease_id", "lease_fence", "expires_at_ms", "receipt_xid")) { + String value = + switch (field) { + case "account_uuid", "lease_id" -> "'" + UUID.randomUUID() + "'::uuid"; + case "receipt_xid" -> "'1'"; + default -> "1"; + }; + assertThatThrownBy( + () -> + context + .transaction() + .executeWithoutResult( + status -> + context + .dsl() + .execute( + "INSERT INTO " + + RECEIPTS + + "(request_id, evidence_sha256, binding_decision_id, finalization_xid, committed_before_ms, " + + field + + ") VALUES (?, ?, ?, ?, ?, " + + value + + ")", + request(ack.evidence()), + ack.evidence().sha256(), + ack.decisionId(), + ack.finalizationXid(), + ack.committedBeforeMs()))) + .hasMessageContaining("binding is database derived"); + } + for (String changed : List.of("digest", "decision", "xid", "bound")) { + assertThatThrownBy( + () -> + context + .transaction() + .executeWithoutResult( + status -> + context + .dsl() + .execute( + "INSERT INTO " + + RECEIPTS + + "(request_id, evidence_sha256, binding_decision_id, finalization_xid, committed_before_ms) VALUES (?, ?, ?, ?, ?)", + request(ack.evidence()), + changed.equals("digest") + ? "b".repeat(64) + : ack.evidence().sha256(), + changed.equals("decision") + ? UUID.randomUUID() + : ack.decisionId(), + changed.equals("xid") ? "1" : ack.finalizationXid(), + changed.equals("bound") + ? expiry(ack) + : ack.committedBeforeMs()))) + .hasMessageContaining("Exact original Account COMMIT acknowledgement required"); + } + var receipt = + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()).confirm(ack); + var before = receipt(context); + for (String mutation : + List.of( + "UPDATE " + RECEIPTS + " SET committed_before_ms = committed_before_ms + 1", + "UPDATE " + RECEIPTS + " SET expires_at_ms = expires_at_ms + 1", + "UPDATE " + RECEIPTS + " SET evidence_sha256 = '" + "b".repeat(64) + "'", + "DELETE FROM " + RECEIPTS, + "TRUNCATE " + RECEIPTS)) { + assertThatThrownBy( + () -> + context + .transaction() + .executeWithoutResult(status -> context.dsl().execute(mutation))) + .hasMessageContaining("receipt is immutable"); + } + assertThat(receipt(context)).isEqualTo(before); + assertThat(receipt.committedBeforeMs()).isEqualTo(ack.committedBeforeMs()); + } + + @Test + void originalLockWaitPastExpiryCannotMintAcknowledgementOrReceipt() throws Exception { + var context = context(); + var evidence = pending(context, 1800); + try (var lock = context.admin().getConnection(); + var executor = Executors.newSingleThreadExecutor()) { + lock.setAutoCommit(false); + var owner = + DSL.using(lock) + .fetchSingle( + "SELECT account_uuid FROM account_gameplay_admission_lease_operations WHERE request_id = ?", + request(evidence)) + .get(0, UUID.class); + DSL.using(lock) + .fetchSingle( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", owner); + var started = new CountDownLatch(1); + var backendPid = new java.util.concurrent.atomic.AtomicInteger(); + var waitingSource = + new org.springframework.jdbc.datasource.DelegatingDataSource(context.admin()) { + @Override + public Connection getConnection() throws SQLException { + Connection connection = super.getConnection(); + try { + backendPid.set( + DSL.using(connection) + .fetchSingle("SELECT pg_backend_pid()") + .get(0, Integer.class)); + started.countDown(); + return connection; + } catch (RuntimeException | Error failure) { + try { + connection.close(); + } catch (SQLException closeFailure) { + failure.addSuppressed(closeFailure); + } + throw failure; + } + } + }; + var attempt = + executor.submit( + () -> + new AccountGameplayAdmissionOriginalCommitExecutor(waitingSource) + .execute(evidence, UUID.randomUUID())); + assertThat(started.await(5, TimeUnit.SECONDS)).isTrue(); + // Verify an actual independent lock wait before the original expiry is allowed to pass. + boolean waiting = false; + long until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (!waiting && System.nanoTime() < until) { + waiting = + context + .dsl() + .fetchSingle( + "SELECT EXISTS(SELECT 1 FROM pg_stat_activity WHERE pid = ? AND wait_event_type = 'Lock')", + backendPid.get()) + .get(0, Boolean.class); + if (!waiting) Thread.sleep(10); + } + assertThat(waiting).isTrue(); + context + .dsl() + .fetchSingle( + "SELECT pg_sleep(GREATEST(0, (? - ceil(extract(epoch FROM clock_timestamp()) * 1000) + 50) / 1000.0))", + Long.parseLong((String) evidence.carrier().get("expiresAt"))); + lock.rollback(); + assertThatThrownBy(() -> attempt.get(5, TimeUnit.SECONDS)) + .isInstanceOf(java.util.concurrent.ExecutionException.class); + } + assertThat(operation(context, evidence).get("status")).isEqualTo("PENDING"); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); + } + + @Test + void originalUpdateBeforeExpiryButPhysicalCommitAfterExpiryCannotMintReceipt() { + var context = context(); + var evidence = pending(context, 1000); + UUID decision = UUID.randomUUID(); + var physicalCommits = new java.util.concurrent.atomic.AtomicInteger(); + var delayed = + new org.springframework.jdbc.datasource.DelegatingDataSource(context.admin()) { + @Override + public Connection getConnection() throws SQLException { + return delayedCommitConnection(super.getConnection()); + } + + private Connection delayedCommitConnection(Connection physical) { + try { + return (Connection) + java.lang.reflect.Proxy.newProxyInstance( + Connection.class.getClassLoader(), + new Class[] {Connection.class}, + (proxy, method, arguments) -> { + if (method.getName().equals("commit") && method.getParameterCount() == 0) { + DSL.using(physical) + .fetchSingle( + "SELECT pg_sleep(GREATEST(0, (? - ceil(extract(epoch FROM clock_timestamp()) * 1000) + 50) / 1000.0))", + Long.parseLong((String) evidence.carrier().get("expiresAt"))); + physical.commit(); + physicalCommits.incrementAndGet(); + return null; + } + try { + return method.invoke(physical, arguments); + } catch (java.lang.reflect.InvocationTargetException failure) { + throw failure.getCause(); + } + }); + } catch (RuntimeException | Error failure) { + try { + physical.close(); + } catch (SQLException closeFailure) { + failure.addSuppressed(closeFailure); + } + throw failure; + } + } + }; + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalCommitExecutor(delayed) + .execute(evidence, decision)) + .hasMessageContaining("post-COMMIT clock bound unavailable"); + assertThat(physicalCommits.get()).isOne(); + assertThat(operation(context, evidence).get("status")).isEqualTo("COMMITTED"); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalCommitExecutor(context.admin()) + .execute(evidence, decision)) + .hasMessageContaining("Fresh owned Account original COMMIT required"); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); + } + + @Test + void lostOriginalCommitAcknowledgementCannotReconstructCapabilityOrRetryFinalization() { + var context = context(); + var evidence = pending(context, 15000); + UUID decision = UUID.randomUUID(); + var pendingOperation = operation(context, evidence); + var sourcesBefore = sourceSnapshot(context); + var physicalCommits = new java.util.concurrent.atomic.AtomicInteger(); + var source = loseCommitAcknowledgementAfter(context.admin(), physicalCommits, 1); + + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalCommitExecutor(source) + .execute(evidence, decision)) + .hasMessageContaining("physical COMMIT unavailable"); + + assertThat(physicalCommits.get()).isOne(); + var committed = operation(context, evidence); + var scope = (Map) evidence.carrier().get("bindingScope"); + assertThat(committed.get("request_id")).isEqualTo(request(evidence)); + assertThat(committed.get("account_uuid")) + .isEqualTo(UUID.fromString((String) scope.get("accountId"))); + assertThat(committed.get("lease_id")) + .isEqualTo(UUID.fromString((String) evidence.carrier().get("leaseId"))); + assertThat(committed.get("lease_fence")).isEqualTo(evidence.leaseFence().longValueExact()); + assertThat(committed.get("evidence_json")).isEqualTo(evidence.canonicalJson()); + assertThat(committed.get("evidence_sha256")).isEqualTo(evidence.sha256()); + assertThat(committed.get("expires_at_ms")) + .isEqualTo(Long.parseLong((String) evidence.carrier().get("expiresAt"))); + assertThat(committed.get("status")).isEqualTo("COMMITTED"); + assertThat(committed.get("binding_decision_id")).isEqualTo(decision); + assertThat((String) committed.get("finalization_xid")).matches("[1-9][0-9]{0,19}"); + assertThat(committed).isNotEqualTo(pendingOperation); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); + + // The physical COMMIT succeeded, but its missing JDBC acknowledgement never yielded the + // opaque capability. A retained retry cannot stamp or reconstruct one. + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalCommitExecutor(context.admin()) + .execute(evidence, decision)) + .hasMessageContaining("Fresh owned Account original COMMIT required"); + assertThat(operation(context, evidence)).isEqualTo(committed); + assertThat(sourceSnapshot(context)).isEqualTo(sourcesBefore); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); + } + + @Test + void acknowledgementFromAnotherPostgresDataSourceCannotCreateReceipt() { + var original = context(); + var other = context(); + var ack = finalized(original, 15000); + var operationBefore = operation(original, ack.evidence()); + + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(other.admin()) + .confirm(ack)) + .hasMessageContaining("Fresh owned Account receipt COMMIT required"); + + assertThat(operation(original, ack.evidence())).isEqualTo(operationBefore); + assertThat(original.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); + assertThat(other.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); + assertThat(other.dsl().fetchCount(DSL.table("account_gameplay_admission_lease_operations"))) + .isZero(); + + // The exact originating DataSource still accepts the same capability after the rejection. + var receipt = + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(original.admin()).confirm(ack); + assertThat(receipt.requestId()).isEqualTo(request(ack.evidence())); + var scope = (Map) ack.evidence().carrier().get("bindingScope"); + assertThat(receipt.accountId()).isEqualTo(UUID.fromString((String) scope.get("accountId"))); + assertThat(receipt.leaseId()) + .isEqualTo(UUID.fromString((String) ack.evidence().carrier().get("leaseId"))); + assertThat(receipt.leaseFence()).isEqualTo(ack.evidence().leaseFence().longValueExact()); + assertThat(receipt.evidenceSha256()).isEqualTo(ack.evidence().sha256()); + assertThat(receipt.bindingDecisionId()).isEqualTo(ack.decisionId()); + assertThat(receipt.finalizationXid()).isEqualTo(ack.finalizationXid()); + assertThat(receipt.committedBeforeMs()).isEqualTo(ack.committedBeforeMs()); + assertThat(receipt.expiresAtMs()).isEqualTo(expiry(ack)); + assertThat(receipt.receiptXid()).isNotEqualTo(ack.finalizationXid()); + assertThat(other.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); + assertThat(other.dsl().fetchCount(DSL.table("account_gameplay_admission_lease_operations"))) + .isZero(); + } + + @Test + void lostReceiptCommitAcknowledgementDoesNotReconstructFreshReceiptDurability() { + var context = context(); + var evidence = pending(context, 15000); + UUID decision = UUID.randomUUID(); + var physicalCommits = new java.util.concurrent.atomic.AtomicInteger(); + var source = loseCommitAcknowledgementAfter(context.admin(), physicalCommits, 2); + var ack = + new AccountGameplayAdmissionOriginalCommitExecutor(source).execute(evidence, decision); + var operationBefore = operation(context, evidence); + var sourcesBefore = sourceSnapshot(context); + assertThat(ack.finalizationXid()).isEqualTo(operationBefore.get("finalization_xid")); + assertThat(ack.committedBeforeMs()).isLessThan(expiry(ack)); + + // Original COMMIT acknowledgement was returned. The separate receipt COMMIT reaches + // PostgreSQL, then its JDBC acknowledgement is lost, so confirm must not return a receipt. + assertThatThrownBy( + () -> new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(source).confirm(ack)) + .hasMessageContaining("physical COMMIT unavailable"); + + assertThat(physicalCommits.get()).isEqualTo(2); + var retained = receipt(context); + var scope = (Map) evidence.carrier().get("bindingScope"); + assertThat(retained.get("request_id")).isEqualTo(request(evidence)); + assertThat(retained.get("account_uuid")) + .isEqualTo(UUID.fromString((String) scope.get("accountId"))); + assertThat(retained.get("lease_id")) + .isEqualTo(UUID.fromString((String) evidence.carrier().get("leaseId"))); + assertThat(retained.get("lease_fence")).isEqualTo(evidence.leaseFence().longValueExact()); + assertThat(retained.get("evidence_sha256")).isEqualTo(evidence.sha256()); + assertThat(retained.get("binding_decision_id")).isEqualTo(decision); + assertThat(retained.get("finalization_xid")).isEqualTo(ack.finalizationXid()); + assertThat(retained.get("committed_before_ms")).isEqualTo(ack.committedBeforeMs()); + assertThat(retained.get("expires_at_ms")).isEqualTo(expiry(ack)); + assertThat(retained.get("receipt_xid")).isNotEqualTo(ack.finalizationXid()); + assertThat(operation(context, evidence)).isEqualTo(operationBefore); + + // PostgreSQL 18 deliberately cannot recover a retained receipt from its retry COMMIT. + assertThatThrownBy( + () -> new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(source).confirm(ack)) + .hasMessageContaining("Supported durable PostgreSQL 16 primary required"); + assertThat(receipt(context)).isEqualTo(retained); + assertThat(operation(context, evidence)).isEqualTo(operationBefore); + assertThat(sourceSnapshot(context)).isEqualTo(sourcesBefore); + } + + @Test + void returnedCommitFaultConnectionClosesItsPhysicalConnection() throws SQLException { + var physicalCommits = new java.util.concurrent.atomic.AtomicInteger(); + var source = loseCommitAcknowledgementAfter(POSTGRES.dataSource(), physicalCommits, 1); + Connection returned = source.getConnection(); + try (returned) { + assertThat(returned.isClosed()).isFalse(); + } + assertThat(returned.isClosed()).isTrue(); + assertThat(physicalCommits.get()).isZero(); + } + + @Test + void retainedCommittedRetryCannotMintFreshAckAndHistoricalReceiptRecoveryStaysDenied() { + var context = context(); + var ack = finalized(context, 15000); + var receiptExecutor = + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()); + var receipt = receiptExecutor.confirm(ack); + var operationBefore = operation(context, ack.evidence()); + var receiptBefore = receipt(context); + + assertThat(receipt.finalizationXid()).isEqualTo(ack.finalizationXid()); + assertThat(receipt.receiptXid()).isNotEqualTo(ack.finalizationXid()); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalCommitExecutor(context.admin()) + .execute(ack.evidence(), ack.decisionId())) + .hasMessageContaining("Fresh owned Account original COMMIT required"); + assertThatThrownBy(() -> receiptExecutor.read(ack.evidence(), ack.decisionId())) + .hasMessageContaining("Supported durable PostgreSQL 16 primary required"); + // A retained receipt's retry COMMIT is not historical durability proof on PostgreSQL 18. + assertThatThrownBy(() -> receiptExecutor.confirm(ack)) + .hasMessageContaining("Supported durable PostgreSQL 16 primary required"); + + assertThat(operation(context, ack.evidence())).isEqualTo(operationBefore); + assertThat(receipt(context)).isEqualTo(receiptBefore); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isOne(); + } + + @Test + void rolledBackAndAbortedOriginalTransitionsCannotInsertFreshAckReceipt() { + for (boolean abort : List.of(false, true)) { + var context = context(); + var evidence = pending(context, 15000); + UUID decision = UUID.randomUUID(); + var original = operation(context, evidence); + if (abort) { + context + .transaction() + .executeWithoutResult( + status -> + new AccountGameplayAdmissionLeaseRepository(context.dsl()) + .recordAborted(evidence, null, decision)); + assertThat(operation(context, evidence).get("status")).isEqualTo("ABORTED"); + } else { + assertThatThrownBy( + () -> + context + .transaction() + .executeWithoutResult( + status -> { + new AccountGameplayAdmissionLeaseRepository(context.dsl()) + .recordCommitted(evidence, decision); + throw new IllegalStateException("rollback original finalization"); + })) + .hasMessageContaining("rollback original finalization"); + assertThat(operation(context, evidence)).isEqualTo(original); + } + assertThatThrownBy( + () -> + context + .transaction() + .executeWithoutResult( + status -> + context + .dsl() + .execute( + "INSERT INTO " + + RECEIPTS + + "(request_id, evidence_sha256, binding_decision_id, finalization_xid, committed_before_ms) VALUES (?, ?, ?, '1', ?)", + request(evidence), + evidence.sha256(), + decision, + Long.parseLong( + (String) evidence.carrier().get("evaluatedAt"))))) + .hasMessageContaining("Exact original Account COMMIT acknowledgement required"); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); + } + } + + @Test + void genuineAckSqlEntryRequiresWritableSerializableTransactionAndKeepsFinalizerStamp() { + var context = context(); + var ack = finalized(context, 15000); + for (int isolation : + List.of( + TransactionDefinition.ISOLATION_READ_COMMITTED, + TransactionDefinition.ISOLATION_REPEATABLE_READ)) { + var unsupported = new TransactionTemplate(new DataSourceTransactionManager(context.admin())); + unsupported.setIsolationLevel(isolation); + assertThatThrownBy( + () -> unsupported.executeWithoutResult(status -> insertAck(context.dsl(), ack))) + .hasMessageContaining("Writable SERIALIZABLE"); + assertThatThrownBy( + () -> + unsupported.executeWithoutResult( + status -> + context + .dsl() + .fetch( + "SELECT * FROM account_gameplay_admission_read_original_ack_receipt_durably(?, ?, ?)", + request(ack.evidence()), + ack.evidence().sha256(), + ack.decisionId()))) + .hasMessageContaining("Writable SERIALIZABLE"); + } + var readOnly = new TransactionTemplate(new DataSourceTransactionManager(context.admin())); + readOnly.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + readOnly.setReadOnly(true); + assertThatThrownBy( + () -> + readOnly.executeWithoutResult( + status -> + context + .dsl() + .fetch( + "SELECT * FROM account_gameplay_admission_read_original_ack_receipt_durably(?, ?, ?)", + request(ack.evidence()), + ack.evidence().sha256(), + ack.decisionId()))) + .hasMessageContaining("Writable SERIALIZABLE"); + assertThatThrownBy( + () -> + context + .transaction() + .executeWithoutResult( + status -> + context + .dsl() + .execute( + "UPDATE account_gameplay_admission_lease_operations SET finalization_xid = '1' WHERE request_id = ?", + request(ack.evidence())))) + .hasMessageContaining("finalization transaction is database stamped"); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); + } + + private static Context context() { + String schema = "protected_" + UUID.randomUUID().toString().replace("-", ""); + var admin = POSTGRES.dataSource(schema); + Flyway.configure() + .dataSource(admin) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + var transaction = new TransactionTemplate(new DataSourceTransactionManager(admin)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + return new Context( + schema, + admin, + DSL.using(new TransactionAwareDataSourceProxy(admin), SQLDialect.POSTGRES), + transaction); + } + + private static javax.sql.DataSource loseCommitAcknowledgementAfter( + javax.sql.DataSource delegate, + java.util.concurrent.atomic.AtomicInteger physicalCommits, + int lostAcknowledgementCommit) { + return new org.springframework.jdbc.datasource.DelegatingDataSource(delegate) { + @SuppressFBWarnings( + value = "ODR_OPEN_DATABASE_RESOURCE", + justification = + "The returned proxy owns this physical connection and explicitly delegates close; " + + "construction failure closes the connection before rethrowing.") + @Override + public Connection getConnection() throws SQLException { + Connection physical = super.getConnection(); + try { + // Ownership transfers to this proxy; its close path below closes the physical handle. + return (Connection) + java.lang.reflect.Proxy.newProxyInstance( + Connection.class.getClassLoader(), + new Class[] {Connection.class}, + (proxy, method, arguments) -> { + if (method.getName().equals("close") && method.getParameterCount() == 0) { + physical.close(); + return null; + } + if (method.getName().equals("commit") && method.getParameterCount() == 0) { + physical.commit(); + if (physicalCommits.incrementAndGet() == lostAcknowledgementCommit) + throw new SQLException("COMMIT acknowledgement lost", "08006"); + return null; + } + try { + return method.invoke(physical, arguments); + } catch (java.lang.reflect.InvocationTargetException failure) { + throw failure.getCause(); + } + }); + } catch (RuntimeException | Error constructionFailure) { + try { + physical.close(); + } catch (SQLException closeFailure) { + constructionFailure.addSuppressed(closeFailure); + } + throw constructionFailure; + } + } + }; + } + + private static OriginalCommitAcknowledgement finalized(Context context, long lifetime) { + return new AccountGameplayAdmissionOriginalCommitExecutor(context.admin()) + .execute(pending(context, lifetime), UUID.randomUUID()); + } + + private static AccountGameplayAdmissionLeaseEvidence pending(Context context, long lifetime) { + return context + .transaction() + .execute( + status -> { + var authorities = new AccountAuthorityGenerationRepository(context.dsl()); + var sources = + new AccountAuthoritySourceEvidenceRepository( + context.dsl(), + authorities, + new AccountAuthorityOutboxRepository(context.dsl())); + sources.initializeIssuerIfAbsent("firemud-account-service"); + var account = new Account(); + account.setUsername("protected-" + UUID.randomUUID()); + account.setEmail(UUID.randomUUID() + "@example.test"); + account.setPasswordHash("shape-fixture-only"); + account.setLoginAuthModes("PASSWORD"); + UUID accountId = + new AccountRepository(context.dsl(), sources).save(account).getAccountUuid(); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + var allocation = repository.allocate(accountId, UUID.randomUUID(), UUID.randomUUID()); + var evidence = evidence(allocation, lifetime); + repository.beginPending(evidence); + return evidence; + }); + } + + private static AccountGameplayAdmissionLeaseEvidence evidence( + AccountGameplayAdmissionLeaseRepository.Allocation allocation, long lifetime) { + long now = Instant.now().toEpochMilli(); + String account = allocation.accountId().toString(); + Map carrier = new LinkedHashMap<>(); + carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + carrier.put("schemaVersion", "1"); + carrier.put("mode", "PUBLIC_PRODUCTION"); + carrier.put("targetNamespace", "test"); + carrier.put("callerWorkload", "spiffe://firemud/ns/test/sa/game-session-service"); + carrier.put("requestId", allocation.requestId().toString()); + carrier.put("leaseId", allocation.leaseId().toString()); + carrier.put("leaseFence", Long.toString(allocation.leaseFence())); + carrier.put("leaseKind", "NEW_BINDING"); + Map scope = new LinkedHashMap<>(); + for (String key : + List.of( + "realmId", + "playableStateNamespaceId", + "gameInstanceId", + "characterId", + "sessionId", + "regionId")) scope.put(key, OTHER); + scope.put("accountId", account); + scope.put("tenantId", TENANT); + scope.put("worldSlug", "world"); + scope.put("realmSlug", "realm"); + scope.put("playableStateScope", "SHARED"); + for (String key : + List.of("bindingGeneration", "catalogRevision", "pointerVersion", "regionEpoch")) + scope.put(key, "1"); + carrier.put("bindingScope", scope); + carrier.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(TENANT, "1"), + "membershipAuthorityGeneration", + Map.of(TENANT, "1"), + "privateRealmGrantVersions", + List.of())); + carrier.put("issuanceFence", "7"); + carrier.put( + "membershipBaseline", + Map.of( + "membershipLifecycleState", + "ACTIVE", + "membershipVersion", + Map.of(TENANT, "1"), + "membershipAuthorityGeneration", + "1")); + carrier.put( + "outboxCheckpoints", + List.of( + "account/" + account, + "issuer/firemud-account-service", + "membership/" + account + "/" + TENANT, + "tenant/" + TENANT) + .stream() + .map( + suffix -> + Map.of( + "outboxStreamKey", + "account:auth-authority:v1:" + suffix, + "outboxSequence", + "1")) + .toList()); + Map token = new LinkedHashMap<>(); + token.put("accountId", account); + for (String key : List.of("operationId", "issuanceRequestId", "tokenJti")) + token.put(key, OTHER); + token.put("tokenSHA256", "a".repeat(64)); + token.put("tokenProfile", "game-session-account-delegation"); + token.put("tokenGeneration", "1"); + token.put("issuanceFence", "7"); + token.put("tokenIdentityFence", "9"); + token.put("issuedAt", Long.toString(now / 1000 - 1)); + token.put("notBefore", Long.toString(now / 1000 - 1)); + token.put("expiresAt", Long.toString(now / 1000 + 300)); + carrier.put("tokenIdentityEvidence", token); + carrier.put("evaluatedAt", Long.toString(now)); + carrier.put("expiresAt", Long.toString(now + lifetime)); + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + } + + private static AccountGameplayAdmissionOriginalAckReceiptRepository repository(Context context) { + return new AccountGameplayAdmissionOriginalAckReceiptRepository( + context.dsl(), new AccountGameplayAdmissionLeaseRepository(context.dsl())); + } + + private static void insertAck(DSLContext dsl, OriginalCommitAcknowledgement ack) { + dsl.execute( + "INSERT INTO " + + RECEIPTS + + "(request_id, evidence_sha256, binding_decision_id, finalization_xid, committed_before_ms) VALUES (?, ?, ?, ?, ?) ON CONFLICT (request_id) DO NOTHING", + request(ack.evidence()), + ack.evidence().sha256(), + ack.decisionId(), + ack.finalizationXid(), + ack.committedBeforeMs()); + } + + private static Map operation( + Context context, AccountGameplayAdmissionLeaseEvidence evidence) { + return context + .dsl() + .fetchSingle( + "SELECT * FROM account_gameplay_admission_lease_operations WHERE request_id = ?", + request(evidence)) + .intoMap(); + } + + private static Map sourceSnapshot(Context context) { + Map snapshot = new LinkedHashMap<>(); + for (String table : + List.of( + "accounts", + "account_gameplay_admission_lease_fences", + "account_gameplay_admission_lease_allocations", + "account_authority_generations", + "account_authority_issuance_fences", + "account_authority_source_records", + "account_authority_outbox_streams", + "account_authority_outbox_events")) { + snapshot.put(table, context.dsl().fetch("SELECT * FROM " + table + " ORDER BY 1").intoMaps()); + } + return snapshot; + } + + private static Map receipt(Context context) { + return context.dsl().fetchSingle("SELECT * FROM " + RECEIPTS).intoMap(); + } + + private static T retrySerialization(java.util.function.Supplier action) { + for (int attempt = 0; ; attempt++) { + try { + return action.get(); + } catch (RuntimeException failure) { + if (!"40001".equals(sqlState(failure)) || attempt >= 4) throw failure; + } + } + } + + private static void waitPastExpiry(Context context, OriginalCommitAcknowledgement ack) { + context + .dsl() + .fetchSingle( + "SELECT pg_sleep(GREATEST(0, (? - ceil(extract(epoch FROM clock_timestamp()) * 1000) + 50) / 1000.0))", + expiry(ack)); + } + + private static long expiry(OriginalCommitAcknowledgement ack) { + return Long.parseLong((String) ack.evidence().carrier().get("expiresAt")); + } + + private static UUID request(AccountGameplayAdmissionLeaseEvidence evidence) { + return UUID.fromString((String) evidence.carrier().get("requestId")); + } + + private static String sqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) + if (cause instanceof SQLException sql) return sql.getSQLState(); + return null; + } + + private record Context( + String schema, + DriverManagerDataSource admin, + DSLContext dsl, + TransactionTemplate transaction) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepositoryTest.java new file mode 100644 index 0000000000..d882831428 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepositoryTest.java @@ -0,0 +1,312 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.startsWith; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.lang.reflect.Modifier; +import java.sql.Connection; +import java.util.Arrays; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Foundation storage proof; deliberately supplies no authenticated admission source. */ +class AccountGameplayAdmissionLeaseRepositoryTest { + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void remainsUnregisteredWithNoPublicMutationOrAuthorizationFacade() { + assertThat(AccountGameplayAdmissionLeaseRepository.class.isAnnotationPresent(Repository.class)) + .isFalse(); + assertThat( + Arrays.stream(AccountGameplayAdmissionLeaseRepository.class.getDeclaredMethods()) + .filter(method -> !method.isSynthetic()) + .anyMatch( + method -> + Modifier.isPublic(method.getModifiers()) + || Modifier.isProtected(method.getModifiers()))) + .isFalse(); + } + + @Test + void requiresWritableSerializableAccountTransactionBeforeReadingOrWriting() { + DSLContext dsl = mock(DSLContext.class); + var repository = new AccountGameplayAdmissionLeaseRepository(dsl); + UUID account = UUID.randomUUID(); + UUID request = UUID.randomUUID(); + UUID lease = UUID.randomUUID(); + assertThatThrownBy(() -> repository.allocate(account, request, lease)) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_READ_COMMITTED); + assertThatThrownBy(() -> repository.allocate(account, request, lease)) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_SERIALIZABLE); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertThatThrownBy(() -> repository.allocate(account, request, lease)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(dsl); + } + + @Test + void rejectsNonV4AccountIdentityBeforeAnyStorageAccess() { + DSLContext dsl = mock(DSLContext.class); + var repository = new AccountGameplayAdmissionLeaseRepository(dsl); + assertThatThrownBy( + () -> + repository.allocate( + UUID.fromString("11111111-1111-1111-8111-111111111111"), + UUID.randomUUID(), + UUID.randomUUID())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("UUIDv4"); + verifyNoInteractions(dsl); + } + + @Test + void missingCounterReadbackCannotPersistAnAllocation() { + assertCounterReadbackRejected(null, "unavailable"); + } + + @ParameterizedTest + @NullSource + @ValueSource(longs = {0L, -1L}) + void nullOrNonpositiveCounterCannotPersistAnAllocation(Long fence) { + Record counter = mock(Record.class); + when(counter.get("last_fence", Long.class)).thenReturn(fence); + assertCounterReadbackRejected(counter, "invalid"); + } + + @Test + void insertedAllocationMustBeReadBackBeforeItCanBeReturned() { + UUID account = UUID.randomUUID(); + UUID request = UUID.randomUUID(); + UUID lease = UUID.randomUUID(); + Record row = allocationRow(account, request, lease, 1L); + DSLContext dsl = allocationDsl(row, 1); + assertThat(new AccountGameplayAdmissionLeaseRepository(dsl).allocate(account, request, lease)) + .isEqualTo( + new AccountGameplayAdmissionLeaseRepository.Allocation(account, request, lease, 1L)); + } + + @Test + void missingInsertedAllocationReadbackIsNotReturnedAsAnInMemoryIdentity() { + DSLContext dsl = allocationDsl(null, 1); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionLeaseRepository(dsl) + .allocate(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID())) + .hasMessage("Account admission lease allocation readback unavailable"); + } + + @ParameterizedTest + @ValueSource(ints = {0, 2}) + void allocationInsertRequiresExactlyOneStoredRow(int insertCount) { + DSLContext dsl = allocationDsl(null, insertCount); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionLeaseRepository(dsl) + .allocate(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID())) + .hasMessage("Account admission lease allocation insert unavailable"); + } + + @ParameterizedTest + @ValueSource(strings = {"account_uuid", "request_id", "lease_id", "lease_fence"}) + void changedInsertedAllocationIdentityFailsClosed(String field) { + UUID account = UUID.randomUUID(); + UUID request = UUID.randomUUID(); + UUID lease = UUID.randomUUID(); + Record row = allocationRow(account, request, lease, 1L); + if (field.equals("lease_fence")) when(row.get(field, Long.class)).thenReturn(2L); + else when(row.get(field, UUID.class)).thenReturn(UUID.randomUUID()); + DSLContext dsl = allocationDsl(row, 1); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionLeaseRepository(dsl).allocate(account, request, lease)) + .hasMessageContaining("identity conflict"); + } + + @Test + void allocationRecoveryReturnsOnlyOriginalStoredIdentity() { + UUID account = UUID.randomUUID(); + UUID request = UUID.randomUUID(); + UUID lease = UUID.randomUUID(); + DSLContext dsl = recoveryDsl(allocationRow(account, request, lease, 17L)); + assertThat(new AccountGameplayAdmissionLeaseRepository(dsl).findAllocation(account, request)) + .contains( + new AccountGameplayAdmissionLeaseRepository.Allocation(account, request, lease, 17L)); + verify(dsl, never()).execute(anyString(), any(Object[].class)); + } + + @ParameterizedTest + @ValueSource(strings = {"account_uuid", "request_id"}) + void allocationRecoveryRejectsDifferentStoredOwnerOrRequest(String field) { + UUID account = UUID.randomUUID(); + UUID request = UUID.randomUUID(); + Record row = allocationRow(account, request, UUID.randomUUID(), 1L); + when(row.get(field, UUID.class)).thenReturn(UUID.randomUUID()); + DSLContext dsl = recoveryDsl(row); + assertThatThrownBy( + () -> new AccountGameplayAdmissionLeaseRepository(dsl).findAllocation(account, request)) + .hasMessageContaining("identity conflict"); + verify(dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void missingRecoveryRowsRemainEmptyStorageWithoutAllocating() { + DSLContext allocationDsl = recoveryDsl(null); + assertThat( + new AccountGameplayAdmissionLeaseRepository(allocationDsl) + .findAllocation(UUID.randomUUID(), UUID.randomUUID())) + .isEmpty(); + verify(allocationDsl, never()).execute(anyString(), any(Object[].class)); + DSLContext operationDsl = recoveryDsl(null); + assertThat( + new AccountGameplayAdmissionLeaseRepository(operationDsl) + .findByRequest( + UUID.randomUUID(), + UUID.randomUUID(), + "spiffe://firemud/ns/test/sa/game-session-service")) + .isEmpty(); + verify(operationDsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void operationRecoveryRejectsMalformedStoredCarrierWithoutWrites() { + Record row = mock(Record.class); + when(row.get("evidence_json", String.class)).thenReturn("{}"); + DSLContext dsl = recoveryDsl(row); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionLeaseRepository(dsl) + .findByRequest( + UUID.randomUUID(), + UUID.randomUUID(), + "spiffe://firemud/ns/test/sa/game-session-service")) + .isInstanceOf(IllegalArgumentException.class); + verify(dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void abortedStorageShapeRetainsUnknownDecisionAndMandatoryPendingCleanup() { + var evidence = mock(AccountGameplayAdmissionLeaseEvidence.class); + UUID cleanup = UUID.randomUUID(); + var unknown = + new AccountGameplayAdmissionLeaseOperation(evidence, State.ABORTED, null, cleanup); + assertThat(unknown.bindingDecisionId()).isNull(); + assertThat(unknown.orphanCleanupId()).isEqualTo(cleanup); + assertThat(unknown.evidence()).isSameAs(evidence); + assertThat(unknown.hasPendingOrphanCleanup()).isTrue(); + assertThatThrownBy( + () -> new AccountGameplayAdmissionLeaseOperation(evidence, State.ABORTED, null, null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> new AccountGameplayAdmissionLeaseOperation(evidence, State.COMMITTED, null, null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionLeaseOperation( + evidence, State.ABORTED, new UUID(0, 0), cleanup)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionLeaseOperation( + evidence, State.ABORTED, null, new UUID(0, 0))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void invalidTerminalPresenceAndPresentUuidsRejectBeforeStorageAccess() { + DSLContext dsl = mock(DSLContext.class); + var repository = new AccountGameplayAdmissionLeaseRepository(dsl); + var evidence = mock(AccountGameplayAdmissionLeaseEvidence.class); + UUID cleanup = UUID.randomUUID(); + assertThatThrownBy(() -> repository.recordCommitted(evidence, null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> repository.recordAborted(evidence, null, null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> repository.recordAborted(evidence, new UUID(0, 0), cleanup)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> repository.recordAborted(evidence, null, new UUID(0, 0))) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(dsl); + } + + private static Record allocationRow(UUID account, UUID request, UUID lease, Long fence) { + Record row = mock(Record.class); + when(row.get("account_uuid", UUID.class)).thenReturn(account); + when(row.get("request_id", UUID.class)).thenReturn(request); + when(row.get("lease_id", UUID.class)).thenReturn(lease); + when(row.get("lease_fence", Long.class)).thenReturn(fence); + return row; + } + + private static DSLContext allocationDsl(Record readback, int insertCount) { + DSLContext dsl = mock(DSLContext.class); + Record owner = mock(Record.class); + Record counter = mock(Record.class); + when(counter.get("last_fence", Long.class)).thenReturn(1L); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(owner, null, counter, readback); + when(dsl.execute( + startsWith("INSERT INTO account_gameplay_admission_lease_allocations "), + any(Object[].class))) + .thenReturn(insertCount); + serializableTransaction(); + return dsl; + } + + private static DSLContext recoveryDsl(Record readback) { + DSLContext dsl = mock(DSLContext.class); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(mock(Record.class), readback); + serializableTransaction(); + return dsl; + } + + private static void serializableTransaction() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_SERIALIZABLE); + } + + /** Mocked storage failure only; this does not establish PostgreSQL or source authority proof. */ + private static void assertCounterReadbackRejected(Record counter, String failureKind) { + DSLContext dsl = mock(DSLContext.class); + Record account = mock(Record.class); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(account, null, counter); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_SERIALIZABLE); + var repository = new AccountGameplayAdmissionLeaseRepository(dsl); + assertThatThrownBy( + () -> repository.allocate(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account admission lease counter readback " + failureKind); + verify(dsl, never()) + .execute( + startsWith("INSERT INTO account_gameplay_admission_lease_allocations "), + any(Object[].class)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutorTest.java new file mode 100644 index 0000000000..b3bba74e0b --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutorTest.java @@ -0,0 +1,476 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.mockingDetails; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionOriginalAckReceipt; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionOriginalCommitExecutor.OriginalCommitAcknowledgement; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.Answers; +import org.mockito.MockedConstruction; +import org.springframework.jdbc.datasource.ConnectionHolder; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * JDBC/repository/opaque-ACK doubles; not PostgreSQL durability, authentication or admission proof. + */ +class AccountGameplayAdmissionOriginalAckReceiptCommitExecutorTest { + @AfterEach + void clearTransaction() { + for (Object key : TransactionSynchronizationManager.getResourceMap().keySet()) { + TransactionSynchronizationManager.unbindResource(key); + } + TransactionSynchronizationManager.clear(); + } + + @Test + void physicalReceiptCommitPrecedesNewConnectionAndExactHistoricalRead() throws Exception { + var fixture = new Fixture(); + try (var repositories = fixture.repositories()) { + assertThat(fixture.executor.confirm(fixture.acknowledgement)).isSameAs(fixture.receipt); + assertThat(repositories.constructed()).hasSize(2); + var order = + inOrder( + fixture.first.connection, + fixture.second.connection, + repositories.constructed().get(0), + repositories.constructed().get(1)); + order.verify(repositories.constructed().get(0)).create(fixture.acknowledgement); + order.verify(fixture.first.connection).commit(); + order.verify(fixture.first.connection).close(); + order.verify(repositories.constructed().get(1)).readExact(fixture.evidence, fixture.decision); + order.verify(fixture.second.connection).commit(); + assertIndependentAcquisition(fixture, repositories.constructed().get(1)); + // This is a historical receipt: receipt persistence does not restamp original expiry. + assertThat(fixture.receipt.expiresAtMs()).isLessThan(System.currentTimeMillis()); + verify(fixture.first.statement).execute("SET LOCAL synchronous_commit = on"); + verify(fixture.second.statement).execute("SET LOCAL synchronous_commit = on"); + } + } + + @Test + void creationApiAcceptsOnlyOpaqueAcknowledgement() { + assertThat( + java.util.Arrays.stream( + AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.class + .getDeclaredMethods()) + .filter(method -> method.getName().equals("confirm")) + .map(method -> java.util.List.of(method.getParameterTypes()))) + .containsExactly(java.util.List.of(OriginalCommitAcknowledgement.class)); + } + + @Test + void anotherDataSourceIsRejectedBeforeAnyConnection() throws Exception { + var fixture = new Fixture(); + var other = mock(DataSource.class); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(other) + .confirm(fixture.acknowledgement)) + .hasMessageContaining("Fresh owned"); + verifyNoInteractions(other); + } + + @Test + void missingOpaqueAcknowledgementCannotStartReceiptPersistence() throws Exception { + var fixture = new Fixture(); + assertThatThrownBy(() -> fixture.executor.confirm(null)) + .isInstanceOf(NullPointerException.class); + verifyNoInteractions(fixture.source); + } + + @ParameterizedTest + @ValueSource(strings = {"xid", "clock"}) + void changedOriginalProofRollsBackWithoutIndependentRead(String fault) throws Exception { + var fixture = new Fixture(); + if (fault.equals("xid")) { + when(fixture.acknowledgement.finalizationXid()).thenReturn("987654"); + } else { + when(fixture.acknowledgement.committedBeforeMs()).thenReturn(1L); + } + try (var repositories = fixture.repositories()) { + assertThatThrownBy(() -> fixture.executor.confirm(fixture.acknowledgement)) + .hasMessageContaining("Fresh owned"); + assertThat(repositories.constructed()).hasSize(1); + verify(fixture.first.connection, never()).commit(); + verify(fixture.first.connection).rollback(); + verifyNoInteractions(fixture.second.connection); + } + } + + @Test + void retryCommitCannotSubstituteForUnavailableHistoricalDurability() throws Exception { + var fixture = new Fixture(); + fixture.inserted = false; + fixture.failRead = true; + try (var repositories = fixture.repositories()) { + assertThatThrownBy(() -> fixture.executor.confirm(fixture.acknowledgement)) + .hasMessage("read unavailable"); + verify(fixture.first.connection).commit(); + verify(repositories.constructed().get(1)).readDurably(fixture.evidence, fixture.decision); + verify(repositories.constructed().get(1), never()).create(any()); + verify(fixture.second.connection, never()).commit(); + } + } + + @Test + void retainedReceiptUsesHistoricalDurabilityRatherThanRetryCommitProof() throws Exception { + var fixture = new Fixture(); + fixture.inserted = false; + try (var repositories = fixture.repositories()) { + assertThat(fixture.executor.confirm(fixture.acknowledgement)).isSameAs(fixture.receipt); + var read = repositories.constructed().get(1); + verify(read).readDurably(fixture.evidence, fixture.decision); + verify(read, never()).readExact(any(), any()); + verify(read, never()).create(any()); + int[] closes = invocationSequences(fixture.first.connection, "close"); + int[] reads = invocationSequences(read, "readDurably"); + assertThat(reads[0]).isGreaterThan(closes[0]); + } + } + + @Test + void uncertainPhysicalReceiptCommitNeverStartsIndependentRead() throws Exception { + var fixture = new Fixture(); + doThrow(new SQLException("COMMIT acknowledgement lost", "08006")) + .when(fixture.first.connection) + .commit(); + try (var repositories = fixture.repositories()) { + assertThatThrownBy(() -> fixture.executor.confirm(fixture.acknowledgement)) + .hasMessageContaining("physical COMMIT unavailable"); + assertThat(repositories.constructed()).hasSize(1); + verify(fixture.first.connection).rollback(); + verifyNoInteractions(fixture.second.connection); + } + } + + @ParameterizedTest + @ValueSource(strings = {"failure", "null", "decision", "evidence"}) + void unavailableOrNonExactCreationNeverCommitsOrReads(String fault) throws Exception { + var fixture = new Fixture(); + try (var repositories = fixture.repositories()) { + fixture.creationFault = fault; + assertThatThrownBy(() -> fixture.executor.confirm(fixture.acknowledgement)) + .isInstanceOf(RuntimeException.class); + assertThat(repositories.constructed()).hasSize(1); + verify(fixture.first.connection, never()).commit(); + verify(fixture.first.connection).rollback(); + verifyNoInteractions(fixture.second.connection); + } + } + + @ParameterizedTest + @ValueSource(strings = {"different", "failure", "commit-failure"}) + void readMismatchOrFailureDoesNotExposeCreatedReceipt(String fault) throws Exception { + var fixture = new Fixture(); + if (fault.equals("different")) { + var r = fixture.receipt; + fixture.readReceipt = + new AccountGameplayAdmissionOriginalAckReceipt( + r.operation(), + r.schemaVersion(), + r.requestId(), + r.accountId(), + r.leaseId(), + r.leaseFence(), + r.evidenceSha256(), + r.bindingDecisionId(), + r.expiresAtMs(), + r.finalizationXid(), + r.committedBeforeMs(), + "123458"); + } + fixture.failRead = fault.equals("failure"); + if (fault.equals("commit-failure")) { + doThrow(new SQLException("read commit lost")).when(fixture.second.connection).commit(); + } + try (var repositories = fixture.repositories()) { + assertThatThrownBy(() -> fixture.executor.confirm(fixture.acknowledgement)) + .isInstanceOf(RuntimeException.class); + verify(fixture.first.connection).commit(); + assertThat(repositories.constructed()).hasSize(2); + } + } + + @Test + void poolMayReuseConnectionAfterCompletedCommitAndCleanup() throws Exception { + var fixture = new Fixture(); + when(fixture.source.getConnection()).thenReturn(fixture.first.connection); + fixture.readConnection = fixture.first.connection; + try (var repositories = fixture.repositories()) { + assertThat(fixture.executor.confirm(fixture.acknowledgement)).isSameAs(fixture.receipt); + assertThat(repositories.constructed()).hasSize(2); + var order = inOrder(fixture.first.connection, repositories.constructed().get(1)); + order.verify(fixture.first.connection).commit(); + order.verify(fixture.first.connection).close(); + order.verify(repositories.constructed().get(1)).readExact(fixture.evidence, fixture.decision); + order.verify(fixture.first.connection).commit(); + assertIndependentAcquisition(fixture, repositories.constructed().get(1)); + verify(fixture.first.connection, never()).rollback(); + } + } + + @Test + void readOnlyValidatesExistingReceipt() throws Exception { + var fixture = new Fixture(); + try (var repositories = fixture.repositories()) { + assertThat(fixture.executor.read(fixture.evidence, fixture.decision)) + .isSameAs(fixture.receipt); + verify(repositories.constructed().getFirst(), never()).create(any()); + verify(repositories.constructed().getFirst(), never()).readExact(any(), any()); + verify(repositories.constructed().getFirst()).readDurably(fixture.evidence, fixture.decision); + verify(fixture.first.connection).commit(); + verifyNoInteractions(fixture.second.connection); + } + } + + @ParameterizedTest + @ValueSource(strings = {"actual", "synchronization", "bound"}) + void ambientContextDeniesBeforeConnectionAcquisition(String ambient) throws Exception { + var fixture = new Fixture(); + switch (ambient) { + case "actual" -> TransactionSynchronizationManager.setActualTransactionActive(true); + case "synchronization" -> TransactionSynchronizationManager.initSynchronization(); + case "bound" -> + TransactionSynchronizationManager.bindResource( + fixture.source, new ConnectionHolder(fixture.first.connection)); + default -> throw new IllegalArgumentException(ambient); + } + assertThatThrownBy(() -> fixture.executor.confirm(fixture.acknowledgement)) + .hasMessageContaining("Fresh owned"); + assertThatThrownBy(() -> fixture.executor.read(fixture.evidence, fixture.decision)) + .hasMessageContaining("Fresh owned"); + verifyNoInteractions(fixture.source, fixture.first.connection); + } + + @ParameterizedTest + @ValueSource( + strings = { + "version", + "recovery", + "fsync", + "sync", + "isolation", + "readonly", + "engine", + "jdbc-isolation", + "jdbc-readonly", + "jdbc-autocommit", + "set-failure" + }) + void invalidDurabilityRollsBackBeforeAutoCommitCleanup(String fault) throws Exception { + var fixture = new Fixture(); + var jdbc = fixture.first; + switch (fault) { + case "version" -> when(jdbc.settings.getInt(1)).thenReturn(160000); + case "recovery" -> when(jdbc.settings.getBoolean(2)).thenReturn(true); + case "fsync" -> when(jdbc.settings.getString(3)).thenReturn("off"); + case "sync" -> when(jdbc.settings.getString(4)).thenReturn("off"); + case "isolation" -> when(jdbc.settings.getString(5)).thenReturn("read committed"); + case "readonly" -> when(jdbc.settings.getString(6)).thenReturn("on"); + case "engine" -> when(jdbc.metadata.getDatabaseProductName()).thenReturn("Other"); + case "jdbc-isolation" -> jdbc.badIsolation = true; + case "jdbc-readonly" -> when(jdbc.connection.isReadOnly()).thenReturn(true); + case "jdbc-autocommit" -> jdbc.badAutoCommit = true; + case "set-failure" -> + doThrow(new SQLException("SET rejected")) + .when(jdbc.statement) + .execute("SET LOCAL synchronous_commit = on"); + default -> throw new IllegalArgumentException(fault); + } + try (var repositories = fixture.repositories()) { + assertThatThrownBy(() -> fixture.executor.confirm(fixture.acknowledgement)) + .isInstanceOf(RuntimeException.class); + verify(jdbc.connection, never()).commit(); + var order = inOrder(jdbc.connection); + order.verify(jdbc.connection).rollback(); + order.verify(jdbc.connection).setAutoCommit(true); + assertThat(repositories.constructed()).hasSize(1); + verifyNoInteractions(fixture.second.connection); + } + } + + private static void assertIndependentAcquisition( + Fixture fixture, AccountGameplayAdmissionOriginalAckReceiptRepository readRepository) { + int[] acquisitions = invocationSequences(fixture.source, "getConnection"); + int[] commits = invocationSequences(fixture.first.connection, "commit"); + int[] closes = invocationSequences(fixture.first.connection, "close"); + int[] reads = invocationSequences(readRepository, "readExact"); + assertThat(acquisitions).hasSize(2); + assertThat(reads).hasSize(1); + assertThat(commits).isNotEmpty(); + assertThat(closes).isNotEmpty(); + assertThat(acquisitions[0]).isLessThan(commits[0]); + assertThat(commits[0]).isLessThan(closes[0]); + assertThat(closes[0]).isLessThan(acquisitions[1]); + assertThat(acquisitions[1]).isLessThan(reads[0]); + } + + private static int[] invocationSequences(Object mock, String method) { + return mockingDetails(mock).getInvocations().stream() + .filter(invocation -> invocation.getMethod().getName().equals(method)) + .mapToInt(invocation -> invocation.getSequenceNumber()) + .toArray(); + } + + private static final class Fixture { + private final DataSource source = mock(DataSource.class); + private final Jdbc first = new Jdbc(); + private final Jdbc second = new Jdbc(); + private Connection readConnection = second.connection; + private final AccountGameplayAdmissionLeaseEvidence evidence = + AccountGameplayAdmissionOriginalAckReceiptTestFixtures.fixture(); + private final UUID decision = UUID.randomUUID(); + private final OriginalCommitAcknowledgement acknowledgement = + mock(OriginalCommitAcknowledgement.class); + private final AccountGameplayAdmissionOriginalAckReceipt receipt = receipt(evidence, decision); + private boolean inserted = true; + private AccountGameplayAdmissionOriginalAckReceipt readReceipt = receipt; + private boolean failRead; + private String creationFault; + private final AccountGameplayAdmissionOriginalAckReceiptCommitExecutor executor = + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(source); + + private Fixture() throws SQLException { + when(source.getConnection()).thenReturn(first.connection, second.connection); + when(acknowledgement.belongsTo(source)).thenReturn(true); + when(acknowledgement.evidence()).thenReturn(evidence); + when(acknowledgement.decisionId()).thenReturn(decision); + when(acknowledgement.finalizationXid()).thenReturn(receipt.finalizationXid()); + when(acknowledgement.committedBeforeMs()).thenReturn(receipt.committedBeforeMs()); + } + + private MockedConstruction + repositories() { + return mockConstruction( + AccountGameplayAdmissionOriginalAckReceiptRepository.class, + (repository, context) -> { + DSLContext dsl = (DSLContext) context.arguments().getFirst(); + Connection enlisted = dsl.connectionResult(value -> value); + assertThat(enlisted) + .isSameAs(context.getCount() == 1 ? first.connection : readConnection); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(Connection.TRANSACTION_SERIALIZABLE); + when(repository.create(acknowledgement)) + .thenAnswer( + ignored -> { + if (creationFault == null) + return new AccountGameplayAdmissionOriginalAckReceiptRepository.Creation( + receipt, inserted); + AccountGameplayAdmissionOriginalAckReceipt value = + switch (creationFault) { + case "failure" -> + throw new IllegalStateException("creation unavailable"); + case "null" -> null; + case "decision" -> receipt(evidence, UUID.randomUUID()); + case "evidence" -> { + var carrier = new java.util.LinkedHashMap<>(evidence.carrier()); + carrier.put("requestId", UUID.randomUUID().toString()); + yield receipt( + AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier), + decision); + } + default -> throw new IllegalArgumentException(creationFault); + }; + return new AccountGameplayAdmissionOriginalAckReceiptRepository.Creation( + value, inserted); + }); + when(repository.readExact(evidence, decision)).thenAnswer(ignored -> readResult()); + when(repository.readDurably(evidence, decision)).thenAnswer(ignored -> readResult()); + }); + } + + private AccountGameplayAdmissionOriginalAckReceipt readResult() { + if (failRead) throw new IllegalStateException("read unavailable"); + return readReceipt; + } + } + + private static AccountGameplayAdmissionOriginalAckReceipt receipt( + AccountGameplayAdmissionLeaseEvidence evidence, UUID decision) { + return AccountGameplayAdmissionOriginalAckReceiptTestFixtures.receipt(evidence, decision); + } + + private static final class Jdbc { + private final DatabaseMetaData metadata = mock(DatabaseMetaData.class); + private final ResultSet settings = mock(ResultSet.class); + private final Statement statement = + mock( + Statement.class, + invocation -> { + if (invocation.getMethod().getName().equals("executeQuery")) { + when(settings.next()).thenReturn(true, false); + return settings; + } + return Answers.RETURNS_DEFAULTS.answer(invocation); + }); + private final Connection connection = + mock( + Connection.class, + invocation -> + invocation.getMethod().getName().equals("createStatement") + ? statement + : Answers.RETURNS_DEFAULTS.answer(invocation)); + private boolean badIsolation; + private boolean badAutoCommit; + + private Jdbc() throws SQLException { + var autoCommit = new AtomicBoolean(true); + var isolation = new AtomicInteger(Connection.TRANSACTION_READ_COMMITTED); + when(connection.getAutoCommit()).thenAnswer(ignored -> badAutoCommit || autoCommit.get()); + doAnswer( + ignored -> { + autoCommit.set(ignored.getArgument(0)); + return null; + }) + .when(connection) + .setAutoCommit(anyBoolean()); + when(connection.getTransactionIsolation()) + .thenAnswer( + ignored -> badIsolation ? Connection.TRANSACTION_READ_COMMITTED : isolation.get()); + doAnswer( + ignored -> { + isolation.set(ignored.getArgument(0)); + return null; + }) + .when(connection) + .setTransactionIsolation(anyInt()); + when(connection.getMetaData()).thenReturn(metadata); + when(metadata.getDatabaseProductName()).thenReturn("PostgreSQL"); + when(settings.getInt(1)).thenReturn(180011); + when(settings.getString(3)).thenReturn("on"); + when(settings.getString(4)).thenReturn("on"); + when(settings.getString(5)).thenReturn("serializable"); + when(settings.getString(6)).thenReturn("off"); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepositoryTest.java new file mode 100644 index 0000000000..9b93ca4a42 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepositoryTest.java @@ -0,0 +1,521 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.sql.Connection; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionOriginalAckReceipt; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionOriginalCommitExecutor.OriginalCommitAcknowledgement; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Repository doubles verify exact storage binding only; they do not prove PostgreSQL durability. + */ +class AccountGameplayAdmissionOriginalAckReceiptRepositoryTest { + private static final String INSERT_SQL = + "INSERT INTO account_gameplay_admission_original_commit_ack_receipts " + + "(request_id, evidence_sha256, binding_decision_id, finalization_xid, committed_before_ms) " + + "VALUES (?, ?, ?, ?, ?) ON CONFLICT (request_id) DO NOTHING RETURNING *"; + private static final String SELECT_SQL = + "SELECT * FROM account_gameplay_admission_original_commit_ack_receipts WHERE request_id = ?"; + private static final String READ_DURABLY_SQL = + "SELECT * FROM account_gameplay_admission_read_original_ack_receipt_durably(?, ?, ?)"; + private static final String ACCOUNT_LOCK_SQL = + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE"; + private static final String OPERATION_SELECT_SQL = + "SELECT * FROM account_gameplay_admission_lease_operations WHERE request_id = ? FOR UPDATE"; + + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void createInsertsTypedAckAndReturnsReattachedExactReceipt() { + var evidence = AccountGameplayAdmissionOriginalAckReceiptTestFixtures.fixture(); + UUID decision = UUID.randomUUID(); + var operation = committed(evidence, decision); + Record inserted = receiptRow(evidence, decision, "123456", 1_014_999L); + DSLContext dsl = dsl(evidence, operation, inserted, inserted); + var repository = repository(dsl); + var acknowledgement = acknowledgement(evidence, decision, "123456", 1_014_999L); + + var created = repository.create(acknowledgement); + + assertThat(created.inserted()).isTrue(); + assertThat(created.receipt()).isEqualTo(decoded(operation, evidence, decision)); + verify(dsl) + .fetchOne( + INSERT_SQL, requestId(evidence), evidence.sha256(), decision, "123456", 1_014_999L); + var order = inOrder(dsl); + order + .verify(dsl) + .fetchOne( + INSERT_SQL, requestId(evidence), evidence.sha256(), decision, "123456", 1_014_999L); + order.verify(dsl).fetchOne(ACCOUNT_LOCK_SQL, accountId(evidence)); + order.verify(dsl).fetchOne(OPERATION_SELECT_SQL, requestId(evidence)); + verify(dsl, never()).fetchOne(eq(READ_DURABLY_SQL), any(Object[].class)); + } + + @Test + void exactRetainedAckReturnsInsertedFalseWithoutChangingOriginalClockOrXids() { + var evidence = AccountGameplayAdmissionOriginalAckReceiptTestFixtures.fixture(); + UUID decision = UUID.randomUUID(); + var operation = committed(evidence, decision); + Record retained = receiptRow(evidence, decision, "123456", 1_014_999L); + var repository = repository(dsl(evidence, operation, null, retained)); + + var created = repository.create(acknowledgement(evidence, decision, "123456", 1_014_999L)); + + assertThat(created.inserted()).isFalse(); + assertThat(created.receipt()).isEqualTo(decoded(operation, evidence, decision)); + } + + @Test + void retainedAckWithChangedOriginalClockOrXidIsRejected() { + var evidence = AccountGameplayAdmissionOriginalAckReceiptTestFixtures.fixture(); + UUID decision = UUID.randomUUID(); + var operation = committed(evidence, decision); + Record retained = receiptRow(evidence, decision, "123456", 1_014_999L); + var repository = repository(dsl(evidence, operation, null, retained)); + + assertThatThrownBy( + () -> repository.create(acknowledgement(evidence, decision, "123456", 1_014_998L))) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> repository.create(acknowledgement(evidence, decision, "123457", 1_014_999L))) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void storageOnlyReadAndDurableReadUseDistinctPathsAndSameExactOperation() { + var evidence = AccountGameplayAdmissionOriginalAckReceiptTestFixtures.fixture(); + UUID decision = UUID.randomUUID(); + var operation = committed(evidence, decision); + Record receipt = receiptRow(evidence, decision, "123456", 1_014_999L); + + DSLContext exactDsl = dsl(evidence, operation, null, receipt); + var repository = repository(exactDsl); + assertThat(repository.readExact(evidence, decision)) + .isEqualTo(decoded(operation, evidence, decision)); + verify(exactDsl).fetchOne(SELECT_SQL, requestId(evidence)); + verify(exactDsl, never()).fetchOne(eq(READ_DURABLY_SQL), any(Object[].class)); + + DSLContext durableDsl = dsl(evidence, operation, receipt, receipt); + assertThat(repository(durableDsl).readDurably(evidence, decision)) + .isEqualTo(decoded(operation, evidence, decision)); + verify(durableDsl).fetchOne(READ_DURABLY_SQL, requestId(evidence), evidence.sha256(), decision); + verify(durableDsl, never()).fetchOne(eq(INSERT_SQL), any(Object[].class)); + } + + @Test + void rejectsMissingChangedAndNonCommittedOriginalOperation() { + var evidence = AccountGameplayAdmissionOriginalAckReceiptTestFixtures.fixture(); + UUID decision = UUID.randomUUID(); + Record receipt = receiptRow(evidence, decision, "123456", 1_014_999L); + DSLContext missing = dsl(evidence, null, null, receipt); + assertThatThrownBy(() -> repository(missing).readExact(evidence, decision)) + .isInstanceOf(IllegalStateException.class); + + for (var state : State.values()) { + if (state == State.COMMITTED) continue; + var operation = + new AccountGameplayAdmissionLeaseOperation( + evidence, state, null, state == State.ABORTED ? UUID.randomUUID() : null); + DSLContext mismatched = dsl(evidence, operation, null, receipt); + assertThatThrownBy(() -> repository(mismatched).readExact(evidence, decision)) + .isInstanceOf(IllegalStateException.class); + } + var wrongDecision = committed(evidence, UUID.randomUUID()); + assertThatThrownBy( + () -> + repository(dsl(evidence, wrongDecision, null, receipt)) + .readExact(evidence, decision)) + .isInstanceOf(IllegalStateException.class); + + var changedCarrier = new java.util.LinkedHashMap<>(evidence.carrier()); + changedCarrier.put("leaseId", UUID.randomUUID().toString()); + var changedEvidence = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changedCarrier); + DSLContext changedDsl = dsl(evidence, committed(evidence, decision), null, receipt); + assertThatThrownBy(() -> repository(changedDsl).readExact(changedEvidence, decision)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void validatesReceiptVersionFullBindingClockAndCanonicalDistinctUnsignedXids() { + var evidence = AccountGameplayAdmissionOriginalAckReceiptTestFixtures.fixture(); + UUID decision = UUID.randomUUID(); + var operation = committed(evidence, decision); + var valid = decoded(operation, evidence, decision); + assertThat(valid.schemaVersion()).isEqualTo((short) 1); + assertThat(valid.receiptXid()).isEqualTo("123457"); + assertThat(valid.committedBeforeMs()).isLessThan(valid.expiresAtMs()); + + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 2, + valid.requestId(), + valid.accountId(), + valid.leaseId(), + valid.leaseFence(), + valid.evidenceSha256(), + decision, + valid.expiresAtMs(), + valid.finalizationXid(), + valid.committedBeforeMs(), + valid.receiptXid())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + UUID.randomUUID(), + valid.accountId(), + valid.leaseId(), + valid.leaseFence(), + valid.evidenceSha256(), + decision, + valid.expiresAtMs(), + valid.finalizationXid(), + valid.committedBeforeMs(), + valid.receiptXid())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + valid.requestId(), + UUID.randomUUID(), + valid.leaseId(), + valid.leaseFence(), + valid.evidenceSha256(), + decision, + valid.expiresAtMs(), + valid.finalizationXid(), + valid.committedBeforeMs(), + valid.receiptXid())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + valid.requestId(), + valid.accountId(), + UUID.randomUUID(), + valid.leaseFence(), + valid.evidenceSha256(), + decision, + valid.expiresAtMs(), + valid.finalizationXid(), + valid.committedBeforeMs(), + valid.receiptXid())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + valid.requestId(), + valid.accountId(), + valid.leaseId(), + valid.leaseFence() + 1, + valid.evidenceSha256(), + decision, + valid.expiresAtMs(), + valid.finalizationXid(), + valid.committedBeforeMs(), + valid.receiptXid())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + valid.requestId(), + valid.accountId(), + valid.leaseId(), + valid.leaseFence(), + "0".repeat(64), + decision, + valid.expiresAtMs(), + valid.finalizationXid(), + valid.committedBeforeMs(), + valid.receiptXid())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + valid.requestId(), + valid.accountId(), + valid.leaseId(), + valid.leaseFence(), + valid.evidenceSha256(), + UUID.randomUUID(), + valid.expiresAtMs(), + valid.finalizationXid(), + valid.committedBeforeMs(), + valid.receiptXid())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + valid.requestId(), + valid.accountId(), + valid.leaseId(), + valid.leaseFence(), + valid.evidenceSha256(), + decision, + valid.expiresAtMs() + 1, + valid.finalizationXid(), + valid.committedBeforeMs(), + valid.receiptXid())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + valid.requestId(), + valid.accountId(), + valid.leaseId(), + valid.leaseFence(), + valid.evidenceSha256(), + decision, + valid.expiresAtMs(), + valid.finalizationXid(), + valid.expiresAtMs(), + valid.receiptXid())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + valid.requestId(), + valid.accountId(), + valid.leaseId(), + valid.leaseFence(), + valid.evidenceSha256(), + decision, + valid.expiresAtMs(), + "18446744073709551616", + valid.committedBeforeMs(), + valid.receiptXid())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + valid.requestId(), + valid.accountId(), + valid.leaseId(), + valid.leaseFence(), + valid.evidenceSha256(), + decision, + valid.expiresAtMs(), + valid.finalizationXid(), + valid.committedBeforeMs(), + valid.finalizationXid())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void receiptValueExposesOnlyImmutableRecordAccessors() { + var evidence = AccountGameplayAdmissionOriginalAckReceiptTestFixtures.fixture(); + UUID decision = UUID.randomUUID(); + var receipt = decoded(committed(evidence, decision), evidence, decision); + assertThat(AccountGameplayAdmissionOriginalAckReceipt.class.isRecord()).isTrue(); + assertThat( + java.util.Arrays.stream( + AccountGameplayAdmissionOriginalAckReceipt.class.getDeclaredFields()) + .filter(field -> !field.isSynthetic()) + .allMatch(field -> java.lang.reflect.Modifier.isFinal(field.getModifiers()))) + .isTrue(); + assertThat( + java.util.Arrays.stream(AccountGameplayAdmissionOriginalAckReceipt.class.getMethods()) + .map(java.lang.reflect.Method::getName) + .noneMatch(name -> name.startsWith("set"))) + .isTrue(); + assertThat(receipt.toString()) + .doesNotContain("committedBeforeMs", "finalizationXid", "receiptXid"); + } + + @Test + void everyRepositoryMethodRequiresWritableSerializableTransactionBeforeStorage() { + var evidence = AccountGameplayAdmissionOriginalAckReceiptTestFixtures.fixture(); + UUID decision = UUID.randomUUID(); + DSLContext dsl = mock(DSLContext.class); + var repository = + new AccountGameplayAdmissionOriginalAckReceiptRepository( + dsl, new AccountGameplayAdmissionLeaseRepository(dsl)); + var acknowledgement = acknowledgement(evidence, decision, "123456", 1_014_999L); + + assertThatThrownBy(() -> repository.create(acknowledgement)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> repository.readExact(evidence, decision)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> repository.readDurably(evidence, decision)) + .isInstanceOf(IllegalStateException.class); + + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_READ_COMMITTED); + assertThatThrownBy(() -> repository.readDurably(evidence, decision)) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_SERIALIZABLE); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertThatThrownBy(() -> repository.create(acknowledgement)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(dsl); + } + + private static AccountGameplayAdmissionOriginalAckReceiptRepository repository(DSLContext dsl) { + serializableTransaction(); + return new AccountGameplayAdmissionOriginalAckReceiptRepository( + dsl, new AccountGameplayAdmissionLeaseRepository(dsl)); + } + + private static DSLContext dsl( + AccountGameplayAdmissionLeaseEvidence evidence, + AccountGameplayAdmissionLeaseOperation operation, + Record inserted, + Record receipt) { + DSLContext dsl = mock(DSLContext.class); + Record account = mock(Record.class); + Record operationRow = operation == null ? null : operationRow(evidence, operation); + when(dsl.fetchOne(eq(INSERT_SQL), any(Object[].class))).thenReturn(inserted); + when(dsl.fetchOne(eq(SELECT_SQL), any(Object[].class))).thenReturn(receipt); + when(dsl.fetchOne(eq(READ_DURABLY_SQL), any(Object[].class))).thenReturn(inserted); + when(dsl.fetchOne(eq(ACCOUNT_LOCK_SQL), any(Object[].class))).thenReturn(account); + when(dsl.fetchOne(eq(OPERATION_SELECT_SQL), any(Object[].class))).thenReturn(operationRow); + return dsl; + } + + private static Record operationRow( + AccountGameplayAdmissionLeaseEvidence evidence, + AccountGameplayAdmissionLeaseOperation operation) { + Record row = mock(Record.class); + when(row.get("evidence_json", String.class)).thenReturn(evidence.canonicalJson()); + when(row.get("evidence_sha256", String.class)).thenReturn(evidence.sha256()); + when(row.get("account_uuid", UUID.class)).thenReturn(accountId(evidence)); + when(row.get("request_id", UUID.class)).thenReturn(requestId(evidence)); + when(row.get("lease_id", UUID.class)).thenReturn(leaseId(evidence)); + when(row.get("lease_fence", Long.class)).thenReturn(evidence.leaseFence().longValueExact()); + when(row.get("caller_workload", String.class)) + .thenReturn((String) evidence.carrier().get("callerWorkload")); + when(row.get("evaluated_at_ms", Long.class)) + .thenReturn(Long.parseLong((String) evidence.carrier().get("evaluatedAt"))); + when(row.get("expires_at_ms", Long.class)) + .thenReturn(Long.parseLong((String) evidence.carrier().get("expiresAt"))); + when(row.get("status", String.class)).thenReturn(operation.state().name()); + when(row.get("binding_decision_id", UUID.class)).thenReturn(operation.bindingDecisionId()); + when(row.get("orphan_cleanup_id", UUID.class)).thenReturn(operation.orphanCleanupId()); + return row; + } + + private static Record receiptRow( + AccountGameplayAdmissionLeaseEvidence evidence, + UUID decision, + String finalizationXid, + long committedBeforeMs) { + Record row = mock(Record.class); + when(row.get("schema_version", Short.class)).thenReturn((short) 1); + when(row.get("request_id", UUID.class)).thenReturn(requestId(evidence)); + when(row.get("account_uuid", UUID.class)).thenReturn(accountId(evidence)); + when(row.get("lease_id", UUID.class)).thenReturn(leaseId(evidence)); + when(row.get("lease_fence", Long.class)).thenReturn(evidence.leaseFence().longValueExact()); + when(row.get("evidence_sha256", String.class)).thenReturn(evidence.sha256()); + when(row.get("binding_decision_id", UUID.class)).thenReturn(decision); + when(row.get("expires_at_ms", Long.class)) + .thenReturn(Long.parseLong((String) evidence.carrier().get("expiresAt"))); + when(row.get("finalization_xid", String.class)).thenReturn(finalizationXid); + when(row.get("committed_before_ms", Long.class)).thenReturn(committedBeforeMs); + when(row.get("receipt_xid", String.class)).thenReturn("123457"); + return row; + } + + private static AccountGameplayAdmissionOriginalAckReceipt decoded( + AccountGameplayAdmissionLeaseOperation operation, + AccountGameplayAdmissionLeaseEvidence evidence, + UUID decision) { + return new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + requestId(evidence), + accountId(evidence), + leaseId(evidence), + evidence.leaseFence().longValueExact(), + evidence.sha256(), + decision, + Long.parseLong((String) evidence.carrier().get("expiresAt")), + "123456", + 1_014_999L, + "123457"); + } + + private static OriginalCommitAcknowledgement acknowledgement( + AccountGameplayAdmissionLeaseEvidence evidence, + UUID decision, + String finalizationXid, + long committedBeforeMs) { + OriginalCommitAcknowledgement acknowledgement = mock(OriginalCommitAcknowledgement.class); + when(acknowledgement.evidence()).thenReturn(evidence); + when(acknowledgement.decisionId()).thenReturn(decision); + when(acknowledgement.finalizationXid()).thenReturn(finalizationXid); + when(acknowledgement.committedBeforeMs()).thenReturn(committedBeforeMs); + return acknowledgement; + } + + private static AccountGameplayAdmissionLeaseOperation committed( + AccountGameplayAdmissionLeaseEvidence evidence, UUID decision) { + return new AccountGameplayAdmissionLeaseOperation(evidence, State.COMMITTED, decision, null); + } + + private static UUID requestId(AccountGameplayAdmissionLeaseEvidence evidence) { + return UUID.fromString((String) evidence.carrier().get("requestId")); + } + + private static UUID leaseId(AccountGameplayAdmissionLeaseEvidence evidence) { + return UUID.fromString((String) evidence.carrier().get("leaseId")); + } + + private static UUID accountId(AccountGameplayAdmissionLeaseEvidence evidence) { + var scope = (Map) evidence.carrier().get("bindingScope"); + return UUID.fromString((String) scope.get("accountId")); + } + + private static void serializableTransaction() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_SERIALIZABLE); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptTestFixtures.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptTestFixtures.java new file mode 100644 index 0000000000..77ab4388fc --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptTestFixtures.java @@ -0,0 +1,124 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionOriginalAckReceipt; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; + +/** Test-only, fabricated storage carriers; neither method creates authority or admission proof. */ +final class AccountGameplayAdmissionOriginalAckReceiptTestFixtures { + private AccountGameplayAdmissionOriginalAckReceiptTestFixtures() {} + + /** Deliberately fabricated expired storage carrier, not issuer or current authority evidence. */ + static AccountGameplayAdmissionLeaseEvidence fixture() { + String account = "11111111-1111-4111-8111-111111111111"; + String tenant = "22222222-2222-4222-8222-222222222222"; + String other = "33333333-3333-4333-8333-333333333333"; + Map value = new LinkedHashMap<>(); + value.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + value.put("schemaVersion", "1"); + value.put("mode", "PUBLIC_PRODUCTION"); + value.put("targetNamespace", "test"); + value.put("callerWorkload", "spiffe://firemud/ns/test/sa/game-session-service"); + value.put("requestId", other); + value.put("leaseId", tenant); + value.put("leaseFence", "1"); + value.put("leaseKind", "NEW_BINDING"); + Map scope = new LinkedHashMap<>(); + for (String key : + List.of( + "realmId", + "playableStateNamespaceId", + "gameInstanceId", + "characterId", + "sessionId", + "regionId")) scope.put(key, other); + scope.put("accountId", account); + scope.put("tenantId", tenant); + scope.put("worldSlug", "world"); + scope.put("realmSlug", "realm"); + scope.put("playableStateScope", "SHARED"); + for (String key : + List.of("bindingGeneration", "catalogRevision", "pointerVersion", "regionEpoch")) + scope.put(key, "1"); + value.put("bindingScope", scope); + value.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(tenant, "1"), + "membershipAuthorityGeneration", + Map.of(tenant, "1"), + "privateRealmGrantVersions", + List.of())); + value.put("issuanceFence", "1"); + value.put( + "membershipBaseline", + Map.of( + "membershipLifecycleState", + "ACTIVE", + "membershipVersion", + Map.of(tenant, "1"), + "membershipAuthorityGeneration", + "1")); + value.put( + "outboxCheckpoints", + List.of( + "account/" + account, + "issuer/firemud-account-service", + "membership/" + account + "/" + tenant, + "tenant/" + tenant) + .stream() + .map( + suffix -> + Map.of( + "outboxStreamKey", + "account:auth-authority:v1:" + suffix, + "outboxSequence", + suffix.startsWith("account/") || suffix.startsWith("issuer/") ? "0" : "1")) + .toList()); + Map token = new LinkedHashMap<>(); + token.put("accountId", account); + for (String key : List.of("operationId", "issuanceRequestId", "tokenJti")) + token.put(key, other); + token.put("tokenSHA256", "a".repeat(64)); + token.put("tokenProfile", "game-session-account-delegation"); + for (String key : List.of("tokenGeneration", "issuanceFence", "tokenIdentityFence")) + token.put(key, "1"); + token.put("issuedAt", "999"); + token.put("notBefore", "999"); + token.put("expiresAt", "1300"); + value.put("tokenIdentityEvidence", token); + value.put("evaluatedAt", "1000000"); + value.put("expiresAt", "1015000"); + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(value); + } + + /** Builds only a non-authorizing storage DTO with the receipt values used by these tests. */ + static AccountGameplayAdmissionOriginalAckReceipt receipt( + AccountGameplayAdmissionLeaseEvidence evidence, UUID decision) { + var operation = + new AccountGameplayAdmissionLeaseOperation(evidence, State.COMMITTED, decision, null); + return new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + UUID.fromString((String) evidence.carrier().get("requestId")), + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString((String) evidence.carrier().get("leaseId")), + 1L, + evidence.sha256(), + decision, + 1_015_000L, + "123456", + 1_014_999L, + "123457"); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutorTest.java new file mode 100644 index 0000000000..8f97cbddc3 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutorTest.java @@ -0,0 +1,412 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.mockingDetails; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.io.Serializable; +import java.lang.reflect.Modifier; +import java.math.BigDecimal; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Arrays; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.Answers; +import org.mockito.MockedConstruction; +import org.springframework.jdbc.datasource.ConnectionHolder; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Concrete Spring/JDBC lifecycle with mocked JDBC responses and repository storage. These unit + * doubles prove neither physical PostgreSQL durability nor a persisted receipt, authentication or + * admission. + */ +class AccountGameplayAdmissionOriginalCommitExecutorTest { + @AfterEach + void clearTransaction() { + for (Object key : TransactionSynchronizationManager.getResourceMap().keySet()) { + TransactionSynchronizationManager.unbindResource(key); + } + TransactionSynchronizationManager.clear(); + } + + @Test + void actualJdbcCommitPrecedesOpaqueAcknowledgement() throws Exception { + var fixture = new Fixture(); + var returned = + new AtomicReference< + AccountGameplayAdmissionOriginalCommitExecutor.OriginalCommitAcknowledgement>(); + doAnswer( + ignored -> { + assertThat(returned.get()).isNull(); + return null; + }) + .when(fixture.connection) + .commit(); + try (var repositories = fixture.repositories(State.PENDING)) { + returned.set(fixture.executor.execute(fixture.evidence, fixture.decision)); + var acknowledgement = returned.get(); + assertThat(acknowledgement.evidence()).isSameAs(fixture.evidence); + assertThat(acknowledgement.decisionId()).isEqualTo(fixture.decision); + assertThat(acknowledgement.finalizationXid()).isEqualTo("42"); + assertThat(acknowledgement.committedBeforeMs()).isEqualTo(9000L); + assertThat(acknowledgement.belongsTo(fixture.source)).isTrue(); + assertThat(acknowledgement.belongsTo(mock(DataSource.class))).isFalse(); + assertThat(acknowledgement.belongsTo(null)).isFalse(); + assertThat(Serializable.class.isAssignableFrom(acknowledgement.getClass())).isFalse(); + assertThat(Arrays.stream(acknowledgement.getClass().getDeclaredConstructors())) + .allMatch(constructor -> Modifier.isPrivate(constructor.getModifiers())); + var order = + inOrder( + repositories.constructed().getFirst(), + fixture.stamp, + fixture.settingsStatement, + fixture.connection, + fixture.clockStatement); + order + .verify(repositories.constructed().getFirst()) + .recordCommitted(fixture.evidence, fixture.decision); + // Verify completed query lifecycles without invoking JDBC resource factories on verify mocks. + order.verify(fixture.stamp).close(); + order.verify(fixture.settingsStatement).execute("SET LOCAL synchronous_commit = on"); + order.verify(fixture.settingsStatement).close(); + order.verify(fixture.connection).commit(); + order.verify(fixture.clockStatement).close(); + var commits = + mockingDetails(fixture.connection).getInvocations().stream() + .filter(invocation -> invocation.getMethod().getName().equals("commit")) + .mapToInt(invocation -> invocation.getSequenceNumber()) + .toArray(); + var clockQueries = + mockingDetails(fixture.clockStatement).getInvocations().stream() + .filter(invocation -> invocation.getMethod().getName().equals("executeQuery")) + .mapToInt(invocation -> invocation.getSequenceNumber()) + .toArray(); + assertThat(commits).hasSize(1); + assertThat(clockQueries).hasSize(1); + assertThat(clockQueries[0]).isGreaterThan(commits[0]); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + } + } + + @Test + void acknowledgementRetainsConfiguredSourceIdentityWhenSpringUnwrapsProxy() throws Exception { + var fixture = new Fixture(); + var configured = new TransactionAwareDataSourceProxy(fixture.source); + try (var repositories = fixture.repositories(State.PENDING)) { + var acknowledgement = + new AccountGameplayAdmissionOriginalCommitExecutor(configured) + .execute(fixture.evidence, fixture.decision); + assertThat(acknowledgement.belongsTo(configured)).isTrue(); + assertThat(acknowledgement.belongsTo(fixture.source)).isFalse(); + assertThat(repositories.constructed()).hasSize(1); + } + } + + @ParameterizedTest + @ValueSource(strings = {"10000", "11000", "0", "-1", "9223372036854775808", "9000.5"}) + void invalidOrLatePostCommitClockCannotReturnCapability(String value) throws Exception { + var fixture = new Fixture(); + when(fixture.clockRow.getBigDecimal(1)).thenReturn(new BigDecimal(value)); + try (var repositories = fixture.repositories(State.PENDING)) { + assertThatThrownBy(() -> fixture.executor.execute(fixture.evidence, fixture.decision)) + .hasMessageContaining("post-COMMIT clock bound unavailable"); + verify(fixture.connection).commit(); + verify(fixture.connection).rollback(); + verify(repositories.constructed().getFirst()) + .recordCommitted(fixture.evidence, fixture.decision); + } + } + + @ParameterizedTest + @ValueSource(strings = {"missing", "null", "query-error"}) + void unavailableClockAfterAcknowledgedCommitCannotReturnCapability(String fault) + throws Exception { + var fixture = new Fixture(); + switch (fault) { + case "missing" -> when(fixture.clockRow.next()).thenReturn(false); + case "null" -> when(fixture.clockRow.getBigDecimal(1)).thenReturn(null); + case "query-error" -> fixture.clockFailure = new SQLException("clock response lost", "08006"); + default -> throw new IllegalArgumentException(fault); + } + try (var repositories = fixture.repositories(State.PENDING)) { + assertThatThrownBy(() -> fixture.executor.execute(fixture.evidence, fixture.decision)) + .hasMessageContaining("post-COMMIT clock"); + verify(fixture.connection).commit(); + verify(fixture.connection).rollback(); + verify(repositories.constructed().getFirst()) + .recordCommitted(fixture.evidence, fixture.decision); + } + } + + @Test + void ambiguousPhysicalCommitThrowsWithoutReturningAcknowledgement() throws Exception { + var fixture = new Fixture(); + doThrow(new SQLException("connection lost during COMMIT", "08006")) + .when(fixture.connection) + .commit(); + try (var repositories = fixture.repositories(State.PENDING)) { + assertThatThrownBy(() -> fixture.executor.execute(fixture.evidence, fixture.decision)) + .hasMessageContaining("physical COMMIT unavailable"); + verify(fixture.connection).commit(); + verify(fixture.connection).rollback(); + assertThat(repositories.constructed()).hasSize(1); + } + } + + @Test + void failureToEnforceSynchronousCommitRollsBackBeforeConnectionCleanup() throws Exception { + var fixture = new Fixture(); + doThrow(new SQLException("SET LOCAL rejected")) + .when(fixture.settingsStatement) + .execute("SET LOCAL synchronous_commit = on"); + try (var repositories = fixture.repositories(State.PENDING)) { + assertThatThrownBy(() -> fixture.executor.execute(fixture.evidence, fixture.decision)) + .hasMessageContaining("physical COMMIT unavailable"); + verify(fixture.connection, never()).commit(); + var order = inOrder(fixture.settingsStatement, fixture.connection); + order.verify(fixture.settingsStatement).execute("SET LOCAL synchronous_commit = on"); + order.verify(fixture.connection).rollback(); + order.verify(fixture.connection).setAutoCommit(true); + assertThat(repositories.constructed()).hasSize(1); + } + } + + @Test + void retainedCommittedRetryCannotMintAnotherAcknowledgement() throws Exception { + var fixture = new Fixture(); + try (var repositories = fixture.repositories(State.COMMITTED)) { + assertThatThrownBy(() -> fixture.executor.execute(fixture.evidence, fixture.decision)) + .hasMessageContaining("Fresh owned Account original COMMIT required"); + verify(repositories.constructed().getFirst(), never()) + .recordCommitted(fixture.evidence, fixture.decision); + verify(fixture.connection, never()).commit(); + verify(fixture.connection).rollback(); + verifyNoInteractions(fixture.stamp, fixture.settingsStatement); + } + } + + @ParameterizedTest + @ValueSource(strings = {"actual", "synchronization", "bound"}) + void ambientContextDeniesBeforeAcquiringConnection(String ambient) throws Exception { + var fixture = new Fixture(); + switch (ambient) { + case "actual" -> TransactionSynchronizationManager.setActualTransactionActive(true); + case "synchronization" -> TransactionSynchronizationManager.initSynchronization(); + case "bound" -> + TransactionSynchronizationManager.bindResource( + fixture.source, new ConnectionHolder(fixture.connection)); + default -> throw new IllegalArgumentException(ambient); + } + assertThatThrownBy(() -> fixture.executor.execute(fixture.evidence, fixture.decision)) + .hasMessageContaining("Fresh owned Account original COMMIT required"); + verifyNoInteractions(fixture.source, fixture.connection); + } + + @ParameterizedTest + @ValueSource( + strings = {"version", "recovery", "fsync", "sync", "isolation", "readonly", "engine"}) + void unsupportedDurabilityAtCommitDenies(String fault) throws Exception { + var fixture = new Fixture(); + switch (fault) { + case "version" -> when(fixture.settings.getInt(1)).thenReturn(160000); + case "recovery" -> when(fixture.settings.getBoolean(2)).thenReturn(true); + case "fsync" -> when(fixture.settings.getString(3)).thenReturn("off"); + case "sync" -> when(fixture.settings.getString(4)).thenReturn("off"); + case "isolation" -> when(fixture.settings.getString(5)).thenReturn("read committed"); + case "readonly" -> when(fixture.settings.getString(6)).thenReturn("on"); + case "engine" -> when(fixture.metadata.getDatabaseProductName()).thenReturn("Other"); + default -> throw new IllegalArgumentException(fault); + } + try (var repositories = fixture.repositories(State.PENDING)) { + assertThatThrownBy(() -> fixture.executor.execute(fixture.evidence, fixture.decision)) + .hasMessageContaining("Fresh owned Account original COMMIT required"); + verify(fixture.connection, never()).commit(); + verify(fixture.connection).rollback(); + assertThat(repositories.constructed()).hasSize(1); + } + } + + @Test + void finalizationStampMustBelongToActualOriginalTransaction() throws Exception { + var fixture = new Fixture(); + when(fixture.stampRow.getString(2)).thenReturn("43"); + try (var repositories = fixture.repositories(State.PENDING)) { + assertThatThrownBy(() -> fixture.executor.execute(fixture.evidence, fixture.decision)) + .hasMessageContaining("Fresh owned Account original COMMIT required"); + verify(fixture.connection, never()).commit(); + verify(fixture.connection).rollback(); + assertThat(repositories.constructed()).hasSize(1); + } + } + + @Test + void replacingEnlistedConnectionCannotCommitOriginalBinding() throws Exception { + var fixture = new Fixture(); + Connection different = mock(Connection.class); + var calls = new AtomicInteger(); + when(fixture.stampRow.next()) + .thenAnswer( + ignored -> { + if (calls.getAndIncrement() == 0) return true; + TransactionSynchronizationManager.unbindResource(fixture.source); + TransactionSynchronizationManager.bindResource( + fixture.source, new ConnectionHolder(different)); + return false; + }); + try (var repositories = fixture.repositories(State.PENDING)) { + assertThatThrownBy(() -> fixture.executor.execute(fixture.evidence, fixture.decision)) + .hasMessageContaining("Fresh owned Account original COMMIT required"); + verify(fixture.connection, never()).commit(); + verify(different, never()).commit(); + assertThat(repositories.constructed()).hasSize(1); + } + } + + private static final class Fixture { + private final DataSource source = mock(DataSource.class); + private final ResultSet clockRow = mock(ResultSet.class); + private SQLException clockFailure; + private final Statement clockStatement = + mock( + Statement.class, + invocation -> { + if (invocation.getMethod().getName().equals("executeQuery")) { + assertThat(invocation.getArgument(0, String.class)) + .isEqualTo("SELECT ceil(extract(epoch FROM clock_timestamp()) * 1000)::bigint"); + if (clockFailure != null) throw clockFailure; + return clockRow; + } + return Answers.RETURNS_DEFAULTS.answer(invocation); + }); + private final AtomicInteger statementCalls = new AtomicInteger(); + private final ResultSet settings = mock(ResultSet.class); + private final Statement settingsStatement = + mock( + Statement.class, + invocation -> + invocation.getMethod().getName().equals("executeQuery") + ? settings + : Answers.RETURNS_DEFAULTS.answer(invocation)); + private final ResultSet stampRow = mock(ResultSet.class); + private final PreparedStatement stamp = + mock( + PreparedStatement.class, + invocation -> + invocation.getMethod().getName().equals("executeQuery") + ? stampRow + : Answers.RETURNS_DEFAULTS.answer(invocation)); + private final Connection connection = + mock( + Connection.class, + invocation -> + switch (invocation.getMethod().getName()) { + case "createStatement" -> + statementCalls.getAndIncrement() == 0 ? settingsStatement : clockStatement; + case "prepareStatement" -> stamp; + default -> Answers.RETURNS_DEFAULTS.answer(invocation); + }); + private final DatabaseMetaData metadata = mock(DatabaseMetaData.class); + private final AccountGameplayAdmissionLeaseEvidence evidence = + mock(AccountGameplayAdmissionLeaseEvidence.class); + private final UUID decision = UUID.randomUUID(); + private final AccountGameplayAdmissionOriginalCommitExecutor executor = + new AccountGameplayAdmissionOriginalCommitExecutor(source); + + private Fixture() throws SQLException { + var autoCommit = new AtomicBoolean(true); + var isolation = new AtomicInteger(Connection.TRANSACTION_READ_COMMITTED); + when(source.getConnection()).thenReturn(connection); + when(connection.getAutoCommit()).thenAnswer(ignored -> autoCommit.get()); + doAnswer( + ignored -> { + autoCommit.set(ignored.getArgument(0)); + return null; + }) + .when(connection) + .setAutoCommit(anyBoolean()); + when(connection.getTransactionIsolation()).thenAnswer(ignored -> isolation.get()); + doAnswer( + ignored -> { + isolation.set(ignored.getArgument(0)); + return null; + }) + .when(connection) + .setTransactionIsolation(anyInt()); + when(connection.getMetaData()).thenReturn(metadata); + when(metadata.getDatabaseProductName()).thenReturn("PostgreSQL"); + when(stampRow.next()).thenReturn(true, false); + when(stampRow.getString(1)).thenReturn("42"); + when(stampRow.getString(2)).thenReturn("42"); + when(settings.next()).thenReturn(true, false); + when(settings.getInt(1)).thenReturn(180011); + when(settings.getString(3)).thenReturn("on"); + when(settings.getString(4)).thenReturn("on"); + when(settings.getString(5)).thenReturn("serializable"); + when(settings.getString(6)).thenReturn("off"); + when(clockRow.next()).thenReturn(true, false); + when(clockRow.getBigDecimal(1)).thenReturn(BigDecimal.valueOf(9000L)); + when(evidence.carrier()) + .thenReturn( + Map.of( + "requestId", UUID.randomUUID().toString(), + "leaseId", UUID.randomUUID().toString(), + "expiresAt", "10000")); + when(evidence.sha256()).thenReturn("a".repeat(64)); + when(evidence.canonicalJson()).thenReturn("synthetic-unit-carrier"); + } + + private MockedConstruction repositories(State prior) { + return mockConstruction( + AccountGameplayAdmissionLeaseRepository.class, + (repository, context) -> { + DSLContext dsl = (DSLContext) context.arguments().getFirst(); + Connection enlisted = dsl.connectionResult(value -> value); + assertThat(enlisted).isSameAs(connection); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(Connection.TRANSACTION_SERIALIZABLE); + when(repository.readExact(evidence)) + .thenReturn( + Optional.of( + new AccountGameplayAdmissionLeaseOperation( + evidence, prior, prior == State.COMMITTED ? decision : null, null))); + when(repository.recordCommitted(evidence, decision)) + .thenReturn( + new AccountGameplayAdmissionLeaseOperation( + evidence, State.COMMITTED, decision, null)); + }); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/GrpcOriginalStartSessionCurrentAttemptClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/GrpcOriginalStartSessionCurrentAttemptClient.java new file mode 100644 index 0000000000..528c648708 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/GrpcOriginalStartSessionCurrentAttemptClient.java @@ -0,0 +1,143 @@ +package net.firedevops.firemud.common.gamesession; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.FileBackedGrpcMtlsPolicy; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.gamesession.v1.OriginalStartSessionCurrentAttemptReadServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Explicit file-backed mTLS client for the unregistered Account-authenticated Game Session read. + */ +public final class GrpcOriginalStartSessionCurrentAttemptClient + extends AbstractReloadingBlockingGrpcClient< + OriginalStartSessionCurrentAttemptReadServiceGrpc + .OriginalStartSessionCurrentAttemptReadServiceBlockingStub> + implements OriginalStartSessionCurrentAttemptClient { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GrpcOriginalStartSessionCurrentAttemptClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GrpcOriginalStartSessionCurrentAttemptClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when an owning caller explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Current original StartSession attempt client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException( + "Current original StartSession attempt client has no gRPC stub"); + } + initialized = true; + } + + /** Reads one bounded live-attempt observation outside all ambient SQL transaction state. */ + @Override + public Result read(Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Current original StartSession attempt read requires no ambient transaction or synchronization"); + } + Objects.requireNonNull(request, "current original StartSession attempt request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Current original StartSession attempt must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readOriginalStartSessionCurrentAttempt( + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toRequest(request)); + try { + return OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Game Session returned invalid current original StartSession attempt evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameSessionService(); + } + + @Override + protected String defaultTarget() { + return "game-session-service:6565"; + } + + @Override + protected OriginalStartSessionCurrentAttemptReadServiceGrpc + .OriginalStartSessionCurrentAttemptReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"; + return OriginalStartSessionCurrentAttemptReadServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize( + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.MAX_RESPONSE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private OriginalStartSessionCurrentAttemptReadServiceGrpc + .OriginalStartSessionCurrentAttemptReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Current original StartSession attempt client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + return FileBackedGrpcMtlsPolicy.require( + tlsProperties, + "Current original StartSession attempt reads", + "Current original StartSession attempt reads require workload mTLS", + "Current original StartSession attempt reads require workload mTLS"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptClient.java new file mode 100644 index 0000000000..7b3714deda --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptClient.java @@ -0,0 +1,13 @@ +package net.firedevops.firemud.common.gamesession; + +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; + +/** Reads one exact current original Game Session attempt as a point-in-time observation. */ +public interface OriginalStartSessionCurrentAttemptClient { + /** + * Returns an observation only. The result is not a transferable claim, lease renewal, or + * continuous authorization to redeem, execute, or admit. + */ + Result read(Request request); +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidence.java new file mode 100644 index 0000000000..47662174f7 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidence.java @@ -0,0 +1,190 @@ +package net.firedevops.firemud.common.gamesession; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; + +/** Observation-only evidence for one exact, currently leased original StartSession attempt. */ +public final class OriginalStartSessionCurrentAttemptEvidence { + public static final int SCHEMA_VERSION = 1; + public static final int MAX_REQUEST_BYTES = + StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + 512; + public static final int MAX_PROJECTION_BYTES = + StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES; + public static final String PENDING_PHASE = "OWNER_EXECUTION_PENDING"; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + + private OriginalStartSessionCurrentAttemptEvidence() {} + + public static String projectionDigest(byte[] projection) { + Objects.requireNonNull(projection, "Account redemption projection is required"); + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(projection)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + /** Exact request selector; all byte arrays are defensively copied. */ + public static final class Request { + private final UUID readRequestId; + private final String targetNamespace; + private final StartSessionPostAuthorizationExecutionTuple originalTuple; + private final byte[] originalTupleBytes; + private final UUID expectedOwnerAttemptId; + private final UUID expectedOwnerMutationId; + private final long expectedOwnerFence; + + public Request( + UUID readRequestId, + String targetNamespace, + byte[] canonicalPostAuthorizationTuple, + UUID expectedOwnerAttemptId, + UUID expectedOwnerMutationId, + long expectedOwnerFence) { + this.readRequestId = requireUuid(readRequestId, "readRequestId"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be a valid workload namespace"); + } + this.targetNamespace = targetNamespace; + Objects.requireNonNull( + canonicalPostAuthorizationTuple, "complete original tuple is required"); + if (canonicalPostAuthorizationTuple.length == 0 + || canonicalPostAuthorizationTuple.length + > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES) { + throw new IllegalArgumentException("Complete original tuple is empty or exceeds its bound"); + } + this.originalTupleBytes = canonicalPostAuthorizationTuple.clone(); + this.originalTuple = + StartSessionPostAuthorizationExecutionTuple.decode(this.originalTupleBytes); + if (!Arrays.equals(this.originalTuple.canonicalBytes(), this.originalTupleBytes) + || !targetNamespace.equals( + this.originalTuple.preAuthorizationTuple().action().scope().targetNamespace())) { + throw new IllegalArgumentException( + "Original tuple must be canonical and target the exact requested namespace"); + } + this.expectedOwnerAttemptId = requireUuid(expectedOwnerAttemptId, "ownerAttemptId"); + this.expectedOwnerMutationId = requireUuid(expectedOwnerMutationId, "ownerMutationId"); + if (expectedOwnerFence <= 0L) { + throw new IllegalArgumentException("ownerFence must be positive"); + } + this.expectedOwnerFence = expectedOwnerFence; + } + + public UUID readRequestId() { + return readRequestId; + } + + public String targetNamespace() { + return targetNamespace; + } + + public StartSessionPostAuthorizationExecutionTuple originalTuple() { + return originalTuple; + } + + public byte[] canonicalPostAuthorizationTuple() { + return originalTupleBytes.clone(); + } + + public UUID expectedOwnerAttemptId() { + return expectedOwnerAttemptId; + } + + public UUID expectedOwnerMutationId() { + return expectedOwnerMutationId; + } + + public long expectedOwnerFence() { + return expectedOwnerFence; + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof Request that)) { + return false; + } + return expectedOwnerFence == that.expectedOwnerFence + && readRequestId.equals(that.readRequestId) + && targetNamespace.equals(that.targetNamespace) + && Arrays.equals(originalTupleBytes, that.originalTupleBytes) + && expectedOwnerAttemptId.equals(that.expectedOwnerAttemptId) + && expectedOwnerMutationId.equals(that.expectedOwnerMutationId); + } + + @Override + public int hashCode() { + int result = + Objects.hash( + readRequestId, + targetNamespace, + expectedOwnerAttemptId, + expectedOwnerMutationId, + expectedOwnerFence); + return 31 * result + Arrays.hashCode(originalTupleBytes); + } + } + + /** Exact successful point-in-time response, including the original unchanged lease expiry. */ + public static final class Result { + private final Request request; + private final Instant originalLeaseExpiresAt; + private final byte[] accountRedemptionProjection; + + public Result(Request request, Instant originalLeaseExpiresAt, byte[] projection) { + this.request = Objects.requireNonNull(request, "request is required"); + this.originalLeaseExpiresAt = + Objects.requireNonNull(originalLeaseExpiresAt, "original lease expiry is required"); + Objects.requireNonNull(projection, "attached Account projection is required"); + if (projection.length == 0 || projection.length > MAX_PROJECTION_BYTES) { + throw new IllegalArgumentException( + "Attached Account projection is empty or exceeds its bound"); + } + this.accountRedemptionProjection = projection.clone(); + } + + public Request request() { + return request; + } + + public String phaseState() { + return PENDING_PHASE; + } + + public Instant originalLeaseExpiresAt() { + return originalLeaseExpiresAt; + } + + public byte[] accountRedemptionProjection() { + return accountRedemptionProjection.clone(); + } + + public String accountRedemptionProjectionDigest() { + return projectionDigest(accountRedemptionProjection); + } + } + + private static UUID requireUuid(UUID value, String name) { + Objects.requireNonNull(value, name + " is required"); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a canonical non-nil UUID"); + } + return value; + } + + static boolean isCanonicalDigest(String value) { + return value != null && SHA256.matcher(value).matches(); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.java new file mode 100644 index 0000000000..8dca147f44 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.java @@ -0,0 +1,159 @@ +package net.firedevops.firemud.common.gamesession; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Timestamp; +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionCurrentAttemptRequest; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionCurrentAttemptResponse; + +/** Closed schema-1 wire mapping for an observation-only live original-attempt read. */ +public final class OriginalStartSessionCurrentAttemptEvidenceGrpcCodec { + private static final long MIN_TIMESTAMP_SECONDS = -62_135_596_800L; + private static final long MAX_TIMESTAMP_SECONDS = 253_402_300_799L; + private static final int MAX_TIMESTAMP_NANOS = 999_999_999; + + public static final int MAX_RESPONSE_BYTES = + OriginalStartSessionCurrentAttemptEvidence.MAX_REQUEST_BYTES + + OriginalStartSessionCurrentAttemptEvidence.MAX_PROJECTION_BYTES + + 1024; + + private OriginalStartSessionCurrentAttemptEvidenceGrpcCodec() {} + + public static ReadOriginalStartSessionCurrentAttemptRequest toRequest(Request request) { + Objects.requireNonNull(request, "request"); + var wire = + ReadOriginalStartSessionCurrentAttemptRequest.newBuilder() + .setSchemaVersion(OriginalStartSessionCurrentAttemptEvidence.SCHEMA_VERSION) + .setReadRequestId(request.readRequestId().toString()) + .setTargetNamespace(request.targetNamespace()) + .setCanonicalPostAuthorizationTuple( + ByteString.copyFrom(request.canonicalPostAuthorizationTuple())) + .setExpectedOwnerAttemptId(request.expectedOwnerAttemptId().toString()) + .setExpectedOwnerMutationId(request.expectedOwnerMutationId().toString()) + .setExpectedOwnerFence(request.expectedOwnerFence()) + .build(); + if (wire.getSerializedSize() > OriginalStartSessionCurrentAttemptEvidence.MAX_REQUEST_BYTES) { + throw new IllegalArgumentException("Current-attempt request exceeds its byte bound"); + } + return wire; + } + + /** Decodes only a closed exact selector; it does not authenticate the caller. */ + public static Request fromRequest(ReadOriginalStartSessionCurrentAttemptRequest request) { + Objects.requireNonNull(request, "request"); + if (request.getSerializedSize() > OriginalStartSessionCurrentAttemptEvidence.MAX_REQUEST_BYTES + || !request.getUnknownFields().asMap().isEmpty() + || request.getSchemaVersion() + != OriginalStartSessionCurrentAttemptEvidence.SCHEMA_VERSION) { + throw new IllegalArgumentException( + "Closed bounded schema-1 current-attempt request required"); + } + try { + Request decoded = + new Request( + canonicalUuid(request.getReadRequestId(), "read_request_id"), + request.getTargetNamespace(), + request.getCanonicalPostAuthorizationTuple().toByteArray(), + canonicalUuid(request.getExpectedOwnerAttemptId(), "expected_owner_attempt_id"), + canonicalUuid(request.getExpectedOwnerMutationId(), "expected_owner_mutation_id"), + request.getExpectedOwnerFence()); + if (!toRequest(decoded).equals(request)) { + throw new IllegalArgumentException("Current-attempt request is not canonical"); + } + return decoded; + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException( + "Exact canonical current-attempt request required", malformed); + } + } + + public static ReadOriginalStartSessionCurrentAttemptResponse toResponse(Result result) { + Objects.requireNonNull(result, "result"); + var response = + ReadOriginalStartSessionCurrentAttemptResponse.newBuilder() + .setRequest(toRequest(result.request())) + .setPhaseState(result.phaseState()) + .setOriginalLeaseExpiresAt(toTimestamp(result.originalLeaseExpiresAt())) + .setAccountRedemptionProjection( + ByteString.copyFrom(result.accountRedemptionProjection())) + .setAccountRedemptionProjectionDigest(result.accountRedemptionProjectionDigest()) + .build(); + if (response.getSerializedSize() > MAX_RESPONSE_BYTES) { + throw new IllegalArgumentException("Current-attempt response exceeds its byte bound"); + } + return response; + } + + public static Result fromResponse( + Request expectedRequest, ReadOriginalStartSessionCurrentAttemptResponse response) { + Objects.requireNonNull(expectedRequest, "expectedRequest"); + Objects.requireNonNull(response, "response"); + if (response.getSerializedSize() > MAX_RESPONSE_BYTES + || !response.getUnknownFields().asMap().isEmpty() + || !response.hasRequest() + || !response.hasOriginalLeaseExpiresAt() + || !response.getOriginalLeaseExpiresAt().getUnknownFields().asMap().isEmpty() + || !OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE.equals( + response.getPhaseState()) + || response.getAccountRedemptionProjection().isEmpty()) { + throw new IllegalArgumentException( + "Closed complete pending current-attempt response required"); + } + Request echoed = fromRequest(response.getRequest()); + if (!expectedRequest.equals(echoed)) { + throw new IllegalArgumentException("Current-attempt response changed the exact read request"); + } + byte[] projection = response.getAccountRedemptionProjection().toByteArray(); + Result result = + new Result(echoed, fromTimestamp(response.getOriginalLeaseExpiresAt()), projection); + if (!OriginalStartSessionCurrentAttemptEvidence.isCanonicalDigest( + response.getAccountRedemptionProjectionDigest()) + || !result + .accountRedemptionProjectionDigest() + .equals(response.getAccountRedemptionProjectionDigest())) { + throw new IllegalArgumentException("Account projection digest differs from its exact bytes"); + } + return result; + } + + private static Timestamp toTimestamp(Instant instant) { + long seconds = instant.getEpochSecond(); + int nanos = instant.getNano(); + requireTimestampRange(seconds, nanos); + return Timestamp.newBuilder().setSeconds(seconds).setNanos(nanos).build(); + } + + private static Instant fromTimestamp(Timestamp timestamp) { + requireTimestampRange(timestamp.getSeconds(), timestamp.getNanos()); + try { + return Instant.ofEpochSecond(timestamp.getSeconds(), timestamp.getNanos()); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException("Original lease timestamp is invalid", malformed); + } + } + + private static void requireTimestampRange(long seconds, int nanos) { + if (seconds < MIN_TIMESTAMP_SECONDS + || seconds > MAX_TIMESTAMP_SECONDS + || nanos < 0 + || nanos > MAX_TIMESTAMP_NANOS) { + throw new IllegalArgumentException("Original lease timestamp is outside the protobuf range"); + } + } + + private static UUID canonicalUuid(String value, String name) { + try { + UUID parsed = UUID.fromString(Objects.requireNonNull(value, name)); + if (!parsed.toString().equals(value) || new UUID(0L, 0L).equals(parsed)) { + throw new IllegalArgumentException(name + " must be canonical and non-nil"); + } + return parsed; + } catch (RuntimeException invalid) { + throw new IllegalArgumentException(name + " must be canonical and non-nil", invalid); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/FileBackedGrpcMtlsPolicy.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/FileBackedGrpcMtlsPolicy.java index 25c4bb4e58..e4f7f1f698 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/FileBackedGrpcMtlsPolicy.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/FileBackedGrpcMtlsPolicy.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.common.grpc; +import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; @@ -25,6 +26,46 @@ public static CommonGrpcClientProperties require( return tlsProperties; } + /** + * Requires non-plaintext gRPC TLS to resolve to three readable filesystem-backed resources. + * + *

The supplied plaintext message keeps the existing caller-specific failure classification. + */ + public static void require( + CommonGrpcClientProperties tlsProperties, + GrpcTlsMaterialResolver resolver, + String purpose, + String plaintextMessage) { + if (tlsProperties == null || resolver == null) { + throw new IllegalStateException(purpose + " requires file-backed workload mTLS"); + } + if (tlsProperties.isPlaintext()) { + throw new IllegalStateException(plaintextMessage); + } + + ResolvedGrpcTlsMaterial material; + try { + material = resolver.resolve(tlsProperties); + } catch (IOException | RuntimeException failure) { + throw readableMaterialRequired(purpose); + } + if (material == null + || !isReadableFile(material.certChain()) + || !isReadableFile(material.privateKey()) + || !isReadableFile(material.caCert())) { + throw readableMaterialRequired(purpose); + } + } + + private static IllegalStateException readableMaterialRequired(String purpose) { + return new IllegalStateException(purpose + " requires readable file-backed workload mTLS"); + } + + private static boolean isReadableFile(ResolvedGrpcTlsMaterial.TlsResource resource) { + Path path = resource == null ? null : resource.watchPath(); + return path != null && Files.isRegularFile(path) && Files.isReadable(path); + } + private static void requireReadableFile(String configuredPath, String label, String purpose) { String materialMessage = purpose + " requires file-backed certificate, key, and CA material"; if (configuredPath == null || configuredPath.isBlank()) { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/FileBackedGrpcMtlsPolicyTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/FileBackedGrpcMtlsPolicyTest.java index b7577ae257..4ab7c49949 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/FileBackedGrpcMtlsPolicyTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/FileBackedGrpcMtlsPolicyTest.java @@ -1,8 +1,11 @@ package net.firedevops.firemud.common.grpc; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.io.IOException; +import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import org.junit.jupiter.api.Test; @@ -73,11 +76,93 @@ void rejectsMissingClasspathInvalidDirectoryAndNonexistentMaterial(@TempDir Path .hasMessageNotContaining(missingPath); } + @Test + void acceptsResolvedReadableFiles(@TempDir Path directory) throws Exception { + CommonGrpcClientProperties properties = propertiesWithFiles(directory); + + assertThatCode( + () -> + requireResolved( + properties, new GrpcTlsMaterialResolver(), "test read requires workload mTLS")) + .doesNotThrowAnyException(); + } + + @Test + void rejectsResolvedClasspathMaterialAndDirectories(@TempDir Path directory) throws Exception { + CommonGrpcClientProperties properties = propertiesWithFiles(directory); + GrpcTlsMaterialResolver classpathResolver = + new GrpcTlsMaterialResolver() { + @Override + public ResolvedGrpcTlsMaterial resolve(CommonGrpcClientProperties ignored) { + ResolvedGrpcTlsMaterial.TlsResource classpathResource = + new ResolvedGrpcTlsMaterial.TlsResource(() -> InputStream.nullInputStream(), null); + return new ResolvedGrpcTlsMaterial( + classpathResource, classpathResource, classpathResource); + } + }; + assertThatThrownBy( + () -> + requireResolved(properties, classpathResolver, "test read requires workload mTLS")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("test read requires readable file-backed workload mTLS"); + + CommonGrpcClientProperties directoryProperties = propertiesWithFiles(directory); + directoryProperties.setCaCert(directory.toString()); + assertThatThrownBy( + () -> + requireResolved( + directoryProperties, + new GrpcTlsMaterialResolver(), + "test read requires workload mTLS")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("test read requires readable file-backed workload mTLS"); + } + + @Test + void rejectsPlaintextAndResolverFailuresWithPurposeSpecificMessages(@TempDir Path directory) + throws Exception { + CommonGrpcClientProperties plaintext = propertiesWithFiles(directory); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + requireResolved( + plaintext, + new GrpcTlsMaterialResolver(), + "StartSession authorization requires file-backed workload mTLS")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("StartSession authorization requires file-backed workload mTLS"); + + GrpcTlsMaterialResolver failingResolver = + new GrpcTlsMaterialResolver() { + @Override + public ResolvedGrpcTlsMaterial resolve(CommonGrpcClientProperties ignored) + throws IOException { + throw new IOException("sensitive resolver detail"); + } + }; + assertThatThrownBy( + () -> + requireResolved( + propertiesWithFiles(directory), + failingResolver, + "Account authorization requires workload mTLS")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("test read requires readable file-backed workload mTLS") + .hasMessageNotContaining("sensitive resolver detail"); + } + private static CommonGrpcClientProperties require(CommonGrpcClientProperties properties) { return FileBackedGrpcMtlsPolicy.require( properties, PURPOSE, NULL_CONFIGURATION_MESSAGE, PLAINTEXT_MESSAGE); } + private static void requireResolved( + CommonGrpcClientProperties properties, + GrpcTlsMaterialResolver resolver, + String plaintextMessage) { + FileBackedGrpcMtlsPolicy.require(properties, resolver, "test read", plaintextMessage); + } + private static CommonGrpcClientProperties propertiesWithFiles(Path directory) throws Exception { CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); properties.setCertChain(Files.createTempFile(directory, "client-cert", ".pem").toString()); diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptClientMtlsTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptClientMtlsTest.java new file mode 100644 index 0000000000..f6a70f8073 --- /dev/null +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptClientMtlsTest.java @@ -0,0 +1,538 @@ +package unit.net.firedevops.firemud.common.gamesession; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.GrpcOriginalStartSessionCurrentAttemptClient; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.gamesession.v1.OriginalStartSessionCurrentAttemptReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionCurrentAttemptRequest; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionCurrentAttemptResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Synthetic loopback mTLS proof; it does not read a real Game Session database. */ +class OriginalStartSessionCurrentAttemptClientMtlsTest { + private static final String NAMESPACE = "world-runtime"; + private static final String GAME_SESSION_URI = + "spiffe://firemud/ns/world-runtime/sa/game-session-service"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/world-runtime/sa/account-service"; + private static final String OTHER_CLIENT_URI = + "spiffe://firemud/ns/world-runtime/sa/entity-management-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + private static final byte[] PROJECTION = + "synthetic-attached-account-projection".getBytes(StandardCharsets.UTF_8); + + @TempDir static Path tempDirectory; + + private static TestPki pki; + private final AtomicInteger calls = new AtomicInteger(); + private final AtomicReference lastPeerUri = new AtomicReference<>(); + private Server server; + private boolean substituteEcho; + private boolean malformedExpiry; + private boolean stall; + + @BeforeAll + static void certificates() throws Exception { + pki = TestPki.create(tempDirectory); + } + + @AfterEach + void closeServerAndClearTransactionContext() throws Exception { + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + TransactionSynchronizationManager.clear(); + } + + @Test + void readsExactPendingObservationOverMutualTlsWithAccountWorkloadPeer() throws Exception { + start(pki.gameSessionServer()); + try (var client = newClient(pki.accountClient())) { + client.init(); + + Result result = + client.read(OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.request()); + + assertThat(result.phaseState()).isEqualTo("OWNER_EXECUTION_PENDING"); + assertThat(result.request()) + .isEqualTo(OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.request()); + assertThat(result.accountRedemptionProjection()).containsExactly(PROJECTION); + assertThat(result.accountRedemptionProjectionDigest()) + .isEqualTo(OriginalStartSessionCurrentAttemptEvidence.projectionDigest(PROJECTION)); + assertThat(lastPeerUri).hasValue(ACCOUNT_URI); + assertThat(calls).hasValue(1); + } + } + + @Test + void rejectsWrongClientPeerAndChangedGameSessionServerPeer() throws Exception { + start(pki.gameSessionServer()); + try (var client = newClient(pki.otherClient())) { + client.init(); + assertThatThrownBy( + () -> client.read(OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + assertThat(lastPeerUri).hasValue(OTHER_CLIENT_URI); + assertThat(calls).hasValue(1); + } + + stopServer(); + start(pki.wrongGameSessionServer()); + int callsBeforeWrongServer = calls.get(); + try (var client = newClient(pki.accountClient())) { + client.init(); + assertThatThrownBy( + () -> client.read(OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(calls).hasValue(callsBeforeWrongServer); + } + } + + @Test + void rejectsWrongNamespaceAmbientTransactionAndSynchronizationBeforeCallingPeer() + throws Exception { + start(pki.gameSessionServer()); + try (var client = newClient(pki.accountClient())) { + client.init(); + var valid = OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.request(); + try (var wrongNamespaceClient = newClient(pki.accountClient(), "another-runtime")) { + wrongNamespaceClient.init(); + assertThatThrownBy(() -> wrongNamespaceClient.read(valid)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + } + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.read(valid)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction or synchronization"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.read(valid)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction or synchronization"); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + assertThat(calls).hasValue(0); + } + } + + @Test + void rejectsSubstitutedRequestEchoAndMalformedLeaseExpiry() throws Exception { + start(pki.gameSessionServer()); + try (var client = newClient(pki.accountClient())) { + client.init(); + var request = OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.request(); + + substituteEcho = true; + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid current original StartSession attempt evidence"); + substituteEcho = false; + malformedExpiry = true; + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid current original StartSession attempt evidence"); + assertThat(calls).hasValue(2); + } + } + + @Test + void boundsUnavailableReadWithFiveSecondRpcDeadline() throws Exception { + stall = true; + start(pki.gameSessionServer()); + try (var client = newClient(pki.accountClient())) { + client.init(); + assertThatThrownBy( + () -> client.read(OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + } + } + + @Test + void requiresMutualTlsFileBackedCredentialsAndExplicitInitialization() throws Exception { + var endpoints = new ServiceEndpointsProperties(); + var plaintext = pki.clientProperties(tempDirectory, pki.accountClient()); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new GrpcOriginalStartSessionCurrentAttemptClient( + endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + var client = + new GrpcOriginalStartSessionCurrentAttemptClient( + endpoints, + pki.clientProperties(tempDirectory, pki.accountClient()), + new GrpcChannelFactory(), + NAMESPACE); + try { + assertThatThrownBy( + () -> client.read(OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + } finally { + client.close(); + } + } + + private void start(TestIdentity serverIdentity) throws Exception { + var service = + new OriginalStartSessionCurrentAttemptReadServiceGrpc + .OriginalStartSessionCurrentAttemptReadServiceImplBase() { + @Override + public void readOriginalStartSessionCurrentAttempt( + ReadOriginalStartSessionCurrentAttemptRequest wire, + StreamObserver observer) { + calls.incrementAndGet(); + var peer = GrpcPeerIdentity.current(); + lastPeerUri.set(peer == null ? null : peer.uri()); + if (peer == null || !ACCOUNT_URI.equals(peer.uri())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + if (stall) { + return; + } + var request = OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromRequest(wire); + var result = + new Result(request, java.time.Instant.parse("2035-01-01T00:00:00Z"), PROJECTION); + var response = OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(result); + if (substituteEcho) { + response = + response.toBuilder() + .setRequest( + wire.toBuilder() + .setReadRequestId("04444444-4444-4444-8444-444444444444") + .build()) + .build(); + } + if (malformedExpiry) { + response = + response.toBuilder() + .setOriginalLeaseExpiresAt( + response.getOriginalLeaseExpiresAt().toBuilder() + .setNanos(1_000_000_000) + .build()) + .build(); + } + observer.onNext(response); + observer.onCompleted(); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverIdentity.privateKey(), serverIdentity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private void stopServer() throws Exception { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + + private GrpcOriginalStartSessionCurrentAttemptClient newClient(TestIdentity identity) + throws Exception { + return newClient(identity, NAMESPACE); + } + + private GrpcOriginalStartSessionCurrentAttemptClient newClient( + TestIdentity identity, String workloadNamespace) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameSessionService("localhost:" + server.getPort()); + return new GrpcOriginalStartSessionCurrentAttemptClient( + endpoints, + pki.clientProperties(tempDirectory, identity), + new GrpcChannelFactory(), + workloadNamespace); + } + + private record TestIdentity(String alias, PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity gameSessionServer, + TestIdentity wrongGameSessionServer, + TestIdentity accountClient, + TestIdentity otherClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("current-attempt-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD current-attempt test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("current-attempt-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + return new TestPki( + readCertificate(caFile), + issueIdentity(directory, caStore, caFile, "game-session-server", GAME_SESSION_URI, true), + issueIdentity( + directory, + caStore, + caFile, + "wrong-game-session-server", + "spiffe://firemud/ns/world-runtime/sa/world-management-service", + true), + issueIdentity(directory, caStore, caFile, "account-client", ACCOUNT_URI, false), + issueIdentity(directory, caStore, caFile, "other-client", OTHER_CLIENT_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + Path certificate = + writePem( + directory.resolve(identity.alias() + ".client.crt"), + "CERTIFICATE", + identity.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve(identity.alias() + ".client.key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()); + Path caFile = + writePem( + directory.resolve("current-attempt-client-ca.crt"), + "CERTIFICATE", + caCertificate.getEncoded()); + var properties = new CommonGrpcClientProperties(); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(caFile.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + alias, + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] encoded) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(encoded); + Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + return path; + } + + private static void runKeytool(String... arguments) throws Exception { + List command = new ArrayList<>(); + command.add(Path.of(System.getProperty("java.home"), "bin", "keytool").toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + process.getInputStream().transferTo(output); + int exitCode = process.waitFor(); + assertThat(exitCode) + .withFailMessage("keytool failed: %s", output.toString(StandardCharsets.UTF_8)) + .isZero(); + } +} diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.java new file mode 100644 index 0000000000..03ad681a46 --- /dev/null +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.java @@ -0,0 +1,205 @@ +package unit.net.firedevops.firemud.common.gamesession; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.Timestamp; +import com.google.protobuf.UnknownFieldSet; +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +import org.junit.jupiter.api.Test; + +class OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest { + private static final UUID READ_ID = UUID.fromString("01111111-1111-4111-8111-111111111111"); + private static final UUID ATTEMPT = UUID.fromString("02222222-2222-4222-8222-222222222222"); + private static final UUID MUTATION = UUID.fromString("03333333-3333-4333-8333-333333333333"); + + @Test + void roundTripsExactRequestAndProjectionWithPendingPhaseAndOriginalExpiry() { + Request request = + new Request( + READ_ID, + "world-runtime", + CurrentAttemptTestData.tuple().canonicalBytes(), + ATTEMPT, + MUTATION, + 8L); + byte[] projection = + "attached-account-projection".getBytes(java.nio.charset.StandardCharsets.UTF_8); + Result result = + new Result(request, Instant.parse("2030-01-01T00:00:00.123456789Z"), projection); + var wireRequest = OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toRequest(request); + var wireResponse = OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(result); + + assertThat(OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromRequest(wireRequest)) + .isEqualTo(request); + var decoded = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse(request, wireResponse); + assertThat(decoded.request()).isEqualTo(request); + assertThat(decoded.phaseState()).isEqualTo("OWNER_EXECUTION_PENDING"); + assertThat(decoded.originalLeaseExpiresAt()).isEqualTo(result.originalLeaseExpiresAt()); + assertThat(decoded.accountRedemptionProjection()).containsExactly(projection); + assertThat(wireResponse.getAccountRedemptionProjectionDigest()) + .isEqualTo(result.accountRedemptionProjectionDigest()); + } + + @Test + void rejectsUnknownFieldsChangedEchoPhaseProjectionDigestAndMalformedSelectors() { + Request request = + new Request( + READ_ID, + "world-runtime", + CurrentAttemptTestData.tuple().canonicalBytes(), + ATTEMPT, + MUTATION, + 8L); + var wire = OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toRequest(request); + var unknownRequest = + wire.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertThatThrownBy( + () -> OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromRequest(unknownRequest)) + .isInstanceOf(IllegalArgumentException.class); + + var response = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse( + new Result(request, Instant.parse("2030-01-01T00:00:00Z"), new byte[] {1, 2, 3})); + assertThatThrownBy( + () -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + request, response.toBuilder().setPhaseState("COMMITTED").build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + request, + response.toBuilder() + .setAccountRedemptionProjectionDigest("0".repeat(64)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + var unknownTimestamp = + response.toBuilder() + .setOriginalLeaseExpiresAt( + response.getOriginalLeaseExpiresAt().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build()) + .build(); + assertThatThrownBy( + () -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + request, unknownTimestamp)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + new Request( + UUID.fromString("04444444-4444-4444-8444-444444444444"), + "world-runtime", + request.canonicalPostAuthorizationTuple(), + ATTEMPT, + MUTATION, + 8L), + response)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromRequest( + wire.toBuilder().setExpectedOwnerFence(0L).build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void roundTripsGoogleTimestampSecondBoundariesExactly() { + Request request = request(); + byte[] projection = {1, 2, 3}; + Instant[] boundaries = { + Instant.ofEpochSecond(-62_135_596_800L), Instant.ofEpochSecond(253_402_300_799L, 999_999_999) + }; + + for (Instant boundary : boundaries) { + var response = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse( + new Result(request, boundary, projection)); + assertThat( + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse(request, response) + .originalLeaseExpiresAt()) + .isEqualTo(boundary); + } + } + + @Test + void rejectsGoogleTimestampSecondsOutsideRangeOnEncodingAndDecoding() { + Request request = request(); + byte[] projection = {1, 2, 3}; + for (Instant outside : + new Instant[] { + Instant.ofEpochSecond(-62_135_596_801L), Instant.ofEpochSecond(253_402_300_800L) + }) { + assertThatThrownBy( + () -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse( + new Result(request, outside, projection))) + .isInstanceOf(IllegalArgumentException.class); + } + + var validResponse = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse( + new Result(request, Instant.parse("2030-01-01T00:00:00Z"), projection)); + for (long outsideSeconds : new long[] {-62_135_596_801L, 253_402_300_800L}) { + var response = + validResponse.toBuilder() + .setOriginalLeaseExpiresAt( + Timestamp.newBuilder().setSeconds(outsideSeconds).setNanos(0).build()) + .build(); + assertThatThrownBy( + () -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + request, response)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsInvalidGoogleTimestampNanosOnDecoding() { + Request request = request(); + var validResponse = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse( + new Result(request, Instant.parse("2030-01-01T00:00:00Z"), new byte[] {1, 2, 3})); + + for (int invalidNanos : new int[] {-1, 1_000_000_000}) { + var response = + validResponse.toBuilder() + .setOriginalLeaseExpiresAt( + Timestamp.newBuilder() + .setSeconds(Instant.parse("2030-01-01T00:00:00Z").getEpochSecond()) + .setNanos(invalidNanos) + .build()) + .build(); + assertThatThrownBy( + () -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + request, response)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + static Request request() { + return new Request( + READ_ID, + "world-runtime", + CurrentAttemptTestData.tuple().canonicalBytes(), + ATTEMPT, + MUTATION, + 8L); + } +} diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceTest.java new file mode 100644 index 0000000000..42b1f4f7c4 --- /dev/null +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceTest.java @@ -0,0 +1,194 @@ +package unit.net.firedevops.firemud.common.gamesession; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class OriginalStartSessionCurrentAttemptEvidenceTest { + private static final UUID READ_ID = uuid("01111111-1111-4111-8111-111111111111"); + private static final UUID ATTEMPT = uuid("02222222-2222-4222-8222-222222222222"); + private static final UUID MUTATION = uuid("03333333-3333-4333-8333-333333333333"); + + @Test + void requestAndResultRetainExactOriginalBytesWithDefensiveCopies() { + StartSessionPostAuthorizationExecutionTuple tuple = CurrentAttemptTestData.tuple(); + byte[] tupleBytes = tuple.canonicalBytes(); + Request request = new Request(READ_ID, "world-runtime", tupleBytes, ATTEMPT, MUTATION, 8L); + tupleBytes[0] ^= 0x7f; + byte[] projection = + "exact-account-projection".getBytes(java.nio.charset.StandardCharsets.UTF_8); + Result result = + new Result(request, java.time.Instant.parse("2030-01-01T00:00:00Z"), projection); + projection[0] ^= 0x7f; + + assertThat(request.canonicalPostAuthorizationTuple()).containsExactly(tuple.canonicalBytes()); + assertThat(request.originalTuple().canonicalBytes()).containsExactly(tuple.canonicalBytes()); + assertThat(result.accountRedemptionProjection()) + .containsExactly( + "exact-account-projection".getBytes(java.nio.charset.StandardCharsets.UTF_8)); + assertThat(result.accountRedemptionProjectionDigest()) + .isEqualTo( + OriginalStartSessionCurrentAttemptEvidence.projectionDigest( + "exact-account-projection".getBytes(java.nio.charset.StandardCharsets.UTF_8))); + assertThat(result.phaseState()) + .isEqualTo(OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE); + } + + @Test + void rejectsChangedNamespaceNilCorrelationAttemptMutationAndNonpositiveFence() { + byte[] tuple = CurrentAttemptTestData.tuple().canonicalBytes(); + assertThatThrownBy(() -> new Request(READ_ID, "other-runtime", tuple, ATTEMPT, MUTATION, 8L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact requested namespace"); + assertThatThrownBy( + () -> new Request(new UUID(0L, 0L), "world-runtime", tuple, ATTEMPT, MUTATION, 8L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> new Request(READ_ID, "world-runtime", tuple, new UUID(0L, 0L), MUTATION, 8L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> new Request(READ_ID, "world-runtime", tuple, ATTEMPT, new UUID(0L, 0L), 8L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(READ_ID, "world-runtime", tuple, ATTEMPT, MUTATION, 0L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("positive"); + assertThatThrownBy( + () -> + new Result( + new Request(READ_ID, "world-runtime", tuple, ATTEMPT, MUTATION, 8L), + java.time.Instant.EPOCH, + new byte[0])) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("projection"); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} + +/** Shared same-package tuple fixture for the two focused codec/model tests. */ +final class CurrentAttemptTestData { + private static final UUID TENANT = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID RESERVATION_OWNER = + UUID.fromString("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID ISSUANCE_ID = UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private CurrentAttemptTestData() {} + + static StartSessionPostAuthorizationExecutionTuple tuple() { + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman( + "current-attempt-test", + ACTOR, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, "world-runtime"), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "canonical StartSession owner attempt")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service", + FINGERPRINT, + RESERVATION_OWNER, + 19L, + authorityBundle(pre), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + String tenant = TENANT.toString(); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenant, "targetNamespace", "world-runtime"), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", tenant), + "accountProjectionEvidence", + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", digest('a'), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenant, 3L), + "membershipAuthorityGeneration", Map.of(tenant, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", + Map.of(tenant, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException invalid) { + throw new IllegalStateException(invalid); + } + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcService.java index c13ead8744..1e7e410c59 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcService.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcService.java @@ -705,17 +705,19 @@ public void findCharacterByName( public void createCharacter( CreateCharacterRequest request, StreamObserver responseObserver) { try { - long tenantId = requireTenantId(request.getTenantId()); - long accountId = RequestIdValidation.requirePositiveLong(request.getAccountId(), "accountId"); - CharacterDto created = - characterService.create( - tenantId, - accountId, - request.getName(), - request.getGameInstanceId(), - requirePlayableStateScope(request.getPlayableStateScope())); + requireTenantId(request.getTenantId()); + RequestIdValidation.requirePositiveLong(request.getAccountId(), "accountId"); + requirePlayableStateScope(request.getPlayableStateScope()); CreateCharacterResponse response = - CreateCharacterResponse.newBuilder().setCharacterId(String.valueOf(created.id())).build(); + CreateCharacterResponse.newBuilder() + .setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "CreateCharacter", + "FAILED_PRECONDITION", + "Character creation is unavailable until owner protections are implemented.")) + .build(); responseObserver.onNext(response); responseObserver.onCompleted(); } catch (NumberFormatException ex) { diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java index f71715185f..8bf1256098 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java @@ -2156,6 +2156,57 @@ public void onCompleted() {} verifyNoInteractions(characterService); } + @Test + void createCharacterDeniesValidSharedAndIsolatedRequestsBeforeAllocation() { + CharacterService characterService = Mockito.mock(CharacterService.class); + EntityManagementGrpcService service = + newService( + Mockito.mock(PingService.class), + characterService, + Mockito.mock(EquipmentService.class), + Mockito.mock(InventoryService.class), + Mockito.mock(RoomEntityService.class), + new SimpleMeterRegistry()); + + for (var scope : + List.of( + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_SHARED, + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_ISOLATED)) { + AtomicReference ref = + new AtomicReference<>(); + service.createCharacter( + net.firedevops.firemud.entitymanagement.v1.CreateCharacterRequest.newBuilder() + .setTenantId("1") + .setAccountId("44") + .setGameInstanceId("44") + .setPlayableStateScope(scope) + .setName("Ember") + .build(), + new StreamObserver<>() { + @Override + public void onNext( + net.firedevops.firemud.entitymanagement.v1.CreateCharacterResponse value) { + ref.set(value); + } + + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + }); + + assertEquals("FAILED_PRECONDITION", ref.get().getError().getCode()); + assertEquals( + "Character creation is unavailable until owner protections are implemented.", + ref.get().getError().getMessage()); + } + + verifyNoInteractions(characterService); + } + @Test void listCharactersRejectsMalformedCurrentAccountClaimWithoutTenantAccess() { CharacterService characterService = Mockito.mock(CharacterService.class); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java index 8909978c52..b51ca577e4 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java @@ -66,7 +66,7 @@ protected GameDesignServiceGrpc.GameDesignServiceBlockingStub buildStub( public ResolveLaunchDescriptorResponse resolveLaunchDescriptor( long tenantId, long gameTemplateId, String controlPlaneRequestId) { - return resolveLaunchDescriptor(tenantId, gameTemplateId, controlPlaneRequestId, null, null); + return authoredWorldLaunchBindingRequired(); } /** Resolves a run-owned fixture launch against its exact Game Design source receipt. */ @@ -95,18 +95,7 @@ public ResolveLaunchDescriptorResponse resolveLaunchDescriptor( String controlPlaneRequestId, Long sourceVersionId, Long targetVersionId) { - ResolveLaunchDescriptorRequest.Builder request = - ResolveLaunchDescriptorRequest.newBuilder() - .setTenantId(Long.toString(tenantId)) - .setGameTemplateId(gameTemplateId) - .setControlPlaneRequestId(controlPlaneRequestId); - if (sourceVersionId != null) { - request.setSourceVersionId(sourceVersionId); - } - if (targetVersionId != null) { - request.setTargetVersionId(targetVersionId); - } - return callStub().resolveLaunchDescriptor(request.build()); + return authoredWorldLaunchBindingRequired(); } public GetPublishedReleaseBundleResponse getPublishedReleaseBundle( @@ -215,6 +204,17 @@ private GameDesignServiceGrpc.GameDesignServiceBlockingStub callStub() { return stub().withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS); } + private static ResolveLaunchDescriptorResponse authoredWorldLaunchBindingRequired() { + return ResolveLaunchDescriptorResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED") + .setMessage( + "Canonical authored-world source binding is required to resolve a launch descriptor") + .build()) + .build(); + } + private static GetPublishedScriptPatchVersionResponse unavailableScriptPatchVersion() { return GetPublishedScriptPatchVersionResponse.newBuilder() .setError( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalGameInstanceLaunchAssociationReadConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalGameInstanceLaunchAssociationReadConfiguration.java new file mode 100644 index 0000000000..4f254caba9 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalGameInstanceLaunchAssociationReadConfiguration.java @@ -0,0 +1,22 @@ +package net.firedevops.firemud.gamesession.config; + +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import org.jooq.DSLContext; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** Explicit opt-in owner-repository prerequisite for canonical initial admission. */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "firemud.canonical-game-instance-launch-association-owner-read", + name = "enabled", + havingValue = "true") +public class CanonicalGameInstanceLaunchAssociationReadConfiguration { + @Bean + CanonicalGameInstanceLaunchAssociationRepository canonicalGameInstanceLaunchAssociationRepository( + DSLContext dsl, @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + return new CanonicalGameInstanceLaunchAssociationRepository(dsl, workloadNamespace); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfiguration.java new file mode 100644 index 0000000000..0f978a05a4 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfiguration.java @@ -0,0 +1,45 @@ +package net.firedevops.firemud.gamesession.config; + +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; +import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionService; +import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionWorldVerifier; +import net.firedevops.firemud.gamesession.service.impl.DatabaseCanonicalInitialAdmissionService; +import org.jooq.DSLContext; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.PlatformTransactionManager; + +/** Explicit opt-in composition for the canonical initial-admission owner. */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "firemud.canonical-game-instance-launch-association-owner-read", + name = "enabled", + havingValue = "true") +public class CanonicalInitialAdmissionOwnerConfiguration { + @Bean + CanonicalInitialAdmissionRepository canonicalInitialAdmissionRepository( + DSLContext dsl, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + GameSessionCanonicalAdmissionPointerRepository pointerRepository, + CanonicalGameInstanceLaunchAssociationRepository launchRepository, + GameplayAdmissionPointerEventRepository eventRepository) { + return new CanonicalInitialAdmissionRepository( + dsl, catalogRepository, pointerRepository, launchRepository, eventRepository); + } + + @Bean + CanonicalInitialAdmissionService canonicalInitialAdmissionService( + CanonicalInitialAdmissionRepository repository, + GameSessionCanonicalAdmissionPointerRepository pointerRepository, + CanonicalInitialAdmissionWorldVerifier worldVerifier, + @Qualifier("transactionManager") PlatformTransactionManager transactionManager) { + return new DatabaseCanonicalInitialAdmissionService( + repository, pointerRepository, worldVerifier, transactionManager); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionStartSessionOperatorAuthorizationConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionStartSessionOperatorAuthorizationConfiguration.java new file mode 100644 index 0000000000..6adccf3c83 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionStartSessionOperatorAuthorizationConfiguration.java @@ -0,0 +1,55 @@ +package net.firedevops.firemud.gamesession.config; + +import java.time.Duration; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.gamesession.client.StartSessionOperatorRedemptionClient; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.service.GameSessionStartSessionOperatorAuthorizationCoordinator; +import org.jooq.DSLContext; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.PlatformTransactionManager; + +/** Explicit, disabled-by-default composition for StartSession authorization preparation only. */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "firemud.start-session-operator-authorization", + name = "enabled", + havingValue = "true") +public class GameSessionStartSessionOperatorAuthorizationConfiguration { + @Bean + GameSessionStartSessionOperatorAttemptRepository gameSessionStartSessionOperatorAttemptRepository( + DSLContext dsl, + @Value("${firemud.start-session-operator-authorization.owner-claim-lease}") + Duration ownerClaimLease) { + return new GameSessionStartSessionOperatorAttemptRepository(dsl, ownerClaimLease); + } + + @Bean(initMethod = "initialize", destroyMethod = "close") + StartSessionOperatorRedemptionClient startSessionOperatorRedemptionClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + BlockingGrpcStubCustomizer stubCustomizer, + @Value("${firemud.grpc.workload-namespace}") String workloadNamespace) { + return new StartSessionOperatorRedemptionClient( + endpoints, tlsProperties, channelFactory, stubCustomizer, workloadNamespace); + } + + @Bean + GameSessionStartSessionOperatorAuthorizationCoordinator + gameSessionStartSessionOperatorAuthorizationCoordinator( + GameSessionStartSessionOperatorAttemptRepository attemptRepository, + StartSessionOperatorRedemptionClient redemptionClient, + @Qualifier("transactionManager") PlatformTransactionManager transactionManager, + @Value("${firemud.grpc.workload-namespace}") String workloadNamespace) { + return new GameSessionStartSessionOperatorAuthorizationCoordinator( + attemptRepository, redemptionClient, transactionManager, workloadNamespace); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java index 48429a3651..eee3783edc 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java @@ -10,6 +10,7 @@ import java.util.Optional; import java.util.UUID; import java.util.regex.Pattern; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; @@ -133,6 +134,80 @@ public AttemptSnapshot validateCurrentClaim(AttemptClaim claim) { return snapshot(row); } + /** + * Reads the exact original pending attempt under its live database-clock lease and original + * Account authorization-reference expiry. The claim-owner identity is loaded only inside this + * repository and is never returned to the caller. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public AttemptSnapshot readCurrentOriginalAttempt( + OriginalStartSessionCurrentAttemptEvidence.Request request) { + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(request, "current original-attempt read request is required"); + StartSessionPostAuthorizationExecutionTuple tuple = request.originalTuple(); + String namespace = request.targetNamespace(); + String requestId = tuple.controlPlaneRequestId(); + Record row = selectAttempt(namespace, requestId, true); + if (row == null) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Exact live original StartSession attempt is unavailable"); + } + + byte[] storedTuple = requiredBytes(row, "post_authorization_execution_tuple"); + if (!Arrays.equals(storedTuple, request.canonicalPostAuthorizationTuple())) { + throw new StartSessionOperatorAttemptConflictException( + "Current original-attempt read differs from the complete StartSession tuple"); + } + StartSessionPostAuthorizationExecutionTuple decodedTuple; + try { + decodedTuple = StartSessionPostAuthorizationExecutionTuple.decode(storedTuple); + } catch (IllegalArgumentException malformed) { + throw new IllegalStateException( + "Persisted current StartSession owner tuple is malformed", malformed); + } + if (!Arrays.equals(decodedTuple.canonicalBytes(), storedTuple) + || !namespace.equals(requiredText(row, "target_namespace")) + || !requestId.equals(requiredText(row, "control_plane_request_id"))) { + throw new IllegalStateException( + "Persisted current StartSession owner identity is not canonical"); + } + requireStoredProjectionColumnsMatch(row, decodedTuple); + if (!request.expectedOwnerAttemptId().equals(requiredUuid(row, "owner_attempt_id")) + || !request.expectedOwnerMutationId().equals(requiredUuid(row, "owner_mutation_id")) + || request.expectedOwnerFence() != requiredLong(row, "owner_fence")) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Current original-attempt read differs from the stored attempt, mutation, or fence"); + } + if (!"OWNER_EXECUTION_PENDING".equals(requiredText(row, "phase_state"))) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Only the original pending StartSession attempt supports a current lease read"); + } + + // The durable claimant credential is used only to revalidate this locked row internally. + AttemptClaim storedClaim = + new AttemptClaim( + namespace, + requestId, + request.expectedOwnerAttemptId(), + request.expectedOwnerMutationId(), + requiredUuid(row, "claim_owner_id"), + request.expectedOwnerFence()); + AttemptSnapshot current = validateCurrentClaim(storedClaim); + byte[] projection = current.accountRedemptionProjection(); + if (projection == null) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Original StartSession attempt has no attached Account projection"); + } + AccountRedemptionProjection expectedProjection = projectionFromTuple(decodedTuple); + if (!Arrays.equals(projection, expectedProjection.canonicalBytes())) { + throw new IllegalStateException( + "Attached Account projection differs from the exact current StartSession tuple"); + } + requireProjectionMatches(decodedTuple, expectedProjection); + requireOriginalAuthorityUnexpired(decodedTuple); + return current; + } + /** * Reads the immutable identity and attached Account projection for historical reconciliation. It * does not require a live lease or reference and grants no permission to continue the mutation. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolver.java new file mode 100644 index 0000000000..df94b0de37 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolver.java @@ -0,0 +1,122 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; + +/** Resolves a canonical region through the authenticated World lifecycle owner read. */ +public final class CanonicalRegionBootstrapAssignmentResolver { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final WorldCanonicalInstanceLifecycleClient lifecycleClient; + + public CanonicalRegionBootstrapAssignmentResolver( + WorldCanonicalInstanceLifecycleClient lifecycleClient) { + this.lifecycleClient = Objects.requireNonNull(lifecycleClient, "lifecycleClient"); + } + + /** + * Reads World-owned lifecycle evidence and resolves one exact canonical region assignment. + * + *

The result is only a validated source assignment. It does not create runtime ownership, + * initialize a tick timeline, or grant admission. + */ + public Assignment resolve( + WorldCanonicalInstanceLifecycleEvidence.Request request, UUID canonicalRegionId) { + Objects.requireNonNull(request, "request"); + requireNonNil(canonicalRegionId, "canonicalRegionId"); + + WorldCanonicalInstanceLifecycleEvidence evidence = lifecycleClient.read(request); + if (evidence == null) { + throw new IllegalStateException("World lifecycle client returned no owner evidence"); + } + if (!request.equals(evidence.request())) { + throw new IllegalStateException( + "World lifecycle response is not bound to the exact requested target"); + } + if (!"ACTIVE".equals(evidence.lifecycleStatus())) { + throw new IllegalStateException("World lifecycle evidence is not ACTIVE"); + } + + Map assignments = evidence.operationalRegionAssignments(); + UUID operationalRegionId = assignments.get(canonicalRegionId); + if (operationalRegionId == null) { + throw new IllegalStateException( + "World lifecycle evidence has no operational assignment for the canonical region"); + } + requireNonNil(operationalRegionId, "operationalRegionId"); + return new Assignment(evidence, canonicalRegionId, operationalRegionId); + } + + private static void requireNonNil(UUID value, String fieldName) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(fieldName + " must be a non-nil UUID"); + } + } + + /** Immutable owner-read result. Construction is restricted to this authenticated resolver. */ + public static final class Assignment { + private final WorldCanonicalInstanceLifecycleEvidence.Request request; + private final UUID canonicalRegionId; + private final UUID operationalRegionId; + private final String lifecycleStatus; + private final long lifecycleEpoch; + private final long lifecycleRowVersion; + private final UUID captureId; + private final String graphSha256; + private final String preparationInputDigest; + + private Assignment( + WorldCanonicalInstanceLifecycleEvidence evidence, + UUID canonicalRegionId, + UUID operationalRegionId) { + this.request = evidence.request(); + this.canonicalRegionId = canonicalRegionId; + this.operationalRegionId = operationalRegionId; + this.lifecycleStatus = evidence.lifecycleStatus(); + this.lifecycleEpoch = evidence.lifecycleEpoch(); + this.lifecycleRowVersion = evidence.rowVersion(); + this.captureId = evidence.captureId(); + this.graphSha256 = evidence.graphSha256(); + this.preparationInputDigest = evidence.preparationInputDigest(); + } + + public WorldCanonicalInstanceLifecycleEvidence.Request request() { + return request; + } + + public UUID canonicalRegionId() { + return canonicalRegionId; + } + + public UUID operationalRegionId() { + return operationalRegionId; + } + + public String lifecycleStatus() { + return lifecycleStatus; + } + + public long lifecycleEpoch() { + return lifecycleEpoch; + } + + public long lifecycleRowVersion() { + return lifecycleRowVersion; + } + + public UUID captureId() { + return captureId; + } + + public String graphSha256() { + return graphSha256; + } + + public String preparationInputDigest() { + return preparationInputDigest; + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultDeniedCanonicalInitialAdmissionWorldVerifier.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultDeniedCanonicalInitialAdmissionWorldVerifier.java new file mode 100644 index 0000000000..62eee4e673 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultDeniedCanonicalInitialAdmissionWorldVerifier.java @@ -0,0 +1,28 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import java.util.Objects; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionWorldProof; +import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionWorldVerifier; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.stereotype.Component; + +/** + * Safe default unless the typed authenticated World initial-admission owner is explicitly composed. + * Caller context, local configuration, and supplied hold identifiers are never owner proof. + */ +@Component +@ConditionalOnProperty( + prefix = "firemud.canonical-initial-admission-world-owner", + name = "enabled", + havingValue = "false", + matchIfMissing = true) +public final class DefaultDeniedCanonicalInitialAdmissionWorldVerifier + implements CanonicalInitialAdmissionWorldVerifier { + @Override + public CanonicalInitialAdmissionWorldProof verify(CanonicalInitialAdmissionRequest request) { + Objects.requireNonNull(request, "request"); + throw new IllegalStateException( + "Canonical initial admission is denied until authenticated World ACTIVE/hold verification is wired"); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java index 518ac43b8f..52924dfb0b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java @@ -4,8 +4,12 @@ import io.grpc.stub.StreamObserver; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; +import java.util.Arrays; import java.util.List; +import java.util.regex.Pattern; import net.firedevops.firemud.common.grpc.GrpcAppErrors; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog; import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog.RealmView; @@ -16,9 +20,12 @@ import net.firedevops.firemud.gamesession.dto.StartSessionRequest; import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot; import net.firedevops.firemud.gamesession.service.AccountPresenceQueryService; import net.firedevops.firemud.gamesession.service.FeatureFlagService; import net.firedevops.firemud.gamesession.service.GameInstanceService; +import net.firedevops.firemud.gamesession.service.GameSessionStartSessionOperatorAuthorizationCoordinator; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.IpConnectionLimiter; @@ -28,6 +35,8 @@ import net.firedevops.firemud.gamesession.v1.AccountPresenceActivityState; import net.firedevops.firemud.gamesession.v1.AccountPresenceEntry; import net.firedevops.firemud.gamesession.v1.AccountRecentPresenceDisposition; +import net.firedevops.firemud.gamesession.v1.AuthorizeStartSessionRequest; +import net.firedevops.firemud.gamesession.v1.AuthorizeStartSessionResponse; import net.firedevops.firemud.gamesession.v1.EnqueueCommandRequest; import net.firedevops.firemud.gamesession.v1.EnqueueCommandResponse; import net.firedevops.firemud.gamesession.v1.GameSessionServiceGrpc; @@ -51,6 +60,7 @@ import net.firedevops.firemud.gamesession.v1.RestartSessionResponse; import net.firedevops.firemud.gamesession.v1.ResumeTicksRequest; import net.firedevops.firemud.gamesession.v1.ResumeTicksResponse; +import net.firedevops.firemud.gamesession.v1.StartSessionOwnerAuthorizationProgress; import net.firedevops.firemud.gamesession.v1.StartSessionResponse; import net.firedevops.firemud.gamesession.v1.StopSessionRequest; import net.firedevops.firemud.gamesession.v1.StopSessionResponse; @@ -62,6 +72,7 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.grpc.server.service.GrpcService; +import org.springframework.lang.Nullable; /** gRPC endpoints for the Game Session Service. */ @GrpcService @@ -70,6 +81,8 @@ justification = "Injected service collaborators are framework-managed and retained internally") public final class GameSessionGrpcService extends GameSessionServiceGrpc.GameSessionServiceImplBase { + private static final String LOGGING_ADMIN_SERVICE = "logging-admin-service"; + private static final Pattern OPAQUE_OPERATOR_REFERENCE = Pattern.compile("[A-Za-z0-9_-]{43}"); private static final Logger LOG = LoggerFactory.getLogger(GameSessionGrpcService.class); private final PingService pingService; private final GameInstanceService gameInstanceService; @@ -92,6 +105,8 @@ public final class GameSessionGrpcService private final IpConnectionLimiter ipConnectionLimiter; + @Nullable private GameSessionStartSessionOperatorAuthorizationCoordinator operatorCoordinator; + @Autowired public GameSessionGrpcService( PingService pingService, @@ -118,6 +133,13 @@ public GameSessionGrpcService( this.ipConnectionLimiter = ipConnectionLimiter; } + /** Optional owner-workflow injection; no coordinator bean is registered by this transport. */ + @Autowired(required = false) + void setOperatorCoordinator( + GameSessionStartSessionOperatorAuthorizationCoordinator operatorCoordinator) { + this.operatorCoordinator = operatorCoordinator; + } + @Override @Timed(value = "gamesessionGrpc.ping") public void ping(PingRequest request, StreamObserver responseObserver) { @@ -228,6 +250,124 @@ public void startSession( } } + /** + * Receives one typed Logging & Admin handoff and records only durable Account-redemption + * progress. This path does not invoke the legacy instance launcher or return a session ID. + */ + @Override + @Timed(value = "gamesessionGrpc.authorizeStartSession") + public void authorizeStartSession( + AuthorizeStartSessionRequest request, + StreamObserver responseObserver) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || !LOGGING_ADMIN_SERVICE.equals(peer.service()) + || !GrpcPeerIdentity.isValidNamespace(peer.namespace())) { + respondOperatorAuthorizationError( + responseObserver, "PERMISSION_DENIED", "Authenticated Logging workload required"); + return; + } + GameSessionStartSessionOperatorAuthorizationCoordinator coordinator = operatorCoordinator; + if (coordinator == null) { + respondOperatorAuthorizationError( + responseObserver, + "FAILED_PRECONDITION", + "StartSession operator authorization is unavailable"); + return; + } + if (request.getUnknownFields().asMap().size() > 0) { + respondOperatorAuthorizationError( + responseObserver, "INVALID_ARGUMENT", "StartSession handoff is malformed"); + return; + } + + byte[] exactTupleBytes = + request.getCanonicalPostAuthorizationExecutionTupleBytes().toByteArray(); + String authorizationReference = request.getOperatorAuthorizationReference(); + if (exactTupleBytes.length == 0 + || exactTupleBytes.length + > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + || !OPAQUE_OPERATOR_REFERENCE.matcher(authorizationReference).matches()) { + respondOperatorAuthorizationError( + responseObserver, "INVALID_ARGUMENT", "StartSession handoff is malformed"); + return; + } + + try { + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(exactTupleBytes); + GameSessionStartSessionOperatorAuthorizationCoordinator.AuthorizationResult result = + coordinator.authorize(tuple, authorizationReference); + AttemptSnapshot snapshot = result.snapshot(); + if (!"OWNER_EXECUTION_PENDING".equals(snapshot.phaseState()) + || snapshot.ownerFence() <= 0L + || !tuple.controlPlaneRequestId().equals(snapshot.controlPlaneRequestId()) + || !Arrays.equals(tuple.canonicalBytes(), snapshot.postAuthorizationExecutionTuple())) { + respondOperatorAuthorizationError( + responseObserver, + "FAILED_PRECONDITION", + "StartSession owner attempt could not be verified"); + return; + } + StartSessionOwnerAuthorizationProgress progress = + switch (result.progress()) { + case EXACT_REPLAY -> + StartSessionOwnerAuthorizationProgress + .START_SESSION_OWNER_AUTHORIZATION_PROGRESS_EXACT_REPLAY; + case ACCOUNT_OUTCOME_AMBIGUOUS -> + StartSessionOwnerAuthorizationProgress + .START_SESSION_OWNER_AUTHORIZATION_PROGRESS_ACCOUNT_OUTCOME_AMBIGUOUS; + case ACCOUNT_PROJECTION_ATTACHED -> + StartSessionOwnerAuthorizationProgress + .START_SESSION_OWNER_AUTHORIZATION_PROGRESS_ACCOUNT_PROJECTION_ATTACHED; + }; + AuthorizeStartSessionResponse response = + AuthorizeStartSessionResponse.newBuilder() + .setTargetNamespace(snapshot.targetNamespace()) + .setControlPlaneRequestId(snapshot.controlPlaneRequestId()) + .setMutationDigest(tuple.mutationDigest()) + .setOwnerAttemptId(snapshot.ownerAttemptId().toString()) + .setOwnerMutationId(snapshot.ownerMutationId().toString()) + .setOwnerFence(snapshot.ownerFence()) + .setOwnerPhaseState(snapshot.phaseState()) + .setProgress(progress) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); + } catch (SecurityException ex) { + respondOperatorAuthorizationError( + responseObserver, "PERMISSION_DENIED", "Authenticated Logging workload required"); + } catch ( + GameSessionStartSessionOperatorAttemptRepository + .StartSessionOperatorAttemptConflictException + ex) { + respondOperatorAuthorizationError( + responseObserver, "IDEMPOTENCY_CONFLICT", "StartSession request identity conflicts"); + } catch ( + GameSessionStartSessionOperatorAttemptRepository + .StaleStartSessionOperatorAttemptClaimException + ex) { + respondOperatorAuthorizationError( + responseObserver, "FAILED_PRECONDITION", "StartSession owner claim is no longer current"); + } catch (IllegalArgumentException ex) { + respondOperatorAuthorizationError( + responseObserver, "INVALID_ARGUMENT", "StartSession handoff is malformed"); + } catch (RuntimeException ex) { + LOG.warn("AuthorizeStartSession failed with exception class {}", ex.getClass().getName()); + respondOperatorAuthorizationError( + responseObserver, "INTERNAL", "StartSession owner handoff failed"); + } + } + + private void respondOperatorAuthorizationError( + StreamObserver responseObserver, String code, String message) { + responseObserver.onNext( + AuthorizeStartSessionResponse.newBuilder() + .setError(GrpcAppErrors.error(meterRegistry, code, message)) + .build()); + responseObserver.onCompleted(); + } + private long parseOwnerAccountId(String ownerAccountIdText) { return ControlPlaneRequestParser.parsePositiveLong(ownerAccountIdText, "ownerAccountId"); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadGrpcService.java new file mode 100644 index 0000000000..7dd25317b8 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadGrpcService.java @@ -0,0 +1,174 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.StaleStartSessionOperatorAttemptClaimException; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.StartSessionOperatorAttemptConflictException; +import net.firedevops.firemud.gamesession.v1.OriginalStartSessionCurrentAttemptReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionCurrentAttemptRequest; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionCurrentAttemptResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionOperations; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Directly constructible, deliberately unregistered current-lease observation producer. + * + *

The response is a point-in-time snapshot. It does not establish continuous Account authority, + * authorize execution, renew the lease, or prove admission or protection of later writes. + */ +public final class OriginalStartSessionCurrentAttemptReadGrpcService + extends OriginalStartSessionCurrentAttemptReadServiceGrpc + .OriginalStartSessionCurrentAttemptReadServiceImplBase { + private static final Logger LOG = + LoggerFactory.getLogger(OriginalStartSessionCurrentAttemptReadGrpcService.class); + private final GameSessionStartSessionOperatorAttemptRepository repository; + private final OriginalStartSessionCurrentAttemptReadWorkloadGuard workloadGuard; + private final TransactionOperations ownerReadTransaction; + + public OriginalStartSessionCurrentAttemptReadGrpcService( + GameSessionStartSessionOperatorAttemptRepository repository, + PlatformTransactionManager transactionManager, + String trustedNamespace) { + this(repository, configuredTransaction(transactionManager), trustedNamespace); + } + + OriginalStartSessionCurrentAttemptReadGrpcService( + GameSessionStartSessionOperatorAttemptRepository repository, + TransactionOperations ownerReadTransaction, + String trustedNamespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.ownerReadTransaction = + Objects.requireNonNull(ownerReadTransaction, "ownerReadTransaction"); + this.workloadGuard = new OriginalStartSessionCurrentAttemptReadWorkloadGuard(trustedNamespace); + } + + @Override + public void readOriginalStartSessionCurrentAttempt( + ReadOriginalStartSessionCurrentAttemptRequest request, + StreamObserver responseObserver) { + Objects.requireNonNull(responseObserver, "responseObserver"); + + OriginalStartSessionCurrentAttemptEvidence.Request decoded; + try { + // Authenticate the peer before inspecting any request bytes. + workloadGuard.requireAccountCurrentAttemptReadCaller(); + if (request == null) { + throw new IllegalArgumentException( + "Current original StartSession read request is required"); + } + decoded = OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromRequest(request); + workloadGuard.requireConfiguredTargetNamespace(decoded.targetNamespace()); + } catch (AdminAuthorizationException denied) { + responseObserver.onError( + Status.PERMISSION_DENIED.withDescription(denied.getMessage()).asRuntimeException()); + return; + } catch (IllegalArgumentException malformed) { + responseObserver.onError( + Status.INVALID_ARGUMENT.withDescription(malformed.getMessage()).asRuntimeException()); + return; + } + + try { + requireNoAmbientTransaction(); + AttemptSnapshot snapshot = + ownerReadTransaction.execute(status -> repository.readCurrentOriginalAttempt(decoded)); + if (snapshot == null) { + throw new IllegalStateException( + "Current original-attempt read transaction returned no row"); + } + requireExactSnapshot(decoded, snapshot); + var result = + new OriginalStartSessionCurrentAttemptEvidence.Result( + decoded, snapshot.leaseExpiresAt(), snapshot.accountRedemptionProjection()); + ReadOriginalStartSessionCurrentAttemptResponse response = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(result); + responseObserver.onNext(response); + responseObserver.onCompleted(); + } catch (StartSessionOperatorAttemptConflictException + | StaleStartSessionOperatorAttemptClaimException unavailable) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription(unavailable.getMessage()) + .asRuntimeException()); + } catch (RuntimeException failure) { + LOG.warn( + "ReadOriginalStartSessionCurrentAttempt failed with exception class {}", + failure.getClass().getName()); + responseObserver.onError( + Status.INTERNAL + .withDescription("Current original StartSession attempt read failed") + .asRuntimeException()); + } + } + + private static TransactionOperations configuredTransaction( + PlatformTransactionManager transactionManager) { + Objects.requireNonNull(transactionManager, "transactionManager"); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + // SELECT FOR UPDATE requires a writable transaction on PostgreSQL; this operation performs no + // INSERT, UPDATE, lease renewal, or other durable mutation. + transaction.setReadOnly(false); + return transaction; + } + + private static void requireExactSnapshot( + OriginalStartSessionCurrentAttemptEvidence.Request request, AttemptSnapshot snapshot) { + var tuple = request.originalTuple(); + if (!request.targetNamespace().equals(snapshot.targetNamespace()) + || !tuple.controlPlaneRequestId().equals(snapshot.controlPlaneRequestId()) + || !request.expectedOwnerAttemptId().equals(snapshot.ownerAttemptId()) + || !request.expectedOwnerMutationId().equals(snapshot.ownerMutationId()) + || request.expectedOwnerFence() != snapshot.ownerFence() + || !OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE.equals(snapshot.phaseState()) + || !Arrays.equals( + request.canonicalPostAuthorizationTuple(), snapshot.postAuthorizationExecutionTuple()) + || !tuple + .preAuthorizationTuple() + .action() + .scope() + .tenantId() + .equals(snapshot.canonicalTenantId()) + || snapshot.leaseExpiresAt() == null + || snapshot.accountRedemptionProjection() == null) { + throw new IllegalStateException( + "Repository returned a different or incomplete current original StartSession attempt"); + } + StartSessionAuthorityEvidenceBundle authority = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + byte[] expectedProjection = + new AccountRedemptionProjection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + authority.issuanceOperationId(), + Long.parseLong(tuple.issuanceFence())) + .canonicalBytes(); + if (!Arrays.equals(expectedProjection, snapshot.accountRedemptionProjection())) { + throw new IllegalStateException( + "Repository returned an Account projection different from the exact original tuple"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Current original StartSession read requires its own READ COMMITTED transaction"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadWorkloadGuard.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadWorkloadGuard.java new file mode 100644 index 0000000000..63dab74cd2 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadWorkloadGuard.java @@ -0,0 +1,46 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.v1.OriginalStartSessionCurrentAttemptReadServiceGrpc; + +/** Exact same-namespace Account workload authorization for the live original-attempt read. */ +public final class OriginalStartSessionCurrentAttemptReadWorkloadGuard { + private static final String METHOD_NAME = + "game_session.v1.OriginalStartSessionCurrentAttemptReadService/" + + "ReadOriginalStartSessionCurrentAttempt"; + private static final String ALLOWED_SERVICE = "account-service"; + + private final String trustedNamespace; + + public OriginalStartSessionCurrentAttemptReadWorkloadGuard(String trustedNamespace) { + this.trustedNamespace = trustedNamespace; + } + + public void requireAccountCurrentAttemptReadCaller() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (!METHOD_NAME.equals( + OriginalStartSessionCurrentAttemptReadServiceGrpc + .getReadOriginalStartSessionCurrentAttemptMethod() + .getFullMethodName()) + || !GrpcPeerIdentity.isValidNamespace(trustedNamespace) + || peer == null + || !ALLOWED_SERVICE.equals(peer.service()) + || !trustedNamespace.equals(peer.namespace()) + || !("spiffe://firemud/ns/" + trustedNamespace + "/sa/" + ALLOWED_SERVICE) + .equals(peer.uri()) + || SessionContext.hasAuthenticatedCallerContext()) { + throw new AdminAuthorizationException( + "Current original StartSession evidence requires the exact same-namespace Account workload without caller context"); + } + } + + public void requireConfiguredTargetNamespace(String targetNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace) + || !trustedNamespace.equals(targetNamespace)) { + throw new AdminAuthorizationException( + "Current original StartSession attempt target namespace is not configured here"); + } + } +} diff --git a/services/game-session-service/src/main/resources/application.yml b/services/game-session-service/src/main/resources/application.yml index 085467d1a1..cebb269764 100644 --- a/services/game-session-service/src/main/resources/application.yml +++ b/services/game-session-service/src/main/resources/application.yml @@ -57,6 +57,9 @@ game: logic: default-room-id: "R-1021" firemud: + start-session-operator-authorization: + enabled: false + owner-claim-lease: ${FIREMUD_START_SESSION_OPERATOR_OWNER_CLAIM_LEASE:} gameplay: pointer-bootstrap: pointers: @@ -129,6 +132,7 @@ firemud: force-internal-service-outbound: true public-methods: - game_session.v1.GameSessionService/Ping + - game_session.v1.GameSessionService/AuthorizeStartSession grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/game-session-service/src/main/resources/db/migration/V40__canonical_authored_world_source_provenance.sql b/services/game-session-service/src/main/resources/db/migration/V40__canonical_authored_world_source_provenance.sql new file mode 100644 index 0000000000..b188e9e8bf --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V40__canonical_authored_world_source_provenance.sql @@ -0,0 +1,16 @@ +-- Preserve immutable legacy V30 evidence while aligning new source rows with Game Design V29. +-- [jooq ignore start] +ALTER TABLE game_session_authored_world_tenant_source_binding + ADD CONSTRAINT chk_gs_authored_world_tenant_source_provenance_v29 + CHECK (provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29')) NOT VALID; + +ALTER TABLE game_session_authored_world_tenant_source_binding + DROP CONSTRAINT chk_gs_authored_world_tenant_source_provenance; + +ALTER TABLE game_session_authored_world_source_intake + ADD CONSTRAINT chk_gs_authored_world_source_intake_provenance_v29 + CHECK (source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29')) NOT VALID; + +ALTER TABLE game_session_authored_world_source_intake + DROP CONSTRAINT chk_gs_authored_world_source_intake_provenance; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java new file mode 100644 index 0000000000..eb0921758b --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java @@ -0,0 +1,979 @@ +package integration.net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository.CatalogConflictException; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository.InvalidCatalogEvidenceException; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository.PreparedInitialPublicProduction; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.flywaydb.core.api.configuration.FluentConfiguration; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameSessionCanonicalRealmCatalogRepositoryIntegrationTest { + private static final String NAMESPACE = "canonical-realm-catalog-it"; + private static final long RETAINED_TENANT_ID = 917L; + private static final long ODD_RETAINED_TENANT_ID = 918L; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final UUID RETAINED_REALM_ID = uuid(801); + private static final UUID RETAINED_PLAYABLE_NAMESPACE_ID = uuid(802); + private static final UUID RETAINED_SHARED_NAMESPACE_ID = uuid(803); + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void persistsExactFreshSelectorsAndSharedNamespaceWithoutChangingRetainedNumericEvidence() { + Fixture fixture = fixture(true); + IntakeReceipt source = fixture.register(tenant(1), "new-world", "Fresh World", "NEW_GAME_ROW"); + CreateCanonicalRealmCatalogRequest request = + request(source, uuid(20), "public-realm-east", "Public Realm", "owner-policy-v2", "SHARED"); + String retainedNamespaceXmin = + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("xmin", String.class); + String retainedPointerXmin = + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM gameplay_admission_pointer WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("xmin", String.class); + String oddRetainedNamespaceXmin = + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + ODD_RETAINED_TENANT_ID) + .get("xmin", String.class); + + CanonicalRealmCatalogSnapshot created = fixture.create(request); + CanonicalRealmCatalogSnapshot replay = fixture.create(request); + + assertThat(created).isEqualTo(replay); + assertThat(created.tenantId()).isEqualTo(tenant(1)); + assertThat(created.tenantSlug()).isEqualTo(source.source().tenantSlug()); + assertThat(created.worldSlug()).isEqualTo("new-world"); + assertThat(created.realmSlug()).isEqualTo("public-realm-east"); + assertThat(created.stateScope()).isEqualTo("SHARED"); + assertThat(created.catalogRevision()).isEqualTo(1L); + assertThat(created.playableStateNamespaceId()).isNotEqualTo(RETAINED_SHARED_NAMESPACE_ID); + assertThat(created.sourceIntakeReceipt()).isEqualTo(source); + assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, request.requestId())) + .contains(created); + assertThat(fixture.catalogRepository.readUniqueVisiblePublicProduction(NAMESPACE, tenant(1))) + .contains(created); + + assertThat( + requiredRecord( + fixture.dsl, + "SELECT tenant_id, canonical_tenant_id, playable_state_namespace_id " + + "FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE canonical_tenant_id = ?", + tenant(1))) + .satisfies( + row -> { + assertThat(row.get("tenant_id", Long.class)).isNull(); + assertThat(row.get("canonical_tenant_id", UUID.class)).isEqualTo(tenant(1)); + assertThat(row.get("playable_state_namespace_id", UUID.class)) + .isEqualTo(created.playableStateNamespaceId()); + }); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT playable_state_namespace_id FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("playable_state_namespace_id", UUID.class)) + .isEqualTo(RETAINED_SHARED_NAMESPACE_ID); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT realm_id, playable_state_namespace_id FROM gameplay_admission_pointer " + + "WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("realm_id", UUID.class)) + .isEqualTo(RETAINED_REALM_ID); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT playable_state_namespace_id FROM gameplay_admission_pointer WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("playable_state_namespace_id", UUID.class)) + .isEqualTo(RETAINED_PLAYABLE_NAMESPACE_ID); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("xmin", String.class)) + .isEqualTo(retainedNamespaceXmin); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM gameplay_admission_pointer WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("xmin", String.class)) + .isEqualTo(retainedPointerXmin); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT playable_state_namespace_id FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + ODD_RETAINED_TENANT_ID) + .get("playable_state_namespace_id", UUID.class)) + .isEqualTo(NIL_UUID); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + ODD_RETAINED_TENANT_ID) + .get("xmin", String.class)) + .isEqualTo(oddRetainedNamespaceXmin); + + // The existing runtime selector remains supported by the new nullable-tenant identity layout. + fixture.dsl.execute( + "INSERT INTO gameplay_tenant_shared_playable_state_namespace " + + "(tenant_id, playable_state_namespace_id) VALUES (?, ?) " + + "ON CONFLICT (tenant_id) DO NOTHING", + RETAINED_TENANT_ID, + uuid(804)); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("gameplay_tenant_shared_playable_state_namespace")))) + .isEqualTo(3); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isEqualTo(1); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("xmin", String.class)) + .isEqualTo(retainedNamespaceXmin); + + assertThatThrownBy( + () -> + fixture.create( + request( + source, + uuid(21), + "another-realm", + "Another Realm", + "owner-mode", + "SHARED"))) + .isInstanceOf(CatalogConflictException.class) + .hasMessageContaining("already has a public-production"); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isEqualTo(1); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "UPDATE game_session_canonical_realm_catalog SET realm_slug = ? " + + "WHERE creation_request_id = ?", + "rewritten-realm", + request.requestId())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("evidence is immutable"); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "DELETE FROM game_session_canonical_realm_catalog WHERE creation_request_id = ?", + request.requestId())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("evidence is immutable"); + assertThatThrownBy(() -> fixture.dsl.execute("TRUNCATE game_session_canonical_realm_catalog")) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("cannot truncate a table referenced in a foreign key constraint"); + // The disposable schema's CASCADE form reaches the statement immutability guards after + // PostgreSQL's separate catalog/pointer foreign-key precondition has been satisfied. + assertThatThrownBy( + () -> fixture.dsl.execute("TRUNCATE game_session_canonical_realm_catalog CASCADE")) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("evidence is immutable"); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "UPDATE gameplay_tenant_shared_playable_state_namespace " + + "SET playable_state_namespace_id = ? WHERE canonical_tenant_id = ?", + uuid(805), + tenant(1))) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("fresh shared namespace identity is immutable"); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "DELETE FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE canonical_tenant_id = ?", + tenant(1))) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("fresh shared namespace identity is immutable"); + assertThatThrownBy( + () -> fixture.dsl.execute("TRUNCATE gameplay_tenant_shared_playable_state_namespace")) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("fresh shared namespace identity is immutable"); + assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, request.requestId())) + .contains(created); + } + + @Test + void requiresOwnerWriteTransactionRejectsChangedRequestAndDeniesRetainedProvenance() { + Fixture fixture = fixture(false); + IntakeReceipt source = fixture.register(tenant(2), "world-two", "World Two", "NEW_GAME_ROW"); + CreateCanonicalRealmCatalogRequest request = + request(source, uuid(30), "realm", "Realm", "owner-mode", "SHARED"); + + PreparedInitialPublicProduction prepared = + fixture.catalogRepository.prepareInitialPublicProduction(request); + assertThatThrownBy(() -> fixture.catalogRepository.createInitialPublicProduction(prepared)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + TransactionTemplate readOnly = new TransactionTemplate(fixture.transactionManager); + readOnly.setReadOnly(true); + assertThatThrownBy( + () -> + readOnly.execute( + status -> fixture.catalogRepository.createInitialPublicProduction(prepared))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("read-write"); + + CanonicalRealmCatalogSnapshot created = fixture.create(request); + String beforeXmin = + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM game_session_canonical_realm_catalog " + + "WHERE creation_request_id = ?", + request.requestId()) + .get("xmin", String.class); + CreateCanonicalRealmCatalogRequest changed = + request(source, request.requestId(), "realm", "Changed Realm", "owner-mode", "SHARED"); + assertThatThrownBy(() -> fixture.create(changed)).isInstanceOf(CatalogConflictException.class); + assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, request.requestId())) + .contains(created); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM game_session_canonical_realm_catalog " + + "WHERE creation_request_id = ?", + request.requestId()) + .get("xmin", String.class)) + .isEqualTo(beforeXmin); + + CreateCanonicalRealmCatalogRequest wrongSource = + new CreateCanonicalRealmCatalogRequest( + uuid(32), + NAMESPACE, + source.source().canonicalTenantId(), + uuid(33), + "other-realm", + "Other Realm", + true, + true, + "SHARED", + "owner-mode", + null, + null); + assertThatThrownBy(() -> fixture.catalogRepository.prepareInitialPublicProduction(wrongSource)) + .isInstanceOf(InvalidCatalogEvidenceException.class) + .hasMessageContaining("source intake is missing"); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isEqualTo(1); + + IntakeReceipt otherTenantSource = + fixture.register(tenant(9), "world-nine", "World Nine", "NEW_GAME_ROW"); + CreateCanonicalRealmCatalogRequest mismatchedSource = + new CreateCanonicalRealmCatalogRequest( + uuid(34), + NAMESPACE, + source.source().canonicalTenantId(), + otherTenantSource.operationId(), + "mismatched-realm", + "Mismatched Realm", + true, + true, + "SHARED", + "owner-mode", + null, + null); + assertThatThrownBy( + () -> fixture.catalogRepository.prepareInitialPublicProduction(mismatchedSource)) + .isInstanceOf(InvalidCatalogEvidenceException.class) + .hasMessageContaining("conflicts with the immutable canonical tenant source binding"); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isEqualTo(1); + + IntakeReceipt retained = + fixture.register(tenant(3), "retained-world", "Retained World", "RETAINED_GAME_V29"); + String retainedBindingXmin = + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM game_session_authored_world_tenant_source_binding " + + "WHERE canonical_tenant_id = ?", + retained.source().canonicalTenantId()) + .get("xmin", String.class); + String retainedIntakeXmin = + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM game_session_authored_world_source_intake " + + "WHERE operation_id = ?", + retained.operationId()) + .get("xmin", String.class); + assertThatThrownBy( + () -> + fixture.create( + request(retained, uuid(31), "retained-realm", "Realm", "owner-mode", "SHARED"))) + .isInstanceOf(InvalidCatalogEvidenceException.class) + .hasMessageContaining("fresh Game Design"); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin, provenance_kind FROM " + + "game_session_authored_world_tenant_source_binding WHERE canonical_tenant_id = ?", + retained.source().canonicalTenantId())) + .satisfies( + row -> { + assertThat(row.get("xmin", String.class)).isEqualTo(retainedBindingXmin); + assertThat(row.get("provenance_kind", String.class)).isEqualTo("RETAINED_GAME_V29"); + }); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin, source_provenance_kind FROM " + + "game_session_authored_world_source_intake WHERE operation_id = ?", + retained.operationId())) + .satisfies( + row -> { + assertThat(row.get("xmin", String.class)).isEqualTo(retainedIntakeXmin); + assertThat(row.get("source_provenance_kind", String.class)) + .isEqualTo("RETAINED_GAME_V29"); + }); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isEqualTo(1); + } + + @Test + void rawSqlRejectsV30AndUnknownProvenanceForNewSourceRows() { + Fixture fixture = fixture(false); + + for (String provenance : new String[] {"RETAINED_GAME_V30", "UNKNOWN_KIND"}) { + int suffix = provenance.equals("RETAINED_GAME_V30") ? 1 : 2; + assertThatThrownBy( + () -> + fixture.dsl.execute( + "INSERT INTO game_session_authored_world_tenant_source_binding " + + "(target_namespace, canonical_tenant_id, tenant_slug, source_game_row_id, " + + "source_game_tenant_key, provenance_kind) VALUES (?, ?, ?, ?, ?, ?)", + NAMESPACE, + uuid(900 + suffix), + "raw-binding-" + suffix, + 990L + suffix, + "legacy-key-" + suffix, + provenance)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("chk_gs_authored_world_tenant_source_provenance_v29"); + + assertThatThrownBy( + () -> + fixture.dsl.execute( + "INSERT INTO game_session_authored_world_source_intake (" + + "operation_id, schema_version, target_namespace, intake_request_id, " + + "request_digest, source_schema_version, source_registration_request_id, " + + "source_operation_id, source_request_digest, canonical_tenant_id, " + + "tenant_slug, world_slug, world_display_name, source_game_row_id, " + + "source_game_tenant_key, source_provenance_kind, source_evidence_digest, " + + "receipt_digest) VALUES (?, 1, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + uuid(910 + suffix), + NAMESPACE, + uuid(920 + suffix), + "sha256:" + "a".repeat(64), + uuid(930 + suffix), + uuid(940 + suffix), + "sha256:" + "b".repeat(64), + uuid(900 + suffix), + "raw-binding-" + suffix, + "raw-world-" + suffix, + "Raw World", + 990L + suffix, + "legacy-key-" + suffix, + provenance, + "sha256:" + "c".repeat(64), + "sha256:" + "d".repeat(64))) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("chk_gs_authored_world_source_intake_provenance_v29"); + } + } + + @Test + void v40PreservesExistingV30SourceRowsAndRejectsNewV30Rows() { + Fixture fixture = fixture(false, MigrationVersion.fromVersion("39")); + UUID canonicalTenantId = uuid(950); + UUID intakeOperationId = uuid(951); + String tenantSlug = "retained-v30-tenant"; + String worldSlug = "retained-v30-world"; + long sourceGameRowId = 9751L; + String sourceGameTenantKey = "gds-retained-v30"; + String requestDigest = "sha256:" + "1".repeat(64); + String sourceRequestDigest = "sha256:" + "2".repeat(64); + String sourceEvidenceDigest = "sha256:" + "3".repeat(64); + String receiptDigest = "sha256:" + "4".repeat(64); + + fixture.transactions.execute( + status -> { + fixture.dsl.execute( + "INSERT INTO game_session_authored_world_tenant_source_binding " + + "(target_namespace, canonical_tenant_id, tenant_slug, source_game_row_id, " + + "source_game_tenant_key, provenance_kind) VALUES (?, ?, ?, ?, ?, 'RETAINED_GAME_V30')", + NAMESPACE, + canonicalTenantId, + tenantSlug, + sourceGameRowId, + sourceGameTenantKey); + fixture.dsl.execute( + "INSERT INTO game_session_authored_world_source_intake (" + + "operation_id, schema_version, target_namespace, intake_request_id, " + + "request_digest, source_schema_version, source_registration_request_id, " + + "source_operation_id, source_request_digest, canonical_tenant_id, tenant_slug, " + + "world_slug, world_display_name, source_game_row_id, source_game_tenant_key, " + + "source_provenance_kind, source_evidence_digest, receipt_digest) " + + "VALUES (?, 1, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'RETAINED_GAME_V30', ?, ?)", + intakeOperationId, + NAMESPACE, + uuid(952), + requestDigest, + uuid(953), + uuid(954), + sourceRequestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + "Retained V30 World", + sourceGameRowId, + sourceGameTenantKey, + sourceEvidenceDigest, + receiptDigest); + return null; + }); + + Record retainedBindingBefore = + requiredRecord( + fixture.dsl, + "SELECT *, xmin::text AS retained_xmin " + + "FROM game_session_authored_world_tenant_source_binding " + + "WHERE canonical_tenant_id = ?", + canonicalTenantId); + Record retainedIntakeBefore = + requiredRecord( + fixture.dsl, + "SELECT *, xmin::text AS retained_xmin FROM game_session_authored_world_source_intake " + + "WHERE operation_id = ?", + intakeOperationId); + + fixture.migrateToLatest(); + + Record retainedBindingAfter = + requiredRecord( + fixture.dsl, + "SELECT *, xmin::text AS retained_xmin " + + "FROM game_session_authored_world_tenant_source_binding " + + "WHERE canonical_tenant_id = ?", + canonicalTenantId); + Record retainedIntakeAfter = + requiredRecord( + fixture.dsl, + "SELECT *, xmin::text AS retained_xmin FROM game_session_authored_world_source_intake " + + "WHERE operation_id = ?", + intakeOperationId); + assertThat(retainedBindingAfter).isEqualTo(retainedBindingBefore); + assertThat(retainedIntakeAfter).isEqualTo(retainedIntakeBefore); + assertThat(retainedIntakeAfter.get("request_digest", String.class)).isEqualTo(requestDigest); + assertThat(retainedIntakeAfter.get("source_request_digest", String.class)) + .isEqualTo(sourceRequestDigest); + assertThat(retainedIntakeAfter.get("source_evidence_digest", String.class)) + .isEqualTo(sourceEvidenceDigest); + assertThat(retainedIntakeAfter.get("receipt_digest", String.class)).isEqualTo(receiptDigest); + + assertThatThrownBy( + () -> + fixture.dsl.execute( + "INSERT INTO game_session_authored_world_tenant_source_binding " + + "(target_namespace, canonical_tenant_id, tenant_slug, source_game_row_id, " + + "source_game_tenant_key, provenance_kind) " + + "VALUES (?, ?, ?, ?, ?, 'RETAINED_GAME_V30')", + NAMESPACE, + uuid(960), + "new-v30-tenant", + 9760L, + "gds-new-v30")) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("chk_gs_authored_world_tenant_source_provenance_v29"); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "INSERT INTO game_session_authored_world_source_intake (" + + "operation_id, schema_version, target_namespace, intake_request_id, " + + "request_digest, source_schema_version, source_registration_request_id, " + + "source_operation_id, source_request_digest, canonical_tenant_id, tenant_slug, " + + "world_slug, world_display_name, source_game_row_id, source_game_tenant_key, " + + "source_provenance_kind, source_evidence_digest, receipt_digest) " + + "VALUES (?, 1, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + + "'RETAINED_GAME_V30', ?, ?)", + uuid(961), + NAMESPACE, + uuid(962), + requestDigest, + uuid(963), + uuid(964), + sourceRequestDigest, + uuid(965), + "new-v30-tenant", + "new-v30-world", + "New V30 World", + 9761L, + "gds-new-v30-intake", + sourceEvidenceDigest, + receiptDigest)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("chk_gs_authored_world_source_intake_provenance_v29"); + } + + @Test + void isolatedCreationAllocatesDistinctRealmLocalNamespacesOutsideSharedRegistry() { + Fixture fixture = fixture(true); + IntakeReceipt firstSource = + fixture.register(tenant(4), "world-four", "World Four", "NEW_GAME_ROW"); + IntakeReceipt secondSource = + fixture.register(tenant(5), "world-five", "World Five", "NEW_GAME_ROW"); + + CanonicalRealmCatalogSnapshot first = + fixture.create( + request(firstSource, uuid(40), "realm-four", "Realm Four", "owner-mode", "ISOLATED")); + CanonicalRealmCatalogSnapshot second = + fixture.create( + request(secondSource, uuid(50), "realm-five", "Realm Five", "owner-mode", "ISOLATED")); + + assertThat(first.playableStateNamespaceId()).isNotEqualTo(second.playableStateNamespaceId()); + assertThat(first.tenantSlug()).isNotEqualTo(first.worldSlug()); + assertThat(second.tenantSlug()).isNotEqualTo(second.worldSlug()); + assertThat( + fixture.dsl.fetch( + "SELECT canonical_tenant_id FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE canonical_tenant_id IS NOT NULL")) + .isEmpty(); + assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, uuid(40))).contains(first); + assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, uuid(50))).contains(second); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "UPDATE gameplay_tenant_shared_playable_state_namespace " + + "SET playable_state_namespace_id = ? WHERE tenant_id = ?", + first.playableStateNamespaceId(), + RETAINED_TENANT_ID)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining( + "Legacy tenant SHARED namespace conflicts with a canonical ISOLATED realm namespace"); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT playable_state_namespace_id FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("playable_state_namespace_id", UUID.class)) + .isEqualTo(RETAINED_SHARED_NAMESPACE_ID); + } + + @Test + void concurrentExactCreationRecoversOneDurableRealmAndNamespace() throws Exception { + Fixture fixture = fixture(false); + IntakeReceipt source = + fixture.register(tenant(6), "concurrent-world", "Concurrent World", "NEW_GAME_ROW"); + CreateCanonicalRealmCatalogRequest request = + request(source, uuid(60), "concurrent-realm", "Concurrent Realm", "owner-mode", "SHARED"); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit(() -> raceCreate(fixture, ready, start, request)); + Future second = + executor.submit(() -> raceCreate(fixture, ready, start, request)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + CanonicalRealmCatalogSnapshot firstResult = first.get(20, TimeUnit.SECONDS); + CanonicalRealmCatalogSnapshot secondResult = second.get(20, TimeUnit.SECONDS); + + assertThat(firstResult).isEqualTo(secondResult); + assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, request.requestId())) + .contains(firstResult); + assertThat( + fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isEqualTo(1); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("gameplay_tenant_shared_playable_state_namespace")))) + .isEqualTo(1); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void freshCatalogAndRetainedAssociationCannotBothAcquireTenantAuthorityInEitherOrder() { + Fixture associationFirst = fixture(false); + IntakeReceipt associationFirstSource = + associationFirst.register( + tenant(7), "association-first-world", "Association First", "NEW_GAME_ROW"); + associationFirst.insertRetainedAssociation(associationFirstSource, uuid(70)); + CreateCanonicalRealmCatalogRequest afterAssociation = + request( + associationFirstSource, + uuid(71), + "association-first-realm", + "Association First Realm", + "owner-mode", + "SHARED"); + assertThatThrownBy( + () -> + associationFirst.catalogRepository.prepareInitialPublicProduction(afterAssociation)) + .isInstanceOf(CatalogConflictException.class) + .hasMessageContaining("retained numeric Game Session identity"); + assertThat( + associationFirst.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isZero(); + assertThat( + associationFirst.dsl.fetchCount( + DSL.table(DSL.name("game_session_retained_tenant_association")))) + .isEqualTo(1); + + Fixture catalogFirst = fixture(false); + IntakeReceipt catalogFirstSource = + catalogFirst.register(tenant(8), "catalog-first-world", "Catalog First", "NEW_GAME_ROW"); + CanonicalRealmCatalogSnapshot catalog = + catalogFirst.create( + request( + catalogFirstSource, + uuid(80), + "catalog-first-realm", + "Catalog First Realm", + "owner-mode", + "SHARED")); + assertThatThrownBy(() -> catalogFirst.insertRetainedAssociation(catalogFirstSource, uuid(81))) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("cannot replace fresh canonical tenant namespace authority"); + assertThat( + catalogFirst.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isEqualTo(1); + assertThat(catalogFirst.catalogRepository.readByRequest(NAMESPACE, uuid(80))).contains(catalog); + assertThat( + catalogFirst.dsl.fetchCount( + DSL.table(DSL.name("game_session_retained_tenant_association")))) + .isZero(); + } + + private CanonicalRealmCatalogSnapshot raceCreate( + Fixture fixture, + CountDownLatch ready, + CountDownLatch start, + CreateCanonicalRealmCatalogRequest request) + throws Exception { + ready.countDown(); + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for canonical realm creation race"); + } + return fixture.create(request); + } + + private static CreateCanonicalRealmCatalogRequest request( + IntakeReceipt source, + UUID requestId, + String realmSlug, + String displayName, + String policy, + String scope) { + return new CreateCanonicalRealmCatalogRequest( + requestId, + NAMESPACE, + source.source().canonicalTenantId(), + source.operationId(), + realmSlug, + displayName, + true, + true, + scope, + policy, + null, + null); + } + + private static AuthoredWorldSourceEvidence source( + UUID tenantId, String worldSlug, String displayName, String provenance) { + UUID registrationRequestId = + UUID.nameUUIDFromBytes( + ("registration-" + tenantId).getBytes(java.nio.charset.StandardCharsets.UTF_8)); + UUID sourceOperationId = + UUID.nameUUIDFromBytes( + ("operation-" + tenantId).getBytes(java.nio.charset.StandardCharsets.UTF_8)); + String tenantSlug = "tenant-" + tenantId.toString().substring(0, 8); + long sourceGameRowId = Math.abs(tenantId.getMostSignificantBits()) + 10L; + String sourceGameTenantKey = "gds-tenant-" + tenantId.toString().substring(0, 8); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequestId, tenantId, tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + provenance); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + provenance, + evidenceDigest); + } + + private Fixture fixture(boolean seedRetainedNumericRows) { + return fixture(seedRetainedNumericRows, null); + } + + private Fixture fixture(boolean seedRetainedNumericRows, MigrationVersion targetVersion) { + String schema = "gs_canonical_realm_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("11")) + .load() + .migrate(); + + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + if (seedRetainedNumericRows) { + dsl.execute( + "INSERT INTO gameplay_tenant_shared_playable_state_namespace " + + "(tenant_id, playable_state_namespace_id) VALUES (?, ?)", + RETAINED_TENANT_ID, + RETAINED_SHARED_NAMESPACE_ID); + dsl.execute( + "INSERT INTO gameplay_tenant_shared_playable_state_namespace " + + "(tenant_id, playable_state_namespace_id) VALUES (?, ?)", + ODD_RETAINED_TENANT_ID, + NIL_UUID); + dsl.execute( + "INSERT INTO gameplay_admission_pointer " + + "(world_slug, world_display_name, realm_slug, realm_display_name, tenant_id, " + + "game_instance_id, pointer_version, visible, requires_character_selection, " + + "state_scope, character_creation_policy, last_updated_by, last_update_reason, " + + "public_production_realm, realm_id, playable_state_namespace_id) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + "legacy-world", + "Legacy World", + "legacy-realm", + "Legacy Realm", + RETAINED_TENANT_ID, + 501L, + 1L, + true, + false, + "SHARED", + "ALLOW_NEW", + "fixture", + "retained evidence", + true, + RETAINED_REALM_ID, + RETAINED_PLAYABLE_NAMESPACE_ID); + } + + FluentConfiguration migrationConfiguration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION); + if (targetVersion != null) { + migrationConfiguration.target(targetVersion); + } + migrationConfiguration.load().migrate(); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + DSLContext transactionalDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new Fixture( + transactionalDsl, + new GameSessionAuthoredWorldSourceRepository(transactionalDsl), + new GameSessionCanonicalRealmCatalogRepository(transactionalDsl), + transactionManager, + transactions, + dataSource, + schema); + } + + private static UUID tenant(int value) { + return uuid(100 + value); + } + + private static Record requiredRecord(DSLContext dsl, String sql, Object... bindings) { + return java.util.Objects.requireNonNull( + dsl.fetchOne(sql, bindings), "Expected owner evidence row is missing"); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } + + private record Fixture( + DSLContext dsl, + GameSessionAuthoredWorldSourceRepository sourceRepository, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + DataSourceTransactionManager transactionManager, + TransactionTemplate transactions, + DriverManagerDataSource dataSource, + String schema) { + void migrateToLatest() { + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + } + + IntakeReceipt register(UUID tenantId, String worldSlug, String displayName, String provenance) { + AuthoredWorldSourceEvidence source = + GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.source( + tenantId, worldSlug, displayName, provenance); + UUID intakeRequestId = + UUID.nameUUIDFromBytes( + ("intake-" + tenantId).getBytes(java.nio.charset.StandardCharsets.UTF_8)); + IntakeReceipt receipt = + transactions.execute(status -> sourceRepository.register(intakeRequestId, source)); + return java.util.Objects.requireNonNull(receipt); + } + + CanonicalRealmCatalogSnapshot create(CreateCanonicalRealmCatalogRequest request) { + PreparedInitialPublicProduction prepared = + catalogRepository.prepareInitialPublicProduction(request); + CanonicalRealmCatalogSnapshot snapshot = + transactions.execute(status -> catalogRepository.createInitialPublicProduction(prepared)); + return java.util.Objects.requireNonNull(snapshot); + } + + void insertRetainedAssociation(IntakeReceipt source, UUID requestId) { + AuthoredWorldSourceEvidence evidence = source.source(); + String digest = "sha256:" + "a".repeat(64); + UUID operationId = + UUID.nameUUIDFromBytes( + ("retained-operation-" + requestId) + .getBytes(java.nio.charset.StandardCharsets.UTF_8)); + dsl.execute( + "INSERT INTO game_session_retained_tenant_association (" + + "operation_id, target_namespace, association_request_id, " + + "legacy_game_session_tenant_id, canonical_tenant_id, source_game_row_id, " + + "source_game_tenant_key, provenance_kind) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + operationId, + NAMESPACE, + requestId, + RETAINED_TENANT_ID, + evidence.canonicalTenantId(), + evidence.sourceGameRowId(), + evidence.sourceGameTenantKey(), + evidence.provenanceKind()); + dsl.execute( + "INSERT INTO game_session_retained_tenant_association_payload (" + + "operation_id, request_digest, approval_operation_id, approval_schema_version, " + + "signer_key_id, approved_by, approval_reference, signed_at, " + + "game_session_evidence_digest, approval_manifest_digest, approval_signature, " + + "snapshot_canonical_json, snapshot_evidence_digest, receipt_digest) " + + "VALUES (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + operationId, + digest, + UUID.nameUUIDFromBytes( + ("approval-operation-" + requestId) + .getBytes(java.nio.charset.StandardCharsets.UTF_8)), + "fixture-key", + "fixture-operator", + "fixture-reference", + "2026-10-03T00:00:00Z", + evidence.evidenceDigest(), + digest, + "A".repeat(86) + "==", + "{\"canonicalTenantId\":\"" + + evidence.canonicalTenantId() + + "\",\"sourceGameRowId\":" + + evidence.sourceGameRowId() + + ",\"sourceGameTenantKey\":\"" + + evidence.sourceGameTenantKey() + + "\",\"provenanceKind\":\"" + + evidence.provenanceKind() + + "\"}", + digest, + digest); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryIntegrationTest.java new file mode 100644 index 0000000000..d3ab440bb2 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryIntegrationTest.java @@ -0,0 +1,499 @@ +package integration.net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository.CanonicalGameInstanceLaunchAssociationConflictException; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalStartingInstanceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalStartingInstanceRepository.CanonicalStartingInstanceConflictException; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalStartingInstanceRepository.InvalidCanonicalStartingInstanceEvidenceException; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalStartingInstanceRepository.StartingInstance; +import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository; +import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * PostgreSQL proof for atomic creation of the V21 UUID-owned STARTING row and V26 launch + * association. Inputs are typed source/release fixtures; this is not Account redemption, World + * activation, runtime activation, or an end-to-end launch producer proof. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameSessionCanonicalStartingInstanceRepositoryIntegrationTest { + private static final String NAMESPACE = "canonical-starting-it"; + private static final UUID TENANT = uuid(201); + private static final UUID REGISTRATION_REQUEST_ID = uuid(202); + private static final UUID SOURCE_OPERATION_ID = uuid(203); + private static final UUID INTAKE_REQUEST_ID = uuid(204); + private static final UUID TENANT_ASSOCIATION_OPERATION_ID = uuid(205); + private static final UUID CATALOG_REQUEST_ID = uuid(206); + private static final UUID CANONICAL_VERSION_ID = uuid(207); + private static final UUID OWNER_ACCOUNT_UUID = uuid(208); + private static final String CONTROL_PLANE_REQUEST_ID = "canonical-starting-control-request-1"; + private static final String REQUEST_DIGEST = "a".repeat(64); + private static final String OTHER_REQUEST_DIGEST = "b".repeat(64); + private static final String RUNTIME_FLAGS_JSON = "{\"eventMode\":true}"; + private static final String OTHER_RUNTIME_FLAGS_JSON = "{\"eventMode\":false}"; + private static final long GAME_TEMPLATE_ID = 301L; + private static final long VERSION_ID = 302L; + private static final long RELEASE_BUNDLE_ID = 303L; + private static final long VERSION_STATE_EPOCH = 7L; + private static final long SOURCE_GAME_ROW_ID = 919L; + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void createsUuidOwnedStartingRowAndAssociationAndExactRetryReturnsOriginalIdentity() { + Fixture fixture = fixture(true); + CompleteLaunchBindingEvidence binding = + launchBinding(fixture.source().source(), CONTROL_PLANE_REQUEST_ID, RUNTIME_FLAGS_JSON); + + StartingInstance first = + fixture.start(OWNER_ACCOUNT_UUID, CONTROL_PLANE_REQUEST_ID, REQUEST_DIGEST, binding); + StartingInstance retry = + fixture.start(OWNER_ACCOUNT_UUID, CONTROL_PLANE_REQUEST_ID, REQUEST_DIGEST, binding); + + assertThat(retry).isEqualTo(first); + assertThat(first.gameInstanceId()).isPositive(); + assertThat(first.gameInstanceUuid()).isNotEqualTo(new UUID(0L, 0L)); + assertThat(first.gameInstanceId()).isNotEqualTo(SOURCE_GAME_ROW_ID); + assertThat(fixture.tenantAssociation().legacyGameSessionTenantId()) + .isNotEqualTo(SOURCE_GAME_ROW_ID); + assertThat(first.launchAssociation().gameInstanceUuid()).isEqualTo(first.gameInstanceUuid()); + assertThat(first.launchAssociation().currentGameInstanceStatus().name()).isEqualTo("STARTING"); + assertThat(first.launchAssociation().capturedStartingRowVersion()).isZero(); + + Record runtime = + requiredRecord( + fixture.dsl(), + "SELECT id, tenant_id, game_instance_uuid, owner_account_id, owner_account_uuid, " + + "runtime_version, status, row_version, game_template_id, launch_descriptor_id, " + + "version_id, release_bundle_id, version_state_epoch, generation_config_revision, " + + "script_patch_version, script_patch_base_version_id, script_pin_epoch, " + + "script_patch_pinned_control_plane_request_id, run_owned_start_request_id, " + + "run_owned_start_request_digest, run_owned_start_published_release_bundle_ref " + + "FROM game_instances WHERE tenant_id = ? AND id = ?", + fixture.tenantAssociation().legacyGameSessionTenantId(), + first.gameInstanceId()); + assertThat(runtime.get("game_instance_uuid", UUID.class)).isEqualTo(first.gameInstanceUuid()); + assertThat(runtime.get("owner_account_id", Long.class)).isNull(); + assertThat(runtime.get("owner_account_uuid", UUID.class)).isEqualTo(OWNER_ACCOUNT_UUID); + assertThat(runtime.get("runtime_version", String.class)).isEqualTo(Long.toString(VERSION_ID)); + assertThat(runtime.get("status", String.class)).isEqualTo("STARTING"); + assertThat(runtime.get("row_version", Long.class)).isZero(); + assertThat(runtime.get("game_template_id", Long.class)).isEqualTo(GAME_TEMPLATE_ID); + assertThat(runtime.get("version_id", Long.class)).isEqualTo(VERSION_ID); + assertThat(runtime.get("release_bundle_id", Long.class)).isEqualTo(RELEASE_BUNDLE_ID); + assertThat(runtime.get("version_state_epoch", Long.class)).isEqualTo(VERSION_STATE_EPOCH); + assertThat(runtime.get("run_owned_start_request_id", String.class)) + .isEqualTo(CONTROL_PLANE_REQUEST_ID); + assertThat(runtime.get("run_owned_start_request_digest", String.class)) + .isEqualTo(REQUEST_DIGEST); + assertThat(runtime.get("script_patch_version", String.class)).isNull(); + assertThat(runtime.get("script_patch_base_version_id", Long.class)).isNull(); + assertThat(runtime.get("script_pin_epoch", Long.class)).isNull(); + assertThat(runtime.get("script_patch_pinned_control_plane_request_id", String.class)).isNull(); + + Record association = + requiredRecord( + fixture.dsl(), + "SELECT complete_launch_binding_evidence -> 'descriptor' ->> 'runtimeFlagsJson' " + + "AS runtime_flags, complete_launch_binding_evidence -> 'descriptor' " + + "->> 'scriptPatchVersion' AS candidate_script_patch, game_instance_uuid " + + "FROM game_session_canonical_instance_launch " + + "WHERE target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + CONTROL_PLANE_REQUEST_ID); + assertThat(association.get("runtime_flags", String.class)).isEqualTo(RUNTIME_FLAGS_JSON); + assertThat(association.get("candidate_script_patch", String.class)) + .isEqualTo("candidate-script-v1"); + assertThat(association.get("game_instance_uuid", UUID.class)) + .isEqualTo(first.gameInstanceUuid()); + assertThat(fixture.dsl().fetchCount(DSL.table(DSL.name("game_instances")))).isEqualTo(1); + assertThat( + fixture.dsl().fetchCount(DSL.table(DSL.name("game_session_canonical_instance_launch")))) + .isEqualTo(1); + assertThat(fixture.dsl().fetchCount(DSL.table(DSL.name("gameplay_admission_pointer")))) + .isZero(); + } + + @Test + void sameRequestContendersReturnOneOriginalRowAndAssociation() throws Exception { + Fixture fixture = fixture(true); + CompleteLaunchBindingEvidence binding = + launchBinding(fixture.source().source(), CONTROL_PLANE_REQUEST_ID, RUNTIME_FLAGS_JSON); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit(() -> contender(fixture, binding, ready, start)); + Future second = + executor.submit(() -> contender(fixture, binding, ready, start)); + assertThat(ready.await(15, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + StartingInstance firstResult = first.get(20, TimeUnit.SECONDS); + StartingInstance secondResult = second.get(20, TimeUnit.SECONDS); + + assertThat(firstResult).isEqualTo(secondResult); + assertThat(fixture.dsl().fetchCount(DSL.table(DSL.name("game_instances")))).isEqualTo(1); + assertThat( + fixture + .dsl() + .fetchCount(DSL.table(DSL.name("game_session_canonical_instance_launch")))) + .isEqualTo(1); + } finally { + executor.shutdownNow(); + } + } + + @Test + void changedOwnerDigestOrBindingConflictsWithoutCreatingAnotherRuntimeRow() { + Fixture fixture = fixture(true); + CompleteLaunchBindingEvidence binding = + launchBinding(fixture.source().source(), CONTROL_PLANE_REQUEST_ID, RUNTIME_FLAGS_JSON); + StartingInstance original = + fixture.start(OWNER_ACCOUNT_UUID, CONTROL_PLANE_REQUEST_ID, REQUEST_DIGEST, binding); + + assertThatThrownBy( + () -> fixture.start(uuid(209), CONTROL_PLANE_REQUEST_ID, REQUEST_DIGEST, binding)) + .isInstanceOf(CanonicalStartingInstanceConflictException.class) + .hasMessageContaining("owner"); + assertThatThrownBy( + () -> + fixture.start( + OWNER_ACCOUNT_UUID, CONTROL_PLANE_REQUEST_ID, OTHER_REQUEST_DIGEST, binding)) + .isInstanceOf(CanonicalStartingInstanceConflictException.class) + .hasMessageContaining("request digest"); + + CompleteLaunchBindingEvidence changedBinding = + launchBinding( + fixture.source().source(), CONTROL_PLANE_REQUEST_ID, OTHER_RUNTIME_FLAGS_JSON); + assertThatThrownBy( + () -> + fixture.start( + OWNER_ACCOUNT_UUID, CONTROL_PLANE_REQUEST_ID, REQUEST_DIGEST, changedBinding)) + .isInstanceOf(CanonicalGameInstanceLaunchAssociationConflictException.class) + .hasMessageContaining("changed tenant, instance, or source binding"); + + assertThat( + requiredRecord( + fixture.dsl(), + "SELECT id, game_instance_uuid FROM game_instances " + + "WHERE tenant_id = ? AND id = ?", + fixture.tenantAssociation().legacyGameSessionTenantId(), + original.gameInstanceId()) + .get("game_instance_uuid", UUID.class)) + .isEqualTo(original.gameInstanceUuid()); + assertThat(fixture.dsl().fetchCount(DSL.table(DSL.name("game_instances")))).isEqualTo(1); + assertThat( + fixture.dsl().fetchCount(DSL.table(DSL.name("game_session_canonical_instance_launch")))) + .isEqualTo(1); + } + + @Test + void invalidPersistedSourceAndMissingRealmLeaveNoPartialStartingRowOrAssociation() { + Fixture fixture = fixture(true); + CompleteLaunchBindingEvidence mismatchedSource = + launchBinding( + fixture.source().source(), CONTROL_PLANE_REQUEST_ID, RUNTIME_FLAGS_JSON, uuid(299)); + assertThatThrownBy( + () -> + fixture.start( + OWNER_ACCOUNT_UUID, CONTROL_PLANE_REQUEST_ID, REQUEST_DIGEST, mismatchedSource)) + .isInstanceOf(InvalidCanonicalStartingInstanceEvidenceException.class) + .hasMessageContaining("persisted authored-world source receipt"); + assertNoStartingRows(fixture); + + Fixture missingRealm = fixture(false); + CompleteLaunchBindingEvidence validBinding = + launchBinding(missingRealm.source().source(), CONTROL_PLANE_REQUEST_ID, RUNTIME_FLAGS_JSON); + assertThatThrownBy( + () -> + missingRealm.start( + OWNER_ACCOUNT_UUID, CONTROL_PLANE_REQUEST_ID, REQUEST_DIGEST, validBinding)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("visible public SHARED realm"); + assertNoStartingRows(missingRealm); + } + + private static StartingInstance contender( + Fixture fixture, + CompleteLaunchBindingEvidence binding, + CountDownLatch ready, + CountDownLatch start) + throws InterruptedException { + ready.countDown(); + if (!start.await(15, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent STARTING contender gate was not released"); + } + return fixture.start(OWNER_ACCOUNT_UUID, CONTROL_PLANE_REQUEST_ID, REQUEST_DIGEST, binding); + } + + private static void assertNoStartingRows(Fixture fixture) { + assertThat(fixture.dsl().fetchCount(DSL.table(DSL.name("game_instances")))).isZero(); + assertThat( + fixture.dsl().fetchCount(DSL.table(DSL.name("game_session_canonical_instance_launch")))) + .isZero(); + } + + private static CompleteLaunchBindingEvidence launchBinding( + AuthoredWorldSourceEvidence source, String requestId, String runtimeFlagsJson) { + return launchBinding(source, requestId, runtimeFlagsJson, source.operationId()); + } + + private static CompleteLaunchBindingEvidence launchBinding( + AuthoredWorldSourceEvidence source, + String requestId, + String runtimeFlagsJson, + UUID authoredWorldSourceOperationId) { + AuthoredWorldLaunchDescriptorEvidence.Request descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + requestId, + source.canonicalTenantId(), + source.worldSlug(), + authoredWorldSourceOperationId, + source.evidenceDigest(), + GAME_TEMPLATE_ID, + true, + "candidate-script-v1", + false, + null, + false, + null, + true, + runtimeFlagsJson); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "descriptor-for-starting", + VERSION_ID, + true, + "candidate-script-v1", + runtimeFlagsJson, + "generation-config-8", + VERSION_STATE_EPOCH, + RELEASE_BUNDLE_ID, + "published-release-bundle-303", + false, + null); + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(VERSION_ID), + false, + null, + "commit-starting-303", + "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence release = + AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + source.canonicalTenantId(), + CANONICAL_VERSION_ID, + source.worldSlug(), + authoredWorldSourceOperationId, + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish-starting-303", + "commit-starting-303", + participants, + "sha256:" + "e".repeat(64), + 1, + List.of(), + List.of(), + List.of("LOOK"), + descriptor.generationConfigRevision()); + return new CompleteLaunchBindingEvidence(descriptor, release); + } + + private static AuthoredWorldSourceEvidence freshSource() { + String tenantSlug = "fresh-tenant-" + TENANT.toString().substring(0, 8); + String worldSlug = "amber-reach"; + String displayName = "Amber Reach"; + String sourceKey = "gd-source-game-919"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, REGISTRATION_REQUEST_ID, TENANT, tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT, + tenantSlug, + worldSlug, + displayName, + SOURCE_GAME_ROW_ID, + sourceKey, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT, + tenantSlug, + worldSlug, + displayName, + SOURCE_GAME_ROW_ID, + sourceKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static Record requiredRecord(DSLContext dsl, String sql, Object... bindings) { + return Objects.requireNonNull(dsl.fetchOne(sql, bindings), "Expected owner row is missing"); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } + + private record Fixture( + DSLContext dsl, + TransactionTemplate transactions, + GameSessionAuthoredWorldSourceRepository sourceRepository, + GameSessionFreshTenantAssociationRepository tenantAssociationRepository, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + GameSessionCanonicalStartingInstanceRepository startingRepository, + IntakeReceipt source, + FreshGameSessionTenantAssociation tenantAssociation) { + StartingInstance start( + UUID ownerAccountUuid, + String controlPlaneRequestId, + String requestDigest, + CompleteLaunchBindingEvidence binding) { + return Objects.requireNonNull( + transactions.execute( + status -> + startingRepository.createStarting( + tenantAssociation, + binding, + ownerAccountUuid, + controlPlaneRequestId, + requestDigest)), + "canonical STARTING owner result"); + } + } + + private static Fixture fixture(boolean createRealm) { + String schema = "gs_starting_owner_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + GameSessionAuthoredWorldSourceRepository sourceRepository = + new GameSessionAuthoredWorldSourceRepository(dsl); + GameSessionFreshTenantAssociationRepository tenantAssociationRepository = + new GameSessionFreshTenantAssociationRepository(dsl); + GameSessionCanonicalRealmCatalogRepository catalogRepository = + new GameSessionCanonicalRealmCatalogRepository(dsl); + GameSessionCanonicalStartingInstanceRepository startingRepository = + new GameSessionCanonicalStartingInstanceRepository(dsl, NAMESPACE); + + IntakeReceipt source = + Objects.requireNonNull( + transactions.execute( + status -> sourceRepository.register(INTAKE_REQUEST_ID, freshSource())), + "registered authored-world source receipt"); + if (createRealm) { + var request = + new CreateCanonicalRealmCatalogRequest( + CATALOG_REQUEST_ID, + NAMESPACE, + TENANT, + source.operationId(), + "amber-realm", + "Amber Realm", + true, + true, + "SHARED", + "explicit-policy-v1", + null, + null); + var prepared = catalogRepository.prepareInitialPublicProduction(request); + transactions.execute(status -> catalogRepository.createInitialPublicProduction(prepared)); + } + FreshGameSessionTenantAssociation tenantAssociation = + Objects.requireNonNull( + transactions.execute( + status -> + tenantAssociationRepository.associateFresh( + TENANT_ASSOCIATION_OPERATION_ID, NAMESPACE, source)), + "fresh source-bound Game Session tenant association"); + return new Fixture( + dsl, + transactions, + sourceRepository, + tenantAssociationRepository, + catalogRepository, + startingRepository, + source, + tenantAssociation); + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java new file mode 100644 index 0000000000..eaff698f94 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java @@ -0,0 +1,500 @@ +package integration.net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldIntakeDigest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository.FreshTenantAssociationConflictException; +import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository.InvalidFreshTenantSourceException; +import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** PostgreSQL proof for the V25 fresh-source-bound tenant owner producer. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameSessionFreshTenantAssociationRepositoryIntegrationTest { + private static final String NAMESPACE = "fresh-tenant-association-it"; + private static final UUID TENANT = uuid(601); + private static final UUID REGISTRATION_REQUEST = uuid(602); + private static final UUID SOURCE_OPERATION = uuid(603); + private static final UUID INTAKE_REQUEST = uuid(604); + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void allocatesPrivateIdentityAndReturnsTheOriginalExactAssociationOnRetry() { + Fixture fixture = fixture(); + IntakeReceipt source = fixture.registerFreshSource(); + UUID associationOperationId = uuid(605); + + FreshGameSessionTenantAssociation first = + fixture.associate(associationOperationId, NAMESPACE, source); + FreshGameSessionTenantAssociation retry = + fixture.associate(associationOperationId, NAMESPACE, source); + + assertThat(retry).isEqualTo(first); + assertThat(first.associationOperationId()).isEqualTo(associationOperationId); + assertThat(first.legacyGameSessionTenantId()).isPositive(); + assertThat(first.legacyGameSessionTenantId()).isNotEqualTo(source.source().sourceGameRowId()); + assertThat(first.sourceEvidence().requestId()) + .isEqualTo(source.source().registrationRequestId()); + assertThat(first.sourceEvidence().canonicalTenantId()).isEqualTo(TENANT); + assertThat(first.sourceEvidence().provenanceKind()).isEqualTo("NEW_GAME_ROW"); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_tenant_scope_reservation")))) + .isEqualTo(1); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_tenant_canonical_claim")))) + .isEqualTo(1); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_fresh_tenant_association")))) + .isEqualTo(1); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_instances")))).isZero(); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer")))).isZero(); + assertThat( + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT reservation_kind FROM game_session_tenant_scope_reservation " + + "WHERE game_session_tenant_id = ?", + first.legacyGameSessionTenantId()), + "expected fresh source-bound reservation row") + .get("reservation_kind", String.class)) + .isEqualTo("FRESH_SOURCE_BOUND"); + } + + @Test + void rejectsChangedReceiptMissingReceiptAndNamespaceMismatchBeforeAllocation() { + Fixture fixture = fixture(); + IntakeReceipt source = fixture.registerFreshSource(); + UUID associationOperationId = uuid(606); + + assertThatThrownBy( + () -> fixture.associate(associationOperationId, NAMESPACE, changedReceipt(source))) + .isInstanceOf(InvalidFreshTenantSourceException.class) + .hasMessageContaining("differs from the requested exact receipt"); + assertThatThrownBy( + () -> fixture.associate(associationOperationId, NAMESPACE + "-other", source)) + .isInstanceOf(FreshTenantAssociationConflictException.class) + .hasMessageContaining("namespace"); + + IntakeReceipt missing = receiptFor(uuid(607), freshSource(uuid(608), uuid(609), TENANT, 960L)); + assertThatThrownBy(() -> fixture.associate(associationOperationId, NAMESPACE, missing)) + .isInstanceOf(InvalidFreshTenantSourceException.class) + .hasMessageContaining("is missing"); + + assertNoFreshAssociation(fixture); + } + + @Test + void rejectsSameOperationWithDifferentSourceOrNamespaceAsAnIdempotencyConflict() { + Fixture fixture = fixture(); + IntakeReceipt firstSource = fixture.registerFreshSource(); + IntakeReceipt secondSource = + fixture.registerSource(uuid(610), uuid(611), uuid(612), uuid(613), 962L, "second-world"); + UUID associationOperationId = uuid(615); + + FreshGameSessionTenantAssociation committed = + fixture.associate(associationOperationId, NAMESPACE, firstSource); + assertThatThrownBy(() -> fixture.associate(associationOperationId, NAMESPACE, secondSource)) + .isInstanceOf(FreshTenantAssociationConflictException.class) + .hasMessageContaining("different source or namespace"); + assertThatThrownBy( + () -> fixture.associate(associationOperationId, NAMESPACE + "-other", firstSource)) + .isInstanceOf(FreshTenantAssociationConflictException.class); + + assertThat( + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT legacy_game_session_tenant_id FROM game_session_fresh_tenant_association " + + "WHERE association_operation_id = ?", + associationOperationId), + "expected retained fresh tenant association row") + .get("legacy_game_session_tenant_id", Long.class)) + .isEqualTo(committed.legacyGameSessionTenantId()); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_tenant_scope_reservation")))) + .isEqualTo(1); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_tenant_canonical_claim")))) + .isEqualTo(1); + } + + @Test + void oneConcurrentContenderOwnsTheCanonicalTenantMapping() throws Exception { + Fixture fixture = fixture(); + IntakeReceipt source = fixture.registerFreshSource(); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit(() -> contender(fixture, uuid(616), source, ready, start)); + Future second = + executor.submit(() -> contender(fixture, uuid(617), source, ready, start)); + assertThat(ready.await(15, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + Attempt firstResult = first.get(20, TimeUnit.SECONDS); + Attempt secondResult = second.get(20, TimeUnit.SECONDS); + + assertThat(firstResult.conflict()).isNotEqualTo(secondResult.conflict()); + FreshGameSessionTenantAssociation owner = + firstResult.conflict() ? secondResult.association() : firstResult.association(); + assertThat(owner).isNotNull(); + assertThat( + fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_tenant_scope_reservation")))) + .isEqualTo(1); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_tenant_canonical_claim")))) + .isEqualTo(1); + assertThat( + fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_fresh_tenant_association")))) + .isEqualTo(1); + } finally { + executor.shutdownNow(); + } + } + + @Test + void retainedSourceProvenanceCannotCreateAFreshTenantMapping() { + Fixture fixture = fixture(); + IntakeReceipt retainedSource = fixture.registerRetainedSource(uuid(618)); + assertThat(retainedSource.source().provenanceKind()).isEqualTo("RETAINED_GAME_V29"); + String bindingXmin = + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT xmin::text AS xmin FROM game_session_authored_world_tenant_source_binding " + + "WHERE canonical_tenant_id = ?", + retainedSource.source().canonicalTenantId()), + "expected retained tenant source binding") + .get("xmin", String.class); + String intakeXmin = + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT xmin::text AS xmin FROM game_session_authored_world_source_intake " + + "WHERE operation_id = ?", + retainedSource.operationId()), + "expected retained source intake") + .get("xmin", String.class); + + assertThatThrownBy(() -> fixture.associate(uuid(622), NAMESPACE, retainedSource)) + .isInstanceOf(InvalidFreshTenantSourceException.class) + .hasMessageContaining("NEW_GAME_ROW"); + + assertThat( + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT xmin::text AS xmin, provenance_kind " + + "FROM game_session_authored_world_tenant_source_binding " + + "WHERE canonical_tenant_id = ?", + retainedSource.source().canonicalTenantId()), + "expected retained tenant source binding after denial")) + .satisfies( + row -> { + assertThat(row.get("xmin", String.class)).isEqualTo(bindingXmin); + assertThat(row.get("provenance_kind", String.class)).isEqualTo("RETAINED_GAME_V29"); + }); + assertThat( + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT xmin::text AS xmin, source_provenance_kind " + + "FROM game_session_authored_world_source_intake WHERE operation_id = ?", + retainedSource.operationId()), + "expected retained source intake after denial")) + .satisfies( + row -> { + assertThat(row.get("xmin", String.class)).isEqualTo(intakeXmin); + assertThat(row.get("source_provenance_kind", String.class)) + .isEqualTo("RETAINED_GAME_V29"); + }); + assertNoFreshAssociation(fixture); + } + + private static Attempt contender( + Fixture fixture, + UUID associationOperationId, + IntakeReceipt source, + CountDownLatch ready, + CountDownLatch start) + throws InterruptedException { + ready.countDown(); + if (!start.await(15, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent tenant association gate was not released"); + } + try { + return new Attempt(fixture.associate(associationOperationId, NAMESPACE, source), false); + } catch (FreshTenantAssociationConflictException conflict) { + return new Attempt(null, true); + } + } + + private static void assertNoFreshAssociation(Fixture fixture) { + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_tenant_scope_reservation")))) + .isZero(); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_tenant_canonical_claim")))) + .isZero(); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_fresh_tenant_association")))) + .isZero(); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_instances")))).isZero(); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer")))).isZero(); + } + + private static IntakeReceipt changedReceipt(IntakeReceipt receipt) { + AuthoredWorldSourceEvidence source = receipt.source(); + String changedName = source.worldDisplayName() + " changed"; + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + source.targetNamespace(), + source.registrationRequestId(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + changedName); + String sourceEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + source.targetNamespace(), + source.registrationRequestId(), + source.operationId(), + sourceRequestDigest, + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + changedName, + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()); + AuthoredWorldSourceEvidence changedSource = + new AuthoredWorldSourceEvidence( + source.schemaVersion(), + source.targetNamespace(), + source.registrationRequestId(), + source.operationId(), + sourceRequestDigest, + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + changedName, + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + sourceEvidenceDigest); + return receiptFor(receipt.operationId(), receipt.intakeRequestId(), changedSource); + } + + private static IntakeReceipt receiptFor(UUID operationId, AuthoredWorldSourceEvidence source) { + return receiptFor(operationId, uuid(623), source); + } + + private static IntakeReceipt receiptFor( + UUID operationId, UUID intakeRequestId, AuthoredWorldSourceEvidence source) { + String requestDigest = + GameSessionAuthoredWorldIntakeDigest.requestDigest(intakeRequestId, source); + return new IntakeReceipt( + operationId, + intakeRequestId, + requestDigest, + source, + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + operationId, requestDigest, source.evidenceDigest())); + } + + private static AuthoredWorldSourceEvidence freshSource( + UUID registrationRequestId, + UUID sourceOperationId, + UUID canonicalTenantId, + long sourceRowId) { + return freshSource( + registrationRequestId, sourceOperationId, canonicalTenantId, sourceRowId, "source-world"); + } + + private static AuthoredWorldSourceEvidence freshSource( + UUID registrationRequestId, + UUID sourceOperationId, + UUID canonicalTenantId, + long sourceRowId, + String worldSlug) { + return sourceWithProvenance( + registrationRequestId, + sourceOperationId, + canonicalTenantId, + sourceRowId, + worldSlug, + "NEW_GAME_ROW"); + } + + private static AuthoredWorldSourceEvidence sourceWithProvenance( + UUID registrationRequestId, + UUID sourceOperationId, + UUID canonicalTenantId, + long sourceRowId, + String worldSlug, + String provenanceKind) { + String tenantSlug = "fresh-tenant-" + canonicalTenantId.toString().substring(0, 8); + String displayName = "Fresh World"; + String sourceKey = "game-design-source-" + sourceRowId; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + displayName, + sourceRowId, + sourceKey, + provenanceKind); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + displayName, + sourceRowId, + sourceKey, + provenanceKind, + evidenceDigest); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } + + private record Attempt(FreshGameSessionTenantAssociation association, boolean conflict) {} + + private record Fixture( + DSLContext dsl, + TransactionTemplate transactions, + GameSessionAuthoredWorldSourceRepository sourceRepository, + GameSessionFreshTenantAssociationRepository associationRepository) { + IntakeReceipt registerFreshSource() { + return registerSource( + INTAKE_REQUEST, REGISTRATION_REQUEST, SOURCE_OPERATION, TENANT, 961L, "source-world"); + } + + IntakeReceipt registerSource( + UUID intakeRequestId, + UUID registrationRequestId, + UUID sourceOperationId, + UUID canonicalTenantId, + long sourceRowId, + String worldSlug) { + return registerSource( + intakeRequestId, + registrationRequestId, + sourceOperationId, + canonicalTenantId, + sourceRowId, + worldSlug, + "NEW_GAME_ROW"); + } + + IntakeReceipt registerRetainedSource(UUID intakeRequestId) { + return registerSource( + intakeRequestId, + uuid(625), + uuid(626), + uuid(624), + 964L, + "retained-world", + "RETAINED_GAME_V29"); + } + + IntakeReceipt registerSource( + UUID intakeRequestId, + UUID registrationRequestId, + UUID sourceOperationId, + UUID canonicalTenantId, + long sourceRowId, + String worldSlug, + String provenanceKind) { + AuthoredWorldSourceEvidence source = + sourceWithProvenance( + registrationRequestId, + sourceOperationId, + canonicalTenantId, + sourceRowId, + worldSlug, + provenanceKind); + return transactions.execute(status -> sourceRepository.register(intakeRequestId, source)); + } + + FreshGameSessionTenantAssociation associateFresh( + UUID associationOperationId, String namespace, IntakeReceipt source) { + return transactions.execute( + status -> + associationRepository.associateFresh(associationOperationId, namespace, source)); + } + + FreshGameSessionTenantAssociation associate( + UUID associationOperationId, String namespace, IntakeReceipt source) { + return Objects.requireNonNull( + associateFresh(associationOperationId, namespace, source), + "fresh tenant association result"); + } + } + + private Fixture fixture() { + String schema = "gs_fresh_tenant_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new Fixture( + dsl, + transactions, + new GameSessionAuthoredWorldSourceRepository(dsl), + new GameSessionFreshTenantAssociationRepository(dsl)); + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java index 77f5e98e5f..bdf726862d 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java @@ -22,6 +22,7 @@ import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec.Resolved; import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; @@ -300,6 +301,153 @@ void exactAccountProjectionAttachesOnceWhileFingerprintAndSourceSubstitutionsCon .isEqualTo(1); } + @Test + void currentOriginalAttemptReadReturnsExactAttachedSnapshotWithoutChangingPersistedRow() { + Fixture fixture = fixture(Duration.ofSeconds(30)); + StartSessionPostAuthorizationExecutionTuple tuple = tuple("operator-attempt-current-read"); + AttemptClaim claim = fixture.reserve(tuple).claim().orElseThrow(); + AttemptSnapshot attached = + fixture.attach( + claim, + projection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + ISSUANCE_ID, + 23L)); + Request request = currentAttemptRequest(tuple, claim); + String before = fixture.ownerAttemptRowJson(tuple.controlPlaneRequestId()); + + AttemptSnapshot current = fixture.currentOriginalAttempt(request); + + assertThat(current.ownerAttemptId()).isEqualTo(claim.ownerAttemptId()); + assertThat(current.ownerMutationId()).isEqualTo(claim.ownerMutationId()); + assertThat(current.ownerFence()).isEqualTo(claim.ownerFence()); + assertThat(current.phaseState()).isEqualTo("OWNER_EXECUTION_PENDING"); + assertThat(current.leaseExpiresAt()).isEqualTo(attached.leaseExpiresAt()); + assertThat(current.postAuthorizationExecutionTuple()).containsExactly(tuple.canonicalBytes()); + assertThat(current.accountRedemptionProjection()) + .containsExactly(attached.accountRedemptionProjection()); + assertThat(fixture.ownerAttemptRowJson(tuple.controlPlaneRequestId())).isEqualTo(before); + } + + @Test + void currentOriginalAttemptReadRejectsExpiredAndUnattachedOrMismatchedEvidenceWithoutMutation() + throws Exception { + Fixture unattached = fixture(Duration.ofSeconds(30)); + StartSessionPostAuthorizationExecutionTuple unattachedTuple = + tuple("operator-attempt-current-read-unattached"); + AttemptClaim unattachedClaim = unattached.reserve(unattachedTuple).claim().orElseThrow(); + String unattachedBefore = + unattached.ownerAttemptRowJson(unattachedTuple.controlPlaneRequestId()); + assertThatThrownBy( + () -> + unattached.currentOriginalAttempt( + currentAttemptRequest(unattachedTuple, unattachedClaim))) + .isInstanceOf(StaleStartSessionOperatorAttemptClaimException.class) + .hasMessageContaining("no attached Account projection"); + assertThat(unattached.ownerAttemptRowJson(unattachedTuple.controlPlaneRequestId())) + .isEqualTo(unattachedBefore); + + Fixture mismatched = fixture(Duration.ofSeconds(30)); + StartSessionPostAuthorizationExecutionTuple tuple = + tuple("operator-attempt-current-read-mismatch"); + AttemptClaim claim = mismatched.reserve(tuple).claim().orElseThrow(); + mismatched.attach( + claim, + projection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + ISSUANCE_ID, + 23L)); + String before = mismatched.ownerAttemptRowJson(tuple.controlPlaneRequestId()); + assertThatThrownBy( + () -> + mismatched.currentOriginalAttempt( + currentAttemptRequest( + tuple, + UUID.fromString("1819a1ce-04d2-4e3f-bb64-4a672d4eb711"), + claim.ownerMutationId(), + claim.ownerFence()))) + .isInstanceOf(StaleStartSessionOperatorAttemptClaimException.class); + assertThatThrownBy( + () -> + mismatched.currentOriginalAttempt( + currentAttemptRequest( + tuple, + claim.ownerAttemptId(), + UUID.fromString("2819a1ce-04d2-4e3f-bb64-4a672d4eb711"), + claim.ownerFence()))) + .isInstanceOf(StaleStartSessionOperatorAttemptClaimException.class); + assertThatThrownBy( + () -> + mismatched.currentOriginalAttempt( + currentAttemptRequest( + tuple, + claim.ownerAttemptId(), + claim.ownerMutationId(), + claim.ownerFence() + 1L))) + .isInstanceOf(StaleStartSessionOperatorAttemptClaimException.class); + StartSessionPostAuthorizationExecutionTuple changedTuple = + tuple(tuple.controlPlaneRequestId(), "different complete action"); + assertThatThrownBy( + () -> mismatched.currentOriginalAttempt(currentAttemptRequest(changedTuple, claim))) + .isInstanceOf( + GameSessionStartSessionOperatorAttemptRepository + .StartSessionOperatorAttemptConflictException.class); + assertThat(mismatched.ownerAttemptRowJson(tuple.controlPlaneRequestId())).isEqualTo(before); + + Fixture expired = fixture(Duration.ofMillis(500)); + StartSessionPostAuthorizationExecutionTuple expiredTuple = + tuple("operator-attempt-current-read-expired"); + AttemptClaim expiredClaim = expired.reserve(expiredTuple).claim().orElseThrow(); + expired.attach( + expiredClaim, + projection( + expiredTuple.authorizationReferenceFingerprint(), + expiredTuple.authorityEvidenceBundleBytes(), + ISSUANCE_ID, + 23L)); + Thread.sleep(750L); + String expiredBefore = expired.ownerAttemptRowJson(expiredTuple.controlPlaneRequestId()); + assertThat(expired.leaseExpired(expiredTuple.controlPlaneRequestId())).isTrue(); + assertThatThrownBy( + () -> expired.currentOriginalAttempt(currentAttemptRequest(expiredTuple, expiredClaim))) + .isInstanceOf(StaleStartSessionOperatorAttemptClaimException.class) + .hasMessageContaining("expired"); + assertThat(expired.ownerAttemptRowJson(expiredTuple.controlPlaneRequestId())) + .isEqualTo(expiredBefore); + } + + @Test + void currentOriginalAttemptReadRejectsExpiredAccountReferenceWithLiveClaimWithoutMutation() { + Fixture fixture = fixture(Duration.ofMinutes(1)); + StartSessionPostAuthorizationExecutionTuple tuple = + tuple( + "operator-attempt-current-read-reference-expired", + "canonical StartSession owner attempt", + RESERVATION_OWNER, + 19L, + FINGERPRINT, + Instant.now().truncatedTo(ChronoUnit.MILLIS).minusSeconds(5)); + AttemptClaim claim = fixture.reserve(tuple).claim().orElseThrow(); + fixture.attach( + claim, + projection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + ISSUANCE_ID, + 23L)); + String before = fixture.ownerAttemptRowJson(tuple.controlPlaneRequestId()); + assertThat(fixture.leaseExpired(tuple.controlPlaneRequestId())).isFalse(); + + assertThatThrownBy(() -> fixture.currentOriginalAttempt(currentAttemptRequest(tuple, claim))) + .isInstanceOf(StaleStartSessionOperatorAttemptClaimException.class) + .hasMessageContaining("authorization reference expired"); + + assertThat(fixture.leaseExpired(tuple.controlPlaneRequestId())).isFalse(); + assertThat(fixture.ownerAttemptRowJson(tuple.controlPlaneRequestId())).isEqualTo(before); + } + @Test void historicalOwnerReadAcceptsExpiredExactAttemptWithoutChangingOwnerState() throws Exception { Fixture fixture = fixture(Duration.ofMillis(500)); @@ -840,6 +988,26 @@ private static AccountRedemptionProjection projection( return new AccountRedemptionProjection(fingerprint, bundle, issuanceOperationId, issuanceFence); } + private static Request currentAttemptRequest( + StartSessionPostAuthorizationExecutionTuple tuple, AttemptClaim claim) { + return currentAttemptRequest( + tuple, claim.ownerAttemptId(), claim.ownerMutationId(), claim.ownerFence()); + } + + private static Request currentAttemptRequest( + StartSessionPostAuthorizationExecutionTuple tuple, + UUID expectedAttemptId, + UUID expectedMutationId, + long expectedFence) { + return new Request( + UUID.fromString("01111111-1111-4111-8111-111111111111"), + NAMESPACE, + tuple.canonicalBytes(), + expectedAttemptId, + expectedMutationId, + expectedFence); + } + private static byte[] bundle( StartSessionPreAuthorizationReservationTuple tuple, String version, String sourceEvidenceId) { return bundle(tuple, version, sourceEvidenceId, Instant.parse("2099-01-01T00:05:00Z")); @@ -1055,6 +1223,12 @@ AttemptSnapshot validate(AttemptClaim claim) { "StartSession attempt claim snapshot"); } + AttemptSnapshot currentOriginalAttempt(Request request) { + return Objects.requireNonNull( + transactions.execute(status -> repository.readCurrentOriginalAttempt(request)), + "Current original StartSession attempt snapshot"); + } + EvidenceContinuation continueEvidence(StartSessionPostAuthorizationExecutionTuple tuple) { return Objects.requireNonNull( transactions.execute(status -> repository.beginEvidenceContinuation(tuple)), @@ -1095,6 +1269,19 @@ org.jooq.Record ownerClaimRow(String requestId) { "persisted owner attempt row"); } + String ownerAttemptRowJson(String requestId) { + org.jooq.Record row = + dsl.fetchOne( + "SELECT to_jsonb(attempt)::text FROM " + + "game_session_start_session_operator_attempt AS attempt " + + "WHERE target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + requestId); + return Objects.requireNonNull( + Objects.requireNonNull(row, "persisted owner attempt row").get(0, String.class), + "persisted owner attempt row JSON"); + } + boolean leaseExpired(String requestId) { var row = dsl.fetchOne( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignClientTest.java index dbffae7fcb..f8bc4e0f33 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignClientTest.java @@ -120,13 +120,53 @@ void rejectsNonpositiveBaseVersionAsInvalidArgumentWithoutCallingGameDesign(long verifyNoInteractions(stub); } + @Test + void legacyNumericLaunchResolveFailsClosedWithoutStubOrChannelInteraction() throws Exception { + GameDesignServiceGrpc.GameDesignServiceBlockingStub stub = + mock(GameDesignServiceGrpc.GameDesignServiceBlockingStub.class); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + GameDesignClient client = newClient(stub, channelFactory); + + ResolveLaunchDescriptorResponse response = client.resolveLaunchDescriptor(1L, 9L, "cp-1"); + + assertLaunchBindingRequired(response); + verifyNoInteractions(stub, channelFactory); + } + + @Test + void legacyNumericReplacementLaunchResolveFailsClosedWithoutStubOrChannelInteraction() + throws Exception { + GameDesignServiceGrpc.GameDesignServiceBlockingStub stub = + mock(GameDesignServiceGrpc.GameDesignServiceBlockingStub.class); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + GameDesignClient client = newClient(stub, channelFactory); + + ResolveLaunchDescriptorResponse response = + client.resolveLaunchDescriptor(1L, 9L, "cp-1", 7L, 8L); + + assertLaunchBindingRequired(response); + verifyNoInteractions(stub, channelFactory); + } + + private static void assertLaunchBindingRequired(ResolveLaunchDescriptorResponse response) { + assertThat(response.getError().getCode()).isEqualTo("AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED"); + assertThat(response.getError().getMessage()) + .contains("Canonical authored-world source binding is required"); + } + private static GameDesignClient newClient( GameDesignServiceGrpc.GameDesignServiceBlockingStub stub) throws Exception { + return newClient(stub, mock(GrpcChannelFactory.class)); + } + + private static GameDesignClient newClient( + GameDesignServiceGrpc.GameDesignServiceBlockingStub stub, GrpcChannelFactory channelFactory) + throws Exception { GameDesignClient client = new GameDesignClient( new ServiceEndpointsProperties(), new CommonGrpcClientProperties(), - mock(GrpcChannelFactory.class), + channelFactory, BlockingGrpcStubCustomizer.noop()); Field field = AbstractBlockingGrpcClient.class.getDeclaredField("stub"); field.setAccessible(true); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalGameInstanceLaunchAssociationReadConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalGameInstanceLaunchAssociationReadConfigurationTest.java new file mode 100644 index 0000000000..7de92397fc --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalGameInstanceLaunchAssociationReadConfigurationTest.java @@ -0,0 +1,58 @@ +package unit.net.firedevops.firemud.gamesession.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +import net.firedevops.firemud.gamesession.config.CanonicalGameInstanceLaunchAssociationReadConfiguration; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; + +class CanonicalGameInstanceLaunchAssociationReadConfigurationTest { + private static final String OWNER_OPT_IN = + "firemud.canonical-game-instance-launch-association-owner-read.enabled"; + + @Test + void associationOwnerRepositoryIsDisabledByDefault() { + new ApplicationContextRunner() + .withUserConfiguration( + CanonicalGameInstanceLaunchAssociationReadConfiguration.class, Dependencies.class) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context) + .doesNotHaveBean(CanonicalGameInstanceLaunchAssociationRepository.class); + }); + } + + @Test + void explicitOptInRequiresAndUsesTheExactWorkloadNamespace() { + new ApplicationContextRunner() + .withUserConfiguration( + CanonicalGameInstanceLaunchAssociationReadConfiguration.class, Dependencies.class) + .withPropertyValues(OWNER_OPT_IN + "=true", "firemud.grpc.workload-namespace=gameplay") + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context) + .hasSingleBean(CanonicalGameInstanceLaunchAssociationRepository.class); + }); + + new ApplicationContextRunner() + .withUserConfiguration( + CanonicalGameInstanceLaunchAssociationReadConfiguration.class, Dependencies.class) + .withPropertyValues(OWNER_OPT_IN + "=true") + .run(context -> assertThat(context).hasFailed()); + } + + @TestConfiguration(proxyBeanMethods = false) + static class Dependencies { + @Bean + DSLContext dsl() { + return mock(DSLContext.class); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfigurationTest.java new file mode 100644 index 0000000000..7aa4812c98 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfigurationTest.java @@ -0,0 +1,112 @@ +package unit.net.firedevops.firemud.gamesession.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +import net.firedevops.firemud.gamesession.config.CanonicalGameInstanceLaunchAssociationReadConfiguration; +import net.firedevops.firemud.gamesession.config.CanonicalInitialAdmissionOwnerConfiguration; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; +import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionService; +import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionWorldVerifier; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.transaction.PlatformTransactionManager; + +class CanonicalInitialAdmissionOwnerConfigurationTest { + private static final String OWNER_OPT_IN = + "firemud.canonical-game-instance-launch-association-owner-read.enabled"; + + @Test + void disabledOwnerCompositionDoesNotRequireCanonicalLaunchRepositories() { + new ApplicationContextRunner() + .withUserConfiguration(CanonicalInitialAdmissionOwnerConfiguration.class) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(CanonicalInitialAdmissionRepository.class); + assertThat(context).doesNotHaveBean(CanonicalInitialAdmissionService.class); + }); + } + + @Test + void enabledOwnerCompositionFailsClosedWithoutItsExplicitLaunchPrerequisite() { + new ApplicationContextRunner() + .withUserConfiguration(CanonicalInitialAdmissionOwnerConfiguration.class) + .withPropertyValues(OWNER_OPT_IN + "=true") + .run(context -> assertThat(context).hasFailed()); + } + + @Test + void enabledCompositionCreatesOwnerServiceOnlyWithItsExplicitDependencies() { + new ApplicationContextRunner() + .withUserConfiguration( + CanonicalGameInstanceLaunchAssociationReadConfiguration.class, + CanonicalInitialAdmissionOwnerConfiguration.class, + OwnerDependencies.class) + .withPropertyValues(OWNER_OPT_IN + "=true", "firemud.grpc.workload-namespace=gameplay") + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).hasSingleBean(CanonicalInitialAdmissionRepository.class); + assertThat(context).hasSingleBean(CanonicalInitialAdmissionService.class); + }); + } + + @Test + void enabledCompositionFailsClosedWithoutOwnerTransactionManager() { + new ApplicationContextRunner() + .withUserConfiguration( + CanonicalGameInstanceLaunchAssociationReadConfiguration.class, + CanonicalInitialAdmissionOwnerConfiguration.class, + OwnerDependencies.class) + .withPropertyValues( + OWNER_OPT_IN + "=true", + "firemud.grpc.workload-namespace=gameplay", + "test.initial-admission.transaction-manager-enabled=false") + .run(context -> assertThat(context).hasFailed()); + } + + @TestConfiguration(proxyBeanMethods = false) + static class OwnerDependencies { + @Bean + DSLContext initialAdmissionDsl() { + return mock(DSLContext.class); + } + + @Bean(name = "transactionManager") + @ConditionalOnProperty( + name = "test.initial-admission.transaction-manager-enabled", + havingValue = "true", + matchIfMissing = true) + PlatformTransactionManager initialAdmissionTransactionManager() { + return mock(PlatformTransactionManager.class); + } + + @Bean + GameSessionCanonicalRealmCatalogRepository initialAdmissionCatalogRepository() { + return mock(GameSessionCanonicalRealmCatalogRepository.class); + } + + @Bean + GameSessionCanonicalAdmissionPointerRepository initialAdmissionPointerRepository() { + return mock(GameSessionCanonicalAdmissionPointerRepository.class); + } + + @Bean + GameplayAdmissionPointerEventRepository initialAdmissionEventRepository() { + return mock(GameplayAdmissionPointerEventRepository.class); + } + + @Bean + CanonicalInitialAdmissionWorldVerifier initialAdmissionWorldVerifier() { + return mock(CanonicalInitialAdmissionWorldVerifier.class); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionStartSessionOperatorAuthorizationConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionStartSessionOperatorAuthorizationConfigurationTest.java new file mode 100644 index 0000000000..0c9a99d052 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionStartSessionOperatorAuthorizationConfigurationTest.java @@ -0,0 +1,312 @@ +package unit.net.firedevops.firemud.gamesession.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import io.grpc.ManagedChannel; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.gamesession.client.StartSessionOperatorRedemptionClient; +import net.firedevops.firemud.gamesession.config.GameSessionStartSessionOperatorAuthorizationConfiguration; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.service.GameSessionStartSessionOperatorAuthorizationCoordinator; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.convert.ApplicationConversionService; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.core.convert.ConversionService; +import org.springframework.core.env.Environment; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +class GameSessionStartSessionOperatorAuthorizationConfigurationTest { + private static final String OWNER_OPT_IN = "firemud.start-session-operator-authorization.enabled"; + private static final String OWNER_CLAIM_LEASE = + "firemud.start-session-operator-authorization.owner-claim-lease"; + private static final String WORKLOAD_NAMESPACE = "firemud.grpc.workload-namespace"; + private static final String TLS_RELOAD_PROPERTY = "firemud.grpc.tls-reload.enabled"; + + @Test + void ownerAuthorizationCompositionIsDisabledByDefault() { + new ApplicationContextRunner() + .withUserConfiguration(GameSessionStartSessionOperatorAuthorizationConfiguration.class) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context) + .doesNotHaveBean(GameSessionStartSessionOperatorAttemptRepository.class); + assertThat(context).doesNotHaveBean(StartSessionOperatorRedemptionClient.class); + assertThat(context) + .doesNotHaveBean(GameSessionStartSessionOperatorAuthorizationCoordinator.class); + }); + } + + @Test + void enabledCompositionRequiresExplicitOwnerLeaseAndWorkloadNamespace() { + withTlsReloadDisabled( + () -> + new ApplicationContextRunner() + .withUserConfiguration( + GameSessionStartSessionOperatorAuthorizationConfiguration.class, + Dependencies.class) + .withPropertyValues( + OWNER_OPT_IN + "=true", + WORKLOAD_NAMESPACE + "=gameplay", + "firemud.grpc.cert-chain=test-cert", + "firemud.grpc.private-key=test-key", + "firemud.grpc.ca-cert=test-ca") + .run(context -> assertThat(context).hasFailed())); + + withTlsReloadDisabled( + () -> + new ApplicationContextRunner() + .withUserConfiguration( + GameSessionStartSessionOperatorAuthorizationConfiguration.class, + Dependencies.class) + .withPropertyValues( + OWNER_OPT_IN + "=true", + OWNER_CLAIM_LEASE + "=30s", + "firemud.grpc.cert-chain=test-cert", + "firemud.grpc.private-key=test-key", + "firemud.grpc.ca-cert=test-ca") + .run(context -> assertThat(context).hasFailed())); + } + + @Test + void enabledCompositionRequiresMutualTlsPropertiesAndOwnerCollaborators() { + withTlsReloadDisabled( + () -> + new ApplicationContextRunner() + .withUserConfiguration( + GameSessionStartSessionOperatorAuthorizationConfiguration.class, + Dependencies.class) + .withPropertyValues( + OWNER_OPT_IN + "=true", + OWNER_CLAIM_LEASE + "=30s", + WORKLOAD_NAMESPACE + "=gameplay") + .run(context -> assertThat(context).hasFailed())); + + withTlsReloadDisabled( + () -> + new ApplicationContextRunner() + .withUserConfiguration( + GameSessionStartSessionOperatorAuthorizationConfiguration.class) + .withPropertyValues(completeOwnerProperties()) + .run(context -> assertThat(context).hasFailed())); + } + + @Test + void enabledCompositionRequiresItsTransactionManager() { + withTlsReloadDisabled( + () -> + new ApplicationContextRunner() + .withUserConfiguration( + GameSessionStartSessionOperatorAuthorizationConfiguration.class, + Dependencies.class) + .withPropertyValues(completeOwnerProperties()) + .withPropertyValues("test.start-session.transaction-manager-enabled=false") + .run(context -> assertThat(context).hasFailed())); + } + + @Test + void ownerClaimLeaseUsesRepositoryFiveMinuteBound() { + withTlsReloadDisabled( + () -> + new ApplicationContextRunner() + .withUserConfiguration( + GameSessionStartSessionOperatorAuthorizationConfiguration.class, + Dependencies.class) + .withPropertyValues( + OWNER_OPT_IN + "=true", + OWNER_CLAIM_LEASE + "=6m", + WORKLOAD_NAMESPACE + "=gameplay", + "firemud.grpc.cert-chain=test-cert", + "firemud.grpc.private-key=test-key", + "firemud.grpc.ca-cert=test-ca") + .run(context -> assertThat(context).hasFailed())); + } + + @Test + void explicitCompositionUsesOwnerDependenciesAndManagedClientLifecycle() { + withTlsReloadDisabled( + () -> + new ApplicationContextRunner() + .withUserConfiguration( + GameSessionStartSessionOperatorAuthorizationConfiguration.class, + Dependencies.class) + .withPropertyValues(completeOwnerProperties()) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context) + .hasSingleBean(GameSessionStartSessionOperatorAttemptRepository.class); + assertThat(context).hasSingleBean(StartSessionOperatorRedemptionClient.class); + assertThat(context) + .hasSingleBean( + GameSessionStartSessionOperatorAuthorizationCoordinator.class); + + var channelFactory = context.getBean(ControlledGrpcChannelFactory.class); + assertThat(channelFactory.buildCount()).isEqualTo(1); + assertThat(channelFactory.lastTarget()).isEqualTo("account-service:6565"); + assertThat(channelFactory.lastDefaultPort()).isEqualTo(6565); + assertThat(channelFactory.lastKeepAlive()).isTrue(); + context.close(); + verify(channelFactory.channel()).shutdown(); + })); + } + + @Test + void enabledCompositionUsesCanonicalTransactionManagerWhenMultipleArePresent() { + withTlsReloadDisabled( + () -> + new ApplicationContextRunner() + .withUserConfiguration( + GameSessionStartSessionOperatorAuthorizationConfiguration.class, + Dependencies.class, + AdditionalTransactionManager.class) + .withPropertyValues(completeOwnerProperties()) + .run( + context -> { + assertThat(context).hasNotFailed(); + var coordinator = + context.getBean( + GameSessionStartSessionOperatorAuthorizationCoordinator.class); + var ownerTransaction = + (TransactionTemplate) + ReflectionTestUtils.getField(coordinator, "ownerTransaction"); + var canonicalTransactionManager = + context.getBean("transactionManager", PlatformTransactionManager.class); + var otherTransactionManager = + context.getBean( + "otherTransactionManager", PlatformTransactionManager.class); + + assertThat(ownerTransaction.getTransactionManager()) + .isSameAs(canonicalTransactionManager) + .isNotSameAs(otherTransactionManager); + })); + } + + private static String[] completeOwnerProperties() { + return new String[] { + OWNER_OPT_IN + "=true", + OWNER_CLAIM_LEASE + "=30s", + WORKLOAD_NAMESPACE + "=gameplay", + "firemud.grpc.cert-chain=test-cert", + "firemud.grpc.private-key=test-key", + "firemud.grpc.ca-cert=test-ca" + }; + } + + private static void withTlsReloadDisabled(Runnable action) { + String previous = System.getProperty(TLS_RELOAD_PROPERTY); + System.setProperty(TLS_RELOAD_PROPERTY, "false"); + try { + action.run(); + } finally { + if (previous == null) { + System.clearProperty(TLS_RELOAD_PROPERTY); + } else { + System.setProperty(TLS_RELOAD_PROPERTY, previous); + } + } + } + + @TestConfiguration(proxyBeanMethods = false) + static class Dependencies { + @Bean(name = "conversionService") + ConversionService applicationConversionService() { + return ApplicationConversionService.getSharedInstance(); + } + + @Bean + DSLContext startSessionOwnerDsl() { + return mock(DSLContext.class); + } + + @Bean(name = "transactionManager") + @ConditionalOnProperty( + name = "test.start-session.transaction-manager-enabled", + havingValue = "true", + matchIfMissing = true) + PlatformTransactionManager startSessionOwnerTransactionManager() { + return mock(PlatformTransactionManager.class); + } + + @Bean + ServiceEndpointsProperties startSessionServiceEndpoints() { + return new ServiceEndpointsProperties(); + } + + @Bean + CommonGrpcClientProperties startSessionGrpcClientProperties(Environment environment) { + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain(environment.getProperty("firemud.grpc.cert-chain")); + properties.setPrivateKey(environment.getProperty("firemud.grpc.private-key")); + properties.setCaCert(environment.getProperty("firemud.grpc.ca-cert")); + return properties; + } + + @Bean + ControlledGrpcChannelFactory startSessionGrpcChannelFactory() { + return new ControlledGrpcChannelFactory(); + } + + @Bean + BlockingGrpcStubCustomizer startSessionGrpcStubCustomizer() { + return BlockingGrpcStubCustomizer.noop(); + } + } + + @TestConfiguration(proxyBeanMethods = false) + static class AdditionalTransactionManager { + @Bean(name = "otherTransactionManager") + PlatformTransactionManager otherTransactionManager() { + return mock(PlatformTransactionManager.class); + } + } + + static class ControlledGrpcChannelFactory extends GrpcChannelFactory { + private final ManagedChannel channel = mock(ManagedChannel.class); + private int buildCount; + private String lastTarget; + private int lastDefaultPort; + private boolean lastKeepAlive; + + @Override + public ManagedChannel buildChannel( + String target, int defaultPort, CommonGrpcClientProperties properties, boolean keepAlive) { + buildCount++; + lastTarget = target; + lastDefaultPort = defaultPort; + lastKeepAlive = keepAlive; + return channel; + } + + int buildCount() { + return buildCount; + } + + String lastTarget() { + return lastTarget; + } + + int lastDefaultPort() { + return lastDefaultPort; + } + + boolean lastKeepAlive() { + return lastKeepAlive; + } + + ManagedChannel channel() { + return channel; + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociationTest.java new file mode 100644 index 0000000000..5308699e5c --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociationTest.java @@ -0,0 +1,189 @@ +package unit.net.firedevops.firemud.gamesession.dto; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import org.junit.jupiter.api.Test; + +class CanonicalGameInstanceLaunchAssociationTest { + private static final String NAMESPACE = "launch-owner"; + private static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID INSTANCE_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID ASSOCIATION_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID STATE_NAMESPACE_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + + @Test + void retainsTheCompleteBindingAndSeparatesCapturedFromCurrentOwnerProjection() { + CompleteLaunchBindingEvidence evidence = evidence(); + CanonicalGameInstanceLaunchAssociation association = + new CanonicalGameInstanceLaunchAssociation( + NAMESPACE, + 701L, + ASSOCIATION_ID, + TENANT_ID, + INSTANCE_ID, + "earth", + STATE_NAMESPACE_ID, + RealmEntryPolicy.StateScope.SHARED, + true, + "launch-request-1", + "descriptor-902", + 3L, + evidence, + CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.RUNNING, + 8L); + + assertThat(association.capturedStartingRowVersion()).isEqualTo(3L); + assertThat(association.currentRowVersion()).isEqualTo(8L); + assertThat(association.currentGameInstanceStatus()) + .isEqualTo(CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.RUNNING); + assertThat(association.launchBindingEvidence()).isSameAs(evidence); + } + + @Test + void rejectsNonSharedAndNonProductionLaunchAssociations() { + assertThatThrownBy( + () -> association(evidence(), RealmEntryPolicy.StateScope.ISOLATED, true, 3L, 3L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("SHARED"); + assertThatThrownBy( + () -> association(evidence(), RealmEntryPolicy.StateScope.SHARED, false, 3L, 3L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("public production"); + } + + @Test + void rejectsSelectorsAndCurrentRowVersionsThatDifferFromTheOwnerEvidence() { + assertThatThrownBy( + () -> + new CanonicalGameInstanceLaunchAssociation( + NAMESPACE, + 701L, + ASSOCIATION_ID, + TENANT_ID, + INSTANCE_ID, + "mars", + STATE_NAMESPACE_ID, + RealmEntryPolicy.StateScope.SHARED, + true, + "launch-request-1", + "descriptor-902", + 3L, + evidence(), + CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.STARTING, + 3L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match"); + assertThatThrownBy( + () -> association(evidence(), RealmEntryPolicy.StateScope.SHARED, true, 4L, 3L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must not precede"); + } + + private static CanonicalGameInstanceLaunchAssociation association( + CompleteLaunchBindingEvidence evidence, + RealmEntryPolicy.StateScope scope, + boolean publicProduction, + long capturedVersion, + long currentVersion) { + return new CanonicalGameInstanceLaunchAssociation( + NAMESPACE, + 701L, + ASSOCIATION_ID, + TENANT_ID, + INSTANCE_ID, + "earth", + STATE_NAMESPACE_ID, + scope, + publicProduction, + "launch-request-1", + "descriptor-902", + capturedVersion, + evidence, + CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.STARTING, + currentVersion); + } + + private static CompleteLaunchBindingEvidence evidence() { + UUID sourceOperationId = UUID.fromString("55555555-5555-4555-8555-555555555555"); + String sourceEvidenceDigest = "sha256:" + "a".repeat(64); + AuthoredWorldLaunchDescriptorEvidence.Request request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + "launch-request-1", + TENANT_ID, + "earth", + sourceOperationId, + sourceEvidenceDigest, + 810L, + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + "descriptor-902", + 902L, + false, + null, + "{}", + "generation-4", + 4L, + 903L, + "prb:tenant:902:903", + false, + null); + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + "902", + false, + null, + "publish-commit-902", + "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence attestation = + AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + TENANT_ID, + UUID.fromString("66666666-6666-4666-8666-666666666666"), + "earth", + sourceOperationId, + sourceEvidenceDigest, + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish:tenant:version:request", + "publish-commit-902", + participants, + "sha256:" + "b".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision()); + return new CompleteLaunchBindingEvidence(descriptor, attestation); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryTest.java new file mode 100644 index 0000000000..b1d81169f7 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryTest.java @@ -0,0 +1,222 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import org.junit.jupiter.api.Test; + +class GameSessionCanonicalRealmCatalogRepositoryTest { + private static final String NAMESPACE = "canonical-realm-catalog-test"; + private static final UUID TENANT_ID = uuid(1); + private static final UUID INTAKE_OPERATION_ID = uuid(2); + private static final UUID INTAKE_REQUEST_ID = uuid(3); + private static final UUID CREATE_REQUEST_ID = uuid(4); + + @Test + void explicitPublicRequestPreservesRealmSelectorAndOpaqueOwnerPolicyExactly() { + CreateCanonicalRealmCatalogRequest request = + request("production-realm-west", "Café 🐉", "realm-local-v7"); + + assertThat(request.realmSlug()).isEqualTo("production-realm-west"); + assertThat(request.characterCreationPolicy()).isEqualTo("realm-local-v7"); + assertThat(request.visible()).isTrue(); + assertThat(request.publicProduction()).isTrue(); + assertThat(request.stateScope()).isEqualTo("SHARED"); + } + + @Test + void rejectsMissingPublicStatePrivateLifecycleAndMalformedUtf8Inputs() { + assertThatThrownBy(() -> request("realm", "Display", "policy", false, true, "SHARED")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("visible public production"); + assertThatThrownBy(() -> request("realm", "Display", "policy", true, false, "SHARED")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("visible public production"); + assertThatThrownBy(() -> request("realm", "Display", "policy", true, true, "PRIVATE")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("stateScope"); + assertThatThrownBy( + () -> + new CreateCanonicalRealmCatalogRequest( + CREATE_REQUEST_ID, + NAMESPACE, + TENANT_ID, + INTAKE_OPERATION_ID, + "realm", + "Display", + true, + true, + "SHARED", + "policy", + uuid(5), + null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("private/playtest"); + String malformedUtf8 = "bad" + (char) 0xD800; + assertThatThrownBy(() -> request(malformedUtf8, "Display", "policy")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("well-formed UTF-8"); + assertThatThrownBy(() -> request("realm", malformedUtf8, "policy")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("well-formed UTF-8"); + assertThatThrownBy(() -> request("realm", "Display", malformedUtf8)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("well-formed UTF-8"); + } + + @Test + void requestDigestIsStableAndBindsEachCreationInputAndExactSourceReceipt() { + IntakeReceipt source = sourceReceipt(); + CreateCanonicalRealmCatalogRequest original = request("arcology", "The City", "owner-mode"); + String digest = GameSessionCanonicalRealmCatalogRepository.requestDigest(original, source); + + assertThat(GameSessionCanonicalRealmCatalogRepository.requestDigest(original, source)) + .isEqualTo(digest); + assertThat( + GameSessionCanonicalRealmCatalogRepository.requestDigest( + request("another-arcology", "The City", "owner-mode"), source)) + .isNotEqualTo(digest); + assertThat( + GameSessionCanonicalRealmCatalogRepository.requestDigest( + request("arcology", "Another Display", "owner-mode"), source)) + .isNotEqualTo(digest); + assertThat( + GameSessionCanonicalRealmCatalogRepository.requestDigest( + request("arcology", "The City", "owner-mode", true, true, "ISOLATED"), source)) + .isNotEqualTo(digest); + assertThat( + GameSessionCanonicalRealmCatalogRepository.requestDigest( + request("arcology", "The City", "another-owner-mode"), source)) + .isNotEqualTo(digest); + assertThat( + GameSessionCanonicalRealmCatalogRepository.requestDigest( + request("arcology", "The City", "owner-mode", uuid(6)), source)) + .isNotEqualTo(digest); + } + + @Test + void snapshotRejectsTenantAndWorldSelectorsThatDifferFromPersistedSource() { + IntakeReceipt source = sourceReceipt(); + assertThatThrownBy( + () -> + new CanonicalRealmCatalogSnapshot( + NAMESPACE, + TENANT_ID, + "different-tenant", + "authored-world", + uuid(7), + "realm", + "Realm", + true, + true, + "SHARED", + uuid(8), + "policy", + 1, + CREATE_REQUEST_ID, + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + source)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("do not match"); + } + + private static CreateCanonicalRealmCatalogRequest request( + String realmSlug, String display, String policy) { + return request(realmSlug, display, policy, true, true, "SHARED"); + } + + private static CreateCanonicalRealmCatalogRequest request( + String realmSlug, + String display, + String policy, + boolean visible, + boolean production, + String scope) { + return new CreateCanonicalRealmCatalogRequest( + CREATE_REQUEST_ID, + NAMESPACE, + TENANT_ID, + INTAKE_OPERATION_ID, + realmSlug, + display, + visible, + production, + scope, + policy, + null, + null); + } + + private static CreateCanonicalRealmCatalogRequest request( + String realmSlug, String display, String policy, UUID requestId) { + return new CreateCanonicalRealmCatalogRequest( + requestId, + NAMESPACE, + TENANT_ID, + INTAKE_OPERATION_ID, + realmSlug, + display, + true, + true, + "SHARED", + policy, + null, + null); + } + + private static IntakeReceipt sourceReceipt() { + String tenantSlug = "stable-tenant"; + String worldSlug = "authored-world"; + String worldDisplayName = "Authored World"; + String sourceTenantKey = "game-design-tenant-42"; + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, uuid(10), TENANT_ID, tenantSlug, worldSlug, worldDisplayName); + String sourceEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + uuid(10), + uuid(11), + sourceRequestDigest, + TENANT_ID, + tenantSlug, + worldSlug, + worldDisplayName, + 42L, + sourceTenantKey, + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + uuid(10), + uuid(11), + sourceRequestDigest, + TENANT_ID, + tenantSlug, + worldSlug, + worldDisplayName, + 42L, + sourceTenantKey, + "NEW_GAME_ROW", + sourceEvidenceDigest); + String intakeRequestDigest = + GameSessionAuthoredWorldIntakeDigest.requestDigest(INTAKE_REQUEST_ID, source); + String intakeReceiptDigest = + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + INTAKE_OPERATION_ID, intakeRequestDigest, source.evidenceDigest()); + return new IntakeReceipt( + INTAKE_OPERATION_ID, INTAKE_REQUEST_ID, intakeRequestDigest, source, intakeReceiptDigest); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryTest.java new file mode 100644 index 0000000000..cc4523e186 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryTest.java @@ -0,0 +1,56 @@ +package unit.net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalStartingInstanceRepository; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameSessionCanonicalStartingInstanceRepositoryTest { + private static final String NAMESPACE = "canonical-starting-test"; + + @AfterEach + void clearTransactionContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void ownerWriteRequiresWritableTransactionBeforeAnyDatabaseRead() { + DSLContext dsl = mock(DSLContext.class); + var repository = new GameSessionCanonicalStartingInstanceRepository(dsl, NAMESPACE); + + assertThatThrownBy(() -> repository.createStarting(null, null, null, null, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable owner transaction"); + + verifyNoInteractions(dsl); + } + + @Test + void refusesReadOnlyOwnerTransactionBeforeAnyOwnerLookup() { + DSLContext dsl = mock(DSLContext.class); + var repository = new GameSessionCanonicalStartingInstanceRepository(dsl, NAMESPACE); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + + assertThatThrownBy(() -> repository.createStarting(null, null, null, null, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable owner transaction"); + + verifyNoInteractions(dsl); + } + + @Test + void repositoryIsNotRegisteredAsAnExecutableSpringComponent() { + assertThat( + GameSessionCanonicalStartingInstanceRepository.class.isAnnotationPresent( + Repository.class)) + .isFalse(); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryTest.java new file mode 100644 index 0000000000..d003c5c09e --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryTest.java @@ -0,0 +1,45 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameSessionFreshTenantAssociationRepositoryTest { + @AfterEach + void clearTransactionSynchronization() { + TransactionSynchronizationManager.clear(); + } + + @Test + void doesNotReadOrWriteOutsideTheWritableOwnerTransaction() { + DSLContext dsl = mock(DSLContext.class); + GameSessionFreshTenantAssociationRepository repository = + new GameSessionFreshTenantAssociationRepository(dsl); + + assertThatThrownBy(() -> repository.associateFresh(null, null, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable owner transaction"); + + verifyNoInteractions(dsl); + } + + @Test + void rejectsReadOnlyOwnerTransactionBeforeTouchingStorage() { + DSLContext dsl = mock(DSLContext.class); + GameSessionFreshTenantAssociationRepository repository = + new GameSessionFreshTenantAssociationRepository(dsl); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + + assertThatThrownBy(() -> repository.associateFresh(null, null, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable owner transaction"); + + verifyNoInteractions(dsl); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryTest.java index 985b2d9f31..7036635b98 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryTest.java @@ -43,6 +43,19 @@ void rejectsReadOnlyOwnerTransactionBeforeStorageAccess() { verifyNoInteractions(dsl); } + @Test + void currentOriginalAttemptReadRequiresTheCallerOwnedReadCommittedTransaction() { + DSLContext dsl = mock(DSLContext.class); + GameSessionStartSessionOperatorAttemptRepository repository = + new GameSessionStartSessionOperatorAttemptRepository(dsl, java.time.Duration.ofSeconds(30)); + + assertThatThrownBy(() -> repository.readCurrentOriginalAttempt(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable READ COMMITTED"); + + verifyNoInteractions(dsl); + } + @Test void requiresAnExplicitlyBoundedClaimLease() { DSLContext dsl = mock(DSLContext.class); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java index 8ddcdfdd87..4899ccb889 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java @@ -2,6 +2,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; import java.sql.Connection; import java.sql.DriverManager; @@ -9,6 +12,9 @@ import java.util.ArrayList; import java.util.List; import java.util.UUID; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService.PointerAuditKey; import org.jooq.DSLContext; @@ -17,6 +23,26 @@ import org.junit.jupiter.api.Test; class GameplayAdmissionPointerEventRepositoryTest { + @Test + void canonicalOpenAuditCannotBeWrittenOutsideItsWritableOwnerTransaction() { + DSLContext dsl = mock(DSLContext.class); + GameplayAdmissionPointerEventRepository repository = + new GameplayAdmissionPointerEventRepository(dsl); + + assertThrows( + IllegalStateException.class, + () -> + repository.appendCanonicalInitialAdmissionOpen( + mock(CanonicalInitialAdmissionRequest.class), + mock(CanonicalRealmCatalogSnapshot.class), + mock(CanonicalInitialAdmissionLaunchTarget.class), + 1L, + 1L, + Instant.EPOCH)); + + verifyNoInteractions(dsl); + } + @Test void savesCatalogRevisionAndStableIdentityAndKeepsUnknownValuesNull() throws Exception { try (Connection connection = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/GameSessionGrpcAuthInterceptorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/GameSessionGrpcAuthInterceptorTest.java index 108b0e86dc..2663c257e7 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/GameSessionGrpcAuthInterceptorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/GameSessionGrpcAuthInterceptorTest.java @@ -26,7 +26,10 @@ void setUp() { jwtUtil = new JwtUtil("testsecretkeytestsecretkeytest1234", 3600000L); interceptor = new AuthTokenInterceptor( - jwtUtil, Set.of(GameSessionServiceGrpc.getPingMethod().getFullMethodName())); + jwtUtil, + Set.of( + GameSessionServiceGrpc.getPingMethod().getFullMethodName(), + GameSessionServiceGrpc.getAuthorizeStartSessionMethod().getFullMethodName())); } @Test @@ -53,6 +56,20 @@ void allowsPingWithoutToken() { assertEquals(null, call.status); } + @Test + void allowsOnlyTheTypedStartSessionHandoffWithoutJwt() { + TestServerCall call = + new TestServerCall( + GameSessionServiceGrpc.getAuthorizeStartSessionMethod().getFullMethodName()); + Metadata headers = new Metadata(); + + ServerCall.Listener listener = + interceptor.interceptCall(call, headers, (c, h) -> new ServerCall.Listener<>() {}); + + assertNotNull(listener); + assertEquals(null, call.status); + } + @Test void rejectsMissingTokenForControlPlaneMutation() { TestServerCall call = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolverTest.java new file mode 100644 index 0000000000..f94a521971 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolverTest.java @@ -0,0 +1,136 @@ +package net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.UUID; +import net.firedevops.firemud.common.testing.AuthoringFixtures; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class CanonicalRegionBootstrapAssignmentResolverTest { + private static final UUID CANONICAL_REGION_ID = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID OPERATIONAL_REGION_ID = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID UNKNOWN_REGION_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private WorldCanonicalInstanceLifecycleClient lifecycleClient; + private CanonicalRegionBootstrapAssignmentResolver resolver; + private WorldCanonicalInstanceLifecycleEvidence.Request request; + private WorldCanonicalInstanceLifecycleEvidence activeEvidence; + + @BeforeEach + void setUp() throws Exception { + lifecycleClient = mock(WorldCanonicalInstanceLifecycleClient.class); + resolver = new CanonicalRegionBootstrapAssignmentResolver(lifecycleClient); + activeEvidence = AuthoringFixtures.lifecycleEvidence("ACTIVE", 7L); + request = activeEvidence.request(); + } + + @Test + void resolvesExactOperationalUuidFromAuthenticatedOwnerRead() { + when(lifecycleClient.read(request)).thenReturn(activeEvidence); + + var assignment = resolver.resolve(request, CANONICAL_REGION_ID); + + assertThat(assignment.request()).isEqualTo(request); + assertThat(assignment.canonicalRegionId()).isEqualTo(CANONICAL_REGION_ID); + assertThat(assignment.operationalRegionId()).isEqualTo(OPERATIONAL_REGION_ID); + assertThat(assignment.lifecycleStatus()).isEqualTo("ACTIVE"); + assertThat(assignment.lifecycleEpoch()).isEqualTo(activeEvidence.lifecycleEpoch()); + assertThat(assignment.lifecycleRowVersion()).isEqualTo(activeEvidence.rowVersion()); + assertThat(assignment.captureId()).isEqualTo(activeEvidence.captureId()); + assertThat(assignment.graphSha256()).isEqualTo(activeEvidence.graphSha256()); + assertThat(assignment.preparationInputDigest()) + .isEqualTo(activeEvidence.preparationInputDigest()); + verify(lifecycleClient).read(request); + } + + @Test + void rejectsNilCanonicalRegionBeforeOwnerRead() { + assertThatThrownBy(() -> resolver.resolve(request, NIL_UUID)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("non-nil UUID"); + + verifyNoInteractions(lifecycleClient); + } + + @Test + void rejectsResponseBoundToDifferentTargetNamespace() { + var mismatchedRequest = copyRequestWithDifferentTargetNamespace(request); + var mismatchedEvidence = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(mismatchedEvidence.request()).thenReturn(mismatchedRequest); + when(mismatchedEvidence.lifecycleStatus()).thenReturn("ACTIVE"); + when(lifecycleClient.read(request)).thenReturn(mismatchedEvidence); + + assertThatThrownBy(() -> resolver.resolve(request, CANONICAL_REGION_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact requested target"); + } + + @Test + void rejectsNonActiveWorldLifecycle() throws Exception { + var terminatedEvidence = AuthoringFixtures.lifecycleEvidence("TERMINATED", 8L); + when(lifecycleClient.read(request)).thenReturn(terminatedEvidence); + + assertThatThrownBy(() -> resolver.resolve(request, CANONICAL_REGION_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not ACTIVE"); + } + + @Test + void rejectsMissingCanonicalRegionWithoutInventingOperationalFallback() { + when(lifecycleClient.read(request)).thenReturn(activeEvidence); + + assertThatThrownBy(() -> resolver.resolve(request, UNKNOWN_REGION_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no operational assignment"); + } + + @Test + void propagatesUnavailableOwnerReadFailure() { + StatusRuntimeException unavailable = Status.UNAVAILABLE.asRuntimeException(); + when(lifecycleClient.read(request)).thenThrow(unavailable); + assertThatThrownBy(() -> resolver.resolve(request, CANONICAL_REGION_ID)).isSameAs(unavailable); + } + + @Test + void propagatesInvalidOwnerEvidenceFailure() { + IllegalStateException invalidEvidence = new IllegalStateException("invalid owner evidence"); + when(lifecycleClient.read(request)).thenThrow(invalidEvidence); + assertThatThrownBy(() -> resolver.resolve(request, CANONICAL_REGION_ID)) + .isSameAs(invalidEvidence); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request + copyRequestWithDifferentTargetNamespace( + WorldCanonicalInstanceLifecycleEvidence.Request source) { + return new WorldCanonicalInstanceLifecycleEvidence.Request( + source.schemaVersion(), + source.readRequestId(), + source.targetNamespace() + "-other", + source.canonicalTenantId(), + source.worldSlug(), + source.canonicalGameInstanceId(), + source.playableStateNamespaceId(), + source.playableStateScope(), + source.publicProduction(), + source.controlPlaneRequestId(), + source.canonicalVersionId(), + source.expectedDescriptorRequestDigest(), + source.expectedDescriptorResultDigest(), + source.expectedReleaseAttestationDigest()); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java index 23e7f0e599..14413fd81d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java @@ -164,6 +164,24 @@ void startSessionSavesState() { assertEquals(OPAQUE_PUBLISHED_RELEASE_BUNDLE_REF, publishedReleaseBundleRef.getValue()); } + @Test + void legacyNumericLaunchFailsClosedBeforeMutation() { + StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-numeric-launch", 42L); + when(gameDesignClient.resolveLaunchDescriptor( + request.tenantId(), request.gameTemplateId(), request.controlPlaneRequestId())) + .thenReturn( + ResolveLaunchDescriptorResponse.newBuilder() + .setError( + net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() + .setCode("AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED") + .setMessage( + "Canonical authored-world source binding is required to resolve a launch descriptor") + .build()) + .build()); + + assertNumericLaunchDeniedWithoutMutation(request); + } + @Test void runOwnedInitialLaunchExactRetryReturnsSameActiveTargetWithoutReplayingActivation() { StartSessionRequest request = @@ -1759,6 +1777,25 @@ private void configureLaunchPreflight() { .build()); } + private void assertNumericLaunchDeniedWithoutMutation(StartSessionRequest request) { + Map before = new HashMap<>(); + store.forEach((id, instance) -> before.put(id, copyOf(instance))); + + IllegalArgumentException error = + assertThrows(IllegalArgumentException.class, () -> service.startSession(request)); + + assertEquals( + "AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED: Canonical authored-world source binding is" + + " required to resolve a launch descriptor", + error.getMessage()); + org.assertj.core.api.Assertions.assertThat(store).usingRecursiveComparison().isEqualTo(before); + verify(gameDesignClient) + .resolveLaunchDescriptor( + request.tenantId(), request.gameTemplateId(), request.controlPlaneRequestId()); + verifyNoMoreInteractions(gameDesignClient); + verifyNoInteractions(repository, worldManagementClient, stateService); + } + private static AuthoredWorldSourceEvidence sourceEvidence(StartSessionRequest request) { return sourceEvidence(request, 29L); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index 1987b15f4f..59559e0116 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -1,18 +1,33 @@ package net.firedevops.firemud.gamesession.service.impl; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import io.grpc.Context; import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.io.IOException; import java.time.Instant; import java.util.List; import java.util.Map; +import java.util.Optional; +import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog; import net.firedevops.firemud.gamesession.command.text.TextCommandInterpretationResult; @@ -21,17 +36,23 @@ import net.firedevops.firemud.gamesession.dto.GameInstanceDto; import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot; import net.firedevops.firemud.gamesession.service.AccountPresenceQueryService; import net.firedevops.firemud.gamesession.service.AccountPresenceSnapshot; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition; import net.firedevops.firemud.gamesession.service.FeatureFlagService; import net.firedevops.firemud.gamesession.service.GameInstanceService; +import net.firedevops.firemud.gamesession.service.GameSessionStartSessionOperatorAuthorizationCoordinator; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.IpConnectionLimiter; import net.firedevops.firemud.gamesession.service.PingService; import net.firedevops.firemud.gamesession.service.TickService; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; +import net.firedevops.firemud.gamesession.v1.AuthorizeStartSessionRequest; +import net.firedevops.firemud.gamesession.v1.AuthorizeStartSessionResponse; import net.firedevops.firemud.gamesession.v1.GetAdmissionPointerRequest; import net.firedevops.firemud.gamesession.v1.GetAdmissionPointerResponse; import net.firedevops.firemud.gamesession.v1.GetTickStatusRequest; @@ -62,8 +83,32 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import org.slf4j.LoggerFactory; +import tools.jackson.databind.json.JsonMapper; class GameSessionGrpcServiceTest { + private static final String OPERATOR_NAMESPACE = "world-runtime"; + private static final String OPERATOR_LOGGING_IDENTITY = + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; + private static final String OPERATOR_REFERENCE = "A".repeat(43); + private static final UUID OPERATOR_TENANT = + UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID OPERATOR_ACTOR = + UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID OPERATOR_ACCOUNT = + UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID OPERATOR_RESERVATION = + UUID.fromString("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID OPERATOR_ATTEMPT = + UUID.fromString("69116466-a576-4fa6-9e11-4c0c6b2a92f0"); + private static final UUID OPERATOR_MUTATION = + UUID.fromString("89da7d84-12f5-4cf8-b69b-30ba8eb115a4"); + private static final UUID OPERATOR_CLAIM_OWNER = + UUID.fromString("31f85ac3-e621-4c38-a207-0e5aab116d34"); + private static final UUID OPERATOR_ISSUANCE = + UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final JsonMapper OPERATOR_JSON = JsonMapper.builder().build(); + @AfterEach void tearDown() { SessionContext.clear(); @@ -3187,4 +3232,363 @@ public void onCompleted() {} }); Mockito.verify(gameInstanceService, Mockito.never()).stopSession(Mockito.anyLong()); } + + @Test + void typedStartSessionHandoffRejectsWrongPeerBeforeDecodingOrOwnerCall() { + GameSessionStartSessionOperatorAuthorizationCoordinator coordinator = + Mockito.mock(GameSessionStartSessionOperatorAuthorizationCoordinator.class); + GameInstanceService gameInstanceService = Mockito.mock(GameInstanceService.class); + GameSessionGrpcService service = operatorService(gameInstanceService, coordinator); + AuthorizeStartSessionRequest malformed = + AuthorizeStartSessionRequest.newBuilder() + .setCanonicalPostAuthorizationExecutionTupleBytes( + com.google.protobuf.ByteString.copyFromUtf8("not canonical")) + .setOperatorAuthorizationReference(OPERATOR_REFERENCE) + .build(); + + AuthorizeStartSessionResponse response = + authorizeWithPeer(service, malformed, operatorPeer("account-service", OPERATOR_NAMESPACE)); + + assertEquals("PERMISSION_DENIED", response.getError().getCode()); + Mockito.verifyNoInteractions(coordinator); + Mockito.verify(gameInstanceService, Mockito.never()) + .startSession( + Mockito.any(net.firedevops.firemud.gamesession.dto.StartSessionRequest.class), + Mockito.anyBoolean()); + } + + @Test + void typedStartSessionHandoffRejectsMalformedTupleBeforeOwnerCall() { + GameSessionStartSessionOperatorAuthorizationCoordinator coordinator = + Mockito.mock(GameSessionStartSessionOperatorAuthorizationCoordinator.class); + GameSessionGrpcService service = + operatorService(Mockito.mock(GameInstanceService.class), coordinator); + AuthorizeStartSessionRequest malformed = + AuthorizeStartSessionRequest.newBuilder() + .setCanonicalPostAuthorizationExecutionTupleBytes( + com.google.protobuf.ByteString.copyFromUtf8("not canonical")) + .setOperatorAuthorizationReference(OPERATOR_REFERENCE) + .build(); + + AuthorizeStartSessionResponse response = + authorizeWithPeer( + service, malformed, operatorPeer("logging-admin-service", OPERATOR_NAMESPACE)); + + assertEquals("INVALID_ARGUMENT", response.getError().getCode()); + Mockito.verifyNoInteractions(coordinator); + } + + @Test + void typedStartSessionHandoffFailsClosedWhenOptionalOwnerCoordinatorIsAbsent() + throws IOException { + GameInstanceService gameInstanceService = Mockito.mock(GameInstanceService.class); + GameSessionGrpcService service = operatorService(gameInstanceService, null); + AuthorizeStartSessionRequest request = operatorRequest(operatorTuple()); + + AuthorizeStartSessionResponse response = + authorizeWithPeer( + service, request, operatorPeer("logging-admin-service", OPERATOR_NAMESPACE)); + + assertEquals("FAILED_PRECONDITION", response.getError().getCode()); + Mockito.verify(gameInstanceService, Mockito.never()) + .startSession( + Mockito.any(net.firedevops.firemud.gamesession.dto.StartSessionRequest.class), + Mockito.anyBoolean()); + } + + @Test + void typedStartSessionHandoffReturnsOnlyExactDurableOwnerProgressWithoutStartingInstance() + throws IOException { + StartSessionPostAuthorizationExecutionTuple expected = operatorTuple(); + GameSessionStartSessionOperatorAuthorizationCoordinator coordinator = + Mockito.mock(GameSessionStartSessionOperatorAuthorizationCoordinator.class); + GameInstanceService gameInstanceService = Mockito.mock(GameInstanceService.class); + GameSessionGrpcService service = operatorService(gameInstanceService, coordinator); + AttemptClaim claim = + new AttemptClaim( + OPERATOR_NAMESPACE, + expected.controlPlaneRequestId(), + OPERATOR_ATTEMPT, + OPERATOR_MUTATION, + OPERATOR_CLAIM_OWNER, + 37L); + AttemptSnapshot snapshot = operatorSnapshot(expected); + GameSessionStartSessionOperatorAuthorizationCoordinator.AuthorizationResult + authorizationResult = + new GameSessionStartSessionOperatorAuthorizationCoordinator.AuthorizationResult( + snapshot, + Optional.of(claim), + GameSessionStartSessionOperatorAuthorizationCoordinator.Progress + .ACCOUNT_OUTCOME_AMBIGUOUS); + Mockito.when( + coordinator.authorize( + Mockito.any(StartSessionPostAuthorizationExecutionTuple.class), + Mockito.eq(OPERATOR_REFERENCE))) + .thenReturn(authorizationResult); + + AuthorizeStartSessionResponse response = + authorizeWithPeer( + service, + operatorRequest(expected), + operatorPeer("logging-admin-service", OPERATOR_NAMESPACE)); + + assertEquals(expected.controlPlaneRequestId(), response.getControlPlaneRequestId()); + assertEquals(expected.mutationDigest(), response.getMutationDigest()); + assertEquals(OPERATOR_ATTEMPT.toString(), response.getOwnerAttemptId()); + assertEquals(OPERATOR_MUTATION.toString(), response.getOwnerMutationId()); + assertEquals(37L, response.getOwnerFence()); + assertEquals("OWNER_EXECUTION_PENDING", response.getOwnerPhaseState()); + assertEquals( + net.firedevops.firemud.gamesession.v1.StartSessionOwnerAuthorizationProgress + .START_SESSION_OWNER_AUTHORIZATION_PROGRESS_ACCOUNT_OUTCOME_AMBIGUOUS, + response.getProgress()); + org.mockito.ArgumentCaptor tupleCaptor = + org.mockito.ArgumentCaptor.forClass(StartSessionPostAuthorizationExecutionTuple.class); + Mockito.verify(coordinator).authorize(tupleCaptor.capture(), Mockito.eq(OPERATOR_REFERENCE)); + assertArrayEquals(expected.canonicalBytes(), tupleCaptor.getValue().canonicalBytes()); + Mockito.verify(gameInstanceService, Mockito.never()) + .startSession( + Mockito.any(net.firedevops.firemud.gamesession.dto.StartSessionRequest.class), + Mockito.anyBoolean()); + } + + @Test + void typedStartSessionHandoffMapsOwnerConflictAndStaleClaimToBoundedErrors() throws IOException { + StartSessionPostAuthorizationExecutionTuple tuple = operatorTuple(); + AuthorizeStartSessionRequest request = operatorRequest(tuple); + GameSessionStartSessionOperatorAuthorizationCoordinator conflictCoordinator = + Mockito.mock(GameSessionStartSessionOperatorAuthorizationCoordinator.class); + Mockito.when( + conflictCoordinator.authorize( + Mockito.any(StartSessionPostAuthorizationExecutionTuple.class), + Mockito.eq(OPERATOR_REFERENCE))) + .thenThrow( + new GameSessionStartSessionOperatorAttemptRepository + .StartSessionOperatorAttemptConflictException(OPERATOR_REFERENCE)); + AuthorizeStartSessionResponse conflict = + authorizeWithPeer( + operatorService(Mockito.mock(GameInstanceService.class), conflictCoordinator), + request, + operatorPeer("logging-admin-service", OPERATOR_NAMESPACE)); + assertEquals("IDEMPOTENCY_CONFLICT", conflict.getError().getCode()); + assertFalse(conflict.getError().getMessage().contains(OPERATOR_REFERENCE)); + + GameSessionStartSessionOperatorAuthorizationCoordinator staleCoordinator = + Mockito.mock(GameSessionStartSessionOperatorAuthorizationCoordinator.class); + Mockito.when( + staleCoordinator.authorize( + Mockito.any(StartSessionPostAuthorizationExecutionTuple.class), + Mockito.eq(OPERATOR_REFERENCE))) + .thenThrow( + new GameSessionStartSessionOperatorAttemptRepository + .StaleStartSessionOperatorAttemptClaimException(OPERATOR_REFERENCE)); + AuthorizeStartSessionResponse stale = + authorizeWithPeer( + operatorService(Mockito.mock(GameInstanceService.class), staleCoordinator), + request, + operatorPeer("logging-admin-service", OPERATOR_NAMESPACE)); + assertEquals("FAILED_PRECONDITION", stale.getError().getCode()); + assertFalse(stale.getError().getMessage().contains(OPERATOR_REFERENCE)); + } + + @Test + void typedStartSessionUnexpectedFailureLogsOnlyExceptionClassAndKeepsInternal() + throws IOException { + String secretMessage = "synthetic owner diagnostic secret"; + String secretReference = "secret-ref-" + "Z".repeat(32); + StartSessionPostAuthorizationExecutionTuple tuple = operatorTuple(); + GameSessionStartSessionOperatorAuthorizationCoordinator coordinator = + Mockito.mock(GameSessionStartSessionOperatorAuthorizationCoordinator.class); + Mockito.when( + coordinator.authorize( + Mockito.any(StartSessionPostAuthorizationExecutionTuple.class), + Mockito.eq(secretReference))) + .thenThrow(new IllegalStateException(secretMessage + " " + secretReference)); + GameSessionGrpcService service = + operatorService(Mockito.mock(GameInstanceService.class), coordinator); + AuthorizeStartSessionRequest request = + operatorRequest(tuple).toBuilder() + .setOperatorAuthorizationReference(secretReference) + .build(); + Logger logger = (Logger) LoggerFactory.getLogger(GameSessionGrpcService.class); + ListAppender appender = new ListAppender<>(); + appender.start(); + logger.addAppender(appender); + + try { + AuthorizeStartSessionResponse response = + authorizeWithPeer( + service, request, operatorPeer("logging-admin-service", OPERATOR_NAMESPACE)); + + assertEquals("INTERNAL", response.getError().getCode()); + assertEquals("StartSession owner handoff failed", response.getError().getMessage()); + assertFalse(response.getError().getMessage().contains(secretReference)); + assertFalse(response.getError().getMessage().contains(secretMessage)); + assertEquals(1, appender.list.size()); + ILoggingEvent event = appender.list.get(0); + assertEquals( + "AuthorizeStartSession failed with exception class java.lang.IllegalStateException", + event.getFormattedMessage()); + assertArrayEquals( + new Object[] {IllegalStateException.class.getName()}, event.getArgumentArray()); + assertNull(event.getThrowableProxy()); + assertFalse(event.getFormattedMessage().contains(secretReference)); + assertFalse(event.getFormattedMessage().contains(secretMessage)); + } finally { + logger.detachAppender(appender); + appender.stop(); + } + } + + private static GameSessionGrpcService operatorService( + GameInstanceService gameInstanceService, + GameSessionStartSessionOperatorAuthorizationCoordinator coordinator) { + GameSessionGrpcService service = + newService( + Mockito.mock(PingService.class), + gameInstanceService, + Mockito.mock(FeatureFlagService.class), + Mockito.mock(TextCommandInterpreter.class), + Mockito.mock(GameInstanceRepository.class), + Mockito.mock(TickService.class), + new SimpleMeterRegistry(), + Mockito.mock(IpConnectionLimiter.class)); + if (coordinator != null) { + service.setOperatorCoordinator(coordinator); + } + return service; + } + + private static AuthorizeStartSessionResponse authorizeWithPeer( + GameSessionGrpcService service, AuthorizeStartSessionRequest request, GrpcPeerIdentity peer) { + AtomicReference response = new AtomicReference<>(); + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .run( + () -> + service.authorizeStartSession( + request, + new StreamObserver<>() { + @Override + public void onNext(AuthorizeStartSessionResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable error) { + fail(error); + } + + @Override + public void onCompleted() {} + })); + return response.get(); + } + + private static GrpcPeerIdentity operatorPeer(String service, String namespace) { + return GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) + .orElseThrow(); + } + + private static AuthorizeStartSessionRequest operatorRequest( + StartSessionPostAuthorizationExecutionTuple tuple) { + return AuthorizeStartSessionRequest.newBuilder() + .setCanonicalPostAuthorizationExecutionTupleBytes( + com.google.protobuf.ByteString.copyFrom(tuple.canonicalBytes())) + .setOperatorAuthorizationReference(OPERATOR_REFERENCE) + .build(); + } + + private static AttemptSnapshot operatorSnapshot( + StartSessionPostAuthorizationExecutionTuple tuple) { + AttemptSnapshot snapshot = Mockito.mock(AttemptSnapshot.class); + Mockito.when(snapshot.targetNamespace()).thenReturn(OPERATOR_NAMESPACE); + Mockito.when(snapshot.controlPlaneRequestId()).thenReturn(tuple.controlPlaneRequestId()); + Mockito.when(snapshot.ownerAttemptId()).thenReturn(OPERATOR_ATTEMPT); + Mockito.when(snapshot.ownerMutationId()).thenReturn(OPERATOR_MUTATION); + Mockito.when(snapshot.ownerFence()).thenReturn(37L); + Mockito.when(snapshot.phaseState()).thenReturn("OWNER_EXECUTION_PENDING"); + Mockito.when(snapshot.postAuthorizationExecutionTuple()).thenReturn(tuple.canonicalBytes()); + return snapshot; + } + + private static StartSessionPostAuthorizationExecutionTuple operatorTuple() throws IOException { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(OPERATOR_TENANT, OPERATOR_NAMESPACE), + new StartSessionOperatorAction.Target(91L, OPERATOR_ACCOUNT), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "Game Session typed owner transport test"); + StartSessionPreAuthorizationReservationTuple preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "grpc-typed-owner-transport", OPERATOR_ACTOR, action); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + OPERATOR_LOGGING_IDENTITY, + "arfp/v1/test-key/" + "b".repeat(64), + OPERATOR_RESERVATION, + 19L, + operatorAuthorityBundle(preTuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] operatorAuthorityBundle(StartSessionPreAuthorizationReservationTuple tuple) + throws IOException { + String tenant = OPERATOR_TENANT.toString(); + Map evidence = + Map.of( + "evidenceType", StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", OPERATOR_ACTOR.toString(), + "controlUiTokenJti", "a681bba7-c215-4cf1-a35b-14348912cbdc", + "role", "tenantAdmin", + "accountGeneration", "2", + "tenantGeneration", "3"); + Map value = + Map.of( + "bundleVersion", StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenant, "targetNamespace", OPERATOR_NAMESPACE), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", OPERATOR_ACTOR.toString(), + "applicableTenantId", tenant), + "accountProjectionEvidence", + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", OPERATOR_ISSUANCE.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenant, 3L), + "membershipAuthorityGeneration", Map.of(tenant, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", Map.of(tenant, 5L), + "issuanceFence", "23", + "issuanceEvidence", evidence); + return Rfc8785CanonicalJson.canonicalizeUtf8(OPERATOR_JSON.writeValueAsString(value)); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadGrpcServiceTest.java new file mode 100644 index 0000000000..76b4f1b532 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadGrpcServiceTest.java @@ -0,0 +1,507 @@ +package unit.net.firedevops.firemud.gamesession.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.StaleStartSessionOperatorAttemptClaimException; +import net.firedevops.firemud.gamesession.service.impl.OriginalStartSessionCurrentAttemptReadGrpcService; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionCurrentAttemptRequest; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionCurrentAttemptResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentMatchers; +import org.slf4j.LoggerFactory; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import tools.jackson.databind.json.JsonMapper; + +class OriginalStartSessionCurrentAttemptReadGrpcServiceTest { + private static final String NAMESPACE = "world-runtime"; + private static final UUID READ_ID = UUID.fromString("01111111-1111-4111-8111-111111111111"); + private static final UUID ATTEMPT = UUID.fromString("02222222-2222-4222-8222-222222222222"); + private static final UUID MUTATION = UUID.fromString("03333333-3333-4333-8333-333333333333"); + private static final long FENCE = 8L; + + @AfterEach + void clearCallerContext() { + SessionContext.clear(); + } + + @Test + void returnsExactPendingSnapshotWithoutMutationRenewalOrRetry() { + Request request = request(NAMESPACE); + byte[] projection = canonicalProjection(request); + Instant leaseExpiry = Instant.parse("2030-01-01T00:00:00.123456789Z"); + AttemptSnapshot snapshot = snapshot(request, leaseExpiry, projection); + GameSessionStartSessionOperatorAttemptRepository repository = mockRepository(); + when(repository.readCurrentOriginalAttempt(request)).thenReturn(snapshot); + var service = newService(repository, NAMESPACE); + + RecordingObserver observer = + invokeAs( + service, + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toRequest(request), + "account-service"); + + assertThat(observer.error()).isNull(); + assertThat(observer.completed()).isTrue(); + var decoded = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + request, observer.response()); + assertThat(decoded.phaseState()).isEqualTo("OWNER_EXECUTION_PENDING"); + assertThat(decoded.originalLeaseExpiresAt()).isEqualTo(leaseExpiry); + assertThat(decoded.accountRedemptionProjection()).containsExactly(projection); + assertThat(observer.response().getRequest()) + .isEqualTo(OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toRequest(request)); + verify(repository).readCurrentOriginalAttempt(request); + verifyNoMoreInteractions(repository); + } + + @Test + void rejectsUnknownAndMalformedRequestsBeforeStorageAndAuthenticatesPeerBeforeDecode() { + Request request = request(NAMESPACE); + var wire = OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toRequest(request); + var unknown = + wire.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + GameSessionStartSessionOperatorAttemptRepository repository = mockRepository(); + var service = newService(repository, NAMESPACE); + + assertThat(invokeAs(service, unknown, "account-service").status()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + // The same malformed bytes from a disallowed peer must fail at authentication first. + assertThat(invokeAs(service, unknown, "world-management-service").status()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + invokeAs(service, wire.toBuilder().setExpectedOwnerFence(0L).build(), "account-service") + .status()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(repository); + } + + @Test + void rejectsWrongTargetNamespaceAndEndUserContextBeforeStorage() { + Request otherNamespace = request("other-runtime"); + GameSessionStartSessionOperatorAttemptRepository repository = mockRepository(); + var service = newService(repository, NAMESPACE); + var wrongNamespace = + invokeAs( + service, + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toRequest(otherNamespace), + "account-service"); + assertThat(wrongNamespace.status()).isEqualTo(Status.Code.PERMISSION_DENIED); + + var endUser = + invokeAsWithEndUser( + service, + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toRequest(request(NAMESPACE))); + assertThat(endUser.status()).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void rejectsChangedAttemptMutationFenceTupleOrPhaseReturnedByRepository() { + Request request = request(NAMESPACE); + byte[] exactProjection = canonicalProjection(request); + AttemptSnapshot changedAttempt = + snapshot(request, Instant.parse("2030-01-01T00:00:00Z"), exactProjection); + when(changedAttempt.ownerAttemptId()).thenReturn(uuid("04444444-4444-4444-8444-444444444444")); + AttemptSnapshot changedMutation = + snapshot(request, Instant.parse("2030-01-01T00:00:00Z"), exactProjection); + when(changedMutation.ownerMutationId()) + .thenReturn(uuid("05555555-5555-4555-8555-555555555555")); + AttemptSnapshot changedFence = + snapshot(request, Instant.parse("2030-01-01T00:00:00Z"), exactProjection); + when(changedFence.ownerFence()).thenReturn(FENCE + 1); + AttemptSnapshot changedTuple = + snapshot(request, Instant.parse("2030-01-01T00:00:00Z"), exactProjection); + when(changedTuple.postAuthorizationExecutionTuple()).thenReturn(new byte[] {4}); + AttemptSnapshot changedPhase = + snapshot(request, Instant.parse("2030-01-01T00:00:00Z"), exactProjection); + when(changedPhase.phaseState()).thenReturn("COMMITTED"); + AttemptSnapshot changedProjection = + snapshot(request, Instant.parse("2030-01-01T00:00:00Z"), new byte[] {2}); + GameSessionStartSessionOperatorAttemptRepository repository = mockRepository(); + when(repository.readCurrentOriginalAttempt(ArgumentMatchers.any(Request.class))) + .thenReturn( + changedAttempt, + changedMutation, + changedFence, + changedTuple, + changedPhase, + changedProjection); + var service = newService(repository, NAMESPACE); + AttemptSnapshot[] mismatches = { + changedAttempt, changedMutation, changedFence, changedTuple, changedPhase, changedProjection + }; + for (int index = 0; index < mismatches.length; index++) { + Request freshRequest = + request( + NAMESPACE, uuid(String.format("%08d-4444-4444-8444-%012d", index + 1, index + 1))); + assertThat( + invokeAs( + service, + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toRequest(freshRequest), + "account-service") + .status()) + .isEqualTo(Status.Code.INTERNAL); + } + verify(repository, org.mockito.Mockito.times(6)) + .readCurrentOriginalAttempt(ArgumentMatchers.any(Request.class)); + verifyNoMoreInteractions(repository); + } + + @Test + void expiredOriginalLeaseRemainsReadOnlyAndReturnsFailedPrecondition() { + Request request = request(NAMESPACE); + GameSessionStartSessionOperatorAttemptRepository repository = mockRepository(); + when(repository.readCurrentOriginalAttempt(request)) + .thenThrow( + new StaleStartSessionOperatorAttemptClaimException( + "Game Session owner attempt claim lease is expired")); + var service = newService(repository, NAMESPACE); + + var observer = + invokeAs( + service, + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toRequest(request), + "account-service"); + + assertThat(observer.status()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(observer.response()).isNull(); + verify(repository).readCurrentOriginalAttempt(request); + verifyNoMoreInteractions(repository); + } + + @Test + void unexpectedFailureLogsOnlyExceptionClassAndKeepsInternal() { + Request request = request(NAMESPACE); + String secretMessage = "synthetic attempt storage diagnostic secret"; + String secretReference = "opaque-reference-secret-123456789"; + String expectedLogMessage = + "ReadOriginalStartSessionCurrentAttempt failed with exception class " + + IllegalStateException.class.getName(); + GameSessionStartSessionOperatorAttemptRepository repository = mockRepository(); + when(repository.readCurrentOriginalAttempt(ArgumentMatchers.any(Request.class))) + .thenThrow(new IllegalStateException(secretMessage + " " + secretReference)); + var service = newService(repository, NAMESPACE); + Logger logger = + (Logger) LoggerFactory.getLogger(OriginalStartSessionCurrentAttemptReadGrpcService.class); + ListAppender appender = new ListAppender<>(); + appender.start(); + logger.addAppender(appender); + + try { + var observer = + invokeAs( + service, + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toRequest(request), + "account-service"); + + assertThat(observer.status()).isEqualTo(Status.Code.INTERNAL); + assertThat(observer.error()).isInstanceOf(StatusRuntimeException.class); + assertThat(observer.error().getMessage()) + .contains("Current original StartSession attempt read failed") + .doesNotContain(secretMessage, secretReference); + assertThat(observer.error()).hasNoCause(); + assertThat(appender.list).hasSize(1); + ILoggingEvent event = appender.list.get(0); + assertThat(event.getFormattedMessage()) + .isEqualTo(expectedLogMessage) + .doesNotContain(secretMessage, secretReference); + assertThat(event.getArgumentArray()).containsExactly(IllegalStateException.class.getName()); + assertThat(event.getThrowableProxy()).isNull(); + } finally { + logger.detachAppender(appender); + appender.stop(); + } + } + + private static OriginalStartSessionCurrentAttemptReadGrpcService newService( + GameSessionStartSessionOperatorAttemptRepository repository, String namespace) { + return new OriginalStartSessionCurrentAttemptReadGrpcService( + repository, immediateTransactionManager(), namespace); + } + + private static PlatformTransactionManager immediateTransactionManager() { + return new PlatformTransactionManager() { + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) {} + + @Override + public void rollback(TransactionStatus status) {} + }; + } + + private static GameSessionStartSessionOperatorAttemptRepository mockRepository() { + return mock(GameSessionStartSessionOperatorAttemptRepository.class); + } + + private static AttemptSnapshot snapshot(Request request, Instant expiry, byte[] projection) { + AttemptSnapshot snapshot = mock(AttemptSnapshot.class); + when(snapshot.targetNamespace()).thenReturn(request.targetNamespace()); + when(snapshot.controlPlaneRequestId()) + .thenReturn(request.originalTuple().controlPlaneRequestId()); + when(snapshot.canonicalTenantId()) + .thenReturn(request.originalTuple().preAuthorizationTuple().action().scope().tenantId()); + when(snapshot.ownerAttemptId()).thenReturn(request.expectedOwnerAttemptId()); + when(snapshot.ownerMutationId()).thenReturn(request.expectedOwnerMutationId()); + when(snapshot.ownerFence()).thenReturn(request.expectedOwnerFence()); + when(snapshot.phaseState()) + .thenReturn(OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE); + when(snapshot.postAuthorizationExecutionTuple()) + .thenReturn(request.canonicalPostAuthorizationTuple()); + when(snapshot.leaseExpiresAt()).thenReturn(expiry); + when(snapshot.accountRedemptionProjection()).thenReturn(projection.clone()); + return snapshot; + } + + private static byte[] canonicalProjection(Request request) { + var tuple = request.originalTuple(); + var authority = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + return new AccountRedemptionProjection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + authority.issuanceOperationId(), + Long.parseLong(tuple.issuanceFence())) + .canonicalBytes(); + } + + private static Request request(String namespace) { + return request(namespace, READ_ID); + } + + private static Request request(String namespace, UUID readRequestId) { + return new Request( + readRequestId, namespace, tuple(namespace).canonicalBytes(), ATTEMPT, MUTATION, FENCE); + } + + private static StartSessionPostAuthorizationExecutionTuple tuple(String namespace) { + UUID tenant = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + UUID actor = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + UUID targetOwner = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + UUID reservationOwner = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + UUID issuanceId = uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + UUID tokenJti = uuid("a681bba7-c215-4cf1-a35b-14348912cbdc"); + String fingerprint = "arfp/v1/test-key/" + "b".repeat(64); + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman( + "current-attempt-service-test", + actor, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(tenant, namespace), + new StartSessionOperatorAction.Target(91L, targetOwner), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "canonical StartSession owner attempt")); + Map evidence = + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + actor.toString(), + "controlUiTokenJti", + tokenJti.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3"); + String tenantId = tenant.toString(); + Map bundle = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantId, "targetNamespace", namespace), + "actionFamily", pre.actionFamily(), + "applicableAccountId", actor.toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", issuanceId.toString(), + "controlPlaneRequestId", pre.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + pre.controlPlaneRequestId()), + "mutationDigest", pre.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", + Map.of(tenantId, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + evidence); + byte[] authorityBytes; + try { + authorityBytes = + Rfc8785CanonicalJson.canonicalizeUtf8( + JsonMapper.builder().build().writeValueAsString(bundle)); + } catch (IOException invalid) { + throw new IllegalStateException(invalid); + } + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", + fingerprint, + reservationOwner, + 19L, + authorityBytes, + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static RecordingObserver invokeAs( + OriginalStartSessionCurrentAttemptReadGrpcService service, + ReadOriginalStartSessionCurrentAttemptRequest request, + String serviceName) { + return invokeWithPeer(service, request, serviceName, NAMESPACE, false); + } + + private static RecordingObserver + invokeAsWithEndUser( + OriginalStartSessionCurrentAttemptReadGrpcService service, + ReadOriginalStartSessionCurrentAttemptRequest request) { + return invokeWithPeer(service, request, "account-service", NAMESPACE, true); + } + + private static RecordingObserver invokeWithPeer( + OriginalStartSessionCurrentAttemptReadGrpcService service, + ReadOriginalStartSessionCurrentAttemptRequest request, + String serviceName, + String namespace, + boolean endUser) { + var peer = + new net.firedevops.firemud.common.grpc.GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + serviceName, namespace, serviceName); + Context context = + Context.current() + .withValue(net.firedevops.firemud.common.grpc.GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + if (endUser) { + SessionContext.setContext("42", List.of("tenantAdmin"), Map.of()); + } + RecordingObserver observer = + new RecordingObserver<>(); + service.readOriginalStartSessionCurrentAttempt(request, observer); + return observer; + } finally { + context.detach(previous); + SessionContext.clear(); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class RecordingObserver implements StreamObserver { + private final AtomicReference response = new AtomicReference<>(); + private final AtomicReference error = new AtomicReference<>(); + private volatile boolean completed; + + @Override + public void onNext(T value) { + response.set(value); + } + + @Override + public void onError(Throwable failure) { + error.set(failure); + } + + @Override + public void onCompleted() { + completed = true; + } + + T response() { + return response.get(); + } + + Throwable error() { + return error.get(); + } + + boolean completed() { + return completed; + } + + Status.Code status() { + Throwable failure = error.get(); + return failure instanceof StatusRuntimeException statusFailure + ? statusFailure.getStatus().getCode() + : null; + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadWorkloadGuardTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadWorkloadGuardTest.java new file mode 100644 index 0000000000..bb3edc3526 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadWorkloadGuardTest.java @@ -0,0 +1,79 @@ +package unit.net.firedevops.firemud.gamesession.service.impl; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.service.impl.OriginalStartSessionCurrentAttemptReadWorkloadGuard; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +class OriginalStartSessionCurrentAttemptReadWorkloadGuardTest { + private static final String NAMESPACE = "gameplay"; + private final OriginalStartSessionCurrentAttemptReadWorkloadGuard guard = + new OriginalStartSessionCurrentAttemptReadWorkloadGuard(NAMESPACE); + + @AfterEach + void clearCallerContext() { + SessionContext.clear(); + } + + @Test + void allowsOnlyExactSameNamespaceAccountWorkloadWithoutEndUserContext() { + assertThatCode( + () -> + withPeer( + "account-service", + NAMESPACE, + () -> { + guard.requireAccountCurrentAttemptReadCaller(); + guard.requireConfiguredTargetNamespace(NAMESPACE); + })) + .doesNotThrowAnyException(); + } + + @Test + void refusesWrongNamespaceWrongServiceEndUserContextAndTargetNamespace() { + assertThatThrownBy( + () -> + withPeer("account-service", "other", guard::requireAccountCurrentAttemptReadCaller)) + .isInstanceOf(AdminAuthorizationException.class); + assertThatThrownBy( + () -> + withPeer( + "world-management-service", + NAMESPACE, + guard::requireAccountCurrentAttemptReadCaller)) + .isInstanceOf(AdminAuthorizationException.class); + assertThatThrownBy( + () -> + withPeer( + "account-service", + NAMESPACE, + () -> { + SessionContext.setContext( + "42", java.util.List.of("tenantAdmin"), java.util.Map.of()); + guard.requireAccountCurrentAttemptReadCaller(); + })) + .isInstanceOf(AdminAuthorizationException.class); + assertThatThrownBy(() -> guard.requireConfiguredTargetNamespace("other")) + .isInstanceOf(AdminAuthorizationException.class); + } + + private static void withPeer(String service, String namespace, Runnable action) { + GrpcPeerIdentity peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + action.run(); + } finally { + context.detach(previous); + SessionContext.clear(); + } + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/GameSessionClient.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/GameSessionClient.java index 5a0091717b..bfbbd87dd8 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/GameSessionClient.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/GameSessionClient.java @@ -2,17 +2,32 @@ import jakarta.annotation.PostConstruct; import java.io.IOException; +import java.security.MessageDigest; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; import javax.net.ssl.SSLException; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.FileBackedGrpcMtlsPolicy; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.grpc.GrpcTlsMaterialResolver; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.gamesession.v1.AuthorizeStartSessionRequest; +import net.firedevops.firemud.gamesession.v1.AuthorizeStartSessionResponse; import net.firedevops.firemud.gamesession.v1.GameSessionServiceGrpc; import net.firedevops.firemud.gamesession.v1.PingRequest; import net.firedevops.firemud.gamesession.v1.PingResponse; +import net.firedevops.firemud.gamesession.v1.StartSessionOwnerAuthorizationProgress; import net.firedevops.firemud.gamesession.v1.StopSessionRequest; import net.firedevops.firemud.gamesession.v1.StopSessionResponse; +import net.firedevops.firemud.loggingadmin.operator.StartSessionAuthorizationCoordinator.TransientOwnerExecutionHandoff; import org.springframework.stereotype.Component; /** gRPC client for communicating with the Game Session Service. */ @@ -20,12 +35,20 @@ public class GameSessionClient extends AbstractReloadingBlockingGrpcClient< GameSessionServiceGrpc.GameSessionServiceBlockingStub> { + private static final long START_SESSION_HANDOFF_DEADLINE_SECONDS = 5L; + private static final Pattern OPAQUE_OPERATOR_REFERENCE = Pattern.compile("[A-Za-z0-9_-]{43}"); + private static final Pattern CANONICAL_UUID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + + private final CommonGrpcClientProperties transportTlsProperties; + public GameSessionClient( ServiceEndpointsProperties endpoints, CommonGrpcClientProperties tlsProps, GrpcChannelFactory channelFactory, BlockingGrpcStubCustomizer stubCustomizer) { super(endpoints, tlsProps, channelFactory, stubCustomizer, GameSessionClient.class); + this.transportTlsProperties = tlsProps.copy(); } @PostConstruct @@ -61,4 +84,181 @@ public StopSessionResponse stopSession(long sessionId) { StopSessionRequest.newBuilder().setSessionId(Long.toString(sessionId)).build(); return stub().stopSession(request); } + + /** + * Sends the one transient handoff returned after Logging durably records owner-pending state. + * This method performs exactly one bounded RPC and never retries an ambiguous owner result. + */ + public StartSessionOwnerHandoffResult authorizeStartSession( + TransientOwnerExecutionHandoff handoff) { + Objects.requireNonNull(handoff, "durable Logging owner handoff is required"); + StartSessionPostAuthorizationExecutionTuple tuple = handoff.postAuthorizationTuple(); + String reference = handoff.accountResponse().operatorAuthorizationReference(); + byte[] tupleBytes = tuple.canonicalBytes(); + if (tupleBytes.length == 0 + || tupleBytes.length > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + || !OPAQUE_OPERATOR_REFERENCE.matcher(reference).matches() + || !tuple + .authenticatedWorkloadIdentity() + .equals(handoff.accountResponse().authenticatedLoggingWorkloadIdentity()) + || !tuple + .authorizationReferenceFingerprint() + .equals(handoff.accountResponse().authorizationReferenceFingerprint()) + || !tuple.bundleReference().equals(handoff.accountResponse().bundleReference()) + || !MessageDigest.isEqual( + tuple.authorityEvidenceBundleBytes(), + handoff.accountResponse().authorityEvidenceBundle())) { + throw new IllegalArgumentException("Logging StartSession handoff is not internally bound"); + } + String targetNamespace = tuple.preAuthorizationTuple().action().scope().targetNamespace(); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Logging StartSession handoff namespace is invalid"); + } + requireFileBackedMtls(); + String expectedServerUri = + "spiffe://firemud/ns/" + targetNamespace + "/sa/game-session-service"; + + AuthorizeStartSessionRequest request = + AuthorizeStartSessionRequest.newBuilder() + .setCanonicalPostAuthorizationExecutionTupleBytes( + com.google.protobuf.ByteString.copyFrom(tupleBytes)) + .setOperatorAuthorizationReference(reference) + .build(); + AuthorizeStartSessionResponse response; + try { + response = + Objects.requireNonNull(stub(), "Game Session client is not initialized") + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedServerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedServerUri)) + .withDeadlineAfter(START_SESSION_HANDOFF_DEADLINE_SECONDS, TimeUnit.SECONDS) + .authorizeStartSession(request); + } catch (io.grpc.StatusRuntimeException ambiguousTransportOutcome) { + throw new AmbiguousOwnerHandoffException(ambiguousTransportOutcome.getStatus().getCode()); + } + return validateOwnerHandoffResponse(tuple, response); + } + + private void requireFileBackedMtls() { + FileBackedGrpcMtlsPolicy.require( + transportTlsProperties, + new GrpcTlsMaterialResolver(), + "StartSession owner handoff", + "StartSession owner handoff requires workload mTLS"); + } + + private static StartSessionOwnerHandoffResult validateOwnerHandoffResponse( + StartSessionPostAuthorizationExecutionTuple tuple, AuthorizeStartSessionResponse response) { + Objects.requireNonNull(response, "Game Session owner response is required"); + if (!response.getUnknownFields().asMap().isEmpty()) { + throw new IllegalStateException("Game Session returned an unknown owner-handoff response"); + } + if (response.hasError()) { + if (!response.getError().getUnknownFields().asMap().isEmpty()) { + throw new IllegalStateException("Game Session returned an unknown owner-handoff error"); + } + throw new OwnerHandoffRejectedException(response.getError().getCode()); + } + + StartSessionOwnerAuthorizationProgress progress = response.getProgress(); + boolean supportedProgress = + switch (progress) { + case START_SESSION_OWNER_AUTHORIZATION_PROGRESS_EXACT_REPLAY, + START_SESSION_OWNER_AUTHORIZATION_PROGRESS_ACCOUNT_OUTCOME_AMBIGUOUS, + START_SESSION_OWNER_AUTHORIZATION_PROGRESS_ACCOUNT_PROJECTION_ATTACHED -> + true; + default -> false; + }; + if (!tuple + .preAuthorizationTuple() + .action() + .scope() + .targetNamespace() + .equals(response.getTargetNamespace()) + || !tuple.controlPlaneRequestId().equals(response.getControlPlaneRequestId()) + || !tuple.mutationDigest().equals(response.getMutationDigest()) + || !canonicalNonNilUuid(response.getOwnerAttemptId()) + || !canonicalNonNilUuid(response.getOwnerMutationId()) + || response.getOwnerFence() <= 0L + || !"OWNER_EXECUTION_PENDING".equals(response.getOwnerPhaseState()) + || !supportedProgress) { + throw new IllegalStateException("Game Session owner response does not match the handoff"); + } + return new StartSessionOwnerHandoffResult( + response.getTargetNamespace(), + response.getControlPlaneRequestId(), + response.getMutationDigest(), + UUID.fromString(response.getOwnerAttemptId()), + UUID.fromString(response.getOwnerMutationId()), + response.getOwnerFence(), + response.getOwnerPhaseState(), + progress); + } + + private static boolean canonicalNonNilUuid(String value) { + if (value == null || !CANONICAL_UUID.matcher(value).matches()) { + return false; + } + try { + UUID parsed = UUID.fromString(value); + return parsed.toString().equals(value) && !parsed.equals(new UUID(0L, 0L)); + } catch (IllegalArgumentException malformed) { + return false; + } + } + + /** Secret-free exact owner echo returned by the bounded StartSession handoff call. */ + public record StartSessionOwnerHandoffResult( + String targetNamespace, + String controlPlaneRequestId, + String mutationDigest, + UUID ownerAttemptId, + UUID ownerMutationId, + long ownerFence, + String ownerPhaseState, + StartSessionOwnerAuthorizationProgress progress) { + public StartSessionOwnerHandoffResult { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + Objects.requireNonNull(controlPlaneRequestId, "controlPlaneRequestId"); + Objects.requireNonNull(mutationDigest, "mutationDigest"); + Objects.requireNonNull(ownerAttemptId, "ownerAttemptId"); + Objects.requireNonNull(ownerMutationId, "ownerMutationId"); + Objects.requireNonNull(ownerPhaseState, "ownerPhaseState"); + Objects.requireNonNull(progress, "progress"); + } + } + + /** Transport ambiguity is surfaced without the raw request or authorization reference. */ + public static final class AmbiguousOwnerHandoffException extends RuntimeException { + private static final long serialVersionUID = 1L; + + private final io.grpc.Status.Code statusCode; + + private AmbiguousOwnerHandoffException(io.grpc.Status.Code statusCode) { + super("Game Session owner-handoff outcome is ambiguous; automatic retry was not attempted"); + this.statusCode = Objects.requireNonNull(statusCode, "statusCode"); + } + + public io.grpc.Status.Code statusCode() { + return statusCode; + } + } + + /** Bounded owner rejection code; no response body or transient reference is retained. */ + public static final class OwnerHandoffRejectedException extends RuntimeException { + private static final long serialVersionUID = 1L; + + private final String code; + + private OwnerHandoffRejectedException(String code) { + super("Game Session rejected the StartSession owner handoff"); + if (code == null || !code.matches("[A-Z][A-Z0-9_]{0,63}")) { + throw new IllegalArgumentException("owner rejection code is invalid"); + } + this.code = code; + } + + public String code() { + return code; + } + } } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java new file mode 100644 index 0000000000..a3cc8ef137 --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java @@ -0,0 +1,404 @@ +package net.firedevops.firemud.loggingadmin.client; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Timestamp; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AuthorityEvidenceBundleReference; +import net.firedevops.firemud.account.v1.IssueHumanOperatorAuthorizationReferenceRequest; +import net.firedevops.firemud.account.v1.IssueHumanOperatorAuthorizationReferenceResponse; +import net.firedevops.firemud.account.v1.RecoverOperatorAuthorizationReferenceRequest; +import net.firedevops.firemud.account.v1.RecoverOperatorAuthorizationReferenceResponse; +import net.firedevops.firemud.account.v1.StartSessionOperatorAuthorizationServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.FileBackedGrpcMtlsPolicy; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.grpc.GrpcTlsMaterialResolver; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; + +/** + * Explicitly initialized, typed Logging & Admin client for Account's StartSession issue/recover + * boundary. This class does not activate a route or authorize a mutation; callers must establish + * the current Logging reservation claim before calling it. + */ +public class StartSessionOperatorAuthorizationClient + extends AbstractReloadingBlockingGrpcClient< + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub> { + private static final int MAX_TUPLE_BYTES = 8 * 1_024; + private static final int MAX_CONTROL_UI_TOKEN_BYTES = 16 * 1_024; + private static final int MAX_REFERENCE_BYTES = 128; + private static final long RPC_DEADLINE_SECONDS = 5L; + private static final long MAX_PROTO_TIMESTAMP_SECONDS = 253_402_300_799L; + private static final Pattern OPAQUE_REFERENCE = Pattern.compile("[A-Za-z0-9_-]{43}"); + private static final Pattern REFERENCE_FINGERPRINT = + Pattern.compile("arfp/v1/[A-Za-z0-9_-]{1,64}/[0-9a-f]{64}"); + + private final Clock clock; + private final CommonGrpcClientProperties transportTlsProperties; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Construction validates and copies inputs only; managed channels and watchers are acquired by initialize().") + public StartSessionOperatorAuthorizationClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + BlockingGrpcStubCustomizer stubCustomizer) { + this(endpoints, tlsProps, channelFactory, stubCustomizer, Clock.systemUTC()); + } + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Construction validates and copies inputs only; managed channels and watchers are acquired by initialize().") + public StartSessionOperatorAuthorizationClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + BlockingGrpcStubCustomizer stubCustomizer, + Clock clock) { + super( + endpoints, + tlsProps, + channelFactory, + stubCustomizer, + StartSessionOperatorAuthorizationClient.class); + this.clock = Objects.requireNonNull(clock, "clock is required"); + this.transportTlsProperties = + Objects.requireNonNull(tlsProps, "TLS properties are required").copy(); + } + + /** + * Opens the standard managed TLS channel only when an owning workflow explicitly initializes it. + */ + public void initialize() throws SSLException, IOException { + initReloadingClient(); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + buildStub(io.grpc.ManagedChannel channel) { + return applyStubCustomizer( + StartSessionOperatorAuthorizationServiceGrpc.newBlockingStub(channel) + .withCompression("gzip")); + } + + /** Issues the original human tenant-admin reference using the current Logging claim tuple. */ + public AuthorizationReference issueHuman( + StartSessionPreAuthorizationReservationTuple tuple, + String controlUiJwt, + UUID reservationOwnerId, + long reservationClaimFence, + UUID currentClaimOwnerId, + long currentClaimFence) { + byte[] tupleBytes = canonicalTupleBytes(tuple); + requireVisibleAsciiToken(controlUiJwt); + requireOwnerFence(reservationOwnerId, reservationClaimFence, "reservation owner"); + requireOwnerFence(currentClaimOwnerId, currentClaimFence, "current claim owner"); + IssueHumanOperatorAuthorizationReferenceRequest request = + IssueHumanOperatorAuthorizationReferenceRequest.newBuilder() + .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(tupleBytes)) + .setControlUiJwt(controlUiJwt) + .setReservationOwnerId(reservationOwnerId.toString()) + .setReservationClaimFence(reservationClaimFence) + .setCurrentClaimOwnerId(currentClaimOwnerId.toString()) + .setCurrentClaimFence(currentClaimFence) + .build(); + IssueHumanOperatorAuthorizationReferenceResponse response = + requirePinnedAccountStub(tuple.action().scope().targetNamespace()) + .withDeadlineAfter(RPC_DEADLINE_SECONDS, TimeUnit.SECONDS) + .issueHumanOperatorAuthorizationReference(request); + return validateResponse( + response.getOperatorAuthorizationReference(), + response.getAuthorizationReferenceFingerprint(), + response.hasExpiresAt(), + response.getExpiresAt(), + response.getAuthorityEvidenceBundle().toByteArray(), + response.hasBundleReference(), + response.getBundleReference(), + response.getUnknownFields().asMap().isEmpty(), + response.getAuthenticatedLoggingWorkloadIdentity(), + tuple); + } + + /** Looks up and recovers only the exact original issuance response under a fresh claim. */ + public AuthorizationReference recover( + StartSessionPreAuthorizationReservationTuple tuple, + UUID reservationOwnerId, + long reservationClaimFence, + UUID currentClaimOwnerId, + long currentClaimFence) { + byte[] tupleBytes = canonicalTupleBytes(tuple); + requireOwnerFence(reservationOwnerId, reservationClaimFence, "reservation owner"); + requireOwnerFence(currentClaimOwnerId, currentClaimFence, "current claim owner"); + RecoverOperatorAuthorizationReferenceRequest request = + RecoverOperatorAuthorizationReferenceRequest.newBuilder() + .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(tupleBytes)) + .setReservationOwnerId(reservationOwnerId.toString()) + .setReservationClaimFence(reservationClaimFence) + .setCurrentClaimOwnerId(currentClaimOwnerId.toString()) + .setCurrentClaimFence(currentClaimFence) + .build(); + RecoverOperatorAuthorizationReferenceResponse response = + requirePinnedAccountStub(tuple.action().scope().targetNamespace()) + .withDeadlineAfter(RPC_DEADLINE_SECONDS, TimeUnit.SECONDS) + .recoverOperatorAuthorizationReference(request); + return validateResponse( + response.getOperatorAuthorizationReference(), + response.getAuthorizationReferenceFingerprint(), + response.hasExpiresAt(), + response.getExpiresAt(), + response.getAuthorityEvidenceBundle().toByteArray(), + response.hasBundleReference(), + response.getBundleReference(), + response.getUnknownFields().asMap().isEmpty(), + response.getAuthenticatedLoggingWorkloadIdentity(), + tuple); + } + + private StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + requireStub() { + var value = stub(); + if (value == null) { + throw new IllegalStateException("Account authorization client has not been initialized"); + } + return value; + } + + private StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + requirePinnedAccountStub(String targetNamespace) { + String expectedServerUri = accountServerUri(targetNamespace); + requireFileBackedMtls(); + return requireStub() + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedServerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedServerUri)); + } + + static String accountServerUri(String targetNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("StartSession target namespace is invalid"); + } + return "spiffe://firemud/ns/" + targetNamespace + "/sa/account-service"; + } + + private void requireFileBackedMtls() { + FileBackedGrpcMtlsPolicy.require( + transportTlsProperties, + new GrpcTlsMaterialResolver(), + "Account authorization", + "Account authorization requires workload mTLS"); + } + + private AuthorizationReference validateResponse( + String opaqueReference, + String fingerprint, + boolean hasExpiry, + Timestamp expiryTimestamp, + byte[] authorityEvidenceBundle, + boolean hasBundleReference, + AuthorityEvidenceBundleReference wireReference, + boolean hasNoUnknownFields, + String authenticatedLoggingWorkloadIdentity, + StartSessionPreAuthorizationReservationTuple tuple) { + try { + if (!hasNoUnknownFields || !hasExpiry || !hasBundleReference) { + throw malformedResponse(); + } + requireAuthenticatedLoggingIdentity( + authenticatedLoggingWorkloadIdentity, tuple.action().scope().targetNamespace()); + if (!OPAQUE_REFERENCE.matcher(opaqueReference).matches() + || opaqueReference.getBytes(StandardCharsets.UTF_8).length > MAX_REFERENCE_BYTES + || !REFERENCE_FINGERPRINT.matcher(fingerprint).matches()) { + throw malformedResponse(); + } + if (!expiryTimestamp.getUnknownFields().asMap().isEmpty()) { + throw malformedResponse(); + } + Instant expiresAt = exactExpiry(expiryTimestamp); + if (!expiresAt.isAfter(clock.instant())) { + throw new IllegalStateException("Account authorization response is expired"); + } + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(authorityEvidenceBundle); + bundle.requireTupleBinding(tuple); + if (!expiresAt.equals(bundle.expiresAt())) { + throw malformedResponse(); + } + StartSessionAuthorityEvidenceBundle.BundleReference reference = + new StartSessionAuthorityEvidenceBundle.BundleReference( + wireReference.getBundleVersion(), + wireReference.getSourceVersion(), + wireReference.getSourceFence(), + wireReference.getLinearization()); + bundle.requireReferenceBinding(reference); + if (!wireReference.getUnknownFields().asMap().isEmpty()) { + throw malformedResponse(); + } + return new AuthorizationReference( + opaqueReference, + fingerprint, + expiresAt, + authorityEvidenceBundle, + reference, + authenticatedLoggingWorkloadIdentity, + bundle); + } catch (IllegalStateException expected) { + throw expected; + } catch (RuntimeException malformed) { + throw malformedResponse(); + } + } + + private static Instant exactExpiry(Timestamp timestamp) { + long seconds = timestamp.getSeconds(); + int nanos = timestamp.getNanos(); + if (seconds <= 0L + || seconds > MAX_PROTO_TIMESTAMP_SECONDS + || nanos < 0 + || nanos >= 1_000_000_000 + || nanos % 1_000_000 != 0) { + throw malformedResponse(); + } + return Instant.ofEpochSecond(seconds, nanos); + } + + private static void requireAuthenticatedLoggingIdentity( + String identityText, String targetNamespace) { + GrpcPeerIdentity identity = + GrpcPeerIdentity.parseUri(identityText) + .orElseThrow(StartSessionOperatorAuthorizationClient::malformedResponse); + if (!identityText.equals(identity.uri()) + || !"logging-admin-service".equals(identity.service()) + || !targetNamespace.equals(identity.namespace())) { + throw malformedResponse(); + } + } + + private static byte[] canonicalTupleBytes(StartSessionPreAuthorizationReservationTuple tuple) { + Objects.requireNonNull(tuple, "pre-authorization tuple is required"); + byte[] bytes = tuple.canonicalJson().getBytes(StandardCharsets.UTF_8); + if (bytes.length == 0 || bytes.length > MAX_TUPLE_BYTES) { + throw new IllegalArgumentException("StartSession tuple exceeds its supported bound"); + } + return bytes; + } + + private static void requireVisibleAsciiToken(String token) { + if (token == null + || token.isEmpty() + || token.getBytes(StandardCharsets.UTF_8).length > MAX_CONTROL_UI_TOKEN_BYTES + || token.chars().anyMatch(value -> value < 0x21 || value > 0x7e)) { + throw new IllegalArgumentException("control-ui token is invalid or over its supported bound"); + } + } + + private static void requireOwnerFence(UUID owner, long fence, String field) { + if (owner == null || owner.equals(new UUID(0L, 0L)) || fence <= 0L) { + throw new IllegalArgumentException(field + " and positive fence are required"); + } + } + + private static IllegalStateException malformedResponse() { + return new IllegalStateException( + "Account returned a malformed StartSession authorization response"); + } + + /** Response identity with defensive bundle bytes and a redacted diagnostic representation. */ + public static final class AuthorizationReference { + private final String operatorAuthorizationReference; + private final String authorizationReferenceFingerprint; + private final Instant expiresAt; + private final byte[] authorityEvidenceBundle; + private final StartSessionAuthorityEvidenceBundle.BundleReference bundleReference; + private final String authenticatedLoggingWorkloadIdentity; + private final StartSessionAuthorityEvidenceBundle decodedBundle; + + private AuthorizationReference( + String operatorAuthorizationReference, + String authorizationReferenceFingerprint, + Instant expiresAt, + byte[] authorityEvidenceBundle, + StartSessionAuthorityEvidenceBundle.BundleReference bundleReference, + String authenticatedLoggingWorkloadIdentity, + StartSessionAuthorityEvidenceBundle decodedBundle) { + this.operatorAuthorizationReference = operatorAuthorizationReference; + this.authorizationReferenceFingerprint = authorizationReferenceFingerprint; + this.expiresAt = expiresAt; + this.authorityEvidenceBundle = authorityEvidenceBundle.clone(); + this.bundleReference = bundleReference; + this.authenticatedLoggingWorkloadIdentity = authenticatedLoggingWorkloadIdentity; + this.decodedBundle = decodedBundle; + } + + public String operatorAuthorizationReference() { + return operatorAuthorizationReference; + } + + public String authorizationReferenceFingerprint() { + return authorizationReferenceFingerprint; + } + + public Instant expiresAt() { + return expiresAt; + } + + public byte[] authorityEvidenceBundle() { + return authorityEvidenceBundle.clone(); + } + + public StartSessionAuthorityEvidenceBundle.BundleReference bundleReference() { + return bundleReference; + } + + /** Account's exact authenticated Logging peer identity echoed after successful verification. */ + public String authenticatedLoggingWorkloadIdentity() { + return authenticatedLoggingWorkloadIdentity; + } + + public StartSessionAuthorityEvidenceBundle decodedBundle() { + return decodedBundle; + } + + @Override + public String toString() { + return "AuthorizationReference[operatorAuthorizationReference=, " + + "authorizationReferenceFingerprint=, expiresAt=" + + expiresAt + + ", authorityEvidenceBundle=, bundleReference=" + + bundleReference + + ", authenticatedLoggingWorkloadIdentity=" + + authenticatedLoggingWorkloadIdentity + + "]"; + } + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/config/StartSessionOperatorAuthorizationConfiguration.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/config/StartSessionOperatorAuthorizationConfiguration.java new file mode 100644 index 0000000000..53bcb79115 --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/config/StartSessionOperatorAuthorizationConfiguration.java @@ -0,0 +1,64 @@ +package net.firedevops.firemud.loggingadmin.config; + +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.FileBackedGrpcMtlsPolicy; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcTlsMaterialResolver; +import net.firedevops.firemud.loggingadmin.client.StartSessionOperatorAuthorizationClient; +import net.firedevops.firemud.loggingadmin.operator.StartSessionAuthorizationCoordinator; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * Disabled-by-default composition for the Logging/Admin StartSession authorization coordinator. + * + *

This supplies no ingress, request authority, reservation state, or TLS material. Enabling it + * requires the existing durable reservation owner, a canonical workload namespace, and readable + * file-backed client mTLS inputs. + */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = StartSessionOperatorAuthorizationConfiguration.PROPERTY_PREFIX, + name = "enabled", + havingValue = "true", + matchIfMissing = false) +public class StartSessionOperatorAuthorizationConfiguration { + static final String PROPERTY_PREFIX = + "firemud.logging-admin.start-session-operator-authorization"; + + /** Opens the standard Account client only when this explicitly enabled composition is loaded. */ + @Bean(initMethod = "initialize", destroyMethod = "close") + public StartSessionOperatorAuthorizationClient startSessionOperatorAuthorizationClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + BlockingGrpcStubCustomizer stubCustomizer, + GrpcTlsMaterialResolver tlsMaterialResolver, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException( + "A valid configured workload namespace is required for StartSession authorization"); + } + FileBackedGrpcMtlsPolicy.require( + tlsProperties, + tlsMaterialResolver, + "StartSession authorization", + "StartSession authorization requires file-backed workload mTLS"); + return new StartSessionOperatorAuthorizationClient( + endpoints, tlsProperties, channelFactory, stubCustomizer); + } + + /** Wires the durable Logging reservation owner to its explicitly initialized Account client. */ + @Bean + public StartSessionAuthorizationCoordinator startSessionAuthorizationCoordinator( + StartSessionPreAuthorizationReservationService reservations, + StartSessionOperatorAuthorizationClient accountClient) { + return new StartSessionAuthorizationCoordinator(reservations, accountClient); + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java new file mode 100644 index 0000000000..17ea2e6784 --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java @@ -0,0 +1,236 @@ +package net.firedevops.firemud.loggingadmin.operator; + +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.loggingadmin.client.GameSessionClient; +import net.firedevops.firemud.loggingadmin.client.StartSessionOperatorAuthorizationClient; +import net.firedevops.firemud.loggingadmin.client.StartSessionOperatorAuthorizationClient.AuthorizationReference; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Acquisition; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.AuthorizationCompletion; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimEvidence; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimHandle; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.OwnerExecutionHandoff; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.OwnerExecutionTransition; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.PendingTransition; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.RecoveryAcquisition; + +/** + * Coordinates Account authorization and durably records the owner handoff without activating an + * ingress. Explicit dispatch methods forward only a newly committed owner-pending handoff. + * + *

The Account issue call occurs only after the original claim wins the durable pending + * transition. The Account recovery call is read-only and uses a fresh recovery claim. A transient + * owner payload is returned only after both the Account response and the OWNER_EXECUTION_PENDING + * handoff are durable; neither the raw reference nor the forwarded control-ui token is persisted or + * logged here. + */ +public final class StartSessionAuthorizationCoordinator { + private final StartSessionPreAuthorizationReservationService reservations; + private final StartSessionOperatorAuthorizationClient accountClient; + + public StartSessionAuthorizationCoordinator( + StartSessionPreAuthorizationReservationService reservations, + StartSessionOperatorAuthorizationClient accountClient) { + this.reservations = Objects.requireNonNull(reservations, "reservation service is required"); + this.accountClient = Objects.requireNonNull(accountClient, "Account client is required"); + } + + /** Begins human issuance only for the first reservation owner that wins AUTHORIZATION_PENDING. */ + public Result issueHuman( + StartSessionPreAuthorizationReservationTuple tuple, String controlUiJwt) { + Objects.requireNonNull(tuple, "pre-authorization tuple is required"); + Acquisition acquisition = reservations.acquire(tuple); + if (!acquisition.newlyAcquired()) { + return Result.alreadyInProgress(); + } + + ClaimHandle claim = acquisition.claim(); + PendingTransition pending = reservations.markAuthorizationPending(claim); + if (!pending.mayDispatchAccountAuthorization()) { + return Result.alreadyInProgress(); + } + + ClaimEvidence claimEvidence = claim.claimEvidence(); + AuthorizationReference accountResponse = + accountClient.issueHuman( + sharedTuple(tuple), + controlUiJwt, + claimEvidence.reservationOwnerId(), + claimEvidence.reservationClaimFence(), + claimEvidence.currentClaimOwnerId(), + claimEvidence.currentClaimFence()); + return persistExactAccountResponse(tuple, claim, accountResponse); + } + + /** Issues the human reference and forwards only this invocation's durable owner-pending win. */ + public OwnerDispatchResult issueHumanAndDispatch( + StartSessionPreAuthorizationReservationTuple tuple, + String controlUiJwt, + GameSessionClient ownerClient) { + Objects.requireNonNull(ownerClient, "Game Session owner client is required"); + return dispatchOwnerPending(issueHuman(tuple, controlUiJwt), ownerClient); + } + + /** Recovers only the original issuance response under a fresh read-only recovery claim. */ + public Result recover(StartSessionPreAuthorizationReservationTuple tuple) { + Objects.requireNonNull(tuple, "pre-authorization tuple is required"); + Optional acquired = reservations.acquireAuthorizationRecoveryClaim(tuple); + if (acquired.isEmpty()) { + return Result.recoveryUnavailable(); + } + + ClaimHandle claim = acquired.orElseThrow().claim(); + ClaimEvidence claimEvidence = claim.claimEvidence(); + AuthorizationReference accountResponse = + accountClient.recover( + sharedTuple(tuple), + claimEvidence.reservationOwnerId(), + claimEvidence.reservationClaimFence(), + claimEvidence.currentClaimOwnerId(), + claimEvidence.currentClaimFence()); + return persistExactAccountResponse(tuple, claim, accountResponse); + } + + /** Recovers the original reference and forwards only a newly persisted owner-pending handoff. */ + public OwnerDispatchResult recoverAndDispatch( + StartSessionPreAuthorizationReservationTuple tuple, GameSessionClient ownerClient) { + Objects.requireNonNull(ownerClient, "Game Session owner client is required"); + return dispatchOwnerPending(recover(tuple), ownerClient); + } + + private static OwnerDispatchResult dispatchOwnerPending( + Result authorization, GameSessionClient ownerClient) { + Objects.requireNonNull(authorization, "authorization result is required"); + Objects.requireNonNull(ownerClient, "Game Session owner client is required"); + if (authorization.progress() != Progress.OWNER_EXECUTION_PENDING) { + return new OwnerDispatchResult(authorization.progress(), Optional.empty()); + } + GameSessionClient.StartSessionOwnerHandoffResult ownerEcho = + Objects.requireNonNull( + ownerClient.authorizeStartSession(authorization.handoff()), + "Game Session owner echo is required"); + return new OwnerDispatchResult(authorization.progress(), Optional.of(ownerEcho)); + } + + private Result persistExactAccountResponse( + StartSessionPreAuthorizationReservationTuple tuple, + ClaimHandle claim, + AuthorizationReference accountResponse) { + Objects.requireNonNull(accountResponse, "validated Account response is required"); + StartSessionPostAuthorizationExecutionTuple postAuthorizationTuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + sharedTuple(tuple), + accountResponse.authenticatedLoggingWorkloadIdentity(), + accountResponse.authorizationReferenceFingerprint(), + claim.claimEvidence().reservationOwnerId(), + claim.claimEvidence().reservationClaimFence(), + accountResponse.authorityEvidenceBundle(), + accountResponse.bundleReference()); + AuthorizationCompletion completion = + reservations.completeAuthorization(claim, postAuthorizationTuple); + if (!completion.transitioned()) { + return Result.alreadyInProgress(); + } + OwnerExecutionHandoff handoff = new OwnerExecutionHandoff(UUID.randomUUID()); + OwnerExecutionTransition ownerTransition = + reservations.beginOwnerExecution(claim, postAuthorizationTuple, handoff); + if (!ownerTransition.mayDispatch()) { + return Result.alreadyInProgress(); + } + return Result.ownerExecutionPending( + new TransientOwnerExecutionHandoff( + ownerTransition.snapshot().handoff(), accountResponse, postAuthorizationTuple)); + } + + private static net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + sharedTuple(StartSessionPreAuthorizationReservationTuple tuple) { + return net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .fromCanonicalJson(tuple.canonicalJson()); + } + + public enum Progress { + OWNER_EXECUTION_PENDING, + ALREADY_IN_PROGRESS, + RECOVERY_UNAVAILABLE + } + + /** Contains no response material unless this call won the durable owner-pending transition. */ + public record Result(Progress progress, TransientOwnerExecutionHandoff handoff) { + public Result { + Objects.requireNonNull(progress, "progress is required"); + if ((progress == Progress.OWNER_EXECUTION_PENDING) != (handoff != null)) { + throw new IllegalArgumentException( + "only newly persisted owner-pending state has a handoff"); + } + } + + private static Result ownerExecutionPending(TransientOwnerExecutionHandoff handoff) { + return new Result(Progress.OWNER_EXECUTION_PENDING, handoff); + } + + private static Result alreadyInProgress() { + return new Result(Progress.ALREADY_IN_PROGRESS, null); + } + + private static Result recoveryUnavailable() { + return new Result(Progress.RECOVERY_UNAVAILABLE, null); + } + + @Override + public String toString() { + return "Result[progress=" + + progress + + ", handoff=" + + (handoff == null ? "null" : "") + + "]"; + } + } + + /** + * Safe composition result: original progress and, only after dispatch, a secret-free owner echo. + */ + public record OwnerDispatchResult( + Progress progress, Optional ownerEcho) { + public OwnerDispatchResult { + Objects.requireNonNull(progress, "progress is required"); + Objects.requireNonNull(ownerEcho, "owner echo optional is required"); + if ((progress == Progress.OWNER_EXECUTION_PENDING) != ownerEcho.isPresent()) { + throw new IllegalArgumentException( + "only a newly committed owner-pending handoff has an owner echo"); + } + } + + @Override + public String toString() { + return "OwnerDispatchResult[progress=" + + progress + + ", ownerEcho=" + + (ownerEcho.isPresent() ? "" : "empty") + + "]"; + } + } + + /** + * Transient caller handoff; its diagnostic representation never includes raw authorization data. + */ + public record TransientOwnerExecutionHandoff( + OwnerExecutionHandoff ownerExecutionHandoff, + AuthorizationReference accountResponse, + StartSessionPostAuthorizationExecutionTuple postAuthorizationTuple) { + public TransientOwnerExecutionHandoff { + Objects.requireNonNull(ownerExecutionHandoff, "owner execution handoff is required"); + Objects.requireNonNull(accountResponse, "Account response is required"); + Objects.requireNonNull(postAuthorizationTuple, "post-authorization tuple is required"); + } + + @Override + public String toString() { + return "TransientOwnerExecutionHandoff[ownerExecutionHandoff=" + + ownerExecutionHandoff + + ", accountResponse=, " + + "postAuthorizationTuple=]"; + } + } +} diff --git a/services/logging-admin-service/src/main/resources/application.yml b/services/logging-admin-service/src/main/resources/application.yml index 6a39443553..95df69e181 100644 --- a/services/logging-admin-service/src/main/resources/application.yml +++ b/services/logging-admin-service/src/main/resources/application.yml @@ -72,3 +72,6 @@ firemud: workload-namespace: ${FIREMUD_GRPC_WORKLOAD_NAMESPACE:} account-reservation-evidence: approved-leaf-file: ${FIREMUD_GRPC_ACCOUNT_RESERVATION_EVIDENCE_APPROVED_LEAF_FILE:} + logging-admin: + start-session-operator-authorization: + enabled: ${FIREMUD_LOGGING_ADMIN_START_SESSION_OPERATOR_AUTHORIZATION_ENABLED:false} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/GameSessionClientTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/GameSessionClientTest.java index 16ac0c1060..a6c8b8266f 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/GameSessionClientTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/GameSessionClientTest.java @@ -1,18 +1,59 @@ package net.firedevops.firemud.loggingadmin.client; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.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.when; +import io.grpc.CallCredentials; +import io.grpc.ClientInterceptor; import io.grpc.ManagedChannel; +import io.grpc.Status; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.gamesession.v1.AuthorizeStartSessionRequest; +import net.firedevops.firemud.gamesession.v1.AuthorizeStartSessionResponse; import net.firedevops.firemud.gamesession.v1.GameSessionServiceGrpc; +import net.firedevops.firemud.gamesession.v1.StartSessionOwnerAuthorizationProgress; +import net.firedevops.firemud.loggingadmin.client.StartSessionOperatorAuthorizationClient.AuthorizationReference; +import net.firedevops.firemud.loggingadmin.operator.StartSessionAuthorizationCoordinator.TransientOwnerExecutionHandoff; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.OwnerExecutionHandoff; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.ArgumentCaptor; class GameSessionClientTest { + @TempDir private Path tlsDirectory; + + private static final long DEADLINE_SECONDS = 5L; + private static final String OPAQUE_REFERENCE = "A".repeat(43); + private static final String LOGGING_IDENTITY = + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; + private static final UUID TENANT_ID = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR_ID = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID OWNER_ID = UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID RESERVATION_OWNER = + UUID.fromString("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID OWNER_ATTEMPT = UUID.fromString("69116466-a576-4fa6-9e11-4c0c6b2a92f0"); + private static final UUID OWNER_MUTATION = + UUID.fromString("89da7d84-12f5-4cf8-b69b-30ba8eb115a4"); @Test void buildStubAppliesInjectedStubCustomizer() { @@ -40,6 +81,245 @@ public > T customize(T candidate) { assertThat(customized.get()).isSameAs(stub); } + @Test + void sendsOneExactTypedHandoffAndValidatesSecretFreeOwnerEcho() throws Exception { + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); + var handoff = handoff(); + StartSessionPostAuthorizationExecutionTuple tuple = handoff.postAuthorizationTuple(); + AuthorizeStartSessionResponse response = + ownerResponse( + tuple, + StartSessionOwnerAuthorizationProgress + .START_SESSION_OWNER_AUTHORIZATION_PROGRESS_ACCOUNT_OUTCOME_AMBIGUOUS); + when(stub.authorizeStartSession(any())).thenReturn(response); + GameSessionClient client = client(stub); + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(AuthorizeStartSessionRequest.class); + ArgumentCaptor interceptorCaptor = + ArgumentCaptor.forClass(ClientInterceptor[].class); + + GameSessionClient.StartSessionOwnerHandoffResult result = client.authorizeStartSession(handoff); + + verify(stub, times(1)) + .withDeadlineAfter(DEADLINE_SECONDS, java.util.concurrent.TimeUnit.SECONDS); + verify(stub, times(1)).authorizeStartSession(requestCaptor.capture()); + verify(stub, never()).stopSession(any()); + assertThat( + requestCaptor + .getValue() + .getCanonicalPostAuthorizationExecutionTupleBytes() + .toByteArray()) + .containsExactly(tuple.canonicalBytes()); + assertThat(requestCaptor.getValue().getOperatorAuthorizationReference()) + .isEqualTo(OPAQUE_REFERENCE); + verify(stub, times(1)).withCallCredentials(any(GrpcServerPeerIdentityCallCredentials.class)); + verify(stub, times(1)).withInterceptors(interceptorCaptor.capture()); + assertThat(interceptorCaptor.getValue()).hasSize(1); + assertThat(interceptorCaptor.getValue()[0]) + .isInstanceOf(GrpcServerPeerIdentityClientInterceptor.class); + assertThat(result.controlPlaneRequestId()).isEqualTo(tuple.controlPlaneRequestId()); + assertThat(result.mutationDigest()).isEqualTo(tuple.mutationDigest()); + assertThat(result.ownerAttemptId()).isEqualTo(OWNER_ATTEMPT); + assertThat(result.ownerMutationId()).isEqualTo(OWNER_MUTATION); + assertThat(result.ownerFence()).isEqualTo(37L); + assertThat(result.progress()) + .isEqualTo( + StartSessionOwnerAuthorizationProgress + .START_SESSION_OWNER_AUTHORIZATION_PROGRESS_ACCOUNT_OUTCOME_AMBIGUOUS); + assertThat(result.toString()).doesNotContain(OPAQUE_REFERENCE); + } + + @Test + void refusesOwnerResponseThatDoesNotEchoTheOriginalTuple() throws Exception { + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); + var handoff = handoff(); + AuthorizeStartSessionResponse substitutedResponse = + ownerResponse( + handoff.postAuthorizationTuple(), + StartSessionOwnerAuthorizationProgress + .START_SESSION_OWNER_AUTHORIZATION_PROGRESS_EXACT_REPLAY) + .toBuilder() + .setMutationDigest("different-digest") + .build(); + when(stub.authorizeStartSession(any())).thenReturn(substitutedResponse); + + assertThatThrownBy(() -> client(stub).authorizeStartSession(handoff)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("does not match") + .hasMessageNotContaining(OPAQUE_REFERENCE); + verify(stub, times(1)).authorizeStartSession(any()); + } + + @Test + void refusesSensitiveHandoffWithoutReadableFileBackedMtlsBeforeRpc() throws Exception { + TransientOwnerExecutionHandoff handoff = handoff(); + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); + + CommonGrpcClientProperties plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy(() -> client(stub, plaintext).authorizeStartSession(handoff)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("requires workload mTLS"); + + CommonGrpcClientProperties missingFiles = new CommonGrpcClientProperties(); + assertThatThrownBy(() -> client(stub, missingFiles).authorizeStartSession(handoff)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("file-backed workload mTLS"); + + CommonGrpcClientProperties directoryInsteadOfCertificate = fileBackedTlsProperties(); + directoryInsteadOfCertificate.setCertChain(tlsDirectory.toString()); + assertThatThrownBy( + () -> client(stub, directoryInsteadOfCertificate).authorizeStartSession(handoff)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("file-backed workload mTLS"); + + verify(stub, never()).authorizeStartSession(any()); + } + + @Test + void rejectsSubstitutedAccountReferenceBeforeCallingGameSession() throws Exception { + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); + TransientOwnerExecutionHandoff handoff = handoff(); + when(handoff.accountResponse().authenticatedLoggingWorkloadIdentity()) + .thenReturn("spiffe://firemud/ns/other/sa/logging-admin-service"); + + assertThatThrownBy(() -> client(stub).authorizeStartSession(handoff)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not internally bound") + .hasMessageNotContaining(OPAQUE_REFERENCE); + verify(stub, never()).authorizeStartSession(any()); + } + + @Test + void surfacesTransportAmbiguityWithoutAutomaticRetryOrReferenceDisclosure() throws Exception { + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); + TransientOwnerExecutionHandoff handoff = handoff(); + when(stub.authorizeStartSession(any())) + .thenThrow(Status.DEADLINE_EXCEEDED.asRuntimeException()); + + assertThatThrownBy(() -> client(stub).authorizeStartSession(handoff)) + .isInstanceOf(GameSessionClient.AmbiguousOwnerHandoffException.class) + .hasMessageNotContaining(OPAQUE_REFERENCE); + verify(stub, times(1)).authorizeStartSession(any()); + } + + private GameSessionClient client(GameSessionServiceGrpc.GameSessionServiceBlockingStub stub) { + try { + return client(stub, fileBackedTlsProperties()); + } catch (IOException failure) { + throw new AssertionError("test TLS fixture creation failed", failure); + } + } + + private GameSessionClient client( + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub, CommonGrpcClientProperties grpc) { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + TestGameSessionClient client = + new TestGameSessionClient( + endpoints, + grpc, + mock(GrpcChannelFactory.class), + new BlockingGrpcStubCustomizer() { + @Override + public > T customize(T candidate) { + return candidate; + } + }, + stub); + try { + client.installStubForTest(); + } catch (javax.net.ssl.SSLException failure) { + throw new AssertionError("test stub installation failed", failure); + } + return client; + } + + private CommonGrpcClientProperties fileBackedTlsProperties() throws IOException { + Path certChain = tlsDirectory.resolve("client.crt"); + Path privateKey = tlsDirectory.resolve("client.key"); + Path caCert = tlsDirectory.resolve("ca.crt"); + Files.writeString(certChain, "test-only certificate placeholder"); + Files.writeString(privateKey, "test-only private-key placeholder"); + Files.writeString(caCert, "test-only CA placeholder"); + CommonGrpcClientProperties grpc = new CommonGrpcClientProperties(); + grpc.setCertChain(certChain.toString()); + grpc.setPrivateKey(privateKey.toString()); + grpc.setCaCert(caCert.toString()); + return grpc; + } + + private static GameSessionServiceGrpc.GameSessionServiceBlockingStub mockStub() { + var stub = mock(GameSessionServiceGrpc.GameSessionServiceBlockingStub.class); + when(stub.withCallCredentials(any(CallCredentials.class))).thenReturn(stub); + when(stub.withInterceptors(any(ClientInterceptor[].class))).thenReturn(stub); + when(stub.withDeadlineAfter(DEADLINE_SECONDS, java.util.concurrent.TimeUnit.SECONDS)) + .thenReturn(stub); + return stub; + } + + private static AuthorizeStartSessionResponse ownerResponse( + StartSessionPostAuthorizationExecutionTuple tuple, + StartSessionOwnerAuthorizationProgress progress) { + return AuthorizeStartSessionResponse.newBuilder() + .setTargetNamespace("world-runtime") + .setControlPlaneRequestId(tuple.controlPlaneRequestId()) + .setMutationDigest(tuple.mutationDigest()) + .setOwnerAttemptId(OWNER_ATTEMPT.toString()) + .setOwnerMutationId(OWNER_MUTATION.toString()) + .setOwnerFence(37L) + .setOwnerPhaseState("OWNER_EXECUTION_PENDING") + .setProgress(progress) + .build(); + } + + private static TransientOwnerExecutionHandoff handoff() throws Exception { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target(91L, OWNER_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "Logging Game Session client transport test"); + StartSessionPreAuthorizationReservationTuple preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "logging-game-session-client-test", ACTOR_ID, action); + StartSessionPostAuthorizationExecutionTuple tuple = mockTuple(preTuple); + AuthorizationReference accountResponse = mock(AuthorizationReference.class); + String tupleFingerprint = tuple.authorizationReferenceFingerprint(); + byte[] tupleAuthorityEvidenceBundle = tuple.authorityEvidenceBundleBytes(); + StartSessionAuthorityEvidenceBundle.BundleReference tupleBundleReference = + tuple.bundleReference(); + when(accountResponse.operatorAuthorizationReference()).thenReturn(OPAQUE_REFERENCE); + when(accountResponse.authenticatedLoggingWorkloadIdentity()).thenReturn(LOGGING_IDENTITY); + when(accountResponse.authorizationReferenceFingerprint()).thenReturn(tupleFingerprint); + when(accountResponse.authorityEvidenceBundle()).thenReturn(tupleAuthorityEvidenceBundle); + when(accountResponse.bundleReference()).thenReturn(tupleBundleReference); + return new TransientOwnerExecutionHandoff( + new OwnerExecutionHandoff(UUID.fromString("5be93a95-79f3-4c08-9857-dc0848b2185d")), + accountResponse, + tuple); + } + + private static StartSessionPostAuthorizationExecutionTuple mockTuple( + StartSessionPreAuthorizationReservationTuple preTuple) { + StartSessionAuthorityEvidenceBundle.BundleReference bundleReference = + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "23", "18446744073709551615"); + var tuple = mock(StartSessionPostAuthorizationExecutionTuple.class); + when(tuple.canonicalBytes()).thenReturn(new byte[] {1, 2, 3}); + when(tuple.preAuthorizationTuple()).thenReturn(preTuple); + when(tuple.controlPlaneRequestId()).thenReturn(preTuple.controlPlaneRequestId()); + when(tuple.mutationDigest()).thenReturn(preTuple.mutationDigest()); + when(tuple.authenticatedWorkloadIdentity()).thenReturn(LOGGING_IDENTITY); + when(tuple.authorizationReferenceFingerprint()) + .thenReturn("arfp/v1/test-key/" + "b".repeat(64)); + when(tuple.authorityEvidenceBundleBytes()).thenReturn(new byte[] {4, 5, 6}); + when(tuple.bundleReference()).thenReturn(bundleReference); + return tuple; + } + private static final class TestGameSessionClient extends GameSessionClient { private final GameSessionServiceGrpc.GameSessionServiceBlockingStub stub; @@ -53,6 +333,10 @@ private TestGameSessionClient( this.stub = stub; } + private void installStubForTest() throws javax.net.ssl.SSLException { + reloadChannel(); + } + @Override protected GameSessionServiceGrpc.GameSessionServiceBlockingStub buildStub( ManagedChannel channel) { diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java new file mode 100644 index 0000000000..a397195770 --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java @@ -0,0 +1,605 @@ +package net.firedevops.firemud.loggingadmin.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.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.when; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Timestamp; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.CallCredentials; +import io.grpc.ClientInterceptor; +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.AuthorityEvidenceBundleReference; +import net.firedevops.firemud.account.v1.IssueHumanOperatorAuthorizationReferenceRequest; +import net.firedevops.firemud.account.v1.IssueHumanOperatorAuthorizationReferenceResponse; +import net.firedevops.firemud.account.v1.RecoverOperatorAuthorizationReferenceRequest; +import net.firedevops.firemud.account.v1.RecoverOperatorAuthorizationReferenceResponse; +import net.firedevops.firemud.account.v1.StartSessionOperatorAuthorizationServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.ArgumentCaptor; +import tools.jackson.databind.json.JsonMapper; + +class StartSessionOperatorAuthorizationClientTest { + @TempDir private Path tlsDirectory; + + private static final UUID TENANT_ID = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR_ID = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID OWNER_ACCOUNT_ID = + UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID RESERVATION_OWNER = + UUID.fromString("a137588f-4ac6-45ae-984d-5792bdf934b4"); + private static final UUID CLAIM_OWNER = UUID.fromString("5f63c9bb-8488-428d-87fa-b7b9b79a7a8a"); + private static final UUID ISSUANCE_ID = UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final Instant NOW = Instant.parse("2026-10-09T00:00:00Z"); + private static final String CONTROL_UI_TOKEN = "eyJhbGciOiJub25lIn0.operator-secret"; + private static final String LOGGING_WORKLOAD_IDENTITY = + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; + private static final String OPAQUE_REFERENCE = "r".repeat(43); + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void issueAndRecoverUseExactTupleAndClaimIdentityAndReturnValidatedOriginalBytes() + throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("client-βeta"); + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + byte[] bundle = bundleBytes(tuple, NOW.plusSeconds(300)); + when(stub.issueHumanOperatorAuthorizationReference(any())) + .thenReturn(issueResponse(tuple, NOW.plusSeconds(300), bundle)); + when(stub.recoverOperatorAuthorizationReference(any())) + .thenReturn(recoverResponse(tuple, NOW.plusSeconds(300), bundle)); + + try (TestClient client = new TestClient(stub, fileBackedTlsProperties())) { + StartSessionOperatorAuthorizationClient.AuthorizationReference issued = + client.issueHuman(tuple, CONTROL_UI_TOKEN, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L); + StartSessionOperatorAuthorizationClient.AuthorizationReference recovered = + client.recover(tuple, RESERVATION_OWNER, 9L, CLAIM_OWNER, 12L); + + assertThat(issued.operatorAuthorizationReference()).isEqualTo(OPAQUE_REFERENCE); + assertThat(issued.authorizationReferenceFingerprint()).isEqualTo(FINGERPRINT); + assertThat(issued.expiresAt()).isEqualTo(NOW.plusSeconds(300)); + assertThat(issued.authorityEvidenceBundle()).containsExactly(bundle); + assertThat(issued.bundleReference().sourceFence()).isEqualTo("23"); + assertThat(issued.authenticatedLoggingWorkloadIdentity()) + .isEqualTo(LOGGING_WORKLOAD_IDENTITY); + assertThat(issued.decodedBundle().controlPlaneRequestId()).isEqualTo("client-βeta"); + assertThat(recovered.authorityEvidenceBundle()).containsExactly(bundle); + assertThat(recovered.operatorAuthorizationReference()).isEqualTo(OPAQUE_REFERENCE); + assertThat(recovered.authenticatedLoggingWorkloadIdentity()) + .isEqualTo(LOGGING_WORKLOAD_IDENTITY); + + byte[] callerBytes = issued.authorityEvidenceBundle(); + callerBytes[0] = (byte) '!'; + assertThat(issued.authorityEvidenceBundle()).containsExactly(bundle); + assertThat(issued.toString()) + .doesNotContain(CONTROL_UI_TOKEN) + .doesNotContain(OPAQUE_REFERENCE) + .doesNotContain(FINGERPRINT); + + var issueCaptor = + org.mockito.ArgumentCaptor.forClass( + IssueHumanOperatorAuthorizationReferenceRequest.class); + verify(stub).issueHumanOperatorAuthorizationReference(issueCaptor.capture()); + assertThat(issueCaptor.getValue().getCanonicalPreAuthorizationTupleBytes().toByteArray()) + .containsExactly(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8)); + assertThat(issueCaptor.getValue().getControlUiJwt()).isEqualTo(CONTROL_UI_TOKEN); + assertThat(issueCaptor.getValue().getReservationOwnerId()) + .isEqualTo(RESERVATION_OWNER.toString()); + assertThat(issueCaptor.getValue().getReservationClaimFence()).isEqualTo(9L); + assertThat(issueCaptor.getValue().getCurrentClaimOwnerId()).isEqualTo(CLAIM_OWNER.toString()); + assertThat(issueCaptor.getValue().getCurrentClaimFence()).isEqualTo(11L); + + var recoverCaptor = + org.mockito.ArgumentCaptor.forClass(RecoverOperatorAuthorizationReferenceRequest.class); + verify(stub).recoverOperatorAuthorizationReference(recoverCaptor.capture()); + assertThat(recoverCaptor.getValue().getCanonicalPreAuthorizationTupleBytes().toByteArray()) + .containsExactly(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8)); + assertThat(recoverCaptor.getValue().getReservationOwnerId()) + .isEqualTo(RESERVATION_OWNER.toString()); + assertThat(recoverCaptor.getValue().getReservationClaimFence()).isEqualTo(9L); + assertThat(recoverCaptor.getValue().getCurrentClaimOwnerId()) + .isEqualTo(CLAIM_OWNER.toString()); + assertThat(recoverCaptor.getValue().getCurrentClaimFence()).isEqualTo(12L); + + var credentialsCaptor = ArgumentCaptor.forClass(CallCredentials.class); + verify(stub, times(2)).withCallCredentials(credentialsCaptor.capture()); + assertThat(credentialsCaptor.getAllValues()) + .allSatisfy( + credentials -> + assertThat(credentials) + .isInstanceOf(GrpcServerPeerIdentityCallCredentials.class)); + var interceptorCaptor = ArgumentCaptor.forClass(ClientInterceptor[].class); + verify(stub, times(2)).withInterceptors(interceptorCaptor.capture()); + assertThat(interceptorCaptor.getAllValues()) + .allSatisfy( + interceptors -> { + assertThat(interceptors).hasSize(1); + assertThat(interceptors[0]) + .isInstanceOf(GrpcServerPeerIdentityClientInterceptor.class); + }); + assertThat(StartSessionOperatorAuthorizationClient.accountServerUri("world-runtime")) + .isEqualTo("spiffe://firemud/ns/world-runtime/sa/account-service"); + } + } + + @Test + void accountEndpointIsTakenFromServiceEndpointsAndOnlyTheAccountStubIsCalled() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("client-endpoint"); + var stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + byte[] bundle = bundleBytes(tuple, NOW.plusSeconds(300)); + when(stub.issueHumanOperatorAuthorizationReference(any())) + .thenReturn(issueResponse(tuple, NOW.plusSeconds(300), bundle)); + + try (TestClient client = new TestClient(stub, fileBackedTlsProperties())) { + assertThat(client.accountTarget()).isEqualTo("account-service.operator.svc:6565"); + client.issueHuman(tuple, CONTROL_UI_TOKEN, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L); + verify(stub).issueHumanOperatorAuthorizationReference(any()); + verify(stub, never()).recoverOperatorAuthorizationReference(any()); + } + } + + @Test + void rejectsMalformedUnknownChangedOrExpiredAccountResponses() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("client-invalid-response"); + byte[] validBundle = bundleBytes(tuple, NOW.plusSeconds(300)); + IssueHumanOperatorAuthorizationReferenceResponse valid = + issueResponse(tuple, NOW.plusSeconds(300), validBundle); + + assertRejected(tuple, valid.toBuilder().setOperatorAuthorizationReference("bad").build()); + assertRejected(tuple, valid.toBuilder().setAuthorizationReferenceFingerprint("bad").build()); + assertRejected(tuple, valid.toBuilder().clearAuthenticatedLoggingWorkloadIdentity().build()); + assertRejected( + tuple, + valid.toBuilder() + .setAuthenticatedLoggingWorkloadIdentity( + "spiffe://firemud/ns/other/sa/logging-admin-service") + .build()); + assertRejected( + tuple, + valid.toBuilder() + .setAuthenticatedLoggingWorkloadIdentity( + "spiffe://firemud/ns/world-runtime/sa/game-session-service") + .build()); + assertRejected( + tuple, + valid.toBuilder() + .setAuthenticatedLoggingWorkloadIdentity( + "SPIFFE://firemud/ns/world-runtime/sa/logging-admin-service") + .build()); + assertRejected(tuple, valid.toBuilder().setUnknownFields(unknownFields()).build()); + assertRejected(tuple, valid.toBuilder().clearExpiresAt().build()); + assertRejected(tuple, valid.toBuilder().clearBundleReference().build()); + assertRejected( + tuple, + valid.toBuilder() + .setExpiresAt( + timestamp(NOW.plusSeconds(300)).toBuilder() + .setUnknownFields(unknownFields()) + .build()) + .build()); + assertRejected( + tuple, + valid.toBuilder() + .setBundleReference(valid.getBundleReference().toBuilder().setSourceFence("24").build()) + .build()); + assertRejected( + tuple, + valid.toBuilder() + .setBundleReference( + valid.getBundleReference().toBuilder().setUnknownFields(unknownFields()).build()) + .build()); + assertRejected(tuple, valid.toBuilder().setExpiresAt(timestamp(NOW.plusSeconds(301))).build()); + assertRejected(tuple, valid.toBuilder().setExpiresAt(timestamp(NOW.minusSeconds(1))).build()); + + RecoverOperatorAuthorizationReferenceResponse validRecovery = + recoverResponse(tuple, NOW.plusSeconds(300), validBundle); + assertRecoverRejected( + tuple, validRecovery.toBuilder().clearAuthenticatedLoggingWorkloadIdentity().build()); + + Map changedTupleBundle = read(validBundle); + object(object(changedTupleBundle.get("issuanceOperationIdentity"))) + .put("mutationDigest", "c".repeat(64)); + assertRejected( + tuple, + valid.toBuilder() + .setAuthorityEvidenceBundle(ByteString.copyFrom(canonical(changedTupleBundle))) + .build()); + + Map extraAssurance = read(validBundle); + object(extraAssurance.get("issuanceEvidence")).put("assurance", "forbidden"); + assertRejected( + tuple, + valid.toBuilder() + .setAuthorityEvidenceBundle(ByteString.copyFrom(canonical(extraAssurance))) + .build()); + } + + @Test + void rejectsInvalidCallerTupleFenceAndTokenBeforeCallingAccount() throws Exception { + var stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + StartSessionPreAuthorizationReservationTuple tuple = tuple("client-invalid-request"); + + try (TestClient client = new TestClient(stub, fileBackedTlsProperties())) { + assertThatThrownBy( + () -> + client.issueHuman( + tuple, CONTROL_UI_TOKEN, RESERVATION_OWNER, 0L, CLAIM_OWNER, 1L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> client.issueHuman(tuple, "bad token\n", RESERVATION_OWNER, 1L, CLAIM_OWNER, 1L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> client.recover(tuple, new UUID(0L, 0L), 1L, CLAIM_OWNER, 1L)) + .isInstanceOf(IllegalArgumentException.class); + verify(stub, never()).issueHumanOperatorAuthorizationReference(any()); + verify(stub, never()).recoverOperatorAuthorizationReference(any()); + } + } + + @Test + void refusesIssueAndRecoverWithoutReadableFileBackedMtlsBeforeCallingAccount() throws Exception { + var stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + StartSessionPreAuthorizationReservationTuple tuple = tuple("client-missing-mtls"); + + CommonGrpcClientProperties plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + CommonGrpcClientProperties missing = new CommonGrpcClientProperties(); + CommonGrpcClientProperties classpath = new CommonGrpcClientProperties(); + classpath.setCertChain("classpath:application.yml"); + classpath.setPrivateKey("classpath:application.yml"); + classpath.setCaCert("classpath:application.yml"); + CommonGrpcClientProperties directoryInsteadOfCertificate = fileBackedTlsProperties(); + directoryInsteadOfCertificate.setCertChain(tlsDirectory.toString()); + CommonGrpcClientProperties incomplete = fileBackedTlsProperties(); + incomplete.setCaCert(null); + + for (CommonGrpcClientProperties invalidTls : + List.of(plaintext, missing, classpath, directoryInsteadOfCertificate, incomplete)) { + try (TestClient client = new TestClient(stub, invalidTls)) { + assertThatThrownBy( + () -> + client.issueHuman( + tuple, CONTROL_UI_TOKEN, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> client.recover(tuple, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L)) + .isInstanceOf(IllegalStateException.class); + } + } + verify(stub, never()).issueHumanOperatorAuthorizationReference(any()); + verify(stub, never()).recoverOperatorAuthorizationReference(any()); + } + + @Test + void unavailableAccountResponseRemainsUnavailableWithoutCreatingFallback() throws Exception { + var stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.issueHumanOperatorAuthorizationReference(any())) + .thenThrow(Status.UNAVAILABLE.withDescription("account unavailable").asRuntimeException()); + StartSessionPreAuthorizationReservationTuple tuple = tuple("client-unavailable"); + + try (TestClient client = new TestClient(stub, fileBackedTlsProperties())) { + Throwable failure = + catchThrowable( + () -> + client.issueHuman( + tuple, CONTROL_UI_TOKEN, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L)); + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.UNAVAILABLE); + } + } + + private void assertRejected( + StartSessionPreAuthorizationReservationTuple tuple, + IssueHumanOperatorAuthorizationReferenceResponse response) + throws Exception { + var stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.issueHumanOperatorAuthorizationReference(any())).thenReturn(response); + try (TestClient client = new TestClient(stub, fileBackedTlsProperties())) { + assertThatThrownBy( + () -> + client.issueHuman( + tuple, CONTROL_UI_TOKEN, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L)) + .isInstanceOf(IllegalStateException.class); + } + } + + private void assertRecoverRejected( + StartSessionPreAuthorizationReservationTuple tuple, + RecoverOperatorAuthorizationReferenceResponse response) + throws Exception { + var stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.recoverOperatorAuthorizationReference(any())).thenReturn(response); + try (TestClient client = new TestClient(stub, fileBackedTlsProperties())) { + assertThatThrownBy(() -> client.recover(tuple, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L)) + .isInstanceOf(IllegalStateException.class); + } + } + + private static IssueHumanOperatorAuthorizationReferenceResponse issueResponse( + StartSessionPreAuthorizationReservationTuple tuple, Instant expiry, byte[] bundle) { + return IssueHumanOperatorAuthorizationReferenceResponse.newBuilder() + .setOperatorAuthorizationReference(OPAQUE_REFERENCE) + .setAuthorizationReferenceFingerprint(FINGERPRINT) + .setExpiresAt(timestamp(expiry)) + .setAuthorityEvidenceBundle(ByteString.copyFrom(bundle)) + .setBundleReference(reference()) + .setAuthenticatedLoggingWorkloadIdentity(LOGGING_WORKLOAD_IDENTITY) + .build(); + } + + private static RecoverOperatorAuthorizationReferenceResponse recoverResponse( + StartSessionPreAuthorizationReservationTuple tuple, Instant expiry, byte[] bundle) { + return RecoverOperatorAuthorizationReferenceResponse.newBuilder() + .setOperatorAuthorizationReference(OPAQUE_REFERENCE) + .setAuthorizationReferenceFingerprint(FINGERPRINT) + .setExpiresAt(timestamp(expiry)) + .setAuthorityEvidenceBundle(ByteString.copyFrom(bundle)) + .setBundleReference(reference()) + .setAuthenticatedLoggingWorkloadIdentity(LOGGING_WORKLOAD_IDENTITY) + .build(); + } + + private static Timestamp timestamp(Instant instant) { + return Timestamp.newBuilder() + .setSeconds(instant.getEpochSecond()) + .setNanos(instant.getNano()) + .build(); + } + + private static AuthorityEvidenceBundleReference reference() { + return AuthorityEvidenceBundleReference.newBuilder() + .setBundleVersion(StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION) + .setSourceVersion("17") + .setSourceFence("23") + .setLinearization("18446744073709551615") + .build(); + } + + private static byte[] bundleBytes( + StartSessionPreAuthorizationReservationTuple tuple, Instant expiry) throws Exception { + String tenantId = TENANT_ID.toString(); + Map projection = + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + NOW.toString(), + "expiresAt", + expiry.toString()); + Map authority = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()); + Map evidence = + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR_ID.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3"); + Map bundle = + new LinkedHashMap<>( + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantId, "targetNamespace", "world-runtime"), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR_ID.toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(tenantId, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + evidence)); + return canonical(bundle); + } + + private static UnknownFieldSet unknownFields() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } + + private static StartSessionPreAuthorizationReservationTuple tuple(String requestId) { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target(91L, OWNER_ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "Logging Account client contract"); + return StartSessionPreAuthorizationReservationTuple.createHuman(requestId, ACTOR_ID, action); + } + + private static byte[] canonical(Object value) throws IOException { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private static Map read(byte[] bytes) throws IOException { + return JSON.readValue(bytes, new tools.jackson.core.type.TypeReference<>() {}); + } + + @SuppressWarnings("unchecked") + private static Map object(Object value) { + return (Map) value; + } + + private static final class TestClient extends StartSessionOperatorAuthorizationClient { + private final StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + stub; + + private TestClient( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + stub, + CommonGrpcClientProperties tlsProperties) + throws Exception { + super( + endpoints(), + tlsProperties, + stubChannelFactory(), + BlockingGrpcStubCustomizer.noop(), + Clock.fixed(NOW, ZoneOffset.UTC)); + this.stub = stub; + when(stub.withCallCredentials(any(CallCredentials.class))).thenReturn(stub); + when(stub.withInterceptors(any(ClientInterceptor[].class))).thenReturn(stub); + String reloadSetting = System.getProperty("firemud.grpc.tls-reload.enabled"); + System.setProperty("firemud.grpc.tls-reload.enabled", "false"); + try { + initialize(); + } finally { + if (reloadSetting == null) { + System.clearProperty("firemud.grpc.tls-reload.enabled"); + } else { + System.setProperty("firemud.grpc.tls-reload.enabled", reloadSetting); + } + } + } + + @Override + protected StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + buildStub(ManagedChannel channel) { + return applyStubCustomizer(stub); + } + + private String accountTarget() { + return configuredTarget(endpoints()); + } + } + + private static ServiceEndpointsProperties endpoints() { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("account-service.operator.svc:6565"); + return endpoints; + } + + private CommonGrpcClientProperties fileBackedTlsProperties() throws IOException { + Path certChain = tlsDirectory.resolve("client.crt"); + Path privateKey = tlsDirectory.resolve("client.key"); + Path caCert = tlsDirectory.resolve("ca.crt"); + Files.writeString(certChain, "test-only certificate placeholder"); + Files.writeString(privateKey, "test-only private-key placeholder"); + Files.writeString(caCert, "test-only CA placeholder"); + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain(certChain.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(caCert.toString()); + return properties; + } + + private static GrpcChannelFactory stubChannelFactory() { + ManagedChannel channel = mock(ManagedChannel.class); + return new GrpcChannelFactory() { + @Override + public ManagedChannel buildChannel( + String target, + int defaultPort, + CommonGrpcClientProperties properties, + boolean keepAlive) { + return channel; + } + }; + } +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/config/StartSessionOperatorAuthorizationConfigurationTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/config/StartSessionOperatorAuthorizationConfigurationTest.java new file mode 100644 index 0000000000..37aa24396a --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/config/StartSessionOperatorAuthorizationConfigurationTest.java @@ -0,0 +1,297 @@ +package unit.net.firedevops.firemud.loggingadmin.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcTlsMaterialResolver; +import net.firedevops.firemud.loggingadmin.client.StartSessionOperatorAuthorizationClient; +import net.firedevops.firemud.loggingadmin.config.StartSessionOperatorAuthorizationConfiguration; +import net.firedevops.firemud.loggingadmin.operator.StartSessionAuthorizationCoordinator; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.boot.convert.ApplicationConversionService; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Import; + +/** Wiring proof only: injected test doubles do not establish a live Logging or Account runtime. */ +class StartSessionOperatorAuthorizationConfigurationTest { + private static final String ENABLED = + "firemud.logging-admin.start-session-operator-authorization.enabled"; + private static final String WORKLOAD_NAMESPACE = "firemud.grpc.workload-namespace"; + private static final String ACCOUNT_ENDPOINT = "firemud.services.account-service"; + private static final String CERT_CHAIN = "firemud.grpc.cert-chain"; + private static final String PRIVATE_KEY = "firemud.grpc.private-key"; + private static final String CA_CERT = "firemud.grpc.ca-cert"; + private static final String TLS_RELOAD_PROPERTY = "firemud.grpc.tls-reload.enabled"; + + @Test + void compositionIsAbsentWhenOptInIsMissingOrFalse() { + new ApplicationContextRunner() + .withUserConfiguration( + StartSessionOperatorAuthorizationConfiguration.class, + SharedGrpcConfiguration.class, + ReservationService.class) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(StartSessionOperatorAuthorizationClient.class); + assertThat(context).doesNotHaveBean(StartSessionAuthorizationCoordinator.class); + assertThat(context.getBean(ControlledGrpcChannelFactory.class).calls()).isEmpty(); + }); + + new ApplicationContextRunner() + .withUserConfiguration( + StartSessionOperatorAuthorizationConfiguration.class, + SharedGrpcConfiguration.class, + ReservationService.class) + .withPropertyValues(ENABLED + "=false") + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(StartSessionOperatorAuthorizationClient.class); + assertThat(context).doesNotHaveBean(StartSessionAuthorizationCoordinator.class); + assertThat(context.getBean(ControlledGrpcChannelFactory.class).calls()).isEmpty(); + }); + } + + @Test + void enabledCompositionRequiresReservationProviderAndFileBackedMtls(@TempDir Path tlsDirectory) + throws IOException { + String[] tlsProperties = fileBackedTlsProperties(tlsDirectory); + withTlsReloadDisabled( + () -> + contextRunner() + .withUserConfiguration( + StartSessionOperatorAuthorizationConfiguration.class, + SharedGrpcConfiguration.class) + .withPropertyValues( + concat( + new String[] { + ENABLED + "=true", + WORKLOAD_NAMESPACE + "=gameplay", + ACCOUNT_ENDPOINT + "=account-service.gameplay.svc:6565" + }, + tlsProperties)) + .run(context -> assertThat(context).hasFailed())); + + withTlsReloadDisabled( + () -> + contextRunner() + .withUserConfiguration( + StartSessionOperatorAuthorizationConfiguration.class, + SharedGrpcConfiguration.class, + ReservationService.class) + .withPropertyValues(ENABLED + "=true", WORKLOAD_NAMESPACE + "=gameplay") + .run(context -> assertThat(context).hasFailed())); + } + + @Test + void enabledCompositionRequiresCanonicalWorkloadNamespace(@TempDir Path tlsDirectory) + throws IOException { + String[] tlsProperties = fileBackedTlsProperties(tlsDirectory); + withTlsReloadDisabled( + () -> + contextRunner() + .withUserConfiguration( + StartSessionOperatorAuthorizationConfiguration.class, + SharedGrpcConfiguration.class, + ReservationService.class) + .withPropertyValues( + concat( + new String[] { + ENABLED + "=true", ACCOUNT_ENDPOINT + "=account-service:6565" + }, + tlsProperties)) + .run(context -> assertThat(context).hasFailed())); + + withTlsReloadDisabled( + () -> + contextRunner() + .withUserConfiguration( + StartSessionOperatorAuthorizationConfiguration.class, + SharedGrpcConfiguration.class, + ReservationService.class) + .withPropertyValues( + concat( + new String[] { + ENABLED + "=true", + WORKLOAD_NAMESPACE + "=Gameplay", + ACCOUNT_ENDPOINT + "=account-service:6565" + }, + tlsProperties)) + .run(context -> assertThat(context).hasFailed())); + } + + @Test + void explicitCompositionUsesManagedClientLifecycleAndCapturedChannelConfiguration( + @TempDir Path tlsDirectory) throws IOException { + String[] tlsProperties = fileBackedTlsProperties(tlsDirectory); + AtomicBoolean channelShutdown = new AtomicBoolean(); + + withTlsReloadDisabled( + () -> + contextRunner() + .withUserConfiguration( + StartSessionOperatorAuthorizationConfiguration.class, + SharedGrpcConfiguration.class, + ReservationService.class) + .withPropertyValues( + concat( + new String[] { + ENABLED + "=true", + WORKLOAD_NAMESPACE + "=gameplay", + ACCOUNT_ENDPOINT + "=account-service.gameplay.svc:6565" + }, + tlsProperties)) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context) + .hasSingleBean(StartSessionOperatorAuthorizationClient.class); + assertThat(context).hasSingleBean(StartSessionAuthorizationCoordinator.class); + + ControlledGrpcChannelFactory channelFactory = + context.getBean(ControlledGrpcChannelFactory.class); + assertThat(channelFactory.calls()).hasSize(1); + ChannelCall call = channelFactory.calls().get(0); + assertThat(call.target()).isEqualTo("account-service.gameplay.svc:6565"); + assertThat(call.defaultPort()).isEqualTo(6565); + assertThat(call.keepAlive()).isTrue(); + assertThat(call.tlsProperties().isPlaintext()).isFalse(); + assertThat(call.tlsProperties().getCertChain()) + .isEqualTo(tlsProperties[0].substring((CERT_CHAIN + "=").length())); + + context.close(); + channelShutdown.set(channelFactory.channelWasShutdown()); + })); + + assertThat(channelShutdown.get()).isTrue(); + } + + private static ApplicationContextRunner contextRunner() { + return new ApplicationContextRunner() + .withInitializer( + context -> + context.getBeanFactory().setConversionService(new ApplicationConversionService())); + } + + private static String[] fileBackedTlsProperties(Path tlsDirectory) throws IOException { + Path certChain = tlsDirectory.resolve("client.crt"); + Path privateKey = tlsDirectory.resolve("client.key"); + Path caCert = tlsDirectory.resolve("ca.crt"); + Files.writeString(certChain, "test-only certificate placeholder"); + Files.writeString(privateKey, "test-only private-key placeholder"); + Files.writeString(caCert, "test-only CA placeholder"); + return new String[] { + CERT_CHAIN + "=" + certChain, PRIVATE_KEY + "=" + privateKey, CA_CERT + "=" + caCert + }; + } + + private static String[] concat(String[] first, String[] second) { + String[] result = new String[first.length + second.length]; + System.arraycopy(first, 0, result, 0, first.length); + System.arraycopy(second, 0, result, first.length, second.length); + return result; + } + + private static void withTlsReloadDisabled(Runnable action) { + String previous = System.getProperty(TLS_RELOAD_PROPERTY); + System.setProperty(TLS_RELOAD_PROPERTY, "false"); + try { + action.run(); + } finally { + if (previous == null) { + System.clearProperty(TLS_RELOAD_PROPERTY); + } else { + System.setProperty(TLS_RELOAD_PROPERTY, previous); + } + } + } + + @TestConfiguration(proxyBeanMethods = false) + @EnableConfigurationProperties({ + ServiceEndpointsProperties.class, + CommonGrpcClientProperties.class + }) + @Import(ControlledChannelConfiguration.class) + static class SharedGrpcConfiguration { + @Bean + GrpcTlsMaterialResolver grpcTlsMaterialResolver() { + return new GrpcTlsMaterialResolver(); + } + + @Bean + BlockingGrpcStubCustomizer blockingGrpcStubCustomizer() { + return BlockingGrpcStubCustomizer.noop(); + } + } + + @TestConfiguration(proxyBeanMethods = false) + static class ControlledChannelConfiguration { + @Bean + ControlledGrpcChannelFactory grpcChannelFactory() { + return new ControlledGrpcChannelFactory(); + } + } + + @TestConfiguration(proxyBeanMethods = false) + static class ReservationService { + @Bean + StartSessionPreAuthorizationReservationService + startSessionPreAuthorizationReservationService() { + return mock(StartSessionPreAuthorizationReservationService.class); + } + } + + private static final class ControlledGrpcChannelFactory extends GrpcChannelFactory { + private final ManagedChannel channel = mock(ManagedChannel.class); + private final AtomicBoolean channelWasShutdown = new AtomicBoolean(); + private final List calls = new ArrayList<>(); + + private ControlledGrpcChannelFactory() { + when(channel.shutdown()) + .thenAnswer( + invocation -> { + channelWasShutdown.set(true); + return channel; + }); + } + + @Override + public ManagedChannel buildChannel( + String target, int defaultPort, CommonGrpcClientProperties properties, boolean keepAlive) { + calls.add(new ChannelCall(target, defaultPort, properties.copy(), keepAlive)); + return channel; + } + + private List calls() { + return List.copyOf(calls); + } + + private boolean channelWasShutdown() { + return channelWasShutdown.get(); + } + } + + private record ChannelCall( + String target, + int defaultPort, + CommonGrpcClientProperties tlsProperties, + boolean keepAlive) {} +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java new file mode 100644 index 0000000000..7c77d6e25e --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java @@ -0,0 +1,858 @@ +package net.firedevops.firemud.loggingadmin.operator; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Status; +import java.io.IOException; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.v1.StartSessionOwnerAuthorizationProgress; +import net.firedevops.firemud.loggingadmin.StartSessionReservationMutationTestFixtures; +import net.firedevops.firemud.loggingadmin.client.GameSessionClient; +import net.firedevops.firemud.loggingadmin.client.GameSessionClient.StartSessionOwnerHandoffResult; +import net.firedevops.firemud.loggingadmin.client.StartSessionOperatorAuthorizationClient; +import net.firedevops.firemud.loggingadmin.client.StartSessionOperatorAuthorizationClient.AuthorizationReference; +import net.firedevops.firemud.loggingadmin.operator.StartSessionAuthorizationCoordinator.OwnerDispatchResult; +import net.firedevops.firemud.loggingadmin.operator.StartSessionAuthorizationCoordinator.Progress; +import net.firedevops.firemud.loggingadmin.operator.StartSessionAuthorizationCoordinator.Result; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.AuthorizedSnapshot; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimPurpose; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimState; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.OwnerExecutionHandoff; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Phase; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Snapshot; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.State; +import net.firedevops.firemud.loggingadmin.repository.StartSessionPreAuthorizationReservationRepository; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import tools.jackson.databind.json.JsonMapper; + +class StartSessionAuthorizationCoordinatorTest { + private static final UUID TENANT_ID = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR_ID = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID OWNER_ACCOUNT_ID = + UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID ORIGINAL_OWNER = + UUID.fromString("a137588f-4ac6-45ae-984d-5792bdf934b4"); + private static final UUID ISSUANCE_ID = UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final UUID OWNER_ATTEMPT_ID = + UUID.fromString("69116466-a576-4fa6-9e11-4c0c6b2a92f0"); + private static final UUID OWNER_MUTATION_ID = + UUID.fromString("89da7d84-12f5-4cf8-b69b-30ba8eb115a4"); + private static final Instant NOW = Instant.parse("2026-10-09T00:00:00Z"); + private static final long NOW_MILLIS = NOW.toEpochMilli(); + private static final String CONTROL_UI_TOKEN = "operator-control-ui-secret"; + private static final String OPAQUE_REFERENCE = "r".repeat(43); + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final String LOGGING_IDENTITY = + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final StartSessionPreAuthorizationReservationRepository repository = + mock(StartSessionPreAuthorizationReservationRepository.class); + private final StartSessionPreAuthorizationReservationService reservations = + StartSessionReservationMutationTestFixtures.forMockBackedUnitTest( + repository, Clock.fixed(NOW, ZoneOffset.UTC)); + private final StartSessionOperatorAuthorizationClient accountClient = + mock(StartSessionOperatorAuthorizationClient.class); + private final StartSessionAuthorizationCoordinator coordinator = + new StartSessionAuthorizationCoordinator(reservations, accountClient); + + @AfterEach + void clearAuthenticatedContext() { + SessionContext.clear(); + } + + @Test + void onlyReservationWinnerIssuesAndOnlyDurableOwnerPendingReturnsTransientReference() + throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-winner"); + Snapshot reserved = snapshot(tuple, State.RESERVED, 1L, 1L); + Snapshot pending = snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 1L); + when(repository.acquire(eq(tuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.AcquireResult(reserved, true), + new StartSessionPreAuthorizationReservationRepository.AcquireResult(pending, false)); + when(repository.markAuthorizationPending( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + eq(NOW_MILLIS))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.TransitionResult(pending, true)); + AuthorizationReference response = authorizationReference(tuple); + when(accountClient.issueHuman( + eq(shared(tuple)), + eq(CONTROL_UI_TOKEN), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L))) + .thenReturn(response); + stubAuthorizationEnrichment(tuple, true, true); + + Result first = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); + Result duplicate = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); + + assertThat(first.progress()).isEqualTo(Progress.OWNER_EXECUTION_PENDING); + assertThat(first.handoff()).isNotNull(); + assertThat(first.handoff().ownerExecutionHandoff().handoffId()).isNotNull(); + assertThat(first.handoff().accountResponse().operatorAuthorizationReference()) + .isEqualTo(OPAQUE_REFERENCE); + assertThat(first.handoff().postAuthorizationTuple().authenticatedWorkloadIdentity()) + .isEqualTo(LOGGING_IDENTITY); + assertThat(duplicate.progress()).isEqualTo(Progress.ALREADY_IN_PROGRESS); + assertThat(duplicate.handoff()).isNull(); + assertThat(first.toString()) + .doesNotContain(CONTROL_UI_TOKEN) + .doesNotContain(OPAQUE_REFERENCE) + .doesNotContain(FINGERPRINT); + assertThat(first.handoff().toString()) + .doesNotContain(CONTROL_UI_TOKEN) + .doesNotContain(OPAQUE_REFERENCE) + .doesNotContain(FINGERPRINT); + + ArgumentCaptor originalOwner = ArgumentCaptor.forClass(UUID.class); + ArgumentCaptor currentOwner = ArgumentCaptor.forClass(UUID.class); + ArgumentCaptor persistedTuple = ArgumentCaptor.forClass(String.class); + ArgumentCaptor handoffId = ArgumentCaptor.forClass(UUID.class); + InOrder persistenceOrder = inOrder(accountClient, repository); + persistenceOrder + .verify(accountClient) + .issueHuman( + eq(shared(tuple)), + eq(CONTROL_UI_TOKEN), + originalOwner.capture(), + eq(1L), + currentOwner.capture(), + eq(1L)); + assertThat(originalOwner.getValue()).isEqualTo(currentOwner.getValue()); + verify(accountClient, never()).recover(any(), any(), anyLong(), any(), anyLong()); + persistenceOrder + .verify(repository) + .completeAuthorization( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + persistedTuple.capture(), + eq(NOW_MILLIS)); + assertThat(persistedTuple.getValue()) + .contains(LOGGING_IDENTITY) + .doesNotContain(OPAQUE_REFERENCE) + .doesNotContain(CONTROL_UI_TOKEN); + persistenceOrder + .verify(repository) + .beginOwnerExecution( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + eq(persistedTuple.getValue()), + handoffId.capture(), + eq(NOW_MILLIS)); + assertThat(handoffId.getValue()).isEqualTo(first.handoff().ownerExecutionHandoff().handoffId()); + } + + @Test + void recoveryUsesOriginalOwnerAndFreshFenceAndNeverCallsIssue() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-recovery"); + Snapshot pending = snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 3L); + when(repository.acquireRecoveryClaim( + eq(tuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L))) + .thenReturn( + Optional.of( + new StartSessionPreAuthorizationReservationRepository.RecoveryClaimResult( + pending, ORIGINAL_OWNER))); + AuthorizationReference response = authorizationReference(tuple); + when(accountClient.recover( + eq(shared(tuple)), eq(ORIGINAL_OWNER), eq(1L), any(UUID.class), eq(3L))) + .thenReturn(response); + stubAuthorizationEnrichment(tuple, true, true); + + Result result = coordinator.recover(tuple); + + assertThat(result.progress()).isEqualTo(Progress.OWNER_EXECUTION_PENDING); + assertThat(result.handoff().postAuthorizationTuple().reservationOwnerId()) + .isEqualTo(ORIGINAL_OWNER); + ArgumentCaptor currentOwner = ArgumentCaptor.forClass(UUID.class); + verify(accountClient) + .recover(eq(shared(tuple)), eq(ORIGINAL_OWNER), eq(1L), currentOwner.capture(), eq(3L)); + assertThat(currentOwner.getValue()).isNotEqualTo(ORIGINAL_OWNER); + verify(accountClient, never()) + .issueHuman(any(), anyString(), any(), anyLong(), any(), anyLong()); + } + + @Test + void issueHumanAndDispatchForwardsOnlyAfterDurableOwnerPendingAndOnlyOnce() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-issue-dispatch"); + Snapshot reserved = snapshot(tuple, State.RESERVED, 1L, 1L); + Snapshot alreadyPending = snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 1L); + when(repository.acquire(eq(tuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.AcquireResult(reserved, true), + new StartSessionPreAuthorizationReservationRepository.AcquireResult( + alreadyPending, false)); + when(repository.markAuthorizationPending( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + eq(NOW_MILLIS))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.TransitionResult( + alreadyPending, true)); + AuthorizationReference response = authorizationReference(tuple); + when(accountClient.issueHuman( + eq(shared(tuple)), + eq(CONTROL_UI_TOKEN), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L))) + .thenReturn(response); + stubAuthorizationEnrichment(tuple, true, true); + GameSessionClient ownerClient = mock(GameSessionClient.class); + StartSessionOwnerHandoffResult ownerEcho = ownerEcho(tuple); + when(ownerClient.authorizeStartSession(any())).thenReturn(ownerEcho); + + OwnerDispatchResult first = + coordinator.issueHumanAndDispatch(tuple, CONTROL_UI_TOKEN, ownerClient); + OwnerDispatchResult duplicate = + coordinator.issueHumanAndDispatch(tuple, CONTROL_UI_TOKEN, ownerClient); + + assertThat(first.progress()).isEqualTo(Progress.OWNER_EXECUTION_PENDING); + assertThat(first.ownerEcho()).contains(ownerEcho); + assertThat(first.toString()) + .doesNotContain(CONTROL_UI_TOKEN) + .doesNotContain(OPAQUE_REFERENCE) + .doesNotContain(FINGERPRINT); + assertThat(duplicate.progress()).isEqualTo(Progress.ALREADY_IN_PROGRESS); + assertThat(duplicate.ownerEcho()).isEmpty(); + + ArgumentCaptor persistedTuple = ArgumentCaptor.forClass(String.class); + ArgumentCaptor + ownerHandoff = + ArgumentCaptor.forClass( + StartSessionAuthorizationCoordinator.TransientOwnerExecutionHandoff.class); + InOrder dispatchOrder = inOrder(accountClient, repository, ownerClient); + dispatchOrder + .verify(accountClient) + .issueHuman( + eq(shared(tuple)), + eq(CONTROL_UI_TOKEN), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L)); + dispatchOrder + .verify(repository) + .completeAuthorization( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + persistedTuple.capture(), + eq(NOW_MILLIS)); + dispatchOrder + .verify(repository) + .beginOwnerExecution( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + eq(persistedTuple.getValue()), + any(UUID.class), + eq(NOW_MILLIS)); + dispatchOrder.verify(ownerClient).authorizeStartSession(ownerHandoff.capture()); + assertThat(ownerHandoff.getValue().postAuthorizationTuple().canonicalJson()) + .isEqualTo(persistedTuple.getValue()); + verify(ownerClient, org.mockito.Mockito.times(1)).authorizeStartSession(any()); + } + + @Test + void recoverAndDispatchForwardsTheOriginalRecoveredOperationOnce() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-recover-dispatch"); + Snapshot pending = snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 3L); + when(repository.acquireRecoveryClaim( + eq(tuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L))) + .thenReturn( + Optional.of( + new StartSessionPreAuthorizationReservationRepository.RecoveryClaimResult( + pending, ORIGINAL_OWNER))); + AuthorizationReference response = authorizationReference(tuple); + when(accountClient.recover( + eq(shared(tuple)), eq(ORIGINAL_OWNER), eq(1L), any(UUID.class), eq(3L))) + .thenReturn(response); + stubAuthorizationEnrichment(tuple, true, true); + GameSessionClient ownerClient = mock(GameSessionClient.class); + StartSessionOwnerHandoffResult ownerEcho = ownerEcho(tuple); + when(ownerClient.authorizeStartSession(any())).thenReturn(ownerEcho); + + OwnerDispatchResult result = coordinator.recoverAndDispatch(tuple, ownerClient); + + assertThat(result.progress()).isEqualTo(Progress.OWNER_EXECUTION_PENDING); + assertThat(result.ownerEcho()).contains(ownerEcho); + InOrder dispatchOrder = inOrder(accountClient, repository, ownerClient); + dispatchOrder + .verify(accountClient) + .recover(eq(shared(tuple)), eq(ORIGINAL_OWNER), eq(1L), any(UUID.class), eq(3L)); + dispatchOrder + .verify(repository) + .completeAuthorization( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(3L), + anyString(), + eq(NOW_MILLIS)); + dispatchOrder + .verify(repository) + .beginOwnerExecution( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(3L), + anyString(), + any(UUID.class), + eq(NOW_MILLIS)); + dispatchOrder.verify(ownerClient).authorizeStartSession(any()); + verify(ownerClient, org.mockito.Mockito.times(1)).authorizeStartSession(any()); + } + + @Test + void nonWinningAndUnavailableAuthorizationPathsNeverDispatchOwner() { + StartSessionPreAuthorizationReservationTuple duplicateTuple = + tuple("coordinator-dispatch-duplicate"); + Snapshot pending = snapshot(duplicateTuple, State.AUTHORIZATION_PENDING, 1L, 1L); + when(repository.acquire( + eq(duplicateTuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.AcquireResult(pending, false)); + StartSessionPreAuthorizationReservationTuple unavailableTuple = + tuple("coordinator-dispatch-unavailable"); + when(repository.acquireRecoveryClaim( + eq(unavailableTuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L))) + .thenReturn(Optional.empty()); + GameSessionClient ownerClient = mock(GameSessionClient.class); + + OwnerDispatchResult duplicate = + coordinator.issueHumanAndDispatch(duplicateTuple, CONTROL_UI_TOKEN, ownerClient); + OwnerDispatchResult unavailable = coordinator.recoverAndDispatch(unavailableTuple, ownerClient); + + assertThat(duplicate.progress()).isEqualTo(Progress.ALREADY_IN_PROGRESS); + assertThat(duplicate.ownerEcho()).isEmpty(); + assertThat(unavailable.progress()).isEqualTo(Progress.RECOVERY_UNAVAILABLE); + assertThat(unavailable.ownerEcho()).isEmpty(); + verifyNoInteractions(ownerClient); + verify(accountClient, never()) + .issueHuman(any(), anyString(), any(), anyLong(), any(), anyLong()); + verify(accountClient, never()).recover(any(), any(), anyLong(), any(), anyLong()); + } + + @Test + void ambiguousOwnerDispatchPropagatesAndExactDuplicateDoesNotRedeliver() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-dispatch-timeout"); + Snapshot reserved = snapshot(tuple, State.RESERVED, 1L, 1L); + Snapshot alreadyPending = snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 1L); + when(repository.acquire(eq(tuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.AcquireResult(reserved, true), + new StartSessionPreAuthorizationReservationRepository.AcquireResult( + alreadyPending, false)); + when(repository.markAuthorizationPending( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + eq(NOW_MILLIS))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.TransitionResult( + alreadyPending, true)); + AuthorizationReference response = authorizationReference(tuple); + when(accountClient.issueHuman( + eq(shared(tuple)), anyString(), any(UUID.class), eq(1L), any(UUID.class), eq(1L))) + .thenReturn(response); + stubAuthorizationEnrichment(tuple, true, true); + GameSessionClient ownerClient = mock(GameSessionClient.class); + io.grpc.StatusRuntimeException ambiguous = Status.UNAVAILABLE.asRuntimeException(); + when(ownerClient.authorizeStartSession(any())).thenThrow(ambiguous); + + assertThatThrownBy( + () -> coordinator.issueHumanAndDispatch(tuple, CONTROL_UI_TOKEN, ownerClient)) + .isSameAs(ambiguous); + OwnerDispatchResult duplicate = + coordinator.issueHumanAndDispatch(tuple, CONTROL_UI_TOKEN, ownerClient); + + assertThat(duplicate.progress()).isEqualTo(Progress.ALREADY_IN_PROGRESS); + assertThat(duplicate.ownerEcho()).isEmpty(); + verify(ownerClient, org.mockito.Mockito.times(1)).authorizeStartSession(any()); + verify(accountClient, org.mockito.Mockito.times(1)) + .issueHuman( + eq(shared(tuple)), anyString(), any(UUID.class), eq(1L), any(UUID.class), eq(1L)); + } + + @Test + void ownerPendingDuplicateCasDoesNotReturnTransientHandoff() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-owner-duplicate"); + stubInitialReservation(tuple); + AuthorizationReference response = authorizationReference(tuple); + when(accountClient.issueHuman( + eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong())) + .thenReturn(response); + stubAuthorizationEnrichment(tuple, true, false); + + Result result = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); + + assertThat(result.progress()).isEqualTo(Progress.ALREADY_IN_PROGRESS); + assertThat(result.handoff()).isNull(); + assertThat(result.toString()) + .doesNotContain(CONTROL_UI_TOKEN) + .doesNotContain(OPAQUE_REFERENCE) + .doesNotContain(FINGERPRINT); + verify(repository) + .beginOwnerExecution( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + anyString(), + any(UUID.class), + eq(NOW_MILLIS)); + } + + @Test + void ownerPendingTransitionFailureNeverReturnsTransientPayload() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-owner-stale"); + stubInitialReservation(tuple); + AuthorizationReference response = authorizationReference(tuple); + when(accountClient.issueHuman( + eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong())) + .thenReturn(response); + stubAuthorizationEnrichment(tuple, true, true); + when(repository.beginOwnerExecution( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + anyString(), + any(UUID.class), + eq(NOW_MILLIS))) + .thenThrow( + new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId())); + + assertThatThrownBy(() -> coordinator.issueHuman(tuple, CONTROL_UI_TOKEN)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + verify(repository) + .completeAuthorization( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + anyString(), + eq(NOW_MILLIS)); + verify(repository) + .beginOwnerExecution( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + anyString(), + any(UUID.class), + eq(NOW_MILLIS)); + } + + @Test + void uncertainAccountCallLeavesPendingAndIsNotRetried() { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-timeout"); + Snapshot reserved = snapshot(tuple, State.RESERVED, 1L, 1L); + Snapshot pending = snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 1L); + when(repository.acquire(eq(tuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.AcquireResult(reserved, true)); + when(repository.markAuthorizationPending( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + eq(NOW_MILLIS))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.TransitionResult(pending, true)); + when(accountClient.issueHuman( + eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong())) + .thenThrow(Status.UNAVAILABLE.asRuntimeException()); + + assertThatThrownBy(() -> coordinator.issueHuman(tuple, CONTROL_UI_TOKEN)) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + + verify(repository, never()) + .completeAuthorization( + any(), anyString(), any(), anyLong(), any(), anyLong(), anyString(), anyLong()); + verify(repository, never()) + .beginOwnerExecution( + any(), anyString(), any(), anyLong(), any(), anyLong(), anyString(), any(), anyLong()); + verify(accountClient, never()).recover(any(), any(), anyLong(), any(), anyLong()); + } + + @Test + void mismatchedResponseTupleAndStaleClaimAfterAccountReturnAreNotForwarded() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-mismatch"); + StartSessionPreAuthorizationReservationTuple substituted = tuple("coordinator-substituted"); + stubInitialReservation(tuple); + AuthorizationReference substitutedResponse = authorizationReference(substituted); + when(accountClient.issueHuman( + eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong())) + .thenReturn(substitutedResponse); + + assertThatThrownBy(() -> coordinator.issueHuman(tuple, CONTROL_UI_TOKEN)) + .isInstanceOf(IllegalArgumentException.class); + verify(repository, never()) + .completeAuthorization( + any(), anyString(), any(), anyLong(), any(), anyLong(), anyString(), anyLong()); + verify(repository, never()) + .beginOwnerExecution( + any(), anyString(), any(), anyLong(), any(), anyLong(), anyString(), any(), anyLong()); + + StartSessionPreAuthorizationReservationTuple staleTuple = tuple("coordinator-stale-return"); + stubInitialReservation(staleTuple); + AuthorizationReference staleResponse = authorizationReference(staleTuple); + when(accountClient.issueHuman( + eq(shared(staleTuple)), + anyString(), + any(UUID.class), + anyLong(), + any(UUID.class), + anyLong())) + .thenReturn(staleResponse); + when(repository.completeAuthorization( + eq(staleTuple), + eq(staleTuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + anyString(), + eq(NOW_MILLIS))) + .thenThrow( + new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + staleTuple.controlPlaneRequestId())); + + assertThatThrownBy(() -> coordinator.issueHuman(staleTuple, CONTROL_UI_TOKEN)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + verify(repository, never()) + .beginOwnerExecution( + any(), anyString(), any(), anyLong(), any(), anyLong(), anyString(), any(), anyLong()); + } + + private void stubInitialReservation(StartSessionPreAuthorizationReservationTuple tuple) { + Snapshot reserved = snapshot(tuple, State.RESERVED, 1L, 1L); + Snapshot pending = snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 1L); + when(repository.acquire(eq(tuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.AcquireResult(reserved, true)); + when(repository.markAuthorizationPending( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + eq(NOW_MILLIS))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.TransitionResult(pending, true)); + } + + private void stubAuthorizationEnrichment( + StartSessionPreAuthorizationReservationTuple tuple, + boolean transitioned, + boolean mayDispatch) { + when(repository.completeAuthorization( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + anyLong(), + any(UUID.class), + anyLong(), + anyString(), + eq(NOW_MILLIS))) + .thenAnswer( + invocation -> { + UUID reservationOwner = invocation.getArgument(2); + long reservationFence = invocation.getArgument(3); + UUID currentOwner = invocation.getArgument(4); + long currentFence = invocation.getArgument(5); + String exactPostTupleJson = invocation.getArgument(6); + StartSessionPostAuthorizationExecutionTuple postTuple = + StartSessionPostAuthorizationExecutionTuple.decode( + exactPostTupleJson.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + Snapshot authorized = + new Snapshot( + tuple, + tuple.mutationDigest(), + Phase.ACCOUNT_AUTHORIZATION, + State.AUTHORIZED, + reservationFence, + currentFence, + NOW_MILLIS + 30_000L, + ClaimState.ACTIVE, + currentOwner.equals(reservationOwner) && currentFence == reservationFence + ? ClaimPurpose.ORIGINAL + : ClaimPurpose.AUTHORIZATION_RECOVERY); + return new StartSessionPreAuthorizationReservationRepository + .AuthorizationTransitionResult( + new AuthorizedSnapshot( + authorized, postTuple, reservationOwner, currentOwner, null), + transitioned); + }); + when(repository.beginOwnerExecution( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + anyLong(), + any(UUID.class), + anyLong(), + anyString(), + any(UUID.class), + eq(NOW_MILLIS))) + .thenAnswer( + invocation -> { + UUID reservationOwner = invocation.getArgument(2); + long reservationFence = invocation.getArgument(3); + UUID currentOwner = invocation.getArgument(4); + long currentFence = invocation.getArgument(5); + String exactPostTupleJson = invocation.getArgument(6); + UUID handoffId = invocation.getArgument(7); + StartSessionPostAuthorizationExecutionTuple postTuple = + StartSessionPostAuthorizationExecutionTuple.decode( + exactPostTupleJson.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + Snapshot ownerPending = + new Snapshot( + tuple, + tuple.mutationDigest(), + Phase.OWNER_EXECUTION, + State.OWNER_EXECUTION_PENDING, + reservationFence, + currentFence, + NOW_MILLIS + 30_000L, + ClaimState.ACTIVE, + currentOwner.equals(reservationOwner) && currentFence == reservationFence + ? ClaimPurpose.ORIGINAL + : ClaimPurpose.AUTHORIZATION_RECOVERY); + return new StartSessionPreAuthorizationReservationRepository + .OwnerExecutionTransitionResult( + new AuthorizedSnapshot( + ownerPending, + postTuple, + reservationOwner, + currentOwner, + new OwnerExecutionHandoff(handoffId)), + mayDispatch); + }); + } + + private static AuthorizationReference authorizationReference( + StartSessionPreAuthorizationReservationTuple tuple) throws Exception { + AuthorizationReference response = mock(AuthorizationReference.class); + when(response.operatorAuthorizationReference()).thenReturn(OPAQUE_REFERENCE); + when(response.authorizationReferenceFingerprint()).thenReturn(FINGERPRINT); + when(response.expiresAt()).thenReturn(NOW.plusSeconds(300)); + when(response.authorityEvidenceBundle()).thenReturn(bundleBytes(tuple, NOW.plusSeconds(300))); + when(response.bundleReference()).thenReturn(bundleReference()); + when(response.authenticatedLoggingWorkloadIdentity()).thenReturn(LOGGING_IDENTITY); + return response; + } + + private static StartSessionOwnerHandoffResult ownerEcho( + StartSessionPreAuthorizationReservationTuple tuple) { + return new StartSessionOwnerHandoffResult( + tuple.action().scope().targetNamespace(), + tuple.controlPlaneRequestId(), + tuple.mutationDigest(), + OWNER_ATTEMPT_ID, + OWNER_MUTATION_ID, + 7L, + "OWNER_EXECUTION_PENDING", + StartSessionOwnerAuthorizationProgress + .START_SESSION_OWNER_AUTHORIZATION_PROGRESS_ACCOUNT_PROJECTION_ATTACHED); + } + + private static byte[] bundleBytes( + StartSessionPreAuthorizationReservationTuple tuple, Instant expiresAt) throws IOException { + String tenantId = TENANT_ID.toString(); + Map projection = + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + NOW.toString(), + "expiresAt", + expiresAt.toString()); + Map authority = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()); + Map evidence = + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR_ID.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3"); + Map bundle = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantId, "targetNamespace", "world-runtime"), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR_ID.toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(tenantId, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + evidence); + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(bundle)); + } + + private static StartSessionAuthorityEvidenceBundle.BundleReference bundleReference() { + return new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "23", "18446744073709551615"); + } + + private static Snapshot snapshot( + StartSessionPreAuthorizationReservationTuple tuple, + State state, + long reservationFence, + long claimFence) { + return new Snapshot( + tuple, + tuple.mutationDigest(), + Phase.ACCOUNT_AUTHORIZATION, + state, + reservationFence, + claimFence, + NOW_MILLIS + 30_000L, + ClaimState.ACTIVE, + claimFence == reservationFence + ? ClaimPurpose.ORIGINAL + : ClaimPurpose.AUTHORIZATION_RECOVERY); + } + + private static StartSessionPreAuthorizationReservationTuple tuple(String requestId) { + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(TENANT_ID.toString(), List.of("tenantAdmin")), + false, + null, + null); + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target(91L, OWNER_ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "StartSession coordinator unit proof"); + return StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin(requestId, action); + } + + private static net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + shared(StartSessionPreAuthorizationReservationTuple tuple) { + return net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .fromCanonicalJson(tuple.canonicalJson()); + } +}