diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 423df7fff9..5d3231b1e7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1054,8 +1054,8 @@ jobs: permissions: contents: read id-token: write - # Account needs 35 minutes for full checks; World, Game Session and Game Design retain 30 minutes including post-job cleanup. - timeout-minutes: ${{ matrix.module == 'account-service' && 35 || (matrix.module == 'world-management-service' || matrix.module == 'game-session-service' || matrix.module == 'game-design-service') && 30 || 20 }} + # Account needs 40 minutes for full checks; World, Game Session and Game Design retain 30 minutes including post-job cleanup. + timeout-minutes: ${{ matrix.module == 'account-service' && 40 || (matrix.module == 'world-management-service' || matrix.module == 'game-session-service' || matrix.module == 'game-design-service') && 30 || 20 }} strategy: fail-fast: false matrix: diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 0a95f09507..26b41dfe71 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -67,6 +67,8 @@ For a `SaveRevision` request carrying `worldDesignMutation`, the same authorizat ## Implementation Status +The prepared standalone original StartSession template-association read authenticates its exact Game Session workload and verifies Account’s exact redeemed operation before local lookup. Passive Template source/reference owners and selected-publication reservation preserve the existing guarded capture and phase contracts; they do not register the target reference-phase RPC or enable launch/release authority. Their qualification belongs to [the authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-template-publication-and-original-launch-reads). + The prepared Draft terminal-read adapter retains the exact original Account-bound owner outcome under the shared [Account terminal-read transport bounds](../account-service/api-contracts.md#account-owned-hosted-terms-and-creator-party). Its producer and consumer codecs enforce the complete response bound; future server composition must admit the bounded request before this currently unregistered adapter is enabled. The coherent selected-publication receiver installs immutable source inventories, selected owner attestations and mandatory fresh-v2 operation/capture guards through V1023, then asset-bound reviewed-base v2 guards in V1024. Current Java callers supply complete v2 operation evidence and the ordinary asset owner participates in synchronized source and export projection. Original v1 operation/review bytes remain readable history without fresh write authority. This adds no registered publication ingress or activation authority. The canonical retention and fresh-operation rule is in [Version Control](./version-control.md#selected-publication-storage-and-retained-operations), with physical owner proof, controlled-input limits and current qualification in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#coherent-owner-receiving-prerequisite). @@ -102,7 +104,7 @@ The following implementation and proof gaps remain in these live paths: The current script-patch publication/read path is also narrower than the target contract: publication accepts an unvalidated caller-supplied `baseVersionId`, and publication reuse must preserve the effective `(tenantId, baseVersionId, scriptPatchVersion)` identity. Tenant readiness remains keyed by `(tenantId, scriptPatchVersion)` while separately validating immutable `baseVersionId` context, as defined in [Version Control](version-control.md#script-patch-versions-and-runtime-behavior); a separate script-only publication `versionId` is metadata/history and must not be substituted for `baseVersionId`. Game Design now rejects a new publish request when a retained script-only row already owns the effective tenant/base/patch tuple; V27 fails closed on retained incomplete or duplicate tuples and installs partial uniqueness without selecting or deleting a winner. Exact same-request replay still resolves its durable attempt first. Launch resolution and `StartSession` do not prove same-base published patch identity or Automation `READY`. `GetPublishedScriptPatchVersion` requires the complete tuple and its service/digest lookups require exactly one script-only row in retained `PUBLISHED`, `ACTIVE`, or `RETIRED` state for publication metadata; new Game Session pin admission remains independently `PUBLISHED`-only. Callers without authoritative base context fail closed. Notification transport and response failures are swallowed without a durable redrive. The remaining publication, projection, and readiness gaps mean the live APIs must not be treated as complete patch publication or launch-readiness authorities. -The target tenant-scoped `GetTemplateReferencePhase` surface is not implemented: it has no current proto RPC, handler, or durable tenant phase authority. The live launch path checks only each `game_templates.template_reference_phase` value (`ENFORCED` or legacy `LEGACY`), not the target monotonic `BACKFILLING`/`VALIDATED`/`ENFORCED` cutover phase consumed by launch and retirement tooling. The API index below marks this surface target-only; no current launch or retirement proof may treat the per-template field as the target tenant phase. +The target tenant-scoped `GetTemplateReferencePhase` RPC is not implemented: it has no current proto RPC or registered handler. Prepared owner-local reference-phase storage and reads remain unregistered and confer no live launch or retirement authority. The live launch path checks only each `game_templates.template_reference_phase` value (`ENFORCED` or legacy `LEGACY`), not the target monotonic `BACKFILLING`/`VALIDATED`/`ENFORCED` cutover phase consumed by launch and retirement tooling. The API index below marks this surface target-only; no current launch or retirement proof may treat the per-template field as the target tenant phase. The live `CompareAndSetVersionState` path now preserves tenant/version lookup, expected-epoch validation, and an exact same-state no-op, but refuses every state-changing request before updating the Version. The deny-only boundary does not implement the target legal transition matrix, require a committed release bundle/artifact for `DRAFT -> PUBLISHED`, or apply retirement predicates for active instances, templates, and in-flight activation. Therefore the live API must not be treated as an activation- or retirement-safe transition authority; transition validation and focused proof remain blocked. @@ -110,7 +112,7 @@ The current `SaveRevision` path is not the complete target Draft-concurrency con Asset lifecycle API status requires the same distinction: the target `CompareAndSetVersionState`, `TombstoneVersionAssets`, `BeginPurgeVersionAssets`, `FinalizePurgeVersionAssets`, and `RepairPublishedVersionAssets` contracts require database epoch predicates/locks, affected-row proof, and the shared ADR 0048 operation envelope with caller-supplied identity, canonical digest, exact replay, and conflict outcomes. State-changing `CompareAndSetVersionState` requests now fail closed before Version mutation; its legal transition and database-CAS proof remain unimplemented. Other lifecycle writes still lack the complete operation ledger, and `BeginPurgeVersionAssets` mints a random workflow ID. The target asset upload guardrails (25 MiB file limit, 2 GiB tenant quota, and streaming/chunked transfer) are likewise not implemented or proved: the live upload service now refuses before multipart access or storage because Account commit-bound owner proof is unavailable, so this containment does not establish upload readiness. The API entries below describe target semantics and must not be read as current race-safe or idempotent proof. See [Asset Storage](asset-storage.md#implementation-status) for the current upload, repair, release-bundle, and purge boundaries. -The registered World Management `ApplyWorldDesignMutation` handler currently returns an error-only `FAILED_PRECONDITION` before owner-side payload decoding, remote Draft reads, or mutation-service dispatch. Consequently, a `SaveRevision` request carrying `worldDesignMutation` is rejected before Game Design maps or saves its revision; ordinary revision requests without that field retain their local save path. `RevisionServiceImplTest` stubs `WorldManagementClient` and proves Game Design-side validation and call-before-save ordering only. `WorldDesignMutationServiceImplTest` covers the owner-local mutation algorithm and ledger in isolation; neither test establishes a successful registered handoff. See [World Management API implementation status](../world-management-service/api-contracts.md#implementation-status). +The registered World Management `ApplyWorldDesignMutation` handler currently returns an error-only `FAILED_PRECONDITION` before owner-side payload decoding, remote Draft reads, or mutation-service dispatch. Otherwise supported legacy `SaveRevision` requests carrying `worldDesignMutation` are therefore rejected before Game Design maps or saves its revision. The legacy service independently rejects the reserved `GAMEPLAY_RULE` family before any repository or World client access; rule authoring requires the separate coordinated source owner. Other ordinary revision requests without a World mutation retain their local save path. Focused proof for the early gameplay-rule refusals and existing ordinary and World-call ordering cases is recorded in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#legacy-gameplay-rule-write-exclusion). These controlled repository and client mocks do not establish coordinated rule authoring, an authenticated creator flow or a successful registered handoff. See [World Management API implementation status](../world-management-service/api-contracts.md#implementation-status). The current runtime therefore provides no cross-owner apply, replay, or partial-application behavior through this RPC to promote as live `SaveRevision` proof. Same-commit convergence, durable cross-owner retry identity, synchronized visibility, and partial-application isolation remain target requirements and implementation/proof gaps under [ADR 0129](../../decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md). @@ -125,7 +127,10 @@ The published realm-policy owner read is present behind the default-off `firemud ## gRPC APIs - `TenantIdentityService.ResolveFreshTenantCreation` – read-only Account/Game Session peer lookup of one exact immutable creation receipt; it does not create tenants or authorize Account association, JOIN, or gameplay. -- `SaveRevision` – persists a version-scoped revision when no `worldDesignMutation` is supplied. Requests carrying a typed World Management mutation, including `WORLD_GENERATION_SUBTREE`, currently receive `FAILED_PRECONDITION` from the registered World Management ingress before the Game Design revision is saved. +- `SaveRevision` – persists an ordinary version-scoped revision when no `worldDesignMutation` is supplied, excluding `GAMEPLAY_RULE`, which is rejected before owner access and requires coordinated source authoring. Otherwise supported requests carrying a typed World Management mutation, including `WORLD_GENERATION_SUBTREE`, currently receive `FAILED_PRECONDITION` from the registered World Management ingress before the Game Design revision is saved. +- `GameDesignStartSessionTemplateAssociationReadService.ReadStartSessionTemplateAssociation` – standalone, unregistered read for the exact same-namespace Game Session peer. It requires a non-nil read-request and owner-attempt UUID, positive owner fence, explicit selection, and a canonical post-authorization tuple of at most 256 KiB; it verifies the original Account operation and returns exact owner evidence. This does not clear genuine Account/World/release-authority or public-publication holds. See the [proto](../../../../protos/game-design/v1/start_session_template_association_service.proto), [template launch contract](game-templates.md#resolved-launch-descriptor), and [selected publication contract](version-control.md#selected-publication-storage-and-retained-operations). +- `GameDesignStartSessionLaunchDescriptorService.ResolveStartSessionLaunchDescriptor` – standalone, unregistered exact-replay read for the same-namespace Game Session peer. It requires the association request's exact-replay selection and the same bounded canonical tuple; it does not accept initial configured selection. This does not clear genuine Account/World/release-authority or public-publication holds. See the [proto](../../../../protos/game-design/v1/start_session_template_association_service.proto), [template launch contract](game-templates.md#resolved-launch-descriptor), and [selected publication contract](version-control.md#selected-publication-storage-and-retained-operations). +- `GameDesignAuthoredInitialActorCoreReadService.ReadAuthoredInitialActorCore` – standalone, unregistered exact-pinned-association evidence read for same-namespace Game Session or Entity Management peers. Its handler checks the 128 KiB request wire size only after gRPC transport receipt and buffering; any future receiving server composition must enforce a 128 KiB inbound limit before registering this adapter. The handler guard remains in place. The response is capped at 16 MiB wire size and the canonical result at 8 MiB; this evidence does not authorize admission or clear public-publication holds. See the [proto](../../../../protos/game-design/v1/authored_initial_actor_core_read.proto), [template launch contract](game-templates.md#resolved-launch-descriptor), and [selected publication contract](version-control.md#selected-publication-storage-and-retained-operations). - `ResolvePublishedRealmEntryPolicy` – returns immutable Game Design policy and provenance for one exact canonical tenant/version and world/realm selector pair; it does not compose runtime catalog or admission state. - `ListPublishedRealmEntryPolicies` – returns the complete bounded policy set and owner-bound count/digest for one exact canonical tenant/version; it does not activate runtime state. - `PublishVersion` – carries the exact selected existing Version, expected state epoch, and synchronized commit request/commit/digest identity, but fails closed before reservation because current Account authorization and authenticated World owner-freeze evidence are unavailable. The shared command boundary also denies fresh/PENDING requests before mutation until a production Version-to-Draft association exists; configured Temporal ingress uses the same guard, while no-selection requests are limited to exact terminal replay. @@ -211,7 +216,10 @@ Detailed request and response schemas are defined in the [OpenAPI specification] - `TenantIdentityService.ResolveFreshTenantCreation(ResolveFreshTenantCreationRequest) returns (ResolveFreshTenantCreationResponse)` – read-only Account/Game Session peer lookup of one exact immutable creation receipt; it does not create tenants or authorize Account association, JOIN, or gameplay. - `AuthoredWorldVersionStateService.GetAuthoredWorldVersionState` (adapter `AuthoredWorldVersionStateGrpcService`) – standalone, unregistered exact version-state evidence read for World Management's UUID-backed version association. It authenticates the same-namespace World workload and accepts no caller context; it does not activate a version or authorize gameplay admission. - `AuthoredWorldSourceReadService.ResolveAuthoredWorldSource` (adapter `AuthoredWorldSourceReadGrpcService`) – standalone, unregistered exact read of Game Design authored-source evidence for World Management. It authenticates the exact same-namespace World workload before decoding or reading, uses no caller context, and does not authorize source mutation or runtime launch. -- `SaveRevision(SaveRevisionRequest) returns (SaveRevisionResponse)` – persists a version-scoped design change when the request omits `worldDesignMutation`; carrying that optional typed mutation currently fails at the registered World Management ingress before the Game Design revision is saved. +- `GameDesignStartSessionTemplateAssociationReadService.ReadStartSessionTemplateAssociation(ReadStartSessionTemplateAssociationRequest) returns (ReadStartSessionTemplateAssociationResponse)` – standalone, unregistered read for the exact same-namespace Game Session peer. It requires non-nil read-request and owner-attempt UUIDs, a positive owner fence, explicit selection, and a canonical post-authorization tuple bounded to 256 KiB; it verifies the original Account operation and returns exact owner evidence. This does not clear genuine Account/World/release-authority or public-publication holds. See the [proto](../../../../protos/game-design/v1/start_session_template_association_service.proto), [template launch contract](game-templates.md#resolved-launch-descriptor), and [selected publication contract](version-control.md#selected-publication-storage-and-retained-operations). +- `GameDesignStartSessionLaunchDescriptorService.ResolveStartSessionLaunchDescriptor(ReadStartSessionTemplateAssociationRequest) returns (ResolveStartSessionLaunchDescriptorResponse)` – standalone, unregistered exact-replay read for the same-namespace Game Session peer. It requires explicit exact-replay selection and the same bounded canonical tuple; initial configured selection is refused. This does not clear genuine Account/World/release-authority or public-publication holds. See the [proto](../../../../protos/game-design/v1/start_session_template_association_service.proto), [template launch contract](game-templates.md#resolved-launch-descriptor), and [selected publication contract](version-control.md#selected-publication-storage-and-retained-operations). +- `GameDesignAuthoredInitialActorCoreReadService.ReadAuthoredInitialActorCore(ReadAuthoredInitialActorCoreRequest) returns (ReadAuthoredInitialActorCoreResponse)` – standalone, unregistered exact-pinned-association evidence read for same-namespace Game Session or Entity Management peers. Its handler checks the 128 KiB request wire size only after gRPC transport receipt and buffering; any future receiving server composition must enforce a 128 KiB inbound limit before registering this adapter. The handler guard remains in place. The response is capped at 16 MiB wire size and the canonical result at 8 MiB; this evidence does not authorize admission or clear public-publication holds. See the [proto](../../../../protos/game-design/v1/authored_initial_actor_core_read.proto), [template launch contract](game-templates.md#resolved-launch-descriptor), and [selected publication contract](version-control.md#selected-publication-storage-and-retained-operations). +- `SaveRevision(SaveRevisionRequest) returns (SaveRevisionResponse)` – persists an ordinary version-scoped design change when the request omits `worldDesignMutation`; the reserved `GAMEPLAY_RULE` family is rejected before owner access. Otherwise supported requests carrying that optional typed World mutation currently fail at the registered World Management ingress before the Game Design revision is saved. - `PublishVersion(PublishVersionRequest) returns (PublishVersionResponse)` – publishes the exact selected frozen version. A new request carries stable `publish_request_id`, canonical selected `version_id`, `expected_version_state_epoch`, `selected_commit_request_id`, `selected_commit_id`, and `selected_commit_digest`; the complete synchronized commit is captured before source material is frozen. The request ID binds exact terminal replay, and the target/conditional Temporal behavior derives one tenant-scoped durable workflow identity from it. Current public and registered Temporal paths fail closed for fresh and `PENDING` requests until genuine Account authorization and authenticated owner-freeze production are available; they do not start publication mechanics. The legacy no-selection request shape is limited to exact retained terminal replay and cannot authorize a new or pending publication. Exact terminal replay remains available: `FAILED` returns its stored attempt result, while `SUCCEEDED` requires exact immutable release readback. Timeout or failure remains explicit and may be outcome-pending until durable readback resolves it; no half-complete success is exposed. Retrying the same request must preserve its original selection and captured source bytes. The current boundary does not prove reachable live publication success. - `PublishScriptPatchVersion(PublishScriptPatchVersionRequest) returns (PublishScriptPatchVersionResponse)` – publishes a script-only patch version. - `GetPublishedScriptPatchVersion(GetPublishedScriptPatchVersionRequest) returns (GetPublishedScriptPatchVersionResponse)` – returns the immutable script-patch publication read model, including base version, lifecycle state, digest identity, and last-changed time. diff --git a/design/architecture/microservices/game-design-service/game-templates.md b/design/architecture/microservices/game-design-service/game-templates.md index d02b292f3e..7e15fd8db5 100644 --- a/design/architecture/microservices/game-design-service/game-templates.md +++ b/design/architecture/microservices/game-design-service/game-templates.md @@ -19,9 +19,9 @@ The additive owner-local launch-descriptor storage accepts the explicit retained - The launch plugin-selection presence modes remain target-only and unimplemented: a presence-capable selection wrapper/mode, fresh omission or explicit empty resolving to the same immutable empty selection, rollback omission reusing a named target, rollback explicit empty, and explicit non-empty selection are not yet represented in proto/generated clients, launch-descriptor persistence/response, the request digest, service logic, or focused proof. Launch-resolution APIs are live, but the current implementation does not yet persist, expose, or prove the complete `enabledPluginVersions[]` set for deterministic retry and rollback. The detailed target contract remains below. - Current script-patch resolution is not yet the target launch predicate: a full-version template/request can persist an arbitrary patch ID without proving a same-base `PUBLISHED` Game Design publication or Automation `READY` status. These are implementation gaps; the target validation and fail-before-instance-row rules remain below. -- The target tenant-scoped `GetTemplateReferencePhase` cutover read is not implemented in the current proto or service. Current launch resolution checks only the per-template `templateReferencePhase` field (`ENFORCED`/`LEGACY`); it does not expose or consume the target durable tenant phase (`BACKFILLING`/`VALIDATED`/`ENFORCED`) required by launch and retirement tooling. -- Normalized `game_template_*_ref` storage and its lifecycle/query authority are target-only. The current implementation persists `game_templates` and revision rows, but has no normalized reference tables, create/update derivation and atomic synchronization, one-time backfill/validation marker, or retirement/reference-query tooling; current lifecycle checks cannot rely on those rows and remain unimplemented or unproven. -- The current REST `POST /templates` path is named and documented as create-only, but a caller-supplied `id` is accepted by the DTO and makes the repository update the row by global `id` while also writing the supplied `tenantId`; the subsequent tenant-filtered readback can then hide the changed row. This is a current cross-tenant reassignment/overwrite gap, not tenant-scoped update safety. The target contract must reject `id` on create and make any future update and readback exact-tenant-qualified while keeping the stored tenant binding immutable; focused cross-tenant denial proof is absent. +- The target tenant-scoped `GetTemplateReferencePhase` RPC is absent from the current proto and registered service. The owner-local tenant phase row, monotonic `BACKFILLING` → `VALIDATED` → `ENFORCED` transitions, full-inventory validator, and passive phase reads are prepared; they remain unregistered and do not provide live launch or retirement enforcement. `StartSessionTemplateAssociationReadService` and `StartSessionLaunchDescriptorProducer` consume persisted `ENFORCED` phase state with its exact phase epoch. Current registered launch resolution checks only the per-template `templateReferencePhase` field (`ENFORCED`/`LEGACY`), not the tenant phase. +- Normalized template-reference coverage is partial. The current implementation projects base-version references into `game_template_version_ref`; the other normalized reference families, complete create/update derivation and atomic synchronization, registered cutover owner, and retirement/reference-query tooling remain absent or unproved. The prepared phase primitive and passive reads do not establish that all template dependencies have normalized rows or that runtime lifecycle checks can rely on them. +- The create-only `POST /templates` service rejects a supplied `id` before mapping or repository access. Repository updates require the exact tenant and template ID, preserve the stored tenant binding and refuse a missing row. Three service units and one native PostgreSQL case cover create refusal, normal create, complete row and row-version preservation on foreign or missing identity, and a valid same-tenant update. The SQL case deliberately uses controlled pre-phase rows, where the later template-reference phase guard cannot hide a missing repository predicate. This focused component proof does not establish REST authentication, the hosted-content gate or production provisioning readiness. - Current template-remap-set APIs persist tenant-scoped `DRAFT`/`APPROVED` sets and entries. When `ResolveLaunchDescriptor` receives a `sourceVersionId` that differs from the resolved target, it selects exactly one `APPROVED` set for the source/target pair and persists and returns that set's `remapSetId`; it does not collect or verify owning-domain attestations. The target attestation predicate remains below. - Schema-three gameplay policy carries `initialActorCore` alongside `creationDescriptor` as retained published inputs consumed by the passive `CHARACTER_CREATE/1` source projection. 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 common-core receiving support; the receiver and shared negative fixtures do not prove Game Design template authoring, persistence, publication, or creation activation. The canonical family contract is in the [CHARACTER_CREATE/1 schema](../entity-management-service/character-create-action-schema.md). @@ -56,7 +56,7 @@ This guarded planning and application is target-state behavior. The current `Sav After a successful upgrade, the exact profile baseline advances to `N`, while retained local differences, explicit deletions, detachments, mappings, and resolution outcomes remain recorded for the next upgrade. This makes repeated upgrades deterministic without turning the profile into an authoring or runtime inheritance layer. -`GameTemplateDto` includes `id`, `tenantId`, `name`, an optional `description`, the raw `config` JSON and a `createdAt` timestamp. On a normal create with `id` omitted, the database assigns the ID when the template is saved. The current DTO/service path also accepts a caller-supplied `id` and can update a row by that global ID while changing its claimed tenant; this is the cross-tenant overwrite/reassignment gap recorded in [Implementation Status](#implementation-status), not supported create behavior. The target create contract rejects `id`, and future updates/readbacks must use exact tenant-qualified identity while keeping the stored tenant binding immutable. The `config` field uses a structured schema describing world layout, starter items, default rulesets, template references, and non-authoritative settings. +`GameTemplateDto` includes `id`, `tenantId`, `name`, an optional `description`, the raw `config` JSON and a `createdAt` timestamp. Create requests must omit `id`; the database assigns it when the template is saved, and the service rejects a supplied value before owner access. Updates and readback use the exact tenant-qualified identity, and the repository never reassigns the stored tenant binding. This does not introduce a public update API. The `config` field uses a structured schema describing world layout, starter items, default rulesets, template references, and non-authoritative settings. The `config` payload does not embed authoritative copies of world, entity, or script definitions. Instead it carries: @@ -388,7 +388,7 @@ Game templates participate in the same version lifecycle as the domain templates ## Creating Templates -The current REST endpoint is a local/internal implementation seam, not an approved official-hosted or general operator provisioning workflow. External exposure of `POST /templates` must remain unavailable until the hosted-content gate, tenant-safe create/readback behavior, and focused proof are implemented. The request must omit `id`; although the database assigns it for a normal create, the current DTO/service path accepts a caller-supplied id and can overwrite a row under the wrong tenant before tenant-filtered readback hides the result. Do not use this current seam for external or production template provisioning. +The current REST endpoint is a local/internal implementation seam, not an approved official-hosted or general operator provisioning workflow. The request must omit `id`; the create service rejects a supplied ID, and the repository requires exact tenant-qualified updates and readback. The focused owner proof in [Implementation Status](#implementation-status) does not establish the hosted-content gate, authenticated creator flow or production provisioning readiness. External exposure of `POST /templates` remains unavailable until those remaining boundaries are implemented and proved. Do not use this current seam for external or production template provisioning. For local or otherwise explicitly isolated development use, creators can submit a `GameTemplateDto` via the REST API: diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index 8f6d4c6c10..4b5dfd2691 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -6,6 +6,10 @@ Game Design is the canonical authored-history, publication-coordination, release ## Implementation Status +The shared strict selected-full attestation and terminal codecs, read-only World lifecycle support for schema 4 and a class-only guarded World evidence fixture are source-prepared and unqualified in this read stage. The actual Game Design writer/storage integration, fixture factory execution and five-store owner composition remain in the full selected-owner successor; this preparation supplies no fresh publication authority. Public fresh/PENDING publication remains denied and no activation or component registration is enabled. Current execution attribution and remaining qualification are recorded in the [selected-template tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-template-publication-and-original-launch-reads). + +Standalone Template source/reference owners, selected-publication reservation and the exact original StartSession template read are prepared over existing guarded storage. They remain unregistered; qualified owner-local storage does not supply genuine Account, World or immutable-release authority. Current source, proof and retention limitations belong to [the authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-template-publication-and-original-launch-reads). + The prepared selected gameplay-rule source export and intake/receipt composition remain standalone and unregistered; they add no full-version publication authority or runtime rule activation. The [gameplay-rule retention tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#selected-gameplay-rule-retention-and-receipt-composition) owns qualification, exact owner composition and controlled-input limits. The combined World source successor implements local shared Draft-writer containment and prepares an unregistered strict Common/protocol foundation for exact owner evidence. Its source foundation alone does not implement Game Design publication orchestration; the standalone World consumer and subsequent Game Design terminal-producer boundaries retain separately scoped proof and authority limits. The [World owner API contract](../world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state) remains authoritative for freeze and terminal operations; separately scoped implementation/proof status is recorded in [the World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#shared-draft-mutation-fence). @@ -34,6 +38,14 @@ Fresh full-version publication requires operation-bound captures of all six Game Original retained three-frame v1 bytes remain readable with their original row and request checksums. They do not establish inventory completeness and cannot authorize a new operation reservation, capture or terminal seal after the v2 storage guards apply. Forward migrations do not rewrite those bytes or fabricate source history. Forward migrations also preserve original `game-design-reviewed-draft-base/v1` rows and their exact bytes. Fresh reviewed-base v2 evidence binds the original policy, command and ordinary asset genesis, or the exact synchronized snapshots and complete owner vector for an authored base. An old review without ordinary asset lineage remains readable and cannot authorize a fresh source write. The database independently reconstructs fresh review bytes from the retained owner records before accepting the claim. Source-family inventories, exact Game Logic and World associations, normalized template references, original Account owner schema and candidate projection remain separate retained owner facts; installing their tables and guards does not produce those facts or enable publication. +### Selected Full Publication Profile + +Fresh selected-full publication uses Game Design attestation schema 4 (`v4`) and one complete ordered participant vector: `WORLD_MANAGEMENT` digest schema 4, `ENTITY_MANAGEMENT` schema 3, `GAME_LOGIC` schema 1, `AUTOMATION_SCRIPTING` schema 6 and `GAME_DESIGN_CONTROL_PLANE` schema 2. Every participant must report successful evidence for the same exact full-Version row and selected authored commit, with no script-patch/base-Version scope, missing participant, duplicate, reordered participant or substituted digest schema. Game Logic additionally supplies its independently scoped ability-schema digest. A legacy or partial vector cannot be relabeled as this profile. + +The selected collector binds the canonical tenant UUID, exact full-Version row, original publication request and derived workflow to the immutable selected operation. World evidence must retain its exact selected selector and complete inventory, and the collector must independently read the actual retained recipient and Game Logic receipts; a generic publication Account binding, identifier lookup, latest owner state or copied response cannot replace recipient-bound evidence. Game Design's participant covers all six immutable selected source families. The current Entity recipient profile requires explicit zero counts for all 23 supported source catalogue families and equipment `NOT_APPLICABLE`; the Automation recipient profile is empty-only and cannot attest arbitrary authored scripts. Owner-local source and receipt validation remains mandatory before accepting either digest. + +Fresh writes and schema-4 readback use the selected publication gate and exact immutable bundle/World joins. Historical attestation schemas 1–3 preserve their original bytes and only their already-supported reads and retries. They do not acquire missing source completeness, recipient receipts or schema-4 authority, and this profile does not widen consumers that do not already support an older schema. The existing V1020 storage owner is used without rewriting retained history or introducing a new Game Design migration. Publication evidence does not grant activation, actor placement or delivery authority. + ## Approach - Each asset revision already stores author and timestamp metadata. diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 7b9d87f583..3c7932ded9 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -2,6 +2,10 @@ ## Implementation Status +The standalone published-spawn requirements read is prepared as unregistered source. It consumes the exact authenticated Game Design release and frozen World selector, accepts only the exact same-namespace Entity workload, and returns immutable design requirements rather than runtime actor or placement authority. Qualification and producer limitations belong to [the World implementation tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#published-spawn-requirements-read-preparation). + +The complete published-spawn response has a 4 MiB serialized Protobuf limit, matching the existing gRPC inbound ceiling. Its owner encoder, client stub and response decoder enforce the same limit; the decoder checks size before recursively validating or constructing evidence. Oversized evidence is refused rather than truncated or partially accepted. + The original StartSession canonical preparation, exact execution recovery and lifecycle-read components are prepared as standalone, unregistered source. Their current qualification and producer dependencies belong to [the World implementation tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#original-startsession-world-preparation-and-recovery). Production Game Design complete-launch reads remain denied; these components do not enable deployment, activation, admission or Entity placement. The existing [World creation workflow](./world-creation-workflow.md) and [runtime storage contracts](./runtime-and-data.md) retain target-state authority. The prepared, unregistered Draft terminal-read adapter accepts only the exact same-namespace Account workload and returns the original Account-bound committed graph application or definitive-abort owner evidence. It enforces the shared [Account terminal-read transport bounds](../account-service/api-contracts.md#account-owned-hosted-terms-and-creator-party); future server composition must admit the corresponding bounded request. It preserves the current graph and original inbound-source closure carriers and inherited SQL history. It supplies no graph mutation, source authorization, visibility change or activation; component proof and remaining limits are recorded in [the authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#account-terminal-settlement-continuation). diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index f9cbfc7188..c87a959f38 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -140,6 +140,11 @@ Entry format: - Recovery: the next foreground canonical attempt on `3c71c8c24379af623ca66550a4f4acaadd0ffd81` completed at 05:27:42 UTC with exit zero, full terminal capture, held-edge and backend proof, authenticated teardown and independently absent project resources. This does not establish why the earlier owner ended. - Reconsideration trigger: a subsequent canonical attempt completes with terminal capture, or bounded process evidence identifies why the previous owner ended. +- `2026-10-16`: Qualify tenant mutation predicates + - Context: Game Design template repository update path (`GameTemplateRepository.save`) and native `GameTemplateRepositoryPostgresIntegrationTest` on the template create/update correction lane. + - Observation: The global-ID update rewrote a retained row's tenant before returning it under the supplied tenant; tenant-filtered readback did not protect the original row. The native counterexample changed the complete row and `xmin`, while the restored exact tenant predicate preserves both owner rows and their versions. + - Expected pattern: Test controlled pre-phase rows as well as later guarded owners. Keep the create-only ID refusal before mapper/repository access, and separate this owner-local SQL proof from authenticated creator or hosted-content readiness. + - `2026-10-16`: Derive focused Gradle selectors from declared Java packages - Context: a Gameplay capture proof supplied `integration.net...` as the selector, and Gradle executed no tests before failing discovery. - Observation: `integration` came from the categorized source root, while the class declared `net...`; a categorized source root is not necessarily part of the Java package, and a zero-test discovery failure establishes no test proof. @@ -148,6 +153,12 @@ Entry format: - Recurrence (`2026-10-17`, #3231): a mixed-selector review-fix gate requested two World classes, but one selector incorrectly included the categorized `unit` source-root segment in its Java package. The matching selector executed nine terminal-read cases, so the task succeeded while the launch-binding comparator class remained unrun. A successful task does not establish coverage of every supplied pattern. Verify every expected class in fresh XML, preserve completed reports before a corrected filtered run replaces task output, and credit the missed class only after its own execution. - Reconsideration trigger: when the canonical Gradle selector tooling or CI guard can verify every explicitly requested test class rather than only aggregate task success, qualify that guard against a mixed valid/invalid selector and revisit this manual proof step. +- `2026-10-17`: Explain inbox read failures during SQLite writes + - Context: Gameplay used the canonical `inbox read` command for an Overseer message at 11:01 UTC on 2026-10-16. + - Observation: the command returned no message body after 9.95 seconds and reported only `SQLite inbox write failed`. The error did not identify the failed write, contention state or safe retry boundary; its underlying cause remains unknown. + - Expected pattern: make message delivery and seen-state recording failures distinguishable, with enough operation context to choose a safe canonical retry without inspecting or mutating the database directly. + - Recovery: one canonical retry returned the full message after 6.30 seconds. Gameplay reported the evidence to Overseer for the User-requested Controller improvements; no database or Controller change was made by this lane. + - `2026-10-17`: Distinguish queued source CI from early metadata runs - Context: Six newly published Gameplay heads initially had only early metadata jobs inspectable. - Observation: The observer reported that the heads had no source validation. Their original source workflows later completed change detection and started the build/test matrices. No missing-source CI defect or cancellation was established; the premature report sent unnecessary investigation to Overseer. @@ -188,8 +199,24 @@ Entry format: - 2026-10-18: CodeRabbit full review 5560170943 for PR #3264 emitted a complete 1/1 publication with one outside-diff Major but no bounded actionable-comment count. The existing manual adoption correctly refused automatic attribution with `Hosted publication has no unique bounded actionable-comment count`. Exact trigger 6241278398, reviewed head `187ab53426caf78cd6a01b61e092b800186aaec2`, provider result and accepted obligation were retained in the CI validation throughput controller job history without invented Hosted credit; no controller adapter change was made in this CI patch. Reconsider format support only in a separately scoped controller maintenance task. +- `2026-10-18`: PR retarget can fail exact merge-parent metadata checks + - Context: After #3237 merged and #3246 was retargeted to `develop`, Runtime Images run `39093729815` and Preview run `39093729854` checked the retargeted head/base pair. + - Observation: Both runs rejected the selected test-merge commit because it did not have its exact parents. Runtime failed before image production; Preview exhausted five merge-computation attempts. The PR Runtime path uses `GITHUB_SHA`; an empty dispatch-only `EVENT_MERGE_SHA` is not the cause. The reason for the mismatched merge selection is unconfirmed. + - Expected pattern: The previous parent's green runs do not qualify the new pair. Preserve the exact-parent guard and do not rerun blindly. No guard was weakened and no blind rerun was requested. + - Recovery: Gameplay reported the captured failures to Overseer in controller message `64512c73-9fa2-44b5-b2b7-e5b607155777`, with Preview evidence in reply `0de28b96-8790-4e5e-b8e5-a915d96de829`. After normal parent reconciliation and the required correction push to `a9d9f27a4139c2be2cbf9b7c1df4c4a33d6b8bf3` on `develop` at `efbc55874894ce5b2b420e19fac5ab23d66e384e`, replacement Runtime Images run `39094799761` and Preview run `39094798308` both succeeded. This establishes recovery of those metadata checks after that publication boundary, without explaining the original mismatch or claiming whole-CI success. + - `2026-10-19`: Independent maintenance temporarily becomes the product queue's parent - Context: Controller recovery maintenance PR #3271 was inserted before the existing product front to obtain the next admissible shared review slot. - Observation: the current controller queue is strictly linear and has no independent maintenance root. Inserting an open maintenance PR before the product front changes the product front's effective parent even though the patches are independent, creating an integration fence until maintenance merges. - Expected pattern: assess and communicate this queue consequence before insertion; preserve the product's qualified head, original parent and proof rather than rebasing it onto unmerged maintenance. Keep the temporary maintenance front through its normal review requirements and release the integration fence at its human-authorized merge. This records the current operational limitation, not a new queue design or review-policy exception. - Reconsideration trigger: if existing tooling gains independent maintenance-root scheduling, qualify its parent/proof behavior before changing this operational assumption. + +- `2026-10-19`: Paginate the complete CI observer context inventory + - Context: On 2026-10-18 UTC / 2026-10-19 NZDT, the first 100 GraphQL contexts omitted the [#3249 Smoke Gate failure](https://github.com/benhook1013/FireMUD/actions/runs/39142129196/job/117718532427) at `b83`, delaying its detection by about 19 minutes; the complete inventory contained 186 contexts. The private observer now reads all pages within its bound and fails closed if the final `pageInfo.hasNextPage` remains true, errors occur, or head identity differs. + - Observation: A first-page result can miss a later failure in the same run. The observer now fails closed when pagination or response checks are incomplete; this records the observer recovery and does not establish or claim an underlying gate bug fix. + - Expected pattern: Treat a complete paginated inventory as authoritative, verify page completion, errors, and the requested head, and report no complete result when any check fails. + +- `2026-10-19`: Tie routed review-thread closure to the published candidate + - Context: On 2026-10-18 UTC / 2026-10-19 NZDT, Main prematurely resolved a routed #3269 H1 thread after the parent #3249 fix was published but before the child carry was published. The thread was immediately reopened and finally resolved after child commit `bc10` was published. + - Observation: A routed parent fix alone did not prove that the child candidate carried the fix. + - Expected pattern: Close a routed thread only against the relevant published candidate; verify the child carry publication before treating the thread as resolved. diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 85a110f177..d72660c752 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,6 +6,72 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +### Historical membership and upstream source validation proof + +The existing runtime membership validator test now checks three supported Account source event formats alongside a positive issuer source while retaining the original historical membership bytes. It verifies positive upstream evidence before returning an empty missing-membership result. Freshly resealed membership events cannot lead the current issuer generation, Account generation, issuance fence or historical Account cutoff sequence; equal and earlier valid Account cutoffs retain their original bytes. The added source fixtures use representable initialized counters above JavaScript's exact-integer range, while the existing maximum-counter case remains intact. The current exact tenant-generation and billing-cutoff rules retain their preceding tests and attribution. + +All seventeen owning structural invocations freshly pass with zero failures, errors or skips, including five added invocations and twelve retained cases. Canonical formatting, Test Checkstyle and SpotBugs pass; final style checks remain up to date against the formatted source. The donor's two earlier fixture range and initialized-counter failures are archived separately from its passing run. These cases construct and seal local event bytes. They do not establish a genuine issuer or Account producer, authenticated currentness, durable runtime projection, admission protection, settlement, activation or a Gameplay handoff. No production validator, wire contract, registration, source schema or installed migration is changed. + +### Immutable Draft fence and closed carrier proof + +The restored dedicated Draft authorization-fence codec test retains the fixed v1 producer bytes and digest, v2 required-owner mapping and ordering, exact owner-readback bytes, and malformed framing, identity, counter, digest and source-vector rejection. These local byte-format cases supplement the existing transport tests. The World terminal codec also rejects string or unsupported closure schemas, opaque inventories, negative counts and unsupported entry members on both original and applied closure paths, plus null and opaque whole closures. The StartSession authority bundle rejects an unsupported bundle version and an issuance fence beyond the supported signed range while preserving its distinct projection and issuance counters. + +All thirty-seven selected structural tests freshly pass in three XML suites with zero failures, errors or skips: twelve Draft fence codec cases, seventeen World terminal codec cases and eight authority bundle cases. Canonical formatting, style, Test Checkstyle and SpotBugs pass. These tests use locally constructed carrier bytes; they do not establish an authenticated owner, durable source application, Account currentness, a genuine immutable release, live settlement, activation or a Gameplay handoff. No production code, wire contract, service registration or installed migration is changed. + +### Retained release identity migration proof + +The existing early launch-descriptor migration case now compares every prior column and PostgreSQL row version in the retained Version, release bundle and unbound descriptor at V34.1 → V35 → V35.1 → V35.2 → V36 → V38 and then the current default. Each checkpoint also preserves every earlier Flyway history row. Newly introduced descriptor bindings, canonical Version and release identities, the opaque bundle reference and asset-proof fields remain explicitly unset. The existing unbound-launch refusal and immutable-descriptor update refusal preserve the complete current rows and their row versions. + +These two storage cases freshly passed on donor code source `25287524a17efa9ea8b5a058f3e06809b13cff33`, with zero failures, errors or skips. Canonical formatting, Integration Checkstyle and SpotBugs passed; style checks remained up to date. Passive capture identified the one run-owned PostgreSQL container and independently confirmed its absence after completion. This controlled historical storage proof has no authenticated creator or issuer, currentness, genuine immutable release, public publication enablement, activation or Gameplay handoff. On receiving source `85dfcfb5e15d1e75e4ccfd80392e932da299be99`, the combined gate freshly passed all ten launch-descriptor cases and all five identity/rollback cases, with zero failures, errors or skips, plus Integration Checkstyle, SpotBugs, formatting and documentation checks (2026-10-16 08:00:11–08:02:51 UTC). Main verified the fresh reports and unchanged source, and independently confirmed both strictly run-owned PostgreSQL containers absent after their recorded forced removal. This is receiving evidence for these historical storage fixtures only. No production, installed migration or registration changes are included. + +### Release bundle identity and owner rollback storage proof + +Five bounded native cases on donor code source `eb9c3bf5342ddfe653f97c8dc77eb93994816506` exercise v1 release-bundle identity and rollback using controlled Game and Version sources. They cover owner-derived canonical identities and an opaque reference, refusal of caller/source/database identity mismatches, immutable mapped and historical unmapped rows, metadata backfill and mapped-row deletion refusal, and TRUNCATE refusal. A nested repository save rolls back with an outer Spring transaction, including its Version state change; an outer jOOQ entrypoint through the existing Spring transaction provider also rolls back its nested bundle insert. Full mapped and retained rows and PostgreSQL row versions remain unchanged. A separate retained-row DELETE case was not run. + +All five donor cases passed with zero failures, errors or skips against the canonical PostgreSQL image and owning migrations; canonical formatting, style, Integration Checkstyle and SpotBugs passed, and passive capture independently confirmed the run-owned PostgreSQL container was absent after completion. These controlled v1 fixtures do not prove selected v3/v4 publication, an authenticated creator or issuer, currentness, a genuine immutable release, activation or Gameplay handoff. The outer jOOQ case uses the existing Spring transaction provider and does not qualify an independent unbridged provider or change transaction policy. The same combined receiving gate above freshly qualifies these five cases; donor results retain their separate source attribution. No production code, installed migration, transaction-provider policy or registration changes are included. + +### Retained publication diagnostics migration proof + +The existing launch-descriptor native test seeds explicitly historical, unbound Version, release, descriptor, attempt and artifact rows before canonical identity enforcement using the current V34.1 predecessor. After V38, the V39 text widening and the forward migrations through the current default preserve every prior column and PostgreSQL row version in those five rows, together with all prior Flyway history rows. Long UTF-8 failure diagnostics round-trip after widening and remain intact after the forward migrations; a later terminal-attempt rewrite refuses without changing the retained rows or inventing a publication operation. + +The single restored migration case freshly passes with zero failures, errors or skips. Canonical formatting, style, Integration Checkstyle and SpotBugs pass; the one passively identified PostgreSQL container is independently absent after completion. This is retained-data migration proof over synthetic historical rows. It does not establish an authenticated source, creator or issuer, currentness, a genuine immutable release, public publication enablement, activation or a Gameplay handoff; the other launch-descriptor cases retain their preceding attribution. No installed migration or production code is changed. + +### Template create and tenant-qualified updates + +The existing create service rejects a caller-supplied template ID before mapping or repository access. The repository updates only the exact tenant and template ID, never writes a replacement tenant binding and requires exactly one affected row before its tenant-qualified readback. No new public update API, migration, registration or hosted-content authority is introduced. + +Fresh old-code proof reproduces both the service accepting a supplied create ID and an actual PostgreSQL row changing from one tenant to another, including its row version. The corrected source freshly passes three service units and one native PostgreSQL case with zero failures, errors or skips; the native case preserves both complete template rows and row versions on foreign or missing identity and permits a normal same-tenant update. The controlled pre-phase fixture uses current default migrations and does not rely on the later reference-phase guard to refuse the mutation. Affected Main, Test and Integration static checks, canonical formatting and style pass. The exact run-owned PostgreSQL container is passively captured and independently absent after teardown. + +These are mocked service-collaborator and direct repository SQL checks. They do not execute the REST or authenticated creator flow, establish Account hosted-terms/currentness authority, enable publication or complete a genuine Gameplay handoff. The existing external provisioning hold remains in [Game Templates](../../architecture/microservices/game-design-service/game-templates.md#creating-templates). + +### Retained release byte and participant proof + +The current Common owner test preserves the historical schema-1 release attestation's fixed canonical digest and domain, alongside the existing exact stored readback and selector non-promotion checks. The selected-full schema-4 case independently refuses each World, Entity, Automation and Game Design participant when that owner alone supplies its retained older digest schema; the complete current vector remains `4/3/1/6/2`. + +All eight focused owner cases freshly pass with zero failures, errors or skips. The affected test static analysis, canonical formatting and style checks pass at the same test source. These are structural known-answer and refusal checks with stipulated values; they do not execute owner SQL, authenticate source provenance, produce a release, enable publication or complete a genuine Gameplay handoff. Historical byte retention does not widen an older profile's supported consumers or grant selected-full authority. + +### Selected template publication and original launch reads + +The prepared source adds owner-local Template configuration genesis, synchronized revision/application, selected source capture and normalized tenant reference-phase owners over the already guarded tables. `SelectedDraftPublicationOwner` retains the exact selection, pending attempt, complete source capture and immutable template/World relation in one caller-owned writable transaction; existing operation bytes are never upgraded and old descriptor or reference provenance is not backfilled. The original StartSession template-association read authenticates Game Session and independently verifies Account’s exact redeemed operation before its read-only snapshot. It accepts only current selector-bound release-v2 evidence for the configured path and refuses older non-selector releases rather than fabricating later bundles. These components are unregistered and add no migration or runtime enabling flag. + +The same closure prepares the actual Game Design original launch-descriptor and authored actor-core projection, Game Session retention bound to its original Human owner attempt, and the Entity-only World published-spawn requirements read with strict Common transport, described in [the World tracker](./world-runtime-and-movement.md#published-spawn-requirements-read-preparation). Game Session's forward V1013 retains the core against the actual existing launch association; it does not allocate another owner or backfill retained rows. These components remain unregistered. + +The latest supported whole-source Game Design gate remains the historical receiving run at `3ad94e6c595dffbb2ca0c01c677512832574e706`: it passed 624 unit, 170 native integration and 25 cross-service cases with zero failures, errors or skips, plus static analysis, formatting and documentation checks (2026-10-16 10:15:37–10:24:43 UTC). Main verified the archived reports and exact absence of all 36 owned PostgreSQL containers. This supersedes the earlier Game Design endpoint gap for that source only; it is not current `a9d9f27a` whole-service qualification. The separate earlier Game Session gate with 325 cases and 34 endpoint/context failures remains incomplete, and no full public StartSession lifecycle is established. + +The prior `a35e155da930714ded1c8ff93d097d9ce2df00b6` attempt failed compiling the native fixture and receives no native proof credit. On source `aa3aa977a5f3d13cdc33b99636e8bd7a9ff33f87`, `StartSessionLaunchDescriptorProducer` and `AuthoredInitialActorCoreReadService` use one shared `SelectedGameplayRuleSourceJoin` predicate for operation, selected-binding and canonical-byte equality across the frozen Gameplay capture, selected source snapshot and retained Game Logic receipt, implementing the [canonical selected-source contract](../../architecture/microservices/game-design-service/version-control.md#selected-publication-storage-and-retained-operations). The corrected focused retry freshly passed all seven cases in `SelectedDraftGameLogicReceiptPostgresIntegrationTest`, including equal-byte acceptance and same-binding unequal-byte refusal after current owner capture and immutable receipt readback; the operation remained `PENDING`, with controlled Account and Game Logic inputs. Integration Checkstyle, SpotBugs and Spotless checks also passed. This qualifies the shared production predicate at the owner boundary, not a public StartSession lifecycle journey, runtime registration, current upstream authority or closure of a genuine Gameplay handoff. + +This read-stage preparation also carries the strict shared attestation and terminal codecs, read-only World lifecycle support for the [canonical selected-full profile](../../architecture/microservices/game-design-service/version-control.md#selected-full-publication-profile), and a class-only guarded World fixture. The eight prepared code paths comprise the two shared models and their focused proofs, the World lifecycle reader and its unit proof, the guarded native fixture and its class-only build export. These postimages are source-prepared and unqualified; no factory execution or passing fresh writer/readback is claimed. Actual Game Design writer/storage integration and five-store proof remain in the full selected-owner successor. Public fresh/PENDING publication remains default-denied; no registration, activation or genuine creator, issuer, environment, release or continuous-protection authority is granted. All four genuine Gameplay handoffs remain open and broader Unit 1B remains paused. + +At candidate `a9d9f27a4139c2be2cbf9b7c1df4c4a33d6b8bf3`, the follow-on correction proof qualifies 103 focused cases across 11 classes, with zero failures, errors or skips, from fresh scoped executions and verified unchanged final postimages. All 103 cases were not rerun together at this candidate. It covers the selected-template producer and read paths, Template source/reference-phase storage, Game Session authored-core retention, World published-spawn owner read and strict Common mTLS transport. Controller `current-gameplay` update 2155 records the scoped attribution and verification that all four exact run-owned PostgreSQL containers were absent after their runs. This is focused correction evidence, not a fresh whole-service gate or registered packaged-runtime proof. It does not establish genuine upstream authority, production registration, publication, activation or a genuine Gameplay handoff. + +The earlier R21/R22 results below remain historical and scope-specific. R21's focused gate freshly passed all 12 Game Design Template configuration cases with zero skips; the three Game Session authored-core cases retain their R20 pass and also passed in R21's fresh unfiltered native execution. Game Session proves the actual V37/V38 immutable pins, exact original live owner selectors, constructor and repository denials, foreign-key and cascading-truncate refusal, unchanged owner/launch/pin row bytes and versions, live-read expiry and V1013 retention/upgrade. Game Design proved first publication reservation, concurrent winning read correlation, exact replay, association-conflict denial and original Template provenance using a real visible public-production `REALM_ENTRY_POLICY` mutation before its complete World-only successor. Upstream Account and World inputs remain stipulated component evidence; these tests do not establish genuine authority. + +Fresh tenant creation initializes persisted phase to `BACKFILLING`; ordinary synchronized source capture preserves that phase. The existing owner-local full-inventory validator explicitly performs persisted cutover, while a registered cutover owner and tenant-scoped phase RPC remain unimplemented. Empty or incomplete inventory refuses cutover. This internal primitive does not establish production launch enforcement. The explicit cutover, actual V1025 retained v1/v2 history and exact replay, strict command payload, frozen source provenance and typed SQL-read corrections pass in the native suite. + +R21's historical unfiltered gate terminated with failure after freshly executing 159 Game Design native cases with six failures and 325 Game Session native cases with 34 failures, all with zero skips. All 40 failures were PostgreSQL connection refusals at four mapped endpoints, including a Spring application-context failure cascade; the corrected owner cases passed. Game Design cross-service and static checks did not execute in that invocation. R22 independently executed all 25 Game Design cross-service cases with zero failures, errors or skips and passed the previously missing Game Design static checks, formatting and documentation gates. Its only build failure was a nullable generic SQL extraction in the Game Session V1013 foreign-key test helper; a typed read preserves the exact trigger assertions, with its affected static recheck pending. Game Design's 616 units retain R17 attribution, Game Session's 2,389 units and 36 cross-service cases retain R14 attribution, World retains R13's 90 PostgreSQL cases and R12's 589 units and four compositions, and Common's 706 units retain R11 attribution. Documentation checks executed and passed. The remaining Game Session static checks passed apart from that single helper finding; full-native qualification remains held. These R21/R22 results do not supersede the `3ad94e6` whole-source Game Design attribution above or the focused `a9d9f27a` correction proof. + +The bounded R17 PostgreSQL diagnosis observed 60 exact run-owned endpoints. All 124 samples whose containers remained running before and after observation passed internal read-only SQL and host TCP/JDBC through localhost, IPv4 and IPv6. All probe failures overlapped teardown. This does not establish a repair: sparse probes can perturb the forwarding path, and historical failure windows remain unexplained. R21 used no extra endpoint probes. Its passive exact-container evidence recorded Testcontainers' log-ready declaration followed by immediate host refusal and a passing adjacent endpoint, but the containers were removed before PID1, mapping and stop state could be recovered. R22 passively captured all ten exact run-owned PostgreSQL lifecycles with no ownership gaps or observer errors; its passing cross-service run did not reproduce the refusal. The cause remains unknown; no readiness-policy or host-settings change is selected. Failed, stale and skipped results establish no qualification. The guarded World class-only artifact remains compiled and inspected, while its actual factory execution stays with the full-owner successor. Genuine immutable release production, current Account authority, World activation, actor placement and operational delivery remain open; broader Unit 1B stays paused. Canonical authoring and retention behavior remains owned by [Version Control](../../architecture/microservices/game-design-service/version-control.md#selected-publication-storage-and-retained-operations), and explicit cutover behavior by [Game Templates](../../architecture/microservices/game-design-service/game-templates.md#backfill-validation-and-runtime-usage). + ### Original Account-ordered World source caller The prepared caller source connects the original Account claim and held-order adapters to the existing Game Design coordinator/source owners and World original graph application. It preserves the original complete binding, independent owner transactions and application slot, exact APPLIED owner results, synchronized visibility and terminal replay. The Account services delegate to the existing `AccountControlUiActorService.claimOriginalDraft`/`readHeldOriginalDraft` and `DraftAuthorizationFenceRepository`; no replacement authority or new migration is introduced. Pure Game Design input validation occurs before a fresh reservation, while exact retained terminal replay remains available before current validation. The target coordination rules remain owned by [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#design-time-synchronization), with Account’s local authority consequences in [its API contract](../../architecture/microservices/account-service/api-contracts.md#account-owned-hosted-terms-and-creator-party). @@ -274,6 +340,14 @@ Design-time revoke is explicit through `RevokePluginVersion`. Upload verificatio Game Design owns revision history, commits, version state, and publish orchestration; World Management owns authoritative Draft and Published world template rows. The `SaveRevision` contract carries typed `worldDesignMutation` payloads, including `WORLD_GENERATION_SUBTREE`, through the canonical World Management API, but the registered WMS handler currently fails closed before applying them. No complete caller path applies the change through this RPC; the owner-local mutation algorithm remains present but is not reached through registered ingress. The design contract permits only Draft version writes, while the current registered seam rejects all requests pending complete caller/tenant authorization and owner publication proof. Publication freeze and terminal handoff are target-only owner operations; their exact fields and current absent implementation/proof are maintained by the [World Management owner contract](../../architecture/microservices/world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state), rather than repeated in this tracker. +### Legacy gameplay-rule write exclusion + +The legacy revision service rejects `GAMEPLAY_RULE` before any Game, Version or revision repository access and before the optional World client call. Rule authoring retains its existing coordinated source boundary; the guard enables no new authoring route, registration or source authority. + +Both restored refusal vectors reproduce the old source defect with controlled collaborators: an ordinary request is accepted by the mocked revision save, while the variant carrying a World mutation first reads owner mocks and then fails the later World-kind check. Neither old case demonstrates an actual SQL or remote World mutation. The restored donor guard freshly passes all fourteen owning service cases with zero failures, errors or skips, including existing ordinary, command and World-call behavior. Affected Main and Test static analysis, canonical formatting and style checks pass at the same source. + +This is service-level mock proof. It does not establish authenticated creator access, Account hosted-terms/currentness protection, coordinated gameplay-rule production, an immutable release or a genuine Gameplay handoff. The separate source-owner and publication holds remain unchanged. + ### Validation and Proof - Historical `888f` foundation proof: the canonical local Core, Game Design, and documentation gates passed. The published [Source Validation run](https://github.com/benhook1013/FireMUD/actions/runs/38180722581) completed with 316 Game Design tests, including 37 fresh PostgreSQL integration cases with zero skips; the [Rebuilt Runtime run](https://github.com/benhook1013/FireMUD/actions/runs/38180722436) verified credential-based `LOGIN`/`PLAY`/`LOOK` over WebSocket and Telnet. The overall Validation workflow and callbacks completed successfully. Startup-refusal proof was skipped; restart, source-bound fixture execution, and `CHARACTER_CREATE` activation remain unproved. These run links record historical evidence from `888f`. Focused local anchors are [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java) and [PublishAttemptServiceTransactionIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java); workflow tooling is linked at [CI validation](../../../.github/workflows/ci.yml), [runtime image builds](../../../.github/workflows/runtime-images.yml), and [smoke validation](../../../.github/workflows/smoke.yml). diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index 4fb6227b40..43e5a853d9 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status +### Published spawn requirements read preparation + +The prepared, unregistered Entity-only read authenticates its exact same-namespace peer and verifies Game Design’s complete immutable launch binding before opening the independent World snapshot. It returns published generation/spawn requirements only from the exact retained frozen graph and APPLIED selector source, preserving complete family counts, source identities and template references. Missing, unsupported or conflicting bindings fail closed; the production Game Design complete-launch producer remains denied. R13's historical gate freshly passed all 90 then-current World PostgreSQL cases with zero failures, errors or skips. World’s 589 unit cases and four compositions retain R12 attribution, while Common's 706 units retain R11 attribution. The guarded World fixture compiles and exports only its three fixture classes and manifest. That combined receiving gate remained incomplete: all Game Design native cases skipped after Docker discovery failed, and Game Session's corrected disposable reset/guard proof awaited compilation and native qualification. This skipped Game Design outcome is historical and does not describe the later Game Design whole-source gate or current focused correction proof; see [Game Authoring](./game-authoring-publishing-and-activation.md#selected-template-publication-and-original-launch-reads) for their separate source and scope attribution. At candidate `a9d9f27a4139c2be2cbf9b7c1df4c4a33d6b8bf3`, the World published-spawn owner test has 33 passing cases from its fresh scoped execution with unchanged final postimages, within the 103 qualified correction cases across 11 classes; this does not qualify a whole-service gate, fixture factory execution or the actual full-vector owner composition. These component results do not qualify genuine upstream release authority. This read creates no runtime schedule, Entity actor, World location/occupancy row, activation, admission or operational region. All genuine Gameplay handoffs remain open. + ### Evolved historical activation preservation The [historical PostgreSQL fixture](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldV1PreparationHistoryPostgresIntegrationTest.java) now also preserves an original schema-2 preparation and schema-1 association created at V1018, followed by the evolved twelve-field legacy activation format accepted by V1025. The installed historical guard retains the activation receipt and consumes its lifecycle execution manifest through an exact PREPARING → ACTIVE compare-and-set in the same physical transaction. Upgrades through V1037, V1039 and the current default retain every original column, byte field and PostgreSQL `xmin` across twenty selected tables, all prior complete Flyway rows, and the activation guard's function OID and ACL. Current read-only lookup and exact legacy request replay return the original result; a fresh request-only activation is denied. No protected activation fence is created, and direct result-row rewrites are refused. @@ -232,7 +236,7 @@ These links add decision provenance only; they do not upgrade world runtime, lif | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `GR-2.1` World topology, rooms, regions, and runtime instances | `partial`: the authored-world source-retention boundary is implemented through `WorldAuthoredSourceIntakeRepository`, `WorldAuthoredVersionIdentityRepository`, `WorldCompleteLaunchBindingRepository`, and `WorldDesignPublicationFenceRepository`, with migrations `V23.1`–`V27.2`; the guarded graph/capture stage adds `V1003`–`V1007.1`, without establishing that external databases applied them. This retained evidence does not activate a runtime or establish gameplay admission. Its focused source, identity, launch-binding, and publication-fence proof is recorded above and linked below. Version-scoped topology and the owner-local Draft mutation algorithm exist, but registered `ApplyWorldDesignMutation` ingress fails closed before dispatch pending complete caller/tenant authorization and owner publication proof; instance lifecycle exists, while generation still has hardcoded inputs, initial event scheduling is absent, and lifecycle prepare/activate retain blocking attestation calls. The retained initial-admission hold contributes to the `AR-3.1` lifecycle handoff through lifecycle serialization and exact owner-proof reconciliation; current fixture preparation does not acquire it. The retained published bootstrap remains separate from explicit canonical source preparation. The canonical owner materializes the sealed fixed preset at PREPARING epoch 1 and row version 0, but the generic RPC does not dispatch it; current source, SQL and owner proof is qualified above. Its concrete implementation includes [RunOwnedCanonicalWorldLaunchEvidenceProvider.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidenceProvider.java), [RunOwnedCanonicalWorldLaunchEvidence.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidence.java), [WorldAuthoredSourceIntakeService.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeService.java), [WorldAuthoredVersionIdentityService.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityService.java), and [V1042.7](../../../services/world-management-service/src/main/resources/db/migration/V1042.7__world_predecessor_fixture_lifecycle_staging.sql). Canonical activation, holds and first OPEN remain unavailable. Packaged runtime proof is limited to the ordinary default-off baseline with fixture mode disabled; it does not qualify the enabled retained fixture coordinator or canonical admission. Accepted publication and procedural-generation decisions now define World-owned topology, request-bounded replay, atomic visibility, explicit replacement, and sparse/full-grid boundaries; typed ingress, destructive plans, staging bounds, and large-grid proof remain incomplete. | `audited`: World retains lifecycle and initial-admission hold storage and read boundaries. Explicit canonical source preparation verifies the sealed receipt and authenticated Game Session STARTING allocation before owner storage; the generic RPC retains predecessor bootstrap behavior. The current source-first source and owner proof is qualified at the exact scope recorded above; bounded V1042.7 predecessor transition/failure/termination owner guards are qualified at the controlled proof scope recorded above. Canonical activation, holds and first OPEN remain unavailable. | [World Management ownership](../../architecture/microservices/world-management-service/README.md); [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [initial-admission bind hold contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract); [runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [InitialAdmissionBindHoldServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java); [InitialAdmissionBindHoldRepository.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java); [GrpcGameSessionInitialAdmissionBindProofClient.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java); [V18 version-scoped templates](../../../services/world-management-service/src/main/resources/db/migration/V18__version_scoped_world_templates.sql); [V19 mutation ledger](../../../services/world-management-service/src/main/resources/db/migration/V19__world_design_mutation_ledger.sql); [V23 initial-admission hold](../../../services/world-management-service/src/main/resources/db/migration/V23__initial_admission_bind_hold.sql); [V23.1 source intake](../../../services/world-management-service/src/main/resources/db/migration/V23.1__world_authored_source_intake.sql); [V24 tenant mutation guard](../../../services/world-management-service/src/main/resources/db/migration/V24__world_canonical_tenant_mutation_guard.sql); [V25 publication fence](../../../services/world-management-service/src/main/resources/db/migration/V25__world_design_publication_fence.sql); [V26 launch binding](../../../services/world-management-service/src/main/resources/db/migration/V26__world_complete_launch_binding.sql); [V27 version identity](../../../services/world-management-service/src/main/resources/db/migration/V27__world_authored_version_identity.sql); [V27.1 publication owner binding](../../../services/world-management-service/src/main/resources/db/migration/V27.1__world_publication_owner_binding.sql); [V27.2 legacy tenant claim concurrency](../../../services/world-management-service/src/main/resources/db/migration/V27.2__world_legacy_tenant_claim_concurrency.sql); [V1003 authored graph snapshot](../../../services/world-management-service/src/main/resources/db/migration/V1003__world_authored_graph_snapshot.sql); [V1004 guarded region commits](../../../services/world-management-service/src/main/resources/db/migration/V1004__world_guarded_region_draft_commits.sql); [V1005 guarded UUID topology commits](../../../services/world-management-service/src/main/resources/db/migration/V1005__world_guarded_uuid_topology_commits.sql); [V1006 canonical frozen topology](../../../services/world-management-service/src/main/resources/db/migration/V1006__world_canonical_frozen_topology.sql); [V1007 digest schema 3 capture](../../../services/world-management-service/src/main/resources/db/migration/V1007__world_digest_schema3_capture.sql); [V1007.1 legacy update fastpath](../../../services/world-management-service/src/main/resources/db/migration/V1007.1__world_restore_stable_legacy_update_fastpath.sql); [WorldDraftTopologyCommitRepository.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java); [WorldAuthoredGraphSnapshotCapture.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java); [RunOwnedWorldLaunchEvidenceProvider.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java); [RunOwnedWorldLaunchEvidence.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java); [RunOwnedWorldFixedPresetResources.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResources.java); [WorldCanonicalInstanceAssociationRepository.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationRepository.java); [V1040 canonical association](../../../services/world-management-service/src/main/resources/db/migration/V1040__world_run_owned_fixture_canonical_association.sql); [V1041 fixed-preset preparation](../../../services/world-management-service/src/main/resources/db/migration/V1041__world_run_owned_fixed_preset_preparation.sql); [V1042 required-field checks](../../../services/world-management-service/src/main/resources/db/migration/V1042__world_canonical_association_required_field_checks.sql); [V1042.1 terminal schema](../../../services/world-management-service/src/main/resources/db/migration/V1042.1__world_execution_terminal_service_schema.sql); [V1042.2 read transactions](../../../services/world-management-service/src/main/resources/db/migration/V1042.2__world_fixed_preset_read_transaction.sql); [V1042.3 mutation diagnostics](../../../services/world-management-service/src/main/resources/db/migration/V1042.3__world_fixture_row_mutation_diagnostic.sql); [V1042.4 owner-copy checks](../../../services/world-management-service/src/main/resources/db/migration/V1042.4__world_fixture_association_owner_copy_checks.sql); [V1042.5 complete room readback](../../../services/world-management-service/src/main/resources/db/migration/V1042.5__world_fixed_preset_complete_room_readback.sql); [V1042.6 terminal and location ownership](../../../services/world-management-service/src/main/resources/db/migration/V1042.6__world_terminal_binding_and_location_operation_checks.sql); [V1042.7 predecessor lifecycle staging](../../../services/world-management-service/src/main/resources/db/migration/V1042.7__world_predecessor_fixture_lifecycle_staging.sql); [V1042.8 terminal affected-unit validation](../../../services/world-management-service/src/main/resources/db/migration/V1042.8__world_terminal_affected_unit_validation.sql); [V1042.9 guard subtransactions](../../../services/world-management-service/src/main/resources/db/migration/V1042.9__world_same_transaction_guard_subtransactions.sql); [V1042.10 initial-location retention](../../../services/world-management-service/src/main/resources/db/migration/V1042.10__world_initial_location_retention_guards.sql); [V1042.11 preparation transaction stamp](../../../services/world-management-service/src/main/resources/db/migration/V1042.11__world_preparation_full_transaction_stamp.sql); [V1042.12 receipt byte digests](../../../services/world-management-service/src/main/resources/db/migration/V1042.12__world_graph_application_receipt_byte_digests.sql); [V1042.13 start-location semantic receipt digest](../../../services/world-management-service/src/main/resources/db/migration/V1042.13__world_start_location_semantic_receipt_digest.sql); [V23.0.1 fixture binding](../../../services/world-management-service/src/main/resources/db/migration/V23.0.1__world_run_owned_fixture_launch_binding.sql) | [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java); [InitialAdmissionBindHoldServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java); [InitialAdmissionBindHoldRepositoryTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java); [InitialAdmissionBindHoldPostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java); [RunOwnedWorldLaunchEvidenceProviderTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java); [RunOwnedCanonicalWorldLaunchEvidenceProviderTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidenceProviderTest.java); [RunOwnedCanonicalWorldLaunchEvidenceMtlsIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/service/impl/RunOwnedCanonicalWorldLaunchEvidenceMtlsIntegrationTest.java); [WorldCanonicalInstanceExecutionTerminalSchemaPostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionTerminalSchemaPostgresIntegrationTest.java); [WorldTerminalAndLocationOwnerGuardsPostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldTerminalAndLocationOwnerGuardsPostgresIntegrationTest.java); [RunOwnedWorldFixedPresetResourcesTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesTest.java); [RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [RunOwnedFixtureOwnerCompositionCrossServiceTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerCompositionCrossServiceTest.java); [RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java); [RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java); [WorldAuthoredSourceIntakeServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java); [WorldAuthoredVersionIdentityServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityServiceTest.java); [WorldCompleteLaunchBindingServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java); [WorldDesignPublicationFenceCommittedReadTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceCommittedReadTest.java); [WorldAuthoredSourceIntakeIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java); [WorldAuthoredVersionIdentityIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredVersionIdentityIntegrationTest.java); [WorldCompleteLaunchBindingIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldCompleteLaunchBindingIntegrationTest.java); [WorldDesignPublicationFenceIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java); [WorldDesignPublicationFenceEvidenceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidenceTest.java); [WorldPublicationOwnerBindingMigrationIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldPublicationOwnerBindingMigrationIntegrationTest.java); [WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java); [WorldGuardedAuthoredTopologyPlanTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredTopologyPlanTest.java) | [AR-3.1 lifecycle in Game Authoring](./game-authoring-publishing-and-activation.md); [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md) | Bounded fixture PREPARING materialization remains qualified by its controlled native proof; canonical activation, continuous Account protection, hold acquisition and first OPEN remain unavailable. Genuine owner handoffs, hold/termination race and restart recovery, strict Account JOIN and generalized runtime-ID migration remain open. Earlier tests retain their recorded revision attribution; source or fixture read evidence supplies no activation authority. | +| `GR-2.1` World topology, rooms, regions, and runtime instances | `partial`: the authored-world source-retention boundary is implemented through `WorldAuthoredSourceIntakeRepository`, `WorldAuthoredVersionIdentityRepository`, `WorldCompleteLaunchBindingRepository`, and `WorldDesignPublicationFenceRepository`, with migrations `V23.1`–`V27.2`; the guarded graph/capture stage adds `V1003`–`V1007.1`, without establishing that external databases applied them. This retained evidence does not activate a runtime or establish gameplay admission. Its focused source, identity, launch-binding, and publication-fence proof is recorded above and linked below. Version-scoped topology and the owner-local Draft mutation algorithm exist, but registered `ApplyWorldDesignMutation` ingress fails closed before dispatch pending complete caller/tenant authorization and owner publication proof; instance lifecycle exists, while generation still has hardcoded inputs, initial event scheduling is absent, and lifecycle prepare/activate retain blocking attestation calls. The retained initial-admission hold contributes to the `AR-3.1` lifecycle handoff through lifecycle serialization and exact owner-proof reconciliation; current fixture preparation does not acquire it. The retained published bootstrap remains separate from explicit canonical source preparation. The canonical owner materializes the sealed fixed preset at PREPARING epoch 1 and row version 0, but the generic RPC does not dispatch it; current source, SQL and owner proof is qualified above. Its concrete implementation includes [RunOwnedCanonicalWorldLaunchEvidenceProvider.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidenceProvider.java), [RunOwnedCanonicalWorldLaunchEvidence.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidence.java), [WorldAuthoredSourceIntakeService.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeService.java), [WorldAuthoredVersionIdentityService.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityService.java), and [V1042.7](../../../services/world-management-service/src/main/resources/db/migration/V1042.7__world_predecessor_fixture_lifecycle_staging.sql). Canonical activation, holds and first OPEN remain unavailable. Packaged runtime proof is limited to the ordinary default-off baseline with fixture mode disabled; it does not qualify the enabled retained fixture coordinator or canonical admission. Accepted publication and procedural-generation decisions now define World-owned topology, request-bounded replay, atomic visibility, explicit replacement, and sparse/full-grid boundaries; typed ingress, destructive plans, staging bounds, and large-grid proof remain incomplete. Published spawn requirements read for Entity is partial: `WorldPublishedSpawnRequirementsReadOwner` and its gRPC service authenticate the exact same-namespace Entity workload, verify Game Design’s complete immutable launch binding, and read published requirements only from the exact retained frozen graph and APPLIED selector source, preserving complete family counts, source identities and template references. Missing, unsupported or conflicting bindings fail closed. The read creates no runtime schedule, Entity actor, World location/occupancy row, activation, admission or operational region. | `audited`: World retains lifecycle and initial-admission hold storage and read boundaries. Explicit canonical source preparation verifies the sealed receipt and authenticated Game Session STARTING allocation before owner storage; the generic RPC retains predecessor bootstrap behavior. The current source-first source and owner proof is qualified at the exact scope recorded above; bounded V1042.7 predecessor transition/failure/termination owner guards are qualified at the controlled proof scope recorded above. Canonical activation, holds and first OPEN remain unavailable. Published-spawn read proof remains `drift-found`: controlled World owner checks cover the exact peer and retained graph/source read; Common client mTLS checks cover caller identity and transport. This proof does not establish genuine upstream authority. | [World Management ownership](../../architecture/microservices/world-management-service/README.md); [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [initial-admission bind hold contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract); [runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries); [Game Design launch binding](../../architecture/microservices/game-design-service/api-contracts.md#authored-world-launch-binding); [World API implementation status](../../architecture/microservices/world-management-service/api-contracts.md#implementation-status) | [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [InitialAdmissionBindHoldServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java); [InitialAdmissionBindHoldRepository.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java); [GrpcGameSessionInitialAdmissionBindProofClient.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java); [V18 version-scoped templates](../../../services/world-management-service/src/main/resources/db/migration/V18__version_scoped_world_templates.sql); [V19 mutation ledger](../../../services/world-management-service/src/main/resources/db/migration/V19__world_design_mutation_ledger.sql); [V23 initial-admission hold](../../../services/world-management-service/src/main/resources/db/migration/V23__initial_admission_bind_hold.sql); [V23.1 source intake](../../../services/world-management-service/src/main/resources/db/migration/V23.1__world_authored_source_intake.sql); [V24 tenant mutation guard](../../../services/world-management-service/src/main/resources/db/migration/V24__world_canonical_tenant_mutation_guard.sql); [V25 publication fence](../../../services/world-management-service/src/main/resources/db/migration/V25__world_design_publication_fence.sql); [V26 launch binding](../../../services/world-management-service/src/main/resources/db/migration/V26__world_complete_launch_binding.sql); [V27 version identity](../../../services/world-management-service/src/main/resources/db/migration/V27__world_authored_version_identity.sql); [V27.1 publication owner binding](../../../services/world-management-service/src/main/resources/db/migration/V27.1__world_publication_owner_binding.sql); [V27.2 legacy tenant claim concurrency](../../../services/world-management-service/src/main/resources/db/migration/V27.2__world_legacy_tenant_claim_concurrency.sql); [V1003 authored graph snapshot](../../../services/world-management-service/src/main/resources/db/migration/V1003__world_authored_graph_snapshot.sql); [V1004 guarded region commits](../../../services/world-management-service/src/main/resources/db/migration/V1004__world_guarded_region_draft_commits.sql); [V1005 guarded UUID topology commits](../../../services/world-management-service/src/main/resources/db/migration/V1005__world_guarded_uuid_topology_commits.sql); [V1006 canonical frozen topology](../../../services/world-management-service/src/main/resources/db/migration/V1006__world_canonical_frozen_topology.sql); [V1007 digest schema 3 capture](../../../services/world-management-service/src/main/resources/db/migration/V1007__world_digest_schema3_capture.sql); [V1007.1 legacy update fastpath](../../../services/world-management-service/src/main/resources/db/migration/V1007.1__world_restore_stable_legacy_update_fastpath.sql); [WorldDraftTopologyCommitRepository.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java); [WorldAuthoredGraphSnapshotCapture.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java); [RunOwnedWorldLaunchEvidenceProvider.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java); [RunOwnedWorldLaunchEvidence.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java); [RunOwnedWorldFixedPresetResources.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResources.java); [WorldCanonicalInstanceAssociationRepository.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationRepository.java); [V1040 canonical association](../../../services/world-management-service/src/main/resources/db/migration/V1040__world_run_owned_fixture_canonical_association.sql); [V1041 fixed-preset preparation](../../../services/world-management-service/src/main/resources/db/migration/V1041__world_run_owned_fixed_preset_preparation.sql); [V1042 required-field checks](../../../services/world-management-service/src/main/resources/db/migration/V1042__world_canonical_association_required_field_checks.sql); [V1042.1 terminal schema](../../../services/world-management-service/src/main/resources/db/migration/V1042.1__world_execution_terminal_service_schema.sql); [V1042.2 read transactions](../../../services/world-management-service/src/main/resources/db/migration/V1042.2__world_fixed_preset_read_transaction.sql); [V1042.3 mutation diagnostics](../../../services/world-management-service/src/main/resources/db/migration/V1042.3__world_fixture_row_mutation_diagnostic.sql); [V1042.4 owner-copy checks](../../../services/world-management-service/src/main/resources/db/migration/V1042.4__world_fixture_association_owner_copy_checks.sql); [V1042.5 complete room readback](../../../services/world-management-service/src/main/resources/db/migration/V1042.5__world_fixed_preset_complete_room_readback.sql); [V1042.6 terminal and location ownership](../../../services/world-management-service/src/main/resources/db/migration/V1042.6__world_terminal_binding_and_location_operation_checks.sql); [V1042.7 predecessor lifecycle staging](../../../services/world-management-service/src/main/resources/db/migration/V1042.7__world_predecessor_fixture_lifecycle_staging.sql); [V1042.8 terminal affected-unit validation](../../../services/world-management-service/src/main/resources/db/migration/V1042.8__world_terminal_affected_unit_validation.sql); [V1042.9 guard subtransactions](../../../services/world-management-service/src/main/resources/db/migration/V1042.9__world_same_transaction_guard_subtransactions.sql); [V1042.10 initial-location retention](../../../services/world-management-service/src/main/resources/db/migration/V1042.10__world_initial_location_retention_guards.sql); [V1042.11 preparation transaction stamp](../../../services/world-management-service/src/main/resources/db/migration/V1042.11__world_preparation_full_transaction_stamp.sql); [V1042.12 receipt byte digests](../../../services/world-management-service/src/main/resources/db/migration/V1042.12__world_graph_application_receipt_byte_digests.sql); [V1042.13 start-location semantic receipt digest](../../../services/world-management-service/src/main/resources/db/migration/V1042.13__world_start_location_semantic_receipt_digest.sql); [V23.0.1 fixture binding](../../../services/world-management-service/src/main/resources/db/migration/V23.0.1__world_run_owned_fixture_launch_binding.sql); [WorldPublishedSpawnRequirementsReadOwner.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwner.java); [WorldPublishedSpawnRequirementsReadGrpcService.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadGrpcService.java) | [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java); [InitialAdmissionBindHoldServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java); [InitialAdmissionBindHoldRepositoryTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java); [InitialAdmissionBindHoldPostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java); [RunOwnedWorldLaunchEvidenceProviderTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java); [RunOwnedCanonicalWorldLaunchEvidenceProviderTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidenceProviderTest.java); [RunOwnedCanonicalWorldLaunchEvidenceMtlsIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/service/impl/RunOwnedCanonicalWorldLaunchEvidenceMtlsIntegrationTest.java); [WorldCanonicalInstanceExecutionTerminalSchemaPostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionTerminalSchemaPostgresIntegrationTest.java); [WorldTerminalAndLocationOwnerGuardsPostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldTerminalAndLocationOwnerGuardsPostgresIntegrationTest.java); [RunOwnedWorldFixedPresetResourcesTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesTest.java); [RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [RunOwnedFixtureOwnerCompositionCrossServiceTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerCompositionCrossServiceTest.java); [RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java); [RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java); [WorldAuthoredSourceIntakeServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java); [WorldAuthoredVersionIdentityServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityServiceTest.java); [WorldCompleteLaunchBindingServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java); [WorldDesignPublicationFenceCommittedReadTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceCommittedReadTest.java); [WorldAuthoredSourceIntakeIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java); [WorldAuthoredVersionIdentityIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredVersionIdentityIntegrationTest.java); [WorldCompleteLaunchBindingIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldCompleteLaunchBindingIntegrationTest.java); [WorldDesignPublicationFenceIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java); [WorldDesignPublicationFenceEvidenceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidenceTest.java); [WorldPublicationOwnerBindingMigrationIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldPublicationOwnerBindingMigrationIntegrationTest.java); [WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java); [WorldGuardedAuthoredTopologyPlanTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredTopologyPlanTest.java); [WorldPublishedSpawnRequirementsReadOwnerTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwnerTest.java); [WorldPublishedSpawnRequirementsClientMtlsTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClientMtlsTest.java) | [AR-3.1 lifecycle in Game Authoring](./game-authoring-publishing-and-activation.md); [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); the published-spawn read depends on [selected-template publication and original-launch reads](./game-authoring-publishing-and-activation.md) and Game Design launch binding | Bounded fixture PREPARING materialization remains qualified by its controlled native proof; canonical activation, continuous Account protection, hold acquisition and first OPEN remain unavailable. Genuine owner handoffs, hold/termination race and restart recovery, strict Account JOIN and generalized runtime-ID migration remain open. Earlier tests retain their recorded revision attribution; source or fixture read evidence supplies no activation authority. The published-spawn read has no registered transport and the Game Design complete-launch producer remains denied; genuine upstream authority is unavailable. It grants no Entity actor creation, World location or occupancy mutation, activation, admission, or operational-region authority. | | `GR-2.2` Location, occupancy, movement, exits, and spatial reads | `partial` | `audited` | [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [World runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [system architecture](../../architecture/system-architecture-overview.md); [spatial and ambient effects](../../architecture/system-architecture-spatial-and-ambient-effects-catalog.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [WorldManagementGrpcService.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java); [LookAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/LookAggregationService.java); [MoveAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/MoveAggregationService.java); [MoveCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/MoveCommandHandler.java); [room contract](../../../protos/world-management/v1/world_management_service.proto) | [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java); [LookAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/LookAggregationServiceTest.java); [MoveAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/MoveAggregationServiceTest.java); [MoveCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/MoveCommandHandlerTest.java); [movement idempotency test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java) | [authoring](./game-authoring-publishing-and-activation.md); [gameplay](./gameplay-rules-entities-and-effects.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [player experience](./player-experience-commands-and-communication.md) | Partial: directional LOOK and movement primitives exist, but the WMS `ListRoomOccupants` handler and target-only `character_location`/`npc_location` location and occupancy persistence are absent. Live `room_instance` topology and the Game Session room binding are not the World-owned location authority, and the final LOOK identity is not yet the causal floor plus opaque World/Entity component versions; served-through proofs remain separate participant validation evidence. DROP/PICKUP also lack the target World `TargetingFactSnapshot` location/version validation in the Entity-local commit. [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md) remains applied; implementation and proof gaps remain. Accepted full-grid topology decision now defines density-independent movement semantics and opaque scalable representation; large-grid identity, chunk/root finalization, base-plus-delta recovery, and movement-policy proof remain incomplete. | | `GR-2.3` Ambient, environmental, and scheduled world state | `partial` | `audited` | [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [World runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [spatial and ambient effects](../../architecture/system-architecture-spatial-and-ambient-effects-catalog.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md) | [WorldEventServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldEventServiceImpl.java); [WorldManagementGrpcService.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java); [RoomSnapshotDto.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/dto/RoomSnapshotDto.java); [V3 world events](../../../services/world-management-service/src/main/resources/db/migration/V3__world_events.sql); [V16 runtime event scope](../../../services/world-management-service/src/main/resources/db/migration/V16__runtime_world_event_scope.sql) | [WorldEventServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldEventServiceImplTest.java); [RoomSnapshotDtoTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/dto/RoomSnapshotDtoTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java) | [authoring](./game-authoring-publishing-and-activation.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [gameplay](./gameplay-rules-entities-and-effects.md) | Partial: scheduled non-Weather event processing and ambient snapshot shape exist, but `ApplyRoomAmbientStatePatch` has no Java handler, durable effect-idempotency and general ambient patches are absent, and the creation workflow does not schedule initial events. Live `WorldEventService` rejects new `WEATHER_CHANGE` scheduling and leaves retained Weather rows unprocessed; the unresolved selector/fenced effect contract still blocks safe ambient mutation, so current code is not proof of the target World-owned fenced ambient-mutation contract. [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md) remains the target owner; its World-side handler, durable replay guard, and focused proof remain unimplemented. | diff --git a/protos/game-design/v1/authored_initial_actor_core_read.proto b/protos/game-design/v1/authored_initial_actor_core_read.proto new file mode 100644 index 0000000000..961d4ed1fc --- /dev/null +++ b/protos/game-design/v1/authored_initial_actor_core_read.proto @@ -0,0 +1,40 @@ +syntax = "proto3"; + +package game_design.v1; + +import "game-design/v1/start_session_template_association_service.proto"; +import "game-design/v1/game_design_service.proto"; + +option java_package = "net.firedevops.firemud.gamedesign.v1"; +option java_multiple_files = true; + +// Standalone, unregistered read of the minimal authored initial actor core. The +// server authenticates Game Session or Entity before decoding and independently +// rechecks the original Account operation. This read is evidence, not admission. +service GameDesignAuthoredInitialActorCoreReadService { + rpc ReadAuthoredInitialActorCore(ReadAuthoredInitialActorCoreRequest) + returns (ReadAuthoredInitialActorCoreResponse); +} + +message ReadAuthoredInitialActorCoreRequest { + // Exact Game Session-pinned association request in ExactReplay mode. + ReadStartSessionTemplateAssociationRequest association_request = 1; +} + +message ReadAuthoredInitialActorCoreProjection { + // Closed RFC 8785 public projection; private proof bytes are never transported. + bytes canonical_projection_bytes = 1; + string projection_digest = 2; +} + +message ReadAuthoredInitialActorCoreResponse { + int32 schema_version = 1; + ReadStartSessionTemplateAssociationRequest request = 2; + ReadStartSessionTemplateAssociationResponse association_read = 3; + gamedesign.v1.LaunchDescriptor launch_descriptor = 4; + repeated ReadAuthoredInitialActorCoreProjection projections = 5; + // Canonical closed result envelope and its digest bind the exact echo and + // ordered public projection list; they do not authenticate the producer. + bytes canonical_result_bytes = 6; + string result_digest = 7; +} diff --git a/protos/world-management/v1/world_published_spawn_requirements.proto b/protos/world-management/v1/world_published_spawn_requirements.proto new file mode 100644 index 0000000000..382f8c06bc --- /dev/null +++ b/protos/world-management/v1/world_published_spawn_requirements.proto @@ -0,0 +1,67 @@ +syntax = "proto3"; + +package world_management.v1; + +import "game-design/v1/game_design_service.proto"; +import "shared/v1/errors.proto"; +import "world-management/v1/world_management_service.proto"; + +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +// Exact immutable source read for the verified same-namespace Entity workload. +service WorldPublishedSpawnRequirementsReadService { + rpc ReadWorldPublishedSpawnRequirements(ReadWorldPublishedSpawnRequirementsRequest) + returns (ReadWorldPublishedSpawnRequirementsResponse); +} + +message ReadWorldPublishedSpawnRequirementsRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + gamedesign.v1.GetLaunchDescriptorRequest launch_binding_request = 4; + string expected_release_attestation_digest = 5; +} + +message WorldPublishedSpawnRequirementsFamilyCount { + WorldDesignAggregateType family = 1; + optional int32 count = 2; +} + +message WorldPublishedSpawnRequirementsEntityTemplateReference { + EntityTemplateReferenceType kind = 1; + string tenant_id = 2; + string version_id = 3; + string template_id = 4; +} + +message WorldPublishedSpawnRequirement { + string revision_order = 1; + string revision_id = 2; + string spawn_binding_id = 3; + RoomTemplateRef room_template = 4; + WorldPublishedSpawnRequirementsEntityTemplateReference entity_template = 5; + int32 spawn_count = 6; + int32 respawn_delay_seconds = 7; +} + +message WorldPublishedGenerationRequirement { + string revision_order = 1; + string revision_id = 2; + string rule_template_id = 3; + WorldDesignAggregateType scope_family = 4; + string scope_id = 5; + string name = 6; + string value = 7; +} + +message ReadWorldPublishedSpawnRequirementsResponse { + ReadWorldPublishedSpawnRequirementsRequest request = 1; + gamedesign.v1.GetCompleteLaunchBindingResponse complete_launch_binding = 2; + string capture_id = 3; + string graph_digest = 4; + repeated WorldPublishedSpawnRequirementsFamilyCount family_counts = 5; + repeated WorldPublishedSpawnRequirement spawn_requirements = 6; + repeated WorldPublishedGenerationRequirement generation_requirements = 7; + shared.v1.ErrorDetail error = 8; +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java index 880de68061..214a8d78ce 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java @@ -41,7 +41,9 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInfo; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; @@ -58,6 +60,7 @@ class AccountRepositoryIntegrationTest { private static final UUID REALM_ID = UUID.fromString("4c4b57d8-e3a2-48fe-9977-e7df0fdce901"); private static final String MIGRATION_LOCATION = "classpath:db/migration"; + private static final String MIGRATION_PROOF_ONLY_TAG = "migration-proof-only"; private final String SCHEMA_SUFFIX = UUID.randomUUID().toString().replace("-", "").substring(0, 12); private final String TEST_SCHEMA = "account_repository_" + SCHEMA_SUFFIX; @@ -84,17 +87,20 @@ static void startPostgres() { } @BeforeEach - void setUpRepository() { + void setUpRepository(TestInfo testInfo) { dataSource = postgres.dataSource(TEST_SCHEMA); - Flyway.configure() - .dataSource(dataSource) - .schemas(TEST_SCHEMA) - .defaultSchema(TEST_SCHEMA) - .placeholders(Map.of("serviceSchema", TEST_SCHEMA)) - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + // Tagged migration proofs create and migrate their own fresh schemas. + if (!testInfo.getTags().contains(MIGRATION_PROOF_ONLY_TAG)) { + Flyway.configure() + .dataSource(dataSource) + .schemas(TEST_SCHEMA) + .defaultSchema(TEST_SCHEMA) + .placeholders(Map.of("serviceSchema", TEST_SCHEMA)) + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + } dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); repository = new AccountRepository(dsl); @@ -1325,7 +1331,12 @@ void saveRejectsMissingEmailBeforeStorage(String email) { } @Test + @Tag(MIGRATION_PROOF_ONLY_TAG) void flywayCanonicalizesLegacyEmailAndRejectsNonCanonicalValues() { + DriverManagerDataSource dataSource = postgres.dataSource(MIGRATION_PROOF_SCHEMA); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + Flyway.configure() .dataSource(dataSource) .locations(MIGRATION_LOCATION) @@ -1364,11 +1375,17 @@ void flywayCanonicalizesLegacyEmailAndRejectsNonCanonicalValues() { + MIGRATION_PROOF_SCHEMA + ".accounts (username, email, password_hash) " + "VALUES ('noncanonical', ' Another@Example.COM ', 'hash')")) - .isInstanceOf(DataAccessException.class); + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("accounts_email_canonical_check"); } @Test + @Tag(MIGRATION_PROOF_ONLY_TAG) void flywayRejectsCanonicalEmailCollisionsBeforeRewriting() { + DriverManagerDataSource dataSource = postgres.dataSource(COLLISION_MIGRATION_PROOF_SCHEMA); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + Flyway.configure() .dataSource(dataSource) .locations(MIGRATION_LOCATION) @@ -1456,7 +1473,13 @@ void profilesAllowOneGlobalAccountAcrossTenantsButRejectDuplicateTenantIdentity( } @Test + @Tag(MIGRATION_PROOF_ONLY_TAG) void flywayRejectsRetainedDuplicateProfileTenantIdentityBeforeAddingConstraint() { + DriverManagerDataSource dataSource = + postgres.dataSource(PROFILE_IDENTITY_MIGRATION_PROOF_SCHEMA); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + Flyway.configure() .dataSource(dataSource) .locations(MIGRATION_LOCATION) @@ -1517,8 +1540,13 @@ void flywayRejectsRetainedDuplicateProfileTenantIdentityBeforeAddingConstraint() } @Test + @Tag(MIGRATION_PROOF_ONLY_TAG) void globalRegistrationMigrationPreservesAndQuarantinesUnprovenTenantRows() { String schema = GLOBAL_REGISTRATION_MIGRATION_PROOF_SCHEMA; + DriverManagerDataSource dataSource = postgres.dataSource(schema); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + Flyway.configure() .dataSource(dataSource) .locations(MIGRATION_LOCATION) @@ -1617,8 +1645,13 @@ void globalRegistrationMigrationPreservesAndQuarantinesUnprovenTenantRows() { } @Test + @Tag(MIGRATION_PROOF_ONLY_TAG) void accountUuidMigrationPreservesRetainedRowsAndRecordsExactSourceIdentity() { String schema = ACCOUNT_UUID_MIGRATION_PROOF_SCHEMA; + DriverManagerDataSource dataSource = postgres.dataSource(schema); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + Flyway.configure() .dataSource(dataSource) .locations(MIGRATION_LOCATION) diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadClient.java new file mode 100644 index 0000000000..0755a700c9 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadClient.java @@ -0,0 +1,10 @@ +package net.firedevops.firemud.common.gamedesign; + +/** Explicit client for the standalone authenticated Game Design authored-core read. */ +public interface AuthoredInitialActorCoreReadClient extends AutoCloseable { + AuthoredInitialActorCoreReadEvidence.ReadResult read( + AuthoredInitialActorCoreReadEvidence.ReadRequest request); + + @Override + void close() throws Exception; +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadEvidence.java new file mode 100644 index 0000000000..a631903c9f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadEvidence.java @@ -0,0 +1,163 @@ +package net.firedevops.firemud.common.gamedesign; + +import com.google.protobuf.Message; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.json.JsonMapper; + +/** Closed public integrity value for an authenticated authored-core source read. */ +public final class AuthoredInitialActorCoreReadEvidence { + public static final int SCHEMA_VERSION = 1; + public static final int MAX_RESULT_BYTES = 8 * 1024 * 1024; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private AuthoredInitialActorCoreReadEvidence() {} + + /** The input is the exact already-pinned original request, never an initial selector. */ + public record ReadRequest(Request associationRequest) { + public ReadRequest { + Objects.requireNonNull(associationRequest, "associationRequest"); + if (!(associationRequest.selection() instanceof ExactReplay)) { + throw new IllegalArgumentException("Exact pinned association replay is required"); + } + } + } + + /** + * Complete public projection with the exact immutable request and owner evidence. Construction + * validates canonical integrity and cross-correlation only; this value and its digest do not + * authenticate the producer. + */ + public static final class ReadResult { + private final Request request; + private final Result associationRead; + private final AuthoredWorldLaunchDescriptorEvidence descriptor; + private final List projections; + private final byte[] canonicalBytes; + private final String digest; + + public ReadResult( + Request request, + Result associationRead, + AuthoredWorldLaunchDescriptorEvidence descriptor, + List projections) { + this.request = Objects.requireNonNull(request, "request"); + this.associationRead = Objects.requireNonNull(associationRead, "associationRead"); + this.descriptor = Objects.requireNonNull(descriptor, "descriptor"); + this.projections = List.copyOf(Objects.requireNonNull(projections, "projections")); + requirePublicCorrelation(); + canonicalBytes = encodeCanonical(); + if (canonicalBytes.length == 0 || canonicalBytes.length > MAX_RESULT_BYTES) { + throw new IllegalArgumentException("Authored-core read result exceeds its closed bound"); + } + digest = sha256(canonicalBytes); + } + + public Request request() { + return request; + } + + public Result associationRead() { + return associationRead; + } + + public AuthoredWorldLaunchDescriptorEvidence descriptor() { + return descriptor; + } + + public List projections() { + return projections; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String digest() { + return digest; + } + + private void requirePublicCorrelation() { + if (!request.equals(associationRead.request()) + || !(request.selection() instanceof ExactReplay replay) + || !replay.canonicalVersionId().equals(associationRead.association().canonicalVersionId()) + || !replay.selectedCommitId().equals(associationRead.association().selectedCommitId()) + || !replay.publishWorkflowId().equals(associationRead.association().publishWorkflowId()) + || !replay + .associationDigest() + .equals(associationRead.association().associationDigest())) { + throw new IllegalArgumentException( + "Association result differs from exact core-read request"); + } + StartSessionLaunchDescriptorGrpcCodec.toDescriptorResponse( + request, associationRead, descriptor); + Set bindingIds = new java.util.HashSet<>(); + var association = associationRead.association(); + for (AuthoredInitialActorCoreProjection projection : projections) { + Objects.requireNonNull(projection, "projection"); + if (!bindingIds.add(projection.bindingId()) + || !projection.worldSourceOperationId().equals(association.sourceOperationId()) + || !projection.worldSourceEvidenceDigest().equals(association.sourceEvidenceDigest()) + || !projection.worldSlug().equals(association.worldSlug()) + || !projection.publicationWorkflowId().equals(association.publishWorkflowId()) + || !projection.canonicalTenantId().equals(association.canonicalTenantId()) + || !projection.canonicalVersionId().equals(association.canonicalVersionId()) + || !projection.selectedCommitId().equals(association.selectedCommitId())) { + throw new IllegalArgumentException( + "Projection differs from exact association or descriptor"); + } + } + } + + private byte[] encodeCanonical() { + Map value = new LinkedHashMap<>(); + value.put("schema", "game-design-authored-initial-actor-core-read/v1"); + value.put("request", base64(StartSessionTemplateAssociationReadGrpcCodec.toRequest(request))); + value.put( + "associationRead", + base64(StartSessionTemplateAssociationReadGrpcCodec.toResponse(associationRead))); + value.put( + "launchDescriptor", + base64(AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(descriptor))); + List> ordered = new ArrayList<>(projections.size()); + for (AuthoredInitialActorCoreProjection projection : projections) { + Map item = new LinkedHashMap<>(); + item.put( + "canonicalProjection", Base64.getEncoder().encodeToString(projection.canonicalBytes())); + item.put("digest", projection.digest()); + ordered.add(item); + } + value.put("projections", ordered); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (Exception invalid) { + throw new IllegalArgumentException("Cannot encode canonical authored-core result", invalid); + } + } + + private static String base64(Message message) { + return Base64.getEncoder().encodeToString(message.toByteArray()); + } + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadGrpcCodec.java new file mode 100644 index 0000000000..0c439f8c8f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadGrpcCodec.java @@ -0,0 +1,141 @@ +package net.firedevops.firemud.common.gamedesign; + +import com.google.protobuf.Descriptors; +import com.google.protobuf.Message; +import java.security.MessageDigest; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence.ReadRequest; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence.ReadResult; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.gamedesign.v1.ReadAuthoredInitialActorCoreProjection; +import net.firedevops.firemud.gamedesign.v1.ReadAuthoredInitialActorCoreRequest; +import net.firedevops.firemud.gamedesign.v1.ReadAuthoredInitialActorCoreResponse; +import net.firedevops.firemud.gamedesign.v1.ResolveStartSessionLaunchDescriptorResponse; + +/** Closed mapping for the authenticated, ordered authored initial actor-core projection. */ +public final class AuthoredInitialActorCoreReadGrpcCodec { + public static final int MAX_RESPONSE_WIRE_BYTES = 16 * 1024 * 1024; + + private AuthoredInitialActorCoreReadGrpcCodec() {} + + public static ReadAuthoredInitialActorCoreRequest toRequest(ReadRequest request) { + Objects.requireNonNull(request, "request"); + return ReadAuthoredInitialActorCoreRequest.newBuilder() + .setAssociationRequest( + StartSessionTemplateAssociationReadGrpcCodec.toRequest(request.associationRequest())) + .build(); + } + + public static ReadRequest fromRequest(ReadAuthoredInitialActorCoreRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "ReadAuthoredInitialActorCoreRequest"); + if (!request.hasAssociationRequest()) { + throw new IllegalArgumentException("Exact association replay request is required"); + } + return new ReadRequest( + StartSessionTemplateAssociationReadGrpcCodec.fromRequest(request.getAssociationRequest())); + } + + public static ReadAuthoredInitialActorCoreResponse toResponse(ReadResult result) { + Objects.requireNonNull(result, "result"); + ReadAuthoredInitialActorCoreRequest request = toRequest(new ReadRequest(result.request())); + var associationRead = + StartSessionTemplateAssociationReadGrpcCodec.toResponse(result.associationRead()); + var descriptor = + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(result.descriptor()); + var builder = + ReadAuthoredInitialActorCoreResponse.newBuilder() + .setSchemaVersion(AuthoredInitialActorCoreReadEvidence.SCHEMA_VERSION) + .setRequest(request.getAssociationRequest()) + .setAssociationRead(associationRead) + .setLaunchDescriptor(descriptor) + .setCanonicalResultBytes( + com.google.protobuf.ByteString.copyFrom(result.canonicalBytes())) + .setResultDigest(result.digest()); + for (AuthoredInitialActorCoreProjection projection : result.projections()) { + builder.addProjections( + ReadAuthoredInitialActorCoreProjection.newBuilder() + .setCanonicalProjectionBytes( + com.google.protobuf.ByteString.copyFrom(projection.canonicalBytes())) + .setProjectionDigest(projection.digest())); + } + ReadAuthoredInitialActorCoreResponse response = builder.build(); + if (response.getSerializedSize() > MAX_RESPONSE_WIRE_BYTES) { + throw new IllegalArgumentException("Authored-core response exceeds its bounded wire size"); + } + fromResponse(result.request(), response); + return response; + } + + public static ReadResult fromResponse( + Request expectedRequest, ReadAuthoredInitialActorCoreResponse response) { + Objects.requireNonNull(expectedRequest, "expectedRequest"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ReadAuthoredInitialActorCoreResponse"); + if (response.getSerializedSize() > MAX_RESPONSE_WIRE_BYTES + || response.getSchemaVersion() != AuthoredInitialActorCoreReadEvidence.SCHEMA_VERSION + || !response.hasRequest() + || !response.hasAssociationRead() + || !response.hasLaunchDescriptor() + || response.getCanonicalResultBytes().isEmpty()) { + throw new IllegalArgumentException("Complete bounded authored-core read response required"); + } + Request echoed = + StartSessionTemplateAssociationReadGrpcCodec.fromRequest(response.getRequest()); + if (!expectedRequest.equals(echoed)) { + throw new IllegalArgumentException("Authored-core read changed the exact request echo"); + } + var associationRead = + StartSessionTemplateAssociationReadGrpcCodec.fromResponse( + expectedRequest, response.getAssociationRead()); + var descriptorEnvelope = + ResolveStartSessionLaunchDescriptorResponse.newBuilder() + .setSchemaVersion(StartSessionLaunchDescriptorGrpcCodec.RESPONSE_SCHEMA_VERSION) + .setAssociationRead(response.getAssociationRead()) + .setLaunchDescriptor(response.getLaunchDescriptor()) + .build(); + var resolved = + StartSessionLaunchDescriptorGrpcCodec.fromResponse(expectedRequest, descriptorEnvelope); + if (!(resolved.outcome() + instanceof StartSessionLaunchDescriptorGrpcCodec.DescriptorOutcome descriptorOutcome)) { + throw new IllegalArgumentException( + "Authored-core read requires a complete launch descriptor outcome"); + } + var descriptor = descriptorOutcome.descriptor(); + List projections = + response.getProjectionsList().stream() + .map( + projection -> + AuthoredInitialActorCoreProjection.fromStored( + projection.getCanonicalProjectionBytes().toByteArray(), + projection.getProjectionDigest())) + .toList(); + ReadResult result = new ReadResult(expectedRequest, associationRead, descriptor, projections); + byte[] canonical = response.getCanonicalResultBytes().toByteArray(); + if (canonical.length > AuthoredInitialActorCoreReadEvidence.MAX_RESULT_BYTES + || !MessageDigest.isEqual(canonical, result.canonicalBytes()) + || !result.digest().equals(response.getResultDigest())) { + throw new IllegalArgumentException( + "Authored-core result digest or canonical complete content differs"); + } + return result; + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + for (Map.Entry field : message.getAllFields().entrySet()) { + if (field.getKey().getJavaType() != Descriptors.FieldDescriptor.JavaType.MESSAGE) continue; + if (field.getKey().isRepeated()) { + for (Object nested : (List) field.getValue()) { + requireNoUnknownFields((Message) nested, label + "." + field.getKey().getName()); + } + } else { + requireNoUnknownFields((Message) field.getValue(), label + "." + field.getKey().getName()); + } + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java index d87b9417d5..f3295b4faa 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java @@ -50,11 +50,14 @@ public record AuthoredWorldReleaseAttestationEvidence( public static final int SCHEMA_VERSION = 1; public static final int SELECTOR_SCHEMA_VERSION = 2; public static final int CLOSURE_SELECTOR_SCHEMA_VERSION = 3; + public static final int SELECTED_FULL_SCHEMA_VERSION = 4; private static final String EVIDENCE_DOMAIN = "game-design-authored-world-release-attestation/v1"; private static final String SELECTOR_EVIDENCE_DOMAIN = "game-design-authored-world-release-attestation/v2"; private static final String CLOSURE_SELECTOR_EVIDENCE_DOMAIN = "game-design-authored-world-release-attestation/v3"; + private static final String SELECTED_FULL_EVIDENCE_DOMAIN = + "game-design-authored-world-release-attestation/v4"; private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); private static final Pattern PARTICIPANT_CONTENT_DIGEST = Pattern.compile("[0-9a-f]{64}"); private static final Pattern CANONICAL_POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*"); @@ -93,12 +96,16 @@ public static int supportedParticipantDigestSchema(String participantKey) { return supportedParticipantDigestSchema(participantKey, SCHEMA_VERSION); } - /** Selects owner schemas from the retained-v1, selected-v2, or closure-selected-v3 contract. */ + /** + * Selects owner schemas from the retained-v1, selected-v2, closure-selected-v3, or full-v4 + * contract. + */ public static int supportedParticipantDigestSchema( String participantKey, int attestationSchemaVersion) { if (attestationSchemaVersion != SCHEMA_VERSION && attestationSchemaVersion != SELECTOR_SCHEMA_VERSION - && attestationSchemaVersion != CLOSURE_SELECTOR_SCHEMA_VERSION) { + && attestationSchemaVersion != CLOSURE_SELECTOR_SCHEMA_VERSION + && attestationSchemaVersion != SELECTED_FULL_SCHEMA_VERSION) { throw new IllegalArgumentException("Unsupported authored-world release-attestation schema"); } Objects.requireNonNull(participantKey, "participantKey"); @@ -110,6 +117,16 @@ public static int supportedParticipantDigestSchema( && "WORLD_MANAGEMENT".equals(participantKey)) { return 4; } + if (attestationSchemaVersion == SELECTED_FULL_SCHEMA_VERSION) { + return switch (participantKey) { + case "WORLD_MANAGEMENT" -> 4; + case "ENTITY_MANAGEMENT" -> 3; + case "GAME_LOGIC" -> 1; + case "AUTOMATION_SCRIPTING" -> 6; + case "GAME_DESIGN_CONTROL_PLANE" -> 2; + default -> throw new IllegalArgumentException("Unsupported full-Version participant owner"); + }; + } return (attestationSchemaVersion == SELECTOR_SCHEMA_VERSION || attestationSchemaVersion == CLOSURE_SELECTOR_SCHEMA_VERSION) && "GAME_DESIGN_CONTROL_PLANE".equals(participantKey) @@ -119,7 +136,8 @@ public static int supportedParticipantDigestSchema( public static boolean requiresWorldStartLocationEvidence(int attestationSchemaVersion) { return attestationSchemaVersion == SELECTOR_SCHEMA_VERSION - || attestationSchemaVersion == CLOSURE_SELECTOR_SCHEMA_VERSION; + || attestationSchemaVersion == CLOSURE_SELECTOR_SCHEMA_VERSION + || attestationSchemaVersion == SELECTED_FULL_SCHEMA_VERSION; } /** One successful, immutable owner digest included in the release attestation. */ @@ -177,7 +195,8 @@ public record Artifact( public AuthoredWorldReleaseAttestationEvidence { if (schemaVersion != SCHEMA_VERSION && schemaVersion != SELECTOR_SCHEMA_VERSION - && schemaVersion != CLOSURE_SELECTOR_SCHEMA_VERSION) { + && schemaVersion != CLOSURE_SELECTOR_SCHEMA_VERSION + && schemaVersion != SELECTED_FULL_SCHEMA_VERSION) { throw new IllegalArgumentException("Unsupported authored-world release-attestation schema"); } Objects.requireNonNull(targetNamespace, "targetNamespace"); @@ -375,6 +394,52 @@ public static AuthoredWorldReleaseAttestationEvidence createClosureSelector( worldStartLocationEvidence); } + /** Creates v4 from the exact selector and complete selected-full participant vector. */ + public static AuthoredWorldReleaseAttestationEvidence createSelectedFull( + String targetNamespace, + String descriptorResultDigest, + UUID canonicalTenantId, + UUID canonicalVersionId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + String launchDescriptorId, + String publishedReleaseBundleRef, + long versionStateEpoch, + String publishWorkflowId, + String commitId, + List participantDigests, + String manifestHash, + int manifestSchemaVersion, + List requiredManifestAssetKeys, + List artifactDigests, + List commandDefinitions, + String generationConfigRevision, + WorldPublishedStartLocationEvidence worldStartLocationEvidence) { + return createSelected( + SELECTED_FULL_SCHEMA_VERSION, + targetNamespace, + descriptorResultDigest, + canonicalTenantId, + canonicalVersionId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + launchDescriptorId, + publishedReleaseBundleRef, + versionStateEpoch, + publishWorkflowId, + commitId, + participantDigests, + manifestHash, + manifestSchemaVersion, + requiredManifestAssetKeys, + artifactDigests, + commandDefinitions, + generationConfigRevision, + worldStartLocationEvidence); + } + private static AuthoredWorldReleaseAttestationEvidence createSelected( int schemaVersion, String targetNamespace, @@ -652,6 +717,7 @@ public static byte[] evidencePreimage(AuthoredWorldReleaseAttestationEvidence ev case SCHEMA_VERSION -> EVIDENCE_DOMAIN; case SELECTOR_SCHEMA_VERSION -> SELECTOR_EVIDENCE_DOMAIN; case CLOSURE_SELECTOR_SCHEMA_VERSION -> CLOSURE_SELECTOR_EVIDENCE_DOMAIN; + case SELECTED_FULL_SCHEMA_VERSION -> SELECTED_FULL_EVIDENCE_DOMAIN; default -> throw new IllegalArgumentException("Unsupported release-attestation schema"); }; return preimage(domain, fields.toArray(Field[]::new)); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java index a0e29e8e4f..dc088b1a07 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java @@ -83,12 +83,14 @@ public record ReleaseContent( switch (attestationSchemaVersion) { case "v2" -> AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION; case "v3" -> AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION; + case "v4" -> AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION; default -> throw new IllegalArgumentException( - "Complete full-Version bundle/v2 or bundle/v3 required"); + "Complete full-Version bundle/v2, bundle/v3, or bundle/v4 required"); }; if (versionNumber <= 0 || manifestSchemaVersion != 1) { - throw new IllegalArgumentException("Complete full-Version bundle/v2 or bundle/v3 required"); + throw new IllegalArgumentException( + "Complete full-Version bundle/v2, bundle/v3, or bundle/v4 required"); } digest(manifestHash); artifactDigests = List.copyOf(artifactDigests); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GrpcAuthoredInitialActorCoreReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GrpcAuthoredInitialActorCoreReadClient.java new file mode 100644 index 0000000000..b794502898 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GrpcAuthoredInitialActorCoreReadClient.java @@ -0,0 +1,123 @@ +package net.firedevops.firemud.common.gamedesign; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +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.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.gamedesign.v1.GameDesignAuthoredInitialActorCoreReadServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** File-backed mTLS client pinned to the same-namespace Game Design workload. */ +public final class GrpcAuthoredInitialActorCoreReadClient + extends AbstractReloadingBlockingGrpcClient< + GameDesignAuthoredInitialActorCoreReadServiceGrpc + .GameDesignAuthoredInitialActorCoreReadServiceBlockingStub> + implements AuthoredInitialActorCoreReadClient { + private static final long CALL_DEADLINE_SECONDS = 5L; + private final String workloadNamespace; + + public GrpcAuthoredInitialActorCoreReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GrpcAuthoredInitialActorCoreReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + public void init() throws SSLException, IOException { + initOnce("Authored-core read client is closed", "Authored-core read client has no stub"); + } + + @Override + public AuthoredInitialActorCoreReadEvidence.ReadResult read( + AuthoredInitialActorCoreReadEvidence.ReadRequest request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("Authored-core read requires no ambient transaction"); + } + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.associationRequest().targetNamespace())) { + throw new IllegalArgumentException( + "Authored-core read namespace differs from client identity"); + } + var response = + requireInitializedStub("Authored-core read client is not initialized") + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readAuthoredInitialActorCore(AuthoredInitialActorCoreReadGrpcCodec.toRequest(request)); + try { + return AuthoredInitialActorCoreReadGrpcCodec.fromResponse( + request.associationRequest(), response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Game Design returned invalid authored-core evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameDesignService(); + } + + @Override + protected String defaultTarget() { + return "game-design-service:6565"; + } + + @Override + protected GameDesignAuthoredInitialActorCoreReadServiceGrpc + .GameDesignAuthoredInitialActorCoreReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expected = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service"; + return GameDesignAuthoredInitialActorCoreReadServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(AuthoredInitialActorCoreReadGrpcCodec.MAX_RESPONSE_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expected)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expected)) + .withCompression("gzip"); + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties properties) { + if (properties == null || properties.isPlaintext()) { + throw new IllegalArgumentException("Authored-core reads require workload mTLS"); + } + requireReadableFile(properties.getCertChain(), "certificate chain"); + requireReadableFile(properties.getPrivateKey(), "private key"); + requireReadableFile(properties.getCaCert(), "CA certificate"); + return properties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null + || configuredPath.isBlank() + || configuredPath.startsWith("classpath:")) { + throw new IllegalArgumentException("Authored-core reads require file-backed TLS material"); + } + Path path; + try { + path = Path.of(configuredPath.trim()); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException("Invalid file-backed " + label, invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException("Authored-core " + label + " must be a readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/TemplateConfigSourceSnapshot.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/TemplateConfigSourceSnapshot.java new file mode 100644 index 0000000000..0f8cd847cb --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/TemplateConfigSourceSnapshot.java @@ -0,0 +1,183 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; + +/** Actual template wiring history only; no Game Logic receipt or total-release completeness. */ +public record TemplateConfigSourceSnapshot( + DraftCommitBinding binding, + String sourceEpoch, + UUID inheritedCommitId, + UUID genesisReceiptId, + List entries, + List ownerSourceInventoryDeclarations) { + public static final String SCHEMA = "game-design-template-config-source-snapshot/v1"; + public static final String SCHEMA_V2 = "game-design-template-config-source-snapshot/v2"; + + public TemplateConfigSourceSnapshot( + DraftCommitBinding binding, + String sourceEpoch, + UUID inheritedCommitId, + UUID genesisReceiptId, + List entries) { + this(binding, sourceEpoch, inheritedCommitId, genesisReceiptId, entries, List.of()); + } + + public TemplateConfigSourceSnapshot { + Objects.requireNonNull(binding); + if (sourceEpoch == null || !sourceEpoch.matches("0|[1-9][0-9]*")) + throw new IllegalArgumentException("Exact template source epoch required"); + DraftAuthorizationFenceBinding.requireUuid(genesisReceiptId); + if (inheritedCommitId != null) DraftAuthorizationFenceBinding.requireUuid(inheritedCommitId); + entries = List.copyOf(entries); + var keys = new java.util.HashSet(); + for (var entry : entries) + if (!entry.sourceBinding().target().equals(binding.target()) || !keys.add(entry.templateId())) + throw new IllegalArgumentException("Template source target or identity conflict"); + if (!entries.equals( + entries.stream() + .sorted(java.util.Comparator.comparing(e -> new BigInteger(e.templateId()))) + .toList())) throw new IllegalArgumentException("Canonical template row order required"); + ownerSourceInventoryDeclarations = List.copyOf(ownerSourceInventoryDeclarations); + var owners = + new java.util.HashSet(); + for (var declaration : ownerSourceInventoryDeclarations) { + if (!declaration.sourceBinding().target().equals(binding.target()) + || !owners.add(declaration.owner())) + throw new IllegalArgumentException("Template owner inventory target or identity conflict"); + } + if (!ownerSourceInventoryDeclarations.equals( + ownerSourceInventoryDeclarations.stream() + .sorted(java.util.Comparator.comparing(value -> value.owner().name())) + .toList())) + throw new IllegalArgumentException("Canonical owner inventory order required"); + } + + public String canonicalJson() { + Map value = + new java.util.LinkedHashMap<>( + Map.of( + "schema", + ownerSourceInventoryDeclarations.isEmpty() ? SCHEMA : SCHEMA_V2, + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + sourceEpoch, + "inheritedCommitId", + inheritedCommitId == null ? "" : inheritedCommitId.toString(), + "genesisReceiptId", + genesisReceiptId.toString(), + "entries", + entries.stream().map(TemplateConfigSourceValues.Entry::object).toList())); + if (!ownerSourceInventoryDeclarations.isEmpty()) + value.put( + "ownerSourceInventoryDeclarations", + ownerSourceInventoryDeclarations.stream() + .map(TemplateConfigOwnerSourceInventoryDeclaration::object) + .toList()); + return TemplateConfigSourceJson.canonical(value); + } + + public byte[] canonicalBytes() { + return canonicalJson().getBytes(StandardCharsets.UTF_8); + } + + public String digest() { + return TemplateConfigSourceJson.sha256(canonicalBytes()); + } + + public static TemplateConfigSourceSnapshot fromStored(String json) { + var root = TemplateConfigSourceJson.tree(json); + String schema = TemplateConfigSourceJson.requiredStoredText(root, "schema"); + if (SCHEMA.equals(schema)) { + TemplateConfigSourceJson.requireStoredFields( + root, + "schema", + "bindingJson", + "bindingDigest", + "sourceEpoch", + "inheritedCommitId", + "genesisReceiptId", + "entries"); + } else if (SCHEMA_V2.equals(schema)) { + TemplateConfigSourceJson.requireStoredFields( + root, + "schema", + "bindingJson", + "bindingDigest", + "sourceEpoch", + "inheritedCommitId", + "genesisReceiptId", + "entries", + "ownerSourceInventoryDeclarations"); + } else { + throw new IllegalArgumentException("Unsupported template config source snapshot"); + } + if (!root.path("entries").isArray() + || (SCHEMA_V2.equals(schema) && !root.path("ownerSourceInventoryDeclarations").isArray())) + throw new IllegalArgumentException( + "Template config source snapshot collections are required"); + var binding = + DraftCommitBinding.fromStored( + TemplateConfigSourceJson.requiredStoredText(root, "bindingJson"), + TemplateConfigSourceJson.requiredStoredText(root, "bindingDigest")); + List entries = new ArrayList<>(); + for (var node : root.path("entries")) { + TemplateConfigSourceJson.requireStoredFields( + node, + "templateId", + "configJson", + "sourceBindingJson", + "sourceBindingDigest", + "revisionOrder", + "revisionId", + "createdName"); + if (!node.path("createdName").isTextual()) + throw new IllegalArgumentException("Explicit source operation identity required"); + String name = node.path("createdName").textValue(); + entries.add( + new TemplateConfigSourceValues.Entry( + TemplateConfigSourceJson.requiredStoredText(node, "templateId"), + new TemplateConfigSourceValues.Config( + TemplateConfigSourceJson.requiredStoredText(node, "configJson")), + DraftCommitBinding.fromStored( + TemplateConfigSourceJson.requiredStoredText(node, "sourceBindingJson"), + TemplateConfigSourceJson.requiredStoredText(node, "sourceBindingDigest")), + TemplateConfigSourceJson.requiredStoredText(node, "revisionOrder"), + TemplateConfigSourceValues.uuid( + TemplateConfigSourceJson.requiredStoredText(node, "revisionId")), + name.isEmpty() ? null : name)); + } + List declarations = new ArrayList<>(); + if (SCHEMA_V2.equals(schema)) + for (var node : root.path("ownerSourceInventoryDeclarations")) + declarations.add(TemplateConfigOwnerSourceInventoryDeclaration.fromStored(node)); + if (!root.path("inheritedCommitId").isTextual()) + throw new IllegalArgumentException("Explicit predecessor required"); + String inherited = root.path("inheritedCommitId").textValue(); + var result = + new TemplateConfigSourceSnapshot( + binding, + TemplateConfigSourceJson.requiredStoredText(root, "sourceEpoch"), + inherited.isEmpty() ? null : TemplateConfigSourceValues.uuid(inherited), + TemplateConfigSourceValues.uuid( + TemplateConfigSourceJson.requiredStoredText(root, "genesisReceiptId")), + entries, + declarations); + if ((SCHEMA.equals(schema) && !result.ownerSourceInventoryDeclarations().isEmpty()) + || (SCHEMA_V2.equals(schema) && result.ownerSourceInventoryDeclarations().isEmpty())) + throw new IllegalArgumentException("Template config source snapshot schema mismatch"); + if (!json.equals(result.canonicalJson())) + throw new IllegalArgumentException("Noncanonical template config snapshot"); + return result; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClient.java new file mode 100644 index 0000000000..036d84a1ba --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClient.java @@ -0,0 +1,156 @@ +package net.firedevops.firemud.common.world; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +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.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedSpawnRequirementsReadServiceGrpc; + +/** + * Explicit file-backed mTLS client for immutable World published spawn-requirement source reads. + */ +public final class WorldPublishedSpawnRequirementsClient + extends AbstractReloadingBlockingGrpcClient< + WorldPublishedSpawnRequirementsReadServiceGrpc + .WorldPublishedSpawnRequirementsReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + private static final String ENTITY_SERVICE = "entity-management-service"; + private static final String WORLD_SERVICE = "world-management-service"; + + private final String workloadNamespace; + + public WorldPublishedSpawnRequirementsClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireEntityMtls(tlsProperties, workloadNamespace), + channelFactory, + WorldPublishedSpawnRequirementsClient.class); + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when the owning Entity service explicitly starts this opt-in client. */ + public void init() throws SSLException, IOException { + initOnce( + "World spawn-requirements client is closed", + "World spawn-requirements client has no gRPC stub"); + } + + /** Reads and validates the complete immutable source evidence for one exact selector. */ + public WorldPublishedSpawnRequirementsEvidence read( + WorldPublishedSpawnRequirementsEvidence.Request request) { + requireNoAmbientSql("World spawn-requirements transport must run outside SQL"); + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "World spawn-requirements request must use the configured workload namespace"); + } + var response = + requireInitializedStub("World spawn-requirements client is not initialized and available") + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readWorldPublishedSpawnRequirements( + WorldPublishedSpawnRequirementsGrpcCodec.toRequest(request)); + try { + return WorldPublishedSpawnRequirementsGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "World returned invalid published spawn-requirements evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected WorldPublishedSpawnRequirementsReadServiceGrpc + .WorldPublishedSpawnRequirementsReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/" + WORLD_SERVICE; + return WorldPublishedSpawnRequirementsReadServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(WorldPublishedSpawnRequirementsGrpcCodec.MAX_RESPONSE_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + private static CommonGrpcClientProperties requireEntityMtls( + CommonGrpcClientProperties tlsProperties, String workloadNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("World spawn-requirements reads require workload mTLS"); + } + Path certificatePath = requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + requireExactEntityCertificate(certificatePath, workloadNamespace); + return tlsProperties; + } + + private static Path requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "World spawn-requirements reads require file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "World spawn-requirements reads require file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "World spawn-requirements " + label + " must be a readable file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "World spawn-requirements " + label + " must be an existing readable file"); + } + return path; + } + + private static void requireExactEntityCertificate(Path certificatePath, String namespace) { + try (InputStream input = Files.newInputStream(certificatePath)) { + X509Certificate certificate = + (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + String expectedUri = "spiffe://firemud/ns/" + namespace + "/sa/" + ENTITY_SERVICE; + if (GrpcPeerIdentity.fromCertificate(certificate) + .filter(identity -> identity.uri().equals(expectedUri)) + .isEmpty()) { + throw new IllegalArgumentException( + "World spawn-requirements client certificate must be the exact same-namespace Entity workload identity"); + } + } catch (IOException | CertificateException invalid) { + throw new IllegalArgumentException( + "World spawn-requirements client certificate must contain an exact Entity workload identity", + invalid); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsEvidence.java new file mode 100644 index 0000000000..ca96738448 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsEvidence.java @@ -0,0 +1,342 @@ +package net.firedevops.firemud.common.world; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.math.BigInteger; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; + +/** Exact immutable published spawn and generation inputs retained from one World source read. */ +public record WorldPublishedSpawnRequirementsEvidence( + Request request, + CompleteLaunchBindingEvidence launchBinding, + UUID captureId, + String graphDigest, + List familyCounts, + List spawnRequirements, + List generationRequirements) { + public static final int SCHEMA_VERSION = 1; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern CANONICAL_DECIMAL = Pattern.compile("0|[1-9][0-9]*"); + private static final List FAMILY_ORDER = + List.of( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING); + + /** Exact source-read selector. The nested Game Design request remains unchanged. */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Generated protobuf request messages are immutable value messages.") + public record Request( + String targetNamespace, + UUID readRequestId, + GetLaunchDescriptorRequest launchBindingRequest, + String expectedReleaseAttestationDigest) { + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Generated protobuf request messages are immutable value messages.") + public Request { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be a canonical DNS label"); + } + requireNonNil(readRequestId, "readRequestId"); + Objects.requireNonNull(launchBindingRequest, "launchBindingRequest"); + requireNoUnknownFields(launchBindingRequest, "launch binding request"); + UUID nestedReadRequestId = + parseCanonicalUuid(launchBindingRequest.getRequestId(), "launch binding request ID"); + if (!readRequestId.equals(nestedReadRequestId)) { + throw new IllegalArgumentException( + "Launch binding request ID must equal the published spawn read request ID"); + } + if (readRequestId.toString().equals(launchBindingRequest.getControlPlaneRequestId())) { + throw new IllegalArgumentException( + "Published spawn read request ID must be distinct from the original control-plane request"); + } + parseCanonicalUuid(launchBindingRequest.getCanonicalTenantId(), "canonical tenant ID"); + requireText(launchBindingRequest.getWorldSlug(), "worldSlug"); + requireText(launchBindingRequest.getControlPlaneRequestId(), "controlPlaneRequestId"); + requireSha256(launchBindingRequest.getExpectedRequestDigest(), "expectedRequestDigest"); + requireSha256(launchBindingRequest.getExpectedResultDigest(), "expectedResultDigest"); + requireSha256(expectedReleaseAttestationDigest, "expectedReleaseAttestationDigest"); + } + } + + /** One explicit count from the original ordered six-family declaration. */ + public record FamilyCount(WorldDesignAggregateType family, int count) { + public FamilyCount { + Objects.requireNonNull(family, "family"); + if (count < 0) { + throw new IllegalArgumentException("Published World family count must be nonnegative"); + } + } + } + + /** Exact authored Entity template reference; the owner payload is intentionally absent. */ + public record EntityTemplateReference( + EntityTemplateReferenceType kind, UUID tenantId, UUID versionId, UUID templateId) { + public EntityTemplateReference { + Objects.requireNonNull(kind, "kind"); + if (kind != EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM + && kind != EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC) { + throw new IllegalArgumentException("Published spawn Entity kind must be ITEM or NPC"); + } + requireNonNil(tenantId, "entity tenantId"); + requireNonNil(versionId, "entity versionId"); + requireNonNil(templateId, "entity templateId"); + } + } + + /** One unchanged authored spawn binding at its original revision position. */ + public record SpawnRequirement( + String revisionOrder, + UUID revisionId, + UUID spawnBindingId, + RoomTemplateRef roomTemplate, + EntityTemplateReference entityTemplate, + int spawnCount, + int respawnDelaySeconds) { + public SpawnRequirement { + requireCanonicalDecimal(revisionOrder, "revisionOrder"); + requireNonNil(revisionId, "revisionId"); + requireNonNil(spawnBindingId, "spawnBindingId"); + Objects.requireNonNull(roomTemplate, "roomTemplate"); + Objects.requireNonNull(entityTemplate, "entityTemplate"); + if (spawnCount < 0 || respawnDelaySeconds < 0) { + throw new IllegalArgumentException( + "Published spawn count and respawn delay must be nonnegative"); + } + } + } + + /** One unchanged authored generation-rule intent at its original revision position. */ + public record GenerationRequirement( + String revisionOrder, + UUID revisionId, + UUID ruleTemplateId, + WorldDesignAggregateType scopeFamily, + UUID scopeId, + String name, + String value) { + public GenerationRequirement { + requireCanonicalDecimal(revisionOrder, "revisionOrder"); + requireNonNil(revisionId, "revisionId"); + requireNonNil(ruleTemplateId, "ruleTemplateId"); + Objects.requireNonNull(scopeFamily, "scopeFamily"); + if (scopeFamily != WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION + && scopeFamily != WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE) { + throw new IllegalArgumentException("Generation requirement scope must be REGION or ZONE"); + } + requireNonNil(scopeId, "scopeId"); + Objects.requireNonNull(name, "name"); + Objects.requireNonNull(value, "value"); + } + } + + public WorldPublishedSpawnRequirementsEvidence { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(launchBinding, "launchBinding"); + requireNonNil(captureId, "captureId"); + requireSha256(graphDigest, "graphDigest"); + familyCounts = List.copyOf(Objects.requireNonNull(familyCounts, "familyCounts")); + spawnRequirements = List.copyOf(Objects.requireNonNull(spawnRequirements, "spawnRequirements")); + generationRequirements = + List.copyOf(Objects.requireNonNull(generationRequirements, "generationRequirements")); + + var descriptor = launchBinding.descriptor(); + var release = launchBinding.releaseAttestation(); + if (!request.targetNamespace().equals(descriptor.targetNamespace()) + || !request.targetNamespace().equals(release.targetNamespace()) + || !descriptor + .canonicalTenantId() + .toString() + .equals(request.launchBindingRequest().getCanonicalTenantId()) + || !descriptor.worldSlug().equals(request.launchBindingRequest().getWorldSlug()) + || !descriptor + .controlPlaneRequestId() + .equals(request.launchBindingRequest().getControlPlaneRequestId()) + || !descriptor + .requestDigest() + .equals(request.launchBindingRequest().getExpectedRequestDigest()) + || !descriptor + .resultDigest() + .equals(request.launchBindingRequest().getExpectedResultDigest())) { + throw new IllegalArgumentException( + "Complete launch binding differs from the exact source-read selector and namespace"); + } + if (request.readRequestId().equals(descriptor.authoredWorldSourceOperationId())) { + throw new IllegalArgumentException( + "Published spawn read request ID must be distinct from the original source operation"); + } + if (!request.expectedReleaseAttestationDigest().equals(release.evidenceDigest())) { + throw new IllegalArgumentException( + "Release attestation digest differs from the exact source-read selector"); + } + if (!AuthoredWorldReleaseAttestationEvidence.requiresWorldStartLocationEvidence( + release.schemaVersion()) + || release.worldStartLocationEvidence() == null) { + throw new IllegalArgumentException( + "Published spawn requirements require selected release World selector evidence"); + } + String boundGraphDigest = + WorldDraftStartLocationEvidence.fromStored( + release.worldStartLocationEvidence().selectorReceiptBytes()) + .graphDigest(); + if (!boundGraphDigest.equals(graphDigest)) { + throw new IllegalArgumentException( + "Published spawn graph digest differs from the exact release World selector receipt"); + } + + if (familyCounts.size() != FAMILY_ORDER.size()) { + throw new IllegalArgumentException("Exactly six ordered World family counts are required"); + } + for (int index = 0; index < FAMILY_ORDER.size(); index++) { + if (familyCounts.get(index).family() != FAMILY_ORDER.get(index)) { + throw new IllegalArgumentException( + "World family counts must use the canonical ordered six-family declaration"); + } + } + requireCount( + familyCounts, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE, + generationRequirements.size()); + requireCount( + familyCounts, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING, + spawnRequirements.size()); + + UUID tenantId = release.canonicalTenantId(); + UUID versionId = release.canonicalVersionId(); + Set revisionIds = new HashSet<>(); + Set spawnBindingIds = new HashSet<>(); + Set> spawnIdentities = new HashSet<>(); + Set ruleTemplateIds = new HashSet<>(); + requireIncreasingOrders( + spawnRequirements.stream().map(SpawnRequirement::revisionOrder).toList()); + for (SpawnRequirement spawn : spawnRequirements) { + if (!revisionIds.add(spawn.revisionId())) { + throw new IllegalArgumentException("Published requirements repeat a revision identity"); + } + if (!spawnBindingIds.add(spawn.spawnBindingId())) { + throw new IllegalArgumentException( + "Published spawn requirements repeat a binding identity"); + } + if (!tenantId.equals(spawn.roomTemplate().tenantId()) + || !versionId.equals(spawn.roomTemplate().versionId()) + || !tenantId.equals(spawn.entityTemplate().tenantId()) + || !versionId.equals(spawn.entityTemplate().versionId())) { + throw new IllegalArgumentException( + "Published spawn references differ from the exact canonical tenant/version context"); + } + List identity = + List.of( + spawn.roomTemplate().roomTemplateId(), + spawn.entityTemplate().kind(), + spawn.entityTemplate().templateId()); + if (!spawnIdentities.add(identity)) { + throw new IllegalArgumentException( + "Published spawn requirements repeat an authored identity"); + } + } + + Set> generationIdentities = new HashSet<>(); + requireIncreasingOrders( + generationRequirements.stream().map(GenerationRequirement::revisionOrder).toList()); + for (GenerationRequirement generation : generationRequirements) { + if (!revisionIds.add(generation.revisionId())) { + throw new IllegalArgumentException("Published requirements repeat a revision identity"); + } + if (!ruleTemplateIds.add(generation.ruleTemplateId())) { + throw new IllegalArgumentException( + "Published generation requirements repeat a rule template identity"); + } + List identity = + List.of(generation.scopeFamily(), generation.scopeId(), generation.name()); + if (!generationIdentities.add(identity)) { + throw new IllegalArgumentException( + "Published generation requirements repeat an authored identity"); + } + } + } + + private static void requireCount( + List familyCounts, WorldDesignAggregateType family, int expectedCount) { + FamilyCount count = + familyCounts.stream().filter(entry -> entry.family() == family).findFirst().orElseThrow(); + if (count.count() != expectedCount) { + throw new IllegalArgumentException( + "Published World family count differs from its complete source list"); + } + } + + private static void requireIncreasingOrders(List orders) { + BigInteger previous = null; + for (String order : orders) { + BigInteger current = new BigInteger(order); + if (previous != null && current.compareTo(previous) <= 0) { + throw new IllegalArgumentException( + "Published requirements must preserve strictly increasing revision order"); + } + previous = current; + } + } + + static UUID parseCanonicalUuid(String value, String label) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || NIL_UUID.equals(parsed)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID", invalid); + } + } + + static void requireCanonicalDecimal(String value, String label) { + Objects.requireNonNull(value, label); + if (!CANONICAL_DECIMAL.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be a canonical nonnegative decimal string"); + } + } + + static void requireNoUnknownFields(com.google.protobuf.Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private static void requireSha256(String value, String label) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be canonical tagged SHA-256 text"); + } + } + + private static void requireText(String value, String label) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(label + " must not be blank"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsGrpcCodec.java new file mode 100644 index 0000000000..f240f743d1 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsGrpcCodec.java @@ -0,0 +1,274 @@ +package net.firedevops.firemud.common.world; + +import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.Message; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.gamedesign.v1.GetCompleteLaunchBindingResponse; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedSpawnRequirementsRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedSpawnRequirementsResponse; +import net.firedevops.firemud.worldmanagement.v1.RoomTemplateRef; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedGenerationRequirement; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedSpawnRequirement; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedSpawnRequirementsEntityTemplateReference; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedSpawnRequirementsFamilyCount; + +/** Closed mapping and exact request-echo validation for published spawn-requirement reads. */ +public final class WorldPublishedSpawnRequirementsGrpcCodec { + public static final int MAX_RESPONSE_WIRE_BYTES = 4 * 1024 * 1024; + + private WorldPublishedSpawnRequirementsGrpcCodec() {} + + public static ReadWorldPublishedSpawnRequirementsRequest toRequest( + WorldPublishedSpawnRequirementsEvidence.Request request) { + Objects.requireNonNull(request, "request"); + return ReadWorldPublishedSpawnRequirementsRequest.newBuilder() + .setSchemaVersion(WorldPublishedSpawnRequirementsEvidence.SCHEMA_VERSION) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setLaunchBindingRequest(request.launchBindingRequest()) + .setExpectedReleaseAttestationDigest(request.expectedReleaseAttestationDigest()) + .build(); + } + + /** Parses the closed owner request only after transport authentication by its caller. */ + public static WorldPublishedSpawnRequirementsEvidence.Request fromRequest( + ReadWorldPublishedSpawnRequirementsRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFieldsRecursively(request, "ReadWorldPublishedSpawnRequirementsRequest"); + if (request.getSchemaVersion() != WorldPublishedSpawnRequirementsEvidence.SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported published spawn-requirements schema version"); + } + if (!request.hasLaunchBindingRequest()) { + throw new IllegalArgumentException( + "Published spawn request lacks its complete binding selector"); + } + return new WorldPublishedSpawnRequirementsEvidence.Request( + request.getTargetNamespace(), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + request.getReadRequestId(), "readRequestId"), + request.getLaunchBindingRequest(), + request.getExpectedReleaseAttestationDigest()); + } + + /** + * Encodes complete immutable evidence without changing its request selector or authored values. + */ + public static ReadWorldPublishedSpawnRequirementsResponse toResponse( + WorldPublishedSpawnRequirementsEvidence.Request request, + WorldPublishedSpawnRequirementsEvidence evidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(evidence, "evidence"); + if (!request.equals(evidence.request())) { + throw new IllegalArgumentException( + "Published spawn evidence differs from the exact source-read request"); + } + var builder = + ReadWorldPublishedSpawnRequirementsResponse.newBuilder() + .setRequest(toRequest(request)) + .setCompleteLaunchBinding( + toCompleteLaunchBindingResponse( + request.launchBindingRequest(), evidence.launchBinding())) + .setCaptureId(evidence.captureId().toString()) + .setGraphDigest(evidence.graphDigest()); + for (WorldPublishedSpawnRequirementsEvidence.FamilyCount familyCount : + evidence.familyCounts()) { + builder.addFamilyCounts( + WorldPublishedSpawnRequirementsFamilyCount.newBuilder() + .setFamily(familyCount.family()) + .setCount(familyCount.count())); + } + for (WorldPublishedSpawnRequirementsEvidence.SpawnRequirement spawn : + evidence.spawnRequirements()) { + builder.addSpawnRequirements( + WorldPublishedSpawnRequirement.newBuilder() + .setRevisionOrder(spawn.revisionOrder()) + .setRevisionId(spawn.revisionId().toString()) + .setSpawnBindingId(spawn.spawnBindingId().toString()) + .setRoomTemplate( + RoomTemplateRef.newBuilder() + .setTenantId(spawn.roomTemplate().tenantId().toString()) + .setVersionId(spawn.roomTemplate().versionId().toString()) + .setRoomTemplateId(spawn.roomTemplate().roomTemplateId().toString())) + .setEntityTemplate( + WorldPublishedSpawnRequirementsEntityTemplateReference.newBuilder() + .setKind(spawn.entityTemplate().kind()) + .setTenantId(spawn.entityTemplate().tenantId().toString()) + .setVersionId(spawn.entityTemplate().versionId().toString()) + .setTemplateId(spawn.entityTemplate().templateId().toString())) + .setSpawnCount(spawn.spawnCount()) + .setRespawnDelaySeconds(spawn.respawnDelaySeconds())); + } + for (WorldPublishedSpawnRequirementsEvidence.GenerationRequirement generation : + evidence.generationRequirements()) { + builder.addGenerationRequirements( + WorldPublishedGenerationRequirement.newBuilder() + .setRevisionOrder(generation.revisionOrder()) + .setRevisionId(generation.revisionId().toString()) + .setRuleTemplateId(generation.ruleTemplateId().toString()) + .setScopeFamily(generation.scopeFamily()) + .setScopeId(generation.scopeId().toString()) + .setName(generation.name()) + .setValue(generation.value())); + } + return requireResponseWithinWireLimit(builder.build()); + } + + /** Validates the complete source response, exact request echo and complete Game Design pair. */ + public static WorldPublishedSpawnRequirementsEvidence fromResponse( + WorldPublishedSpawnRequirementsEvidence.Request request, + ReadWorldPublishedSpawnRequirementsResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireResponseWithinWireLimit(response); + requireNoUnknownFieldsRecursively(response, "ReadWorldPublishedSpawnRequirementsResponse"); + if (response.hasError()) { + throw new IllegalArgumentException("World rejected the published spawn-requirements read"); + } + if (!response.hasRequest() || !response.hasCompleteLaunchBinding()) { + throw new IllegalArgumentException( + "Published spawn response lacks its exact request or complete launch binding"); + } + WorldPublishedSpawnRequirementsEvidence.Request echoed = fromRequest(response.getRequest()); + if (!request.equals(echoed)) { + throw new IllegalArgumentException( + "Published spawn response changed the exact source-read request"); + } + CompleteLaunchBindingEvidence launchBinding = + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request.launchBindingRequest(), response.getCompleteLaunchBinding()); + + List familyCounts = + new ArrayList<>(response.getFamilyCountsCount()); + for (WorldPublishedSpawnRequirementsFamilyCount count : response.getFamilyCountsList()) { + requireNoUnknownFieldsRecursively(count, "WorldPublishedSpawnRequirementsFamilyCount"); + if (!count.hasCount()) { + throw new IllegalArgumentException( + "Published World family count is not explicitly present"); + } + familyCounts.add( + new WorldPublishedSpawnRequirementsEvidence.FamilyCount( + count.getFamily(), count.getCount())); + } + + List spawns = + new ArrayList<>(response.getSpawnRequirementsCount()); + for (WorldPublishedSpawnRequirement spawn : response.getSpawnRequirementsList()) { + requireNoUnknownFieldsRecursively(spawn, "WorldPublishedSpawnRequirement"); + if (!spawn.hasRoomTemplate() || !spawn.hasEntityTemplate()) { + throw new IllegalArgumentException("Published spawn requirement lacks typed references"); + } + var room = spawn.getRoomTemplate(); + var entity = spawn.getEntityTemplate(); + spawns.add( + new WorldPublishedSpawnRequirementsEvidence.SpawnRequirement( + spawn.getRevisionOrder(), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + spawn.getRevisionId(), "revisionId"), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + spawn.getSpawnBindingId(), "spawnBindingId"), + new net.firedevops.firemud.common.world.RoomTemplateRef( + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + room.getTenantId(), "room tenantId"), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + room.getVersionId(), "room versionId"), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + room.getRoomTemplateId(), "roomTemplateId")), + new WorldPublishedSpawnRequirementsEvidence.EntityTemplateReference( + entity.getKind(), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + entity.getTenantId(), "entity tenantId"), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + entity.getVersionId(), "entity versionId"), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + entity.getTemplateId(), "entity templateId")), + spawn.getSpawnCount(), + spawn.getRespawnDelaySeconds())); + } + + List generations = + new ArrayList<>(response.getGenerationRequirementsCount()); + for (WorldPublishedGenerationRequirement generation : + response.getGenerationRequirementsList()) { + requireNoUnknownFieldsRecursively(generation, "WorldPublishedGenerationRequirement"); + generations.add( + new WorldPublishedSpawnRequirementsEvidence.GenerationRequirement( + generation.getRevisionOrder(), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + generation.getRevisionId(), "revisionId"), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + generation.getRuleTemplateId(), "ruleTemplateId"), + generation.getScopeFamily(), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + generation.getScopeId(), "scopeId"), + generation.getName(), + generation.getValue())); + } + return new WorldPublishedSpawnRequirementsEvidence( + request, + launchBinding, + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + response.getCaptureId(), "captureId"), + response.getGraphDigest(), + familyCounts, + spawns, + generations); + } + + /** Encodes a parsed launch pair for the outer response while validating its exact selector. */ + public static GetCompleteLaunchBindingResponse toCompleteLaunchBindingResponse( + GetLaunchDescriptorRequest request, CompleteLaunchBindingEvidence evidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(evidence, "evidence"); + GetCompleteLaunchBindingResponse response = + GetCompleteLaunchBindingResponse.newBuilder() + .setRequestId(request.getRequestId()) + .setLaunchDescriptor( + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage( + evidence.descriptor())) + .setReleaseAttestation( + AuthoredWorldLaunchDescriptorGrpcCodec.toReleaseAttestation( + evidence.releaseAttestation())) + .build(); + CompleteLaunchBindingEvidence decoded = + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse(request, response); + if (!decoded.equals(evidence)) { + throw new IllegalArgumentException( + "Encoded complete launch binding differs from its immutable evidence pair"); + } + return response; + } + + private static void requireNoUnknownFieldsRecursively(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + for (var entry : message.getAllFields().entrySet()) { + FieldDescriptor field = entry.getKey(); + if (field.getJavaType() != FieldDescriptor.JavaType.MESSAGE) { + continue; + } + Object value = entry.getValue(); + if (field.isRepeated()) { + for (Object element : (List) value) { + requireNoUnknownFieldsRecursively((Message) element, field.getName()); + } + } else { + requireNoUnknownFieldsRecursively((Message) value, field.getName()); + } + } + } + + private static ReadWorldPublishedSpawnRequirementsResponse requireResponseWithinWireLimit( + ReadWorldPublishedSpawnRequirementsResponse response) { + if (response.getSerializedSize() > MAX_RESPONSE_WIRE_BYTES) { + throw new IllegalArgumentException( + "Published spawn-requirements response exceeds the maximum wire size"); + } + return response; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorTest.java index f8bf447019..ce55464658 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorTest.java @@ -3,7 +3,9 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.math.BigInteger; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -15,6 +17,8 @@ import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; class RuntimeMembershipAuthorityEvidenceValidatorTest { private static final String ISSUER_ID = "firemud-account-service"; @@ -28,6 +32,285 @@ class RuntimeMembershipAuthorityEvidenceValidatorTest { private static final String MEMBERSHIP_STREAM = PREFIX + "membership/" + ACCOUNT_ID + "/" + TENANT_ID; private static final String LARGE_COUNTER = "9223372036854775807"; + private static final String HISTORY_GENERATION = "9007199254740999"; + private static final String HISTORY_SEQUENCE = "9007199254740998"; + + @ParameterizedTest + @ValueSource(strings = {"PASSWORD_RESET", "LOGOUT_ALL", "ACCOUNT_STATE"}) + void positiveIssuerAndSupportedAccountSourcesPreserveOriginalHistoricalMembership(String kind) { + var baseline = historicalSnapshot(); + var account = retainedAccountSource(kind, baseline.sourceEvidence().getFirst()); + var issuer = + AccountAuthoritySourceEventV1Codec.sealIssuer( + new AccountAuthoritySourceEventV1Codec.IssuerPreimage( + "retained-issuer-event", + "retained-issuer-event", + ISSUER_STREAM, + "1", + ISSUER_ID, + "2", + "2", + "ISSUER_SECURITY_CHANGE")); + var current = baseline.authorityTuple(); + var tuple = + new AuthorityTuple( + "2", + current.accountAuthorityGeneration(), + current.tenantAuthorityGeneration(), + current.membershipAuthorityGeneration(), + current.privateRealmGrantVersions(), + current.accountSecurityCutoff(), + current.tenantBillingCutoff()); + var originalMembership = baseline.sourceEvidence().get(1); + var snapshot = + new RuntimeMembershipAuthorityEvidenceValidator.Snapshot( + baseline.issuerId(), + baseline.accountId(), + baseline.tenantId(), + true, + "ACTIVE", + true, + baseline.membershipVersion(), + baseline.membershipAuthorityGeneration(), + baseline.roles(), + tuple, + baseline.issuanceFence(), + List.of( + baseline.checkpoints().get(0), + new RuntimeMembershipAuthorityEvidenceValidator.Checkpoint(ISSUER_STREAM, "1"), + baseline.checkpoints().get(2), + baseline.checkpoints().get(3)), + List.of( + account, + new RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence( + ISSUER_STREAM, + "1", + issuer.eventId(), + issuer.eventDigest(), + issuer.canonicalJson()), + originalMembership)); + + var result = RuntimeMembershipAuthorityEvidenceValidator.validate(snapshot).orElseThrow(); + assertThat(result.canonicalJson()).isEqualTo(originalMembership.canonicalEventJson()); + assertThat(result.authorityTuple().issuerAuthGeneration()).isEqualTo("1"); + assertThat(snapshot.authorityTuple().issuerAuthGeneration()).isEqualTo("2"); + assertThat(result.authorityTuple().accountAuthorityGeneration()).isEqualTo("1"); + assertThat(snapshot.authorityTuple().accountAuthorityGeneration()) + .isEqualTo(HISTORY_GENERATION); + } + + @Test + void missingMembershipStillRequiresItsPositiveCurrentAccountSource() { + var baseline = currentSnapshot(); + var missing = + new RuntimeMembershipAuthorityEvidenceValidator.Snapshot( + baseline.issuerId(), + baseline.accountId(), + baseline.tenantId(), + false, + "MISSING", + false, + baseline.membershipVersion(), + baseline.membershipAuthorityGeneration(), + List.of(), + baseline.authorityTuple(), + baseline.issuanceFence(), + List.of( + baseline.checkpoints().get(0), + baseline.checkpoints().get(1), + new RuntimeMembershipAuthorityEvidenceValidator.Checkpoint(MEMBERSHIP_STREAM, "0"), + baseline.checkpoints().get(3)), + List.of(baseline.sourceEvidence().getFirst())); + assertThat(RuntimeMembershipAuthorityEvidenceValidator.validate(missing)).isEmpty(); + assertThatThrownBy( + () -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + copyWith(missing, missing.checkpoints(), List.of()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("one source for each positive checkpoint"); + } + + @Test + void resealedHistoricalMembershipCannotLeadIssuerAccountFenceOrAccountCutoff() throws Exception { + var baseline = historicalSnapshot(); + String earlier = new BigInteger(HISTORY_GENERATION).subtract(BigInteger.ONE).toString(); + String later = new BigInteger(HISTORY_GENERATION).add(BigInteger.ONE).toString(); + for (MembershipEvent event : + List.of( + resealedMembershipSource(baseline, "2", "1", "1", null), + resealedMembershipSource( + baseline, + "1", + later, + "1", + new AccountSecurityCutoff(later, ACCOUNT_STREAM, HISTORY_SEQUENCE)), + resealedMembershipSource(baseline, "1", "1", "2", null), + resealedMembershipSource( + baseline, + "1", + earlier, + "1", + new AccountSecurityCutoff(earlier, ACCOUNT_STREAM, later)))) { + // The supplied event is freshly sealed and valid independently of current carrier authority. + assertThat(MembershipAuthorityEventV1Codec.verify(event.canonicalJson()).eventDigest()) + .isEqualTo(event.eventDigest()); + assertThatThrownBy( + () -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + copyWithMembershipSource(baseline, event))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must not be ahead"); + } + for (AccountSecurityCutoff cutoff : + List.of( + new AccountSecurityCutoff( + earlier, + ACCOUNT_STREAM, + new BigInteger(HISTORY_SEQUENCE).subtract(BigInteger.ONE).toString()), + new AccountSecurityCutoff(HISTORY_GENERATION, ACCOUNT_STREAM, HISTORY_SEQUENCE))) { + var event = + resealedMembershipSource(baseline, "1", cutoff.accountAuthorityGeneration(), "1", cutoff); + assertThat( + RuntimeMembershipAuthorityEvidenceValidator.validate( + copyWithMembershipSource(baseline, event)) + .orElseThrow() + .canonicalJson()) + .isEqualTo(event.canonicalJson()); + } + } + + private static RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence retainedAccountSource( + String kind, RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence resetSource) { + if (kind.equals("PASSWORD_RESET")) return resetSource; + String eventId; + String digest; + String json; + if (kind.equals("LOGOUT_ALL")) { + String requestId = "55555555-5555-4555-8555-555555555555"; + var preimage = new HashMap(historicalAccountPreimage()); + preimage.put("schemaVersion", AccountLogoutAllAuthorityEventV1Codec.SCHEMA_VERSION); + preimage.put("eventType", AccountLogoutAllAuthorityEventV1Codec.EVENT_TYPE); + preimage.put("requestId", requestId); + preimage.put("eventId", AccountLogoutAllAuthorityEventV1Codec.EVENT_ID_PREFIX + requestId); + var event = AccountLogoutAllAuthorityEventV1Codec.seal(preimage); + eventId = event.eventId(); + digest = event.eventDigest(); + json = event.canonicalJson(); + } else { + var event = + AccountAuthoritySourceEventV1Codec.sealAccount( + new AccountAuthoritySourceEventV1Codec.AccountPreimage( + "retained-account-state", + "retained-account-state", + ACCOUNT_STREAM, + HISTORY_SEQUENCE, + ACCOUNT_ID, + HISTORY_GENERATION, + HISTORY_GENERATION, + HISTORY_GENERATION, + HISTORY_GENERATION, + List.of("GLOBAL_ROLE_CHANGED"), + new AccountAuthoritySourceEventV1Codec.AccountState( + true, List.of("PASSWORD"), "admin", "ACTIVE"))); + eventId = event.eventId(); + digest = event.eventDigest(); + json = event.canonicalJson(); + } + return new RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence( + ACCOUNT_STREAM, HISTORY_SEQUENCE, eventId, digest, json); + } + + private static Map historicalAccountPreimage() { + var preimage = new HashMap(accountSourcePreimage()); + preimage.put("outboxSequence", HISTORY_SEQUENCE); + preimage.put("accountAuthorityGeneration", HISTORY_GENERATION); + preimage.put("sourceVersion", HISTORY_GENERATION); + preimage.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + HISTORY_GENERATION, + "outboxStreamKey", + ACCOUNT_STREAM, + "outboxSequence", + HISTORY_SEQUENCE)); + return preimage; + } + + private static RuntimeMembershipAuthorityEvidenceValidator.Snapshot historicalSnapshot() { + var baseline = currentSnapshot(); + var account = PasswordResetAuthorityEventV1Codec.seal(historicalAccountPreimage()); + var current = baseline.authorityTuple(); + var tuple = + new AuthorityTuple( + current.issuerAuthGeneration(), + HISTORY_GENERATION, + current.tenantAuthorityGeneration(), + current.membershipAuthorityGeneration(), + current.privateRealmGrantVersions(), + Optional.of( + new AccountSecurityCutoff(HISTORY_GENERATION, ACCOUNT_STREAM, HISTORY_SEQUENCE)), + current.tenantBillingCutoff()); + return new RuntimeMembershipAuthorityEvidenceValidator.Snapshot( + baseline.issuerId(), + baseline.accountId(), + baseline.tenantId(), + baseline.membershipExists(), + baseline.membershipLifecycleState(), + baseline.gameplayAdmissionAllowed(), + baseline.membershipVersion(), + baseline.membershipAuthorityGeneration(), + baseline.roles(), + tuple, + baseline.issuanceFence(), + List.of( + new RuntimeMembershipAuthorityEvidenceValidator.Checkpoint( + ACCOUNT_STREAM, HISTORY_SEQUENCE), + baseline.checkpoints().get(1), + baseline.checkpoints().get(2), + baseline.checkpoints().get(3)), + List.of( + new RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence( + ACCOUNT_STREAM, + HISTORY_SEQUENCE, + account.eventId(), + account.eventDigest(), + account.canonicalJson()), + baseline.sourceEvidence().get(1))); + } + + private static MembershipEvent resealedMembershipSource( + RuntimeMembershipAuthorityEvidenceValidator.Snapshot snapshot, + String issuerGeneration, + String accountGeneration, + String issuanceFence, + AccountSecurityCutoff cutoff) + throws Exception { + var json = new tools.jackson.databind.ObjectMapper(); + var preimage = + (tools.jackson.databind.node.ObjectNode) + json.readTree(snapshot.sourceEvidence().get(1).canonicalEventJson()); + preimage.remove("eventDigest"); + preimage.put("issuanceFence", issuanceFence); + var tuple = (tools.jackson.databind.node.ObjectNode) preimage.get("authorityTuple"); + tuple.put("issuerAuthGeneration", issuerGeneration); + tuple.put("accountAuthorityGeneration", accountGeneration); + if (cutoff == null) tuple.remove("accountSecurityCutoff"); + else + tuple.set( + "accountSecurityCutoff", + json.valueToTree( + Map.of( + "accountAuthorityGeneration", + cutoff.accountAuthorityGeneration(), + "outboxStreamKey", + cutoff.outboxStreamKey(), + "outboxSequence", + cutoff.outboxSequence()))); + return MembershipAuthorityEventV1Codec.seal( + json.convertValue( + preimage, new tools.jackson.core.type.TypeReference>() {})); + } @Test void validatesCurrentMembershipAgainstAccountSourceAndLargeDecimalCheckpoints() { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBindingCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBindingCodecTest.java new file mode 100644 index 0000000000..c7cdff15e9 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBindingCodecTest.java @@ -0,0 +1,699 @@ +package net.firedevops.firemud.common.authoring; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import org.junit.jupiter.api.Test; + +class DraftAuthorizationFenceBindingCodecTest { + private static final UUID OPERATION_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID COMMIT_ID = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID FENCE_ID = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID ACTOR_ID = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private static final UUID TENANT_ID = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION_ID = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID REVISION_ID = uuid("66666666-6666-4666-8666-666666666666"); + private static final UUID SOURCE_SCOPE_ID = uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + private static final String EXPECTED_DRAFT_EPOCH = "9007199254741009"; + private static final String LARGE_SOURCE_VERSION = "9007199254740993"; + private static final String GAME_DESIGN_DIGEST = + "sha256:2a6fe4b88eb642dac5eb64b04d0123d11a4944ec94f4b4304f9416753c09742f"; + private static final String FENCE_DIGEST = + "sha256:1ee6345cf8420f08f59f4570a62bef8b149b56f12c5b0c66ba5d3f77bd57b7e2"; + private static final String GAME_DESIGN_JSON = + "{\"affectedUnits\":[{\"aggregateId\":\"world-1\",\"aggregateType\":\"WORLD_TEMPLATE\"," + + "\"expectedEpoch\":\"0\",\"owner\":\"WORLD_MANAGEMENT\",\"scopeId\":\"room-1\"," + + "\"scopeType\":\"ROOM_SCOPE\"}],\"baseCommitId\":\"base-source-1\"," + + "\"canonicalTenantId\":\"11111111-1111-4111-8111-111111111111\"," + + "\"canonicalVersionId\":\"22222222-2222-4222-8222-222222222222\"," + + "\"commitId\":\"55555555-5555-4555-8555-555555555555\"," + + "\"requestId\":\"44444444-4444-4444-8444-444444444444\"," + + "\"requiredOwners\":[\"WORLD_MANAGEMENT\"],\"revisions\":[{" + + "\"owner\":\"WORLD_MANAGEMENT\",\"payload\":\"{}\"," + + "\"revisionId\":\"66666666-6666-4666-8666-666666666666\"," + + "\"revisionOrder\":\"0\"}],\"schemaVersion\":\"1\",\"target\":{" + + "\"gameDesignVersionRowId\":\"19\",\"gameDesignVersionTenantKey\":\"tenant-key\"," + + "\"sourceGameRowId\":\"42\",\"sourceGameTenantKey\":\"tenant-key\"," + + "\"sourceProvenanceKind\":\"NEW_GAME_ROW\"}}"; + + @Test + void preservesV57ProducerGoldenBytesAndDigestAndRoundTripsEveryField() { + DraftAuthorizationFenceBinding original = binding(List.of(source())); + byte[] golden = goldenBytes(); + + assertThat(original.gameDesignBinding()) + .containsExactly(GAME_DESIGN_JSON.getBytes(StandardCharsets.UTF_8)); + assertThat(original.inputDigest()).isEqualTo(GAME_DESIGN_DIGEST); + assertThat(original.canonicalBytes()).containsExactly(golden); + assertThat(DraftAuthorizationFenceBinding.digest(golden)).isEqualTo(FENCE_DIGEST); + + DraftAuthorizationFenceBinding restored = DraftAuthorizationFenceBinding.fromStored(golden); + assertBindingValues(original, restored); + assertThat(restored.canonicalBytes()).containsExactly(golden); + assertThat(restored.schemaVersion()).isEqualTo(DraftAuthorizationFenceBinding.SCHEMA_V1); + assertThat(restored.requiredOwners()) + .containsExactly( + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Owner.WORLD); + } + + @Test + void v2BindsWorldAndEntityAndRoundTripsTheCanonicalRequiredOwnerSet() { + DraftAuthorizationFenceBinding original = + bindingForOwners(List.of(Owner.WORLD_MANAGEMENT, Owner.ENTITY_MANAGEMENT)) + .withRequiredOwners(); + List expectedOwners = + List.of( + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Owner.WORLD, + DraftAuthorizationFenceBinding.Owner.ENTITY); + + assertThat(original.schemaVersion()).isEqualTo(DraftAuthorizationFenceBinding.SCHEMA_V2); + assertThat(original.requiredOwners()).containsExactlyElementsOf(expectedOwners); + assertThat(original.canonicalBytes()).containsExactly(goldenV2Bytes(original, expectedOwners)); + + DraftAuthorizationFenceBinding restored = + DraftAuthorizationFenceBinding.fromStored(original.canonicalBytes()); + assertBindingValues(original, restored); + assertThat(restored.canonicalBytes()).containsExactly(original.canonicalBytes()); + assertThat(restored.requiredOwners()).containsExactlyElementsOf(expectedOwners); + } + + @Test + void v2MapsEveryCommitOwnerAndAlwaysIncludesTheGameDesignCoordinator() { + DraftAuthorizationFenceBinding multiOwner = + bindingForOwners(Arrays.asList(Owner.values())).withRequiredOwners(); + assertThat(multiOwner.requiredOwners()) + .containsExactly( + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Owner.WORLD, + DraftAuthorizationFenceBinding.Owner.ENTITY, + DraftAuthorizationFenceBinding.Owner.GAME_LOGIC, + DraftAuthorizationFenceBinding.Owner.AUTOMATION); + assertBindingValues( + multiOwner, DraftAuthorizationFenceBinding.fromStored(multiOwner.canonicalBytes())); + + DraftAuthorizationFenceBinding controlPlaneOnly = + bindingForOwners(List.of(Owner.GAME_DESIGN_CONTROL_PLANE)).withRequiredOwners(); + assertThat(controlPlaneOnly.requiredOwners()) + .containsExactly(DraftAuthorizationFenceBinding.Owner.GAME_DESIGN); + assertBindingValues( + controlPlaneOnly, + DraftAuthorizationFenceBinding.fromStored(controlPlaneOnly.canonicalBytes())); + } + + @Test + void v2RejectsMissingExtraUnknownReorderedAndSubstitutedOwners() { + DraftAuthorizationFenceBinding binding = + bindingForOwners(List.of(Owner.WORLD_MANAGEMENT, Owner.ENTITY_MANAGEMENT)) + .withRequiredOwners(); + List canonicalFrames = readFrames(binding.canonicalBytes()); + + List missing = new ArrayList<>(canonicalFrames); + missing.set(16, utf8("2")); + missing.remove(missing.size() - 1); + assertInvalid(writeFrames(missing)); + + List extra = new ArrayList<>(canonicalFrames); + extra.set(16, utf8("4")); + extra.add(utf8("AUTOMATION")); + assertInvalid(writeFrames(extra)); + + List unknown = new ArrayList<>(canonicalFrames); + unknown.set(18, utf8("UNKNOWN_OWNER")); + assertInvalid(writeFrames(unknown)); + + List reordered = new ArrayList<>(canonicalFrames); + byte[] gameDesign = reordered.get(17); + reordered.set(17, reordered.get(18)); + reordered.set(18, gameDesign); + assertInvalid(writeFrames(reordered)); + + List substituted = new ArrayList<>(canonicalFrames); + substituted.set(18, utf8("GAME_LOGIC")); + assertInvalid(writeFrames(substituted)); + } + + @Test + void v2RejectsChangedCompleteBindingAndNoncanonicalOwnerCount() { + DraftAuthorizationFenceBinding binding = + bindingForOwners(List.of(Owner.WORLD_MANAGEMENT, Owner.ENTITY_MANAGEMENT)) + .withRequiredOwners(); + List changedInput = readFrames(binding.canonicalBytes()); + changedInput.set(11, utf8("{}")); + assertInvalid(writeFrames(changedInput)); + + List noncanonicalCount = readFrames(binding.canonicalBytes()); + noncanonicalCount.set(16, utf8("03")); + assertInvalid(writeFrames(noncanonicalCount)); + + List excessiveCount = readFrames(binding.canonicalBytes()); + excessiveCount.set(16, utf8("999999999999999999999999999999999999")); + assertInvalid(writeFrames(excessiveCount)); + } + + @Test + void v2OwnerReadbackUsesMatchingVersionAndOnlyAllowsRequiredOwners() { + DraftAuthorizationFenceBinding binding = + bindingForOwners(List.of(Owner.WORLD_MANAGEMENT, Owner.ENTITY_MANAGEMENT)) + .withRequiredOwners(); + var worldReadback = + ownerReadback(binding, DraftAuthorizationFenceBinding.Owner.WORLD, new byte[] {1}); + List frames = readFrames(worldReadback.canonicalBytes()); + assertThat(new String(frames.get(0), StandardCharsets.UTF_8)) + .isEqualTo("account-draft-owner-readback/v2"); + DraftAuthorizationFenceBinding.OwnerReadback.fromStored(worldReadback.canonicalBytes()) + .requireBinding(binding); + + var wrongOwner = new ArrayList<>(frames); + wrongOwner.set(1, utf8("AUTOMATION")); + assertThatThrownBy( + () -> DraftAuthorizationFenceBinding.OwnerReadback.fromStored(writeFrames(wrongOwner))) + .isInstanceOf(IllegalArgumentException.class); + + for (int field : List.of(3, 4, 5, 6, 7)) { + var changedBinding = new ArrayList<>(frames); + changedBinding.set( + field, + switch (field) { + case 3, 4, 5 -> utf8("99999999-9999-4999-8999-999999999999"); + case 6 -> utf8("sha256:" + "f".repeat(64)); + default -> binding(List.of(source())).canonicalBytes(); + }); + assertThatThrownBy( + () -> + DraftAuthorizationFenceBinding.OwnerReadback.fromStored( + writeFrames(changedBinding))) + .isInstanceOf(IllegalArgumentException.class); + } + + var mismatchedVersion = new ArrayList<>(frames); + mismatchedVersion.set(0, utf8("account-draft-owner-readback/v1")); + assertThatThrownBy( + () -> + DraftAuthorizationFenceBinding.OwnerReadback.fromStored( + writeFrames(mismatchedVersion))) + .isInstanceOf(IllegalArgumentException.class); + + var changedResult = new ArrayList<>(frames); + changedResult.set(changedResult.size() - 1, new byte[] {2}); + var changedReadback = + DraftAuthorizationFenceBinding.OwnerReadback.fromStored(writeFrames(changedResult)); + assertThat(changedReadback.result()).containsExactly((byte) 2); + assertThat(changedReadback.canonicalBytes()).containsExactly(writeFrames(changedResult)); + assertThat(changedReadback.canonicalBytes()).isNotEqualTo(worldReadback.canonicalBytes()); + } + + @Test + void v1OwnerReadbackSchemaCannotBeSubstitutedForV2Binding() { + DraftAuthorizationFenceBinding binding = + bindingForOwners(List.of(Owner.WORLD_MANAGEMENT)).withRequiredOwners(); + var readback = + ownerReadback(binding, DraftAuthorizationFenceBinding.Owner.WORLD, new byte[] {1}); + List frames = readFrames(readback.canonicalBytes()); + frames.set(0, utf8("account-draft-owner-readback/v1")); + assertThatThrownBy( + () -> DraftAuthorizationFenceBinding.OwnerReadback.fromStored(writeFrames(frames))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void aDifferentCanonicalOperationDecodesAsDifferentImmutableDataNotAuthorization() { + DraftAuthorizationFenceBinding original = binding(List.of(source())); + List frames = readFrames(original.canonicalBytes()); + frames.set(1, utf8("99999999-9999-4999-8999-999999999999")); + byte[] changedOperation = writeFrames(frames); + + DraftAuthorizationFenceBinding restored = + DraftAuthorizationFenceBinding.fromStored(changedOperation); + + assertThat(restored.operationId()).isNotEqualTo(original.operationId()); + assertThat(restored.canonicalBytes()).containsExactly(changedOperation); + assertThat(DraftAuthorizationFenceBinding.digest(restored.canonicalBytes())) + .isNotEqualTo(DraftAuthorizationFenceBinding.digest(original.canonicalBytes())); + } + + @Test + void rejectsOperationSourceOrderDigestTargetAndCounterSubstitutions() { + byte[] original = goldenBytes(); + + List nilOperation = readFrames(original); + nilOperation.set(1, utf8("00000000-0000-0000-0000-000000000000")); + assertInvalid(writeFrames(nilOperation)); + + List noncanonicalOperation = readFrames(original); + noncanonicalOperation.set(1, utf8("AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA")); + assertInvalid(writeFrames(noncanonicalOperation)); + + List changedDigest = readFrames(original); + changedDigest.set(13, utf8("sha256:" + "f".repeat(64))); + assertInvalid(writeFrames(changedDigest)); + + List changedTenant = readFrames(original); + changedTenant.set(6, utf8("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee")); + assertInvalid(writeFrames(changedTenant)); + + List reorderedOwners = readFrames(original); + byte[] gameDesignOwner = reorderedOwners.get(16); + reorderedOwners.set(16, reorderedOwners.get(17)); + reorderedOwners.set(17, gameDesignOwner); + assertInvalid(writeFrames(reorderedOwners)); + + List noncanonicalEpoch = readFrames(original); + noncanonicalEpoch.set(10, utf8("09007199254741009")); + assertInvalid(writeFrames(noncanonicalEpoch)); + + List noncanonicalCount = readFrames(original); + noncanonicalCount.set(14, utf8("01")); + assertInvalid(writeFrames(noncanonicalCount)); + + List excessiveCount = readFrames(original); + excessiveCount.set(14, utf8("999999999999999999999999999999999999")); + assertInvalid(writeFrames(excessiveCount)); + } + + @Test + void rejectsReorderedSourceVectorAndMalformedStoredFrames() { + DraftAuthorizationFenceBinding twoSources = binding(List.of(source(), accountSource())); + List reversedSources = readFrames(twoSources.canonicalBytes()); + byte[] firstSource = reversedSources.get(15); + reversedSources.set(15, reversedSources.get(16)); + reversedSources.set(16, firstSource); + assertInvalid(writeFrames(reversedSources)); + + List invalidUtf8 = readFrames(goldenBytes()); + invalidUtf8.set(8, new byte[] {(byte) 0xc3, 0x28}); + assertInvalid(writeFrames(invalidUtf8)); + + List unknownSchema = readFrames(goldenBytes()); + unknownSchema.set(0, utf8("account-draft-authorization-fence/v2")); + assertInvalid(writeFrames(unknownSchema)); + + byte[] golden = goldenBytes(); + assertInvalid(Arrays.copyOf(golden, golden.length - 1)); + byte[] trailing = Arrays.copyOf(golden, golden.length + 1); + trailing[trailing.length - 1] = 1; + assertInvalid(trailing); + + byte[] negativeLength = golden.clone(); + ByteBuffer.wrap(negativeLength).putInt(0, -1); + assertInvalid(negativeLength); + byte[] oversizedLength = golden.clone(); + ByteBuffer.wrap(oversizedLength).putInt(0, Integer.MAX_VALUE); + assertInvalid(oversizedLength); + } + + @Test + void ownerReadbackRoundTripsExactBytesAndOriginalBindingForEveryOutcome() { + var binding = binding(List.of(source())); + for (var owner : + List.of( + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Owner.WORLD)) { + for (var outcome : DraftAuthorizationFenceBinding.Outcome.values()) { + var original = + new DraftAuthorizationFenceBinding.OwnerReadback( + owner, + outcome, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + new byte[] {1, 2, 3}); + var decoded = + DraftAuthorizationFenceBinding.OwnerReadback.fromStored(original.canonicalBytes()); + decoded.requireBinding(binding); + assertThat(decoded.owner()).isEqualTo(owner); + assertThat(decoded.outcome()).isEqualTo(outcome); + assertThat(decoded.result()).containsExactly(new byte[] {1, 2, 3}); + assertThat(decoded.canonicalBytes()).containsExactly(original.canonicalBytes()); + assertThat(original.canonicalBytes()) + .containsExactly(goldenOwnerReadbackV1(binding, owner, outcome, new byte[] {1, 2, 3})); + } + } + } + + @Test + void ownerReadbackRejectsCorruptFramingNoncanonicalFieldsAndContradictoryBinding() { + var binding = binding(List.of(source())); + var original = + new DraftAuthorizationFenceBinding.OwnerReadback( + DraftAuthorizationFenceBinding.Owner.WORLD, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + new byte[] {1}); + byte[] bytes = original.canonicalBytes(); + for (int field : List.of(0, 1, 2, 3, 4, 5, 6, 7, 8)) { + var fields = readFrames(bytes); + fields.set( + field, + switch (field) { + case 0 -> utf8("account-draft-owner-readback/v2"); + case 1 -> utf8("world"); + case 2 -> utf8("UNKNOWN"); + case 3 -> utf8(binding.operationId().toString().toUpperCase(java.util.Locale.ROOT)); + case 4, 5 -> utf8("99999999-9999-4999-8999-999999999999"); + case 6 -> utf8("sha256:" + "f".repeat(64)); + case 7 -> new byte[] {1}; + default -> new byte[0]; + }); + assertThatThrownBy( + () -> DraftAuthorizationFenceBinding.OwnerReadback.fromStored(writeFrames(fields))) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> + DraftAuthorizationFenceBinding.OwnerReadback.fromStored( + Arrays.copyOf(bytes, bytes.length - 1))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + DraftAuthorizationFenceBinding.OwnerReadback.fromStored( + Arrays.copyOf(bytes, bytes.length + 1))) + .isInstanceOf(IllegalArgumentException.class); + byte[] negative = bytes.clone(); + ByteBuffer.wrap(negative).putInt(-1); + assertThatThrownBy(() -> DraftAuthorizationFenceBinding.OwnerReadback.fromStored(negative)) + .isInstanceOf(IllegalArgumentException.class); + var invalidUtf8 = readFrames(bytes); + invalidUtf8.set(1, new byte[] {(byte) 0xc3, 0x28}); + assertThatThrownBy( + () -> DraftAuthorizationFenceBinding.OwnerReadback.fromStored(writeFrames(invalidUtf8))) + .isInstanceOf(IllegalArgumentException.class); + + var expandedV1Owner = readFrames(bytes); + expandedV1Owner.set(1, utf8("ENTITY")); + assertThatThrownBy( + () -> + DraftAuthorizationFenceBinding.OwnerReadback.fromStored( + writeFrames(expandedV1Owner))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static void assertBindingValues( + DraftAuthorizationFenceBinding expected, DraftAuthorizationFenceBinding actual) { + assertThat(actual.operationId()).isEqualTo(expected.operationId()); + assertThat(actual.requestId()).isEqualTo(expected.requestId()); + assertThat(actual.commitId()).isEqualTo(expected.commitId()); + assertThat(actual.fenceId()).isEqualTo(expected.fenceId()); + assertThat(actual.actorAccountId()).isEqualTo(expected.actorAccountId()); + assertThat(actual.tenantId()).isEqualTo(expected.tenantId()); + assertThat(actual.versionId()).isEqualTo(expected.versionId()); + assertThat(actual.baseCommitId()).isEqualTo(expected.baseCommitId()); + assertThat(actual.expectedDraftEpoch()).isEqualTo(expected.expectedDraftEpoch()); + assertThat(actual.gameDesignBinding()).containsExactly(expected.gameDesignBinding()); + assertThat(actual.normalizedInput()).containsExactly(expected.normalizedInput()); + assertThat(actual.inputDigest()).isEqualTo(expected.inputDigest()); + assertThat(actual.schemaVersion()).isEqualTo(expected.schemaVersion()); + assertThat(actual.requiredOwners()).containsExactlyElementsOf(expected.requiredOwners()); + assertThat(actual.sources()).hasSize(expected.sources().size()); + for (int index = 0; index < expected.sources().size(); index++) { + SourceEvidence expectedSource = expected.sources().get(index); + SourceEvidence actualSource = actual.sources().get(index); + assertThat(actualSource.kind()).isEqualTo(expectedSource.kind()); + assertThat(actualSource.scopeId()).isEqualTo(expectedSource.scopeId()); + assertThat(actualSource.generation()).isEqualTo(expectedSource.generation()); + assertThat(actualSource.sourceVersion()).isEqualTo(expectedSource.sourceVersion()); + assertThat(actualSource.checkpointStream()).isEqualTo(expectedSource.checkpointStream()); + assertThat(actualSource.checkpointSequence()).isEqualTo(expectedSource.checkpointSequence()); + assertThat(actualSource.evidence()).containsExactly(expectedSource.evidence()); + } + } + + private static DraftAuthorizationFenceBinding binding(List sources) { + DraftCommitBinding gameDesign = gameDesignBinding(); + byte[] gameDesignBytes = gameDesign.canonicalBytes(); + return new DraftAuthorizationFenceBinding( + OPERATION_ID, + REQUEST_ID, + COMMIT_ID, + FENCE_ID, + ACTOR_ID, + TENANT_ID, + VERSION_ID, + "base-source-1", + EXPECTED_DRAFT_EPOCH, + gameDesignBytes, + gameDesignBytes, + gameDesign.digest(), + sources); + } + + private static DraftCommitBinding gameDesignBinding() { + return DraftCommitBinding.create( + new TargetProof( + TENANT_ID, VERSION_ID, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + REQUEST_ID, + COMMIT_ID, + "base-source-1", + List.of(new RevisionPayload("0", REVISION_ID, Owner.WORLD_MANAGEMENT, "{}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, "WORLD_TEMPLATE", "world-1", "ROOM_SCOPE", "room-1", "0"))); + } + + private static DraftAuthorizationFenceBinding bindingForOwners(List owners) { + DraftCommitBinding gameDesign = gameDesignBinding(owners); + byte[] gameDesignBytes = gameDesign.canonicalBytes(); + return new DraftAuthorizationFenceBinding( + OPERATION_ID, + REQUEST_ID, + COMMIT_ID, + FENCE_ID, + ACTOR_ID, + TENANT_ID, + VERSION_ID, + "base-source-1", + EXPECTED_DRAFT_EPOCH, + gameDesignBytes, + gameDesignBytes, + gameDesign.digest(), + List.of(source())); + } + + private static DraftCommitBinding gameDesignBinding(List owners) { + List revisions = new ArrayList<>(); + List affectedUnits = new ArrayList<>(); + for (int index = 0; index < owners.size(); index++) { + Owner owner = owners.get(index); + revisions.add( + new RevisionPayload( + Integer.toString(index), + UUID.nameUUIDFromBytes(("revision-" + owner.name()).getBytes(StandardCharsets.UTF_8)), + owner, + "{}")); + affectedUnits.add( + new AffectedUnit( + owner, + "TEST_AGGREGATE", + owner.name().toLowerCase(java.util.Locale.ROOT), + "TEST_SCOPE", + "scope-" + owner.name().toLowerCase(java.util.Locale.ROOT), + "0")); + } + return DraftCommitBinding.create( + new TargetProof( + TENANT_ID, VERSION_ID, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + REQUEST_ID, + COMMIT_ID, + "base-source-1", + revisions, + affectedUnits); + } + + private static DraftAuthorizationFenceBinding.OwnerReadback ownerReadback( + DraftAuthorizationFenceBinding binding, + DraftAuthorizationFenceBinding.Owner owner, + byte[] result) { + return new DraftAuthorizationFenceBinding.OwnerReadback( + owner, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + result); + } + + private static byte[] goldenV2Bytes( + DraftAuthorizationFenceBinding binding, + List requiredOwners) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + appendFrame(output, DraftAuthorizationFenceBinding.SCHEMA_V2); + for (String value : + List.of( + binding.operationId().toString(), + binding.requestId().toString(), + binding.commitId().toString(), + binding.fenceId().toString(), + binding.actorAccountId().toString(), + binding.tenantId().toString(), + binding.versionId().toString(), + binding.baseCommitId(), + "DRAFT", + binding.expectedDraftEpoch())) { + appendFrame(output, value); + } + appendFrame(output, binding.gameDesignBinding()); + appendFrame(output, binding.normalizedInput()); + appendFrame(output, binding.inputDigest()); + appendFrame(output, Integer.toString(binding.sources().size())); + binding.sources().forEach(source -> appendFrame(output, source.canonicalBytes())); + appendFrame(output, Integer.toString(requiredOwners.size())); + requiredOwners.forEach(owner -> appendFrame(output, owner.name())); + return output.toByteArray(); + } + + private static byte[] goldenOwnerReadbackV1( + DraftAuthorizationFenceBinding binding, + DraftAuthorizationFenceBinding.Owner owner, + DraftAuthorizationFenceBinding.Outcome outcome, + byte[] result) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + for (String value : + List.of( + "account-draft-owner-readback/v1", + owner.name(), + outcome.name(), + binding.operationId().toString(), + binding.commitId().toString(), + binding.fenceId().toString(), + binding.inputDigest())) { + appendFrame(output, value); + } + appendFrame(output, binding.canonicalBytes()); + appendFrame(output, result); + return output.toByteArray(); + } + + private static SourceEvidence source() { + return new SourceEvidence( + SourceKind.GLOBAL_ROLES, + SOURCE_SCOPE_ID.toString(), + null, + LARGE_SOURCE_VERSION, + null, + null, + new byte[] {1, 2, 3}); + } + + private static SourceEvidence accountSource() { + return new SourceEvidence( + SourceKind.ACCOUNT, + "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee", + "1", + "2", + "account:source", + "0", + new byte[] {4, 5}); + } + + private static byte[] goldenBytes() { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + for (String value : + List.of( + "account-draft-authorization-fence/v1", + OPERATION_ID.toString(), + REQUEST_ID.toString(), + COMMIT_ID.toString(), + FENCE_ID.toString(), + ACTOR_ID.toString(), + TENANT_ID.toString(), + VERSION_ID.toString(), + "base-source-1", + "DRAFT", + EXPECTED_DRAFT_EPOCH)) { + appendFrame(output, value); + } + byte[] gameDesign = GAME_DESIGN_JSON.getBytes(StandardCharsets.UTF_8); + appendFrame(output, gameDesign); + appendFrame(output, gameDesign); + appendFrame(output, GAME_DESIGN_DIGEST); + appendFrame(output, "1"); + appendFrame(output, goldenSourceBytes()); + appendFrame(output, "GAME_DESIGN"); + appendFrame(output, "WORLD"); + return output.toByteArray(); + } + + private static byte[] goldenSourceBytes() { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + appendFrame(output, "account-draft-source-evidence/v1"); + appendFrame(output, "GLOBAL_ROLES"); + appendFrame(output, SOURCE_SCOPE_ID.toString()); + appendFrame(output, "ABSENT"); + appendFrame(output, LARGE_SOURCE_VERSION); + appendFrame(output, "ABSENT"); + appendFrame(output, new byte[] {1, 2, 3}); + return output.toByteArray(); + } + + private static List readFrames(byte[] stored) { + ByteBuffer input = ByteBuffer.wrap(stored); + List frames = new ArrayList<>(); + while (input.hasRemaining()) { + if (input.remaining() < Integer.BYTES) { + throw new IllegalArgumentException("Incomplete test frame"); + } + int length = input.getInt(); + if (length < 0 || length > input.remaining()) { + throw new IllegalArgumentException("Invalid test frame length"); + } + byte[] frame = new byte[length]; + input.get(frame); + frames.add(frame); + } + return frames; + } + + private static byte[] writeFrames(List frames) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + frames.forEach(frame -> appendFrame(output, frame)); + return output.toByteArray(); + } + + private static void appendFrame(ByteArrayOutputStream output, String value) { + appendFrame(output, utf8(value)); + } + + private static void appendFrame(ByteArrayOutputStream output, byte[] value) { + output.write((value.length >>> 24) & 0xff); + output.write((value.length >>> 16) & 0xff); + output.write((value.length >>> 8) & 0xff); + output.write(value.length & 0xff); + output.writeBytes(value); + } + + private static byte[] utf8(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static void assertInvalid(byte[] stored) { + assertThatThrownBy(() -> DraftAuthorizationFenceBinding.fromStored(stored)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java index 9fa31f1a28..e34958050f 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java @@ -529,6 +529,15 @@ void graph3RejectsMalformedOriginalAndAppliedInboundClosureVectors() throws Exce List> invalidClosures = List.of( closure -> closure.put("schemaVersion", 2), + closure -> closure.put("schemaVersion", "1"), + closure -> closure.put("unsupported", "opaque"), + closure -> closure.put("familyCounts", "opaque"), + closure -> + ((tools.jackson.databind.node.ObjectNode) familyCounts(closure).get(0)) + .put("count", -1), + closure -> + ((tools.jackson.databind.node.ObjectNode) familyCounts(closure).get(0)) + .put("members", "opaque"), closure -> familyCounts(closure).remove(6), closure -> ((tools.jackson.databind.node.ObjectNode) familyCounts(closure).get(1)) @@ -554,6 +563,31 @@ void graph3RejectsMalformedOriginalAndAppliedInboundClosureVectors() throws Exce } } + @Test + void graph3RejectsNullAndOpaqueClosureValuesInOriginalAndAppliedEvidence() throws Exception { + for (tools.jackson.databind.JsonNode closure : + List.of(JSON.getNodeFactory().nullNode(), JSON.getNodeFactory().textNode("opaque"))) { + assertGraph3Rejected( + graph3Fixture( + ignored -> {}, + ignored -> {}, + declaration -> declaration.set("inboundSourceClosure", closure), + ignored -> {}, + "3", + true, + true)); + assertGraph3Rejected( + graph3Fixture( + ignored -> {}, + ignored -> {}, + ignored -> {}, + graph -> graph.set("inboundSourceClosure", closure), + "3", + true, + true)); + } + } + private static Graph3Fixture graph3Fixture( Consumer changeSourceClosure, Consumer changeGraphClosure, diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredCoreAndSpawnReadClientLifecycleTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredCoreAndSpawnReadClientLifecycleTest.java new file mode 100644 index 0000000000..2c22d87c47 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredCoreAndSpawnReadClientLifecycleTest.java @@ -0,0 +1,344 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BooleanSupplier; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.TlsCertificateWatcher; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeClient; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryClient; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsClient; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.api.parallel.ResourceLock; +import org.junit.jupiter.api.parallel.Resources; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; + +/** + * Real file-watcher lifecycle proof with mocked channels, not a TLS handshake. The controlled + * self-signed Entity certificate satisfies only the spawn client's local constructor URI check; key + * and CA files are readable placeholders, never production credentials. + */ +class AuthoredCoreAndSpawnReadClientLifecycleTest { + private static final String TLS_RELOAD_PROPERTY = "firemud.grpc.tls-reload.enabled"; + + @ParameterizedTest + @EnumSource(ClientKind.class) + @Timeout(30) + @ResourceLock(Resources.SYSTEM_PROPERTIES) + void closeReleasesClientMonitorBeforeDrainingCertificateCallback( + ClientKind kind, @TempDir Path directory) throws Exception { + String previousReloadPolicy = System.getProperty(TLS_RELOAD_PROPERTY); + System.setProperty(TLS_RELOAD_PROPERTY, "true"); + CountDownLatch releaseClientMonitor = new CountDownLatch(1); + AtomicReference closeFailure = new AtomicReference<>(); + Thread monitorHolder = null; + Thread closeThread = null; + AbstractReloadingBlockingGrpcClient client = null; + TlsCertificateWatcher originalWatcher = null; + List channels = new CopyOnWriteArrayList<>(); + try { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("world.internal:6565"); + CommonGrpcClientProperties tls = tls(directory); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + when(channelFactory.buildChannel( + any(String.class), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenAnswer( + invocation -> { + ManagedChannel channel = mock(ManagedChannel.class); + channels.add(channel); + return channel; + }); + ClientHandle handle = kind.create(endpoints, tls, channelFactory); + client = handle.client(); + handle.initialize().run(); + AbstractReloadingBlockingGrpcClient clientUnderTest = client; + + originalWatcher = watcher(client); + Set activeCallbacks = activeCallbacks(originalWatcher); + TlsCertificateWatcher closeBoundary = mock(TlsCertificateWatcher.class); + TlsCertificateWatcher delegatedWatcher = originalWatcher; + doAnswer( + invocation -> { + assertThat(Thread.holdsLock(clientUnderTest)) + .as("the client monitor must be released before watcher shutdown") + .isFalse(); + delegatedWatcher.close(); + return null; + }) + .when(closeBoundary) + .close(); + setWatcher(clientUnderTest, closeBoundary); + CountDownLatch clientMonitorHeld = new CountDownLatch(1); + monitorHolder = + new Thread( + () -> { + synchronized (clientUnderTest) { + clientMonitorHeld.countDown(); + awaitLatch(releaseClientMonitor); + } + }, + "authored-core-spawn-client-monitor-holder"); + monitorHolder.start(); + assertThat(clientMonitorHeld.await(5, TimeUnit.SECONDS)).isTrue(); + + CountDownLatch closeStarted = new CountDownLatch(1); + Thread closeWorker = + new Thread( + () -> { + closeStarted.countDown(); + try { + clientUnderTest.close(); + } catch (Throwable failure) { + closeFailure.set(failure); + } + }, + "authored-core-spawn-client-close"); + closeThread = closeWorker; + closeWorker.start(); + assertThat(closeStarted.await(5, TimeUnit.SECONDS)).isTrue(); + awaitCondition(() -> closeWorker.getState() == Thread.State.BLOCKED); + + Files.writeString(Path.of(tls.getCertChain()), "certificate-rotated"); + Thread callback = awaitBlockedReloadCallback(activeCallbacks); + assertThat(callback).isNotNull(); + + releaseClientMonitor.countDown(); + closeWorker.join(TimeUnit.SECONDS.toMillis(4)); + assertThat(closeWorker.isAlive()) + .as("close must not hold the client monitor while the watcher drains its callback") + .isFalse(); + assertThat(closeFailure.get()).isNull(); + + clientUnderTest.close(); + assertThatThrownBy(() -> handle.initialize().run()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("closed"); + assertThat(channels).isNotEmpty(); + for (ManagedChannel channel : channels) { + verify(channel, times(1)).shutdown(); + } + } finally { + releaseClientMonitor.countDown(); + if (monitorHolder != null) { + monitorHolder.join(TimeUnit.SECONDS.toMillis(5)); + } + if (closeThread != null) { + closeThread.join(TimeUnit.SECONDS.toMillis(7)); + } + try { + if (originalWatcher != null) { + originalWatcher.close(); + } + } finally { + try { + if (client != null) { + if (originalWatcher != null) { + setWatcher(client, originalWatcher); + } + client.close(); + } + } finally { + restoreReloadPolicy(previousReloadPolicy); + } + } + } + } + + @FunctionalInterface + private interface Initialize { + void run() throws Exception; + } + + private record ClientHandle( + AbstractReloadingBlockingGrpcClient client, Initialize initialize) {} + + private enum ClientKind { + AUTHORED_CORE, + SPAWN_REQUIREMENTS, + WORLD_SELECTED_FREEZE, + WORLD_SELECTED_INVENTORY; + + ClientHandle create( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory factory) { + return switch (this) { + case AUTHORED_CORE -> { + var client = new GrpcAuthoredInitialActorCoreReadClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case SPAWN_REQUIREMENTS -> { + var client = new WorldPublishedSpawnRequirementsClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case WORLD_SELECTED_FREEZE -> { + var client = + new WorldSelectedDraftPublicationFreezeClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case WORLD_SELECTED_INVENTORY -> { + var client = + new WorldSelectedPublicationArtifactInventoryClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + }; + } + } + + private static Thread awaitBlockedReloadCallback(Set activeCallbacks) + throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (System.nanoTime() < deadline) { + for (Thread callback : activeCallbacks) { + if (callback.getState() == Thread.State.BLOCKED + && hasFrame(callback, "AbstractReloadingBlockingGrpcClient", "reloadChannel")) { + return callback; + } + } + Thread.sleep(10); + } + return null; + } + + private static boolean hasFrame(Thread thread, String className, String methodName) { + for (StackTraceElement frame : thread.getStackTrace()) { + if (frame.getClassName().endsWith(className) && frame.getMethodName().equals(methodName)) { + return true; + } + } + return false; + } + + private static void awaitCondition(BooleanSupplier condition) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (!condition.getAsBoolean() && System.nanoTime() < deadline) { + Thread.sleep(10); + } + assertThat(condition.getAsBoolean()).isTrue(); + } + + private static void awaitLatch(CountDownLatch latch) { + try { + latch.await(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + } + } + + private static TlsCertificateWatcher watcher(AbstractReloadingBlockingGrpcClient client) + throws ReflectiveOperationException { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("watcher"); + field.setAccessible(true); + return (TlsCertificateWatcher) field.get(client); + } + + private static void setWatcher( + AbstractReloadingBlockingGrpcClient client, TlsCertificateWatcher watcher) + throws ReflectiveOperationException { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("watcher"); + field.setAccessible(true); + field.set(client, watcher); + } + + @SuppressWarnings("unchecked") + private static Set activeCallbacks(TlsCertificateWatcher watcher) + throws ReflectiveOperationException { + Field field = TlsCertificateWatcher.class.getDeclaredField("activeCallbacks"); + field.setAccessible(true); + return (Set) field.get(watcher); + } + + private static CommonGrpcClientProperties tls(Path directory) throws Exception { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(entityCertificate(directory).toString()); + tls.setPrivateKey(Files.writeString(directory.resolve("client.key"), "private key").toString()); + tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "CA certificate").toString()); + return tls; + } + + /** Only the constructor's local Entity URI check uses this controlled certificate. */ + private static Path entityCertificate(Path directory) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase(java.util.Locale.ROOT).contains("windows") + ? "keytool.exe" + : "keytool"); + Path store = directory.resolve("entity.p12"); + Path output = directory.resolve("keytool.log"); + // Matches the existing spawn mTLS fixture's JDK keytool certificate-generation mechanism. + Process process = + new ProcessBuilder( + keytool.toString(), + "-genkeypair", + "-alias", + "entity", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=Controlled lifecycle Entity", + "-validity", + "1", + "-ext", + "SAN=URI:spiffe://firemud/ns/test/sa/entity-management-service", + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + "controlled-lifecycle", + "-keypass", + "controlled-lifecycle") + .redirectErrorStream(true) + .redirectOutput(output.toFile()) + .start(); + if (!process.waitFor(10, TimeUnit.SECONDS)) { + process.destroyForcibly(); + throw new IllegalStateException("Controlled lifecycle certificate generation timed out"); + } + if (process.exitValue() != 0) { + throw new IllegalStateException( + "Controlled lifecycle certificate generation failed: " + Files.readString(output)); + } + var keys = java.security.KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keys.load(input, "controlled-lifecycle".toCharArray()); + } + return Files.write(directory.resolve("client.crt"), keys.getCertificate("entity").getEncoded()); + } + + private static void restoreReloadPolicy(String previousValue) { + if (previousValue == null) { + System.clearProperty(TLS_RELOAD_PROPERTY); + } else { + System.setProperty(TLS_RELOAD_PROPERTY, previousValue); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadClientMtlsTest.java new file mode 100644 index 0000000000..891aa71d24 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadClientMtlsTest.java @@ -0,0 +1,62 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** File-backed workload-mTLS policy is enforced before any channel can be built. */ +class AuthoredInitialActorCoreReadClientMtlsTest { + @Test + void rejectsPlaintextClasspathAndMissingCredentialFilesBeforeChannelCreation(@TempDir Path dir) + throws Exception { + GrpcChannelFactory factory = mock(GrpcChannelFactory.class); + CommonGrpcClientProperties plaintext = fileBackedTls(dir); + plaintext.setPlaintext(true); + assertThatThrownBy(() -> newClient(plaintext, factory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload mTLS"); + + assertThatThrownBy(() -> newClient(new CommonGrpcClientProperties(), factory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + CommonGrpcClientProperties classpath = fileBackedTls(dir); + classpath.setCaCert("classpath:certs/ca.crt"); + assertThatThrownBy(() -> newClient(classpath, factory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + CommonGrpcClientProperties missingFiles = new CommonGrpcClientProperties(); + missingFiles.setCertChain(dir.resolve("missing-client.crt").toString()); + missingFiles.setPrivateKey(dir.resolve("missing-client.key").toString()); + missingFiles.setCaCert(dir.resolve("missing-ca.crt").toString()); + assertThatThrownBy(() -> newClient(missingFiles, factory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("readable file"); + verifyNoInteractions(factory); + } + + private static GrpcAuthoredInitialActorCoreReadClient newClient( + CommonGrpcClientProperties tls, GrpcChannelFactory factory) { + return new GrpcAuthoredInitialActorCoreReadClient( + new ServiceEndpointsProperties(), tls, factory, "test"); + } + + private static CommonGrpcClientProperties fileBackedTls(Path directory) throws IOException { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(Files.writeString(directory.resolve("client.crt"), "certificate").toString()); + tls.setPrivateKey(Files.writeString(directory.resolve("client.key"), "private key").toString()); + tls.setCaCert( + Files.writeString(directory.resolve("server-ca.crt"), "CA certificate").toString()); + return tls; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadClientTest.java new file mode 100644 index 0000000000..a55277a3d2 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadClientTest.java @@ -0,0 +1,101 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +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 net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence.ReadRequest; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AuthoredInitialActorCoreReadClientTest { + private static final String NAMESPACE = "test"; + + @AfterEach + void clearTransactionFlags() { + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void requiresExplicitInitializationExactNamespaceAndNoAmbientOwnerTransaction(@TempDir Path dir) + throws Exception { + GrpcChannelFactory factory = mock(GrpcChannelFactory.class); + var client = newClient(fileBackedTls(dir), factory); + var request = new ReadRequest(AuthoredInitialActorCoreReadTestFixture.request()); + + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + assertThatThrownBy( + () -> + client.read( + new ReadRequest(AuthoredInitialActorCoreReadTestFixture.request("other")))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("client identity"); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient transaction"); + verifyNoInteractions(factory); + } + + @Test + void initializesOnlyTheExplicitGameDesignEndpoint(@TempDir Path dir) throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("game-design.internal:6565"); + CommonGrpcClientProperties tls = fileBackedTls(dir); + GrpcChannelFactory factory = mock(GrpcChannelFactory.class); + ManagedChannel channel = mock(ManagedChannel.class); + when(factory.buildChannel( + eq("game-design.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true))) + .thenReturn(channel); + var client = new GrpcAuthoredInitialActorCoreReadClient(endpoints, tls, factory, NAMESPACE); + + try { + client.init(); + verify(factory) + .buildChannel( + eq("game-design.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true)); + } finally { + client.close(); + } + } + + private static GrpcAuthoredInitialActorCoreReadClient newClient( + CommonGrpcClientProperties tls, GrpcChannelFactory factory) { + return new GrpcAuthoredInitialActorCoreReadClient( + new ServiceEndpointsProperties(), tls, factory, NAMESPACE); + } + + private static CommonGrpcClientProperties fileBackedTls(Path directory) throws IOException { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(Files.writeString(directory.resolve("client.crt"), "certificate").toString()); + tls.setPrivateKey(Files.writeString(directory.resolve("client.key"), "private key").toString()); + tls.setCaCert( + Files.writeString(directory.resolve("server-ca.crt"), "CA certificate").toString()); + return tls; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadEvidenceTest.java new file mode 100644 index 0000000000..61f1d915a5 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadEvidenceTest.java @@ -0,0 +1,586 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Audience; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Disposition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Feedback; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Visibility; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +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.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.gamedesign.v1.ParticipantDigest; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class AuthoredInitialActorCoreReadEvidenceTest { + @Test + void completeResultBindsTheExactAssociationDescriptorAndOrderedProjectionSet() throws Exception { + var fixture = AuthoredInitialActorCoreReadTestFixture.create(); + var projection = fixture.projection(UUID.fromString("1e9c2424-5669-4b6a-8f8f-7b452ab64c62")); + var result = fixture.result(List.of(projection)); + + assertThat(result.request()).isEqualTo(fixture.request()); + assertThat(result.associationRead()).isEqualTo(fixture.associationRead()); + assertThat(result.descriptor()).isEqualTo(fixture.descriptor()); + assertThat(result.projections()).containsExactly(projection); + assertThat(projection.worldSourceOperationId()) + .isEqualTo(fixture.associationRead().association().sourceOperationId()); + assertThat(projection.worldSourceEvidenceDigest()) + .isEqualTo(fixture.associationRead().association().sourceEvidenceDigest()); + assertThat(projection.worldSlug()) + .isEqualTo(fixture.associationRead().association().worldSlug()); + assertThat(projection.publicationWorkflowId()) + .isEqualTo(fixture.associationRead().association().publishWorkflowId()); + assertThat(projection.canonicalTenantId()) + .isEqualTo(fixture.associationRead().association().canonicalTenantId()); + assertThat(projection.canonicalVersionId()) + .isEqualTo(fixture.associationRead().association().canonicalVersionId()); + assertThat(projection.selectedCommitId()) + .isEqualTo(fixture.associationRead().association().selectedCommitId()); + assertThat(result.canonicalBytes()).isNotEmpty(); + assertThat(result.digest()).startsWith("sha256:"); + } + + @Test + void refusesDuplicateProjectionBindingIds() throws Exception { + var fixture = AuthoredInitialActorCoreReadTestFixture.create(); + UUID bindingId = UUID.fromString("2e9c2424-5669-4b6a-8f8f-7b452ab64c62"); + var first = fixture.projection(bindingId); + var duplicate = fixture.projection(bindingId); + + assertThatThrownBy(() -> fixture.result(List.of(first, duplicate))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Projection differs from exact association or descriptor"); + } + + @Test + void refusesAValidProjectionCorrelatedToAnotherWorldSourceOperation() throws Exception { + var fixture = AuthoredInitialActorCoreReadTestFixture.create(); + var projection = + fixture.projection( + UUID.fromString("3e9c2424-5669-4b6a-8f8f-7b452ab64c62"), + UUID.fromString("4e9c2424-5669-4b6a-8f8f-7b452ab64c62")); + assertThat(projection.worldSourceOperationId()) + .isNotEqualTo(fixture.associationRead().association().sourceOperationId()); + + assertThatThrownBy(() -> fixture.result(List.of(projection))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Projection differs from exact association or descriptor"); + } + + @Test + void refusesInitialSelectionAsActorCoreReadAuthority() throws Exception { + var fixture = AuthoredInitialActorCoreReadTestFixture.create(); + var initial = + new Request( + fixture.request().schemaVersion(), + fixture.request().targetNamespace(), + fixture.request().readRequestId(), + fixture.request().canonicalPostAuthorizationTuple(), + fixture.request().ownerAttemptId(), + fixture.request().ownerFence(), + new StartSessionTemplateAssociationReadEvidence.InitialConfigured()); + + assertThatThrownBy(() -> new AuthoredInitialActorCoreReadEvidence.ReadRequest(initial)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Exact pinned association replay"); + } +} + +/** Shared, owner-shaped value fixture for the directly owning Common transport tests. */ +final class AuthoredInitialActorCoreReadTestFixture { + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID ACTOR = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + 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 INTAKE_ID = uuid("04444444-4444-4444-8444-444444444444"); + private static final UUID WORLD_OPERATION_ID = uuid("05555555-5555-4555-8555-555555555555"); + private static final UUID SOURCE_OPERATION_ID = uuid("06666666-6666-4666-8666-666666666666"); + private static final UUID WORLD_READ_ID = uuid("07777777-7777-4777-8777-777777777777"); + private static final UUID RESERVATION_OWNER = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID ISSUANCE_ID = uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = uuid("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final String NAMESPACE = "test"; + private static final String WORKFLOW = "selected-publication-workflow"; + private static final String WORLD_SLUG = "synthetic-world"; + private static final long TEMPLATE_ID = 19L; + private static final UUID POLICY_REVISION = uuid("13333333-3333-4333-8333-333333333333"); + private static final UUID DISPOSITION_REVISION = uuid("14444444-4444-4444-8444-444444444444"); + private static final UUID FEEDBACK_REVISION = uuid("15555555-5555-4555-8555-555555555555"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private AuthoredInitialActorCoreReadTestFixture() {} + + static Fixture create() throws Exception { + var worldEvidence = AuthoredWorldReleaseAttestationSelectorTest.selectorEvidence(); + UUID tenant = worldEvidence.request().canonicalTenantId(); + UUID version = worldEvidence.request().canonicalVersionId(); + UUID commit = uuid(worldEvidence.request().appliedCommitId()); + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, INTAKE_ID, tenant, "tenant-key", WORLD_SLUG, "Synthetic World"); + String sourceEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + INTAKE_ID, + SOURCE_OPERATION_ID, + sourceRequestDigest, + tenant, + "tenant-key", + WORLD_SLUG, + "Synthetic World", + 42L, + "tenant-key", + "NEW_GAME_ROW"); + var source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + INTAKE_ID, + SOURCE_OPERATION_ID, + sourceRequestDigest, + tenant, + "tenant-key", + WORLD_SLUG, + "Synthetic World", + 42L, + "tenant-key", + "NEW_GAME_ROW", + sourceEvidenceDigest); + var intake = + new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( + 1, NAMESPACE, INTAKE_ID, tenant, WORLD_SLUG, SOURCE_OPERATION_ID, sourceEvidenceDigest); + var receipt = + new WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt( + 1, + NAMESPACE, + INTAKE_ID, + WORLD_OPERATION_ID, + tenant, + WORLD_SLUG, + SOURCE_OPERATION_ID, + sourceEvidenceDigest, + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(intake), + digest('e'), + source); + var worldRead = + new WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest( + 1, NAMESPACE, WORLD_READ_ID, INTAKE_ID, tenant); + var association = + new StartSessionTemplateAssociationReadEvidence.Association( + tenant, + TEMPLATE_ID, + version, + commit, + worldEvidence.request().publishWorkflowId(), + digest('c'), + digest('a'), + NAMESPACE, + INTAKE_ID, + WORLD_OPERATION_ID, + SOURCE_OPERATION_ID, + WORLD_SLUG, + sourceEvidenceDigest, + worldRead, + receipt); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + "actor-core-original-start-session", + tenant, + WORLD_SLUG, + SOURCE_OPERATION_ID, + sourceEvidenceDigest, + TEMPLATE_ID, + false, + null, + false, + null, + false, + null, + true, + "{}"); + var descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "descriptor-1", + 42L, + false, + null, + "{}", + "generation", + 9L, + 7L, + "release-1", + false, + null); + var releaseEvidence = + AuthoredWorldReleaseAttestationSelectorTest.release(descriptor, worldEvidence); + PublishedReleaseBundle.Builder release = + PublishedReleaseBundle.newBuilder() + .setId(7L) + .setVersionId(42L) + .setVersionNumber(1) + .setAttestationSchemaVersion("v2") + .setPublishWorkflowId(worldEvidence.request().publishWorkflowId()) + .setManifestHash(releaseEvidence.manifestHash()) + .setManifestSchemaVersion(releaseEvidence.manifestSchemaVersion()) + .addAllRequiredManifestAssetKeys(releaseEvidence.requiredManifestAssetKeys()) + .setGenerationConfigRevision(releaseEvidence.generationConfigRevision()) + .setPublishedReleaseBundleRef(releaseEvidence.publishedReleaseBundleRef()) + .setCanonicalTenantId(tenant.toString()) + .setCanonicalVersionId(version.toString()) + .addAllCommandDefinitions(releaseEvidence.commandDefinitions()); + for (var participant : releaseEvidence.participantDigests()) { + ParticipantDigest.Builder item = + ParticipantDigest.newBuilder() + .setParticipantKey(participant.participantKey()) + .setScopeValue(participant.scopeValue()) + .setAppliedCommitId(participant.appliedCommitId()) + .setContentDigest(participant.contentDigest()) + .setDigestSchemaVersion(participant.digestSchemaVersion()); + if (participant.abilitySchemaDigestPresent()) { + item.setAbilitySchemaDigest(participant.abilitySchemaDigest()); + } + release.addParticipantDigests(item); + } + var request = + new Request( + 1, + NAMESPACE, + READ_ID, + postTuple(tenant, NAMESPACE).canonicalBytes(), + ATTEMPT, + 8L, + new ExactReplay( + version, + commit, + worldEvidence.request().publishWorkflowId(), + association.associationDigest())); + var associationRead = + new StartSessionTemplateAssociationReadEvidence.Result( + request, association, release.build(), worldEvidence, 23L); + return new Fixture(request, associationRead, descriptor, source); + } + + static StartSessionTemplateAssociationReadEvidence.Request request() throws Exception { + return create().request(); + } + + static StartSessionTemplateAssociationReadEvidence.Request request(String namespace) + throws Exception { + var original = create().request(); + return new Request( + original.schemaVersion(), + namespace, + original.readRequestId(), + postTuple( + original.decodedTuple().preAuthorizationTuple().action().scope().tenantId(), + namespace) + .canonicalBytes(), + original.ownerAttemptId(), + original.ownerFence(), + original.selection()); + } + + private static AuthoredInitialActorCoreSourceBinding sourceBinding( + Fixture fixture, UUID worldSourceOperationId) { + var association = fixture.associationRead().association(); + var policy = + RealmEntryPolicy.parse( + "{\"schemaVersion\":3,\"worldSlug\":\"" + + association.worldSlug() + + "\",\"worldDisplayName\":\"Synthetic World\"," + + "\"realmSlug\":\"realm\",\"realmDisplayName\":\"Realm\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\"," + + "\"entryPolicy\":\"PLAYER_CREATED\",\"creationDescriptor\":{" + + "\"schemaVersion\":1,\"descriptorId\":\"aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa\"," + + "\"descriptorRevisionId\":\"bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb\"," + + "\"inputKind\":\"EMPTY_OBJECT\",\"dependencies\":[]}," + + "\"initialActorCore\":{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}}", + JSON); + var policyPayload = + RealmPolicySource.canonical( + Map.of( + "revisionKind", + RealmPolicySource.REVISION_KIND, + "logicalRevisionId", + "policy-logical-r1", + "policy", + RealmPolicySource.tree(policy.canonicalJson()))); + var disposition = new Disposition("newcomer", List.of(), "welcome"); + var feedback = + new Feedback( + "welcome", + "actor_created", + Audience.SOURCE_ACTOR, + "welcome_message", + "Welcome, traveler.", + List.of(), + Visibility.PUBLIC, + GameplayRuleManifest.ReplayPolicy.EFFECT_IDEMPOTENT); + List revisions = + List.of( + new RevisionPayload( + "0", POLICY_REVISION, Owner.GAME_DESIGN_CONTROL_PLANE, policyPayload), + new RevisionPayload( + "1", + DISPOSITION_REVISION, + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload(disposition)), + new RevisionPayload( + "2", + FEEDBACK_REVISION, + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload(feedback))); + TargetProof target = + new TargetProof( + association.canonicalTenantId(), + association.canonicalVersionId(), + 23L, + "tenant-key", + 42L, + "tenant-key", + "NEW_GAME_ROW"); + DraftCommitBinding commit = + DraftCommitBinding.create( + target, + uuid("1eeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + association.selectedCommitId(), + "base-0", + revisions, + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + association.canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + "0"), + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.SCOPE, + association.canonicalVersionId().toString(), + GameplayRuleSource.SCOPE, + GameplayRuleSource.SCOPE_ID, + "0"))); + var selectedPolicy = RealmPolicySource.revision(commit, revisions.getFirst()); + var policySnapshot = new RealmPolicySnapshot(commit, "1", List.of(selectedPolicy)); + var dispositionEntry = + new GameplayRuleSource.Entry( + Family.DISPOSITIONS, disposition, commit, "1", DISPOSITION_REVISION); + var feedbackEntry = + new GameplayRuleSource.Entry(Family.FEEDBACK, feedback, commit, "2", FEEDBACK_REVISION); + var gameplay = + new GameplayRuleSelectedSource( + gameplaySnapshot(commit, List.of(dispositionEntry, feedbackEntry))); + return AuthoredInitialActorCoreSourceBinding.resolveAll( + worldSourceOperationId, + association.sourceEvidenceDigest(), + association.worldSlug(), + association.publishWorkflowId(), + bytes("selected publication operation bytes"), + bytes("selected release terminal evidence"), + commit, + policySnapshot, + gameplay) + .getFirst(); + } + + private static String gameplaySnapshot( + DraftCommitBinding binding, List entries) { + Map families = new java.util.LinkedHashMap<>(); + for (Family family : Family.values()) { + families.put( + family.name(), + entries.stream() + .filter(value -> value.family() == family) + .map(GameplayRuleSource.Entry::definition) + .toList()); + } + var manifest = + GameplayRuleManifest.fromStored( + GameplayRuleManifest.canonical( + Map.of("schema", GameplayRuleManifest.SCHEMA, "families", families))); + Map snapshot = new java.util.LinkedHashMap<>(); + snapshot.put("schema", "game-design-gameplay-rule-source-snapshot/v1"); + snapshot.put("bindingJson", binding.canonicalJson()); + snapshot.put("bindingDigest", binding.digest()); + snapshot.put("sourceEpoch", "1"); + snapshot.put("inheritedCommitId", ""); + snapshot.put("genesisReceiptId", "77777777-7777-4777-8777-777777777777"); + snapshot.put("manifestJson", manifest.canonicalJson()); + snapshot.put( + "entries", + entries.stream() + .map( + entry -> + Map.of( + "family", entry.family().name(), + "definitionJson", GameplayRuleManifest.canonical(entry.definition()), + "sourceBindingJson", entry.sourceBinding().canonicalJson(), + "sourceBindingDigest", entry.sourceBinding().digest(), + "revisionOrder", entry.revisionOrder(), + "revisionId", entry.revisionId().toString())) + .toList()); + return CommandSource.canonical(snapshot); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static StartSessionPostAuthorizationExecutionTuple postTuple( + UUID tenant, String namespace) { + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman( + "actor-core-original-start-session", + ACTOR, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(tenant, namespace), + new StartSessionOperatorAction.Target(TEMPLATE_ID, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "exact original selected authored actor core")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + RESERVATION_OWNER, + 19L, + authorityBundle(pre, tenant, namespace), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle( + StartSessionPreAuthorizationReservationTuple tuple, UUID tenant, String namespace) { + String tenantText = tenant.toString(); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantText, "targetNamespace", namespace), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", tenantText), + "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(tenantText, 3L), + "membershipAuthorityGeneration", Map.of(tenantText, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", + Map.of(tenantText, 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 net.firedevops.firemud.common.json.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); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + record Fixture( + Request request, + Result associationRead, + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldSourceEvidence source) { + AuthoredInitialActorCoreReadEvidence.ReadResult result() { + return result(List.of(projection(uuid("0e9c2424-5669-4b6a-8f8f-7b452ab64c62")))); + } + + AuthoredInitialActorCoreReadEvidence.ReadResult result( + List projections) { + return new AuthoredInitialActorCoreReadEvidence.ReadResult( + request, associationRead, descriptor, projections); + } + + AuthoredInitialActorCoreProjection projection(UUID bindingId) { + return projection(bindingId, associationRead.association().sourceOperationId()); + } + + AuthoredInitialActorCoreProjection projection(UUID bindingId, UUID worldSourceOperationId) { + return AuthoredInitialActorCoreProjection.fromValidatedBinding( + bindingId, sourceBinding(this, worldSourceOperationId)); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadGrpcCodecTest.java new file mode 100644 index 0000000000..a41d74a8a9 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadGrpcCodecTest.java @@ -0,0 +1,150 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence.ReadRequest; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.gamedesign.v1.ReadAuthoredInitialActorCoreResponse; +import org.junit.jupiter.api.Test; + +class AuthoredInitialActorCoreReadGrpcCodecTest { + @Test + void roundTripsExactReadRequestAndCompleteCanonicalResult() throws Exception { + var fixture = AuthoredInitialActorCoreReadTestFixture.create(); + var request = new ReadRequest(fixture.request()); + var wireRequest = AuthoredInitialActorCoreReadGrpcCodec.toRequest(request); + var first = fixture.projection(UUID.fromString("5e9c2424-5669-4b6a-8f8f-7b452ab64c62")); + var second = fixture.projection(UUID.fromString("6e9c2424-5669-4b6a-8f8f-7b452ab64c62")); + var result = fixture.result(java.util.List.of(second, first)); + var response = AuthoredInitialActorCoreReadGrpcCodec.toResponse(result); + + var decoded = AuthoredInitialActorCoreReadGrpcCodec.fromResponse(fixture.request(), response); + + assertThat(AuthoredInitialActorCoreReadGrpcCodec.fromRequest(wireRequest)).isEqualTo(request); + assertThat(decoded.canonicalBytes()).containsExactly(result.canonicalBytes()); + assertThat(decoded.request()).isEqualTo(fixture.request()); + assertThat(decoded.associationRead()).isEqualTo(fixture.associationRead()); + assertThat(decoded.descriptor()).isEqualTo(fixture.descriptor()); + assertThat(decoded.projections()) + .extracting(AuthoredInitialActorCoreProjection::bindingId) + .containsExactly(second.bindingId(), first.bindingId()); + assertThat(decoded.projections()) + .extracting(AuthoredInitialActorCoreProjection::digest) + .containsExactly(second.digest(), first.digest()); + } + + @Test + void rejectsMissingInitialUnknownAndChangedExactRequestSelectors() throws Exception { + var fixture = AuthoredInitialActorCoreReadTestFixture.create(); + var wire = AuthoredInitialActorCoreReadGrpcCodec.toRequest(new ReadRequest(fixture.request())); + assertThatThrownBy( + () -> + AuthoredInitialActorCoreReadGrpcCodec.fromRequest( + wire.toBuilder().clearAssociationRequest().build())) + .isInstanceOf(IllegalArgumentException.class); + + var noSelection = + wire.toBuilder() + .setAssociationRequest( + wire.getAssociationRequest().toBuilder().clearSelection().build()) + .build(); + assertThatThrownBy(() -> AuthoredInitialActorCoreReadGrpcCodec.fromRequest(noSelection)) + .isInstanceOf(IllegalArgumentException.class); + + var unknown = + wire.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(88, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertThatThrownBy(() -> AuthoredInitialActorCoreReadGrpcCodec.fromRequest(unknown)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + + var changedSelector = + wire.toBuilder() + .setAssociationRequest( + wire.getAssociationRequest().toBuilder() + .setExactReplay( + wire.getAssociationRequest().getExactReplay().toBuilder() + .setSelectedCommitId(UUID.randomUUID().toString()) + .build()) + .build()) + .build(); + assertThat(AuthoredInitialActorCoreReadGrpcCodec.fromRequest(changedSelector)) + .isNotEqualTo(AuthoredInitialActorCoreReadGrpcCodec.fromRequest(wire)); + } + + @Test + void rejectsChangedEchoCanonicalBytesDigestAndUnknownNestedFields() throws Exception { + var fixture = AuthoredInitialActorCoreReadTestFixture.create(); + ReadAuthoredInitialActorCoreResponse response = + AuthoredInitialActorCoreReadGrpcCodec.toResponse(fixture.result()); + + assertThatThrownBy( + () -> + AuthoredInitialActorCoreReadGrpcCodec.fromResponse( + changedRequest(fixture.request()), response)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact request echo"); + assertThatThrownBy( + () -> + AuthoredInitialActorCoreReadGrpcCodec.fromResponse( + fixture.request(), + response.toBuilder() + .setCanonicalResultBytes(com.google.protobuf.ByteString.copyFromUtf8("{}")) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical complete content"); + assertThatThrownBy( + () -> + AuthoredInitialActorCoreReadGrpcCodec.fromResponse( + fixture.request(), + response.toBuilder().setResultDigest("sha256:" + "0".repeat(64)).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical complete content"); + + var unknownNested = + response.toBuilder() + .setLaunchDescriptor( + response.getLaunchDescriptor().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(89, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build()) + .build(); + assertThatThrownBy( + () -> + AuthoredInitialActorCoreReadGrpcCodec.fromResponse( + fixture.request(), unknownNested)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + } + + private static net.firedevops.firemud.common.gamedesign + .StartSessionTemplateAssociationReadEvidence.Request + changedRequest( + net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence + .Request + request) { + var replay = (ExactReplay) request.selection(); + return new net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence + .Request( + request.schemaVersion(), + request.targetNamespace(), + request.readRequestId(), + request.canonicalPostAuthorizationTuple(), + request.ownerAttemptId(), + request.ownerFence() + 1L, + new ExactReplay( + replay.canonicalVersionId(), + replay.selectedCommitId(), + replay.publishWorkflowId(), + replay.associationDigest())); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java index a0d3a67a2c..675196d45d 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java @@ -108,6 +108,85 @@ void v3BindsClosureQualifiedWorldSchema4InItsOwnDomainAndSurvivesStoredReadback( .hasMessageContaining("Participant digest schema is unsupported"); } + @Test + void v4BindsTheExactSelectedFullParticipantVectorInANewDomain() throws Exception { + var selector = selectorEvidence(4); + var descriptor = descriptor(selector); + var release = + release( + descriptor, + selector, + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); + var stored = JSON.writeValueAsString(release); + var readback = JSON.readValue(stored, AuthoredWorldReleaseAttestationEvidence.class); + + assertThat(release.schemaVersion()) + .isEqualTo(AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); + assertThat(release.participantDigests()) + .extracting(AuthoredWorldReleaseAttestationEvidence.Participant::digestSchemaVersion) + .containsExactly(4, 3, 1, 6, 2); + assertThat(readback).isEqualTo(release); + readback.requireValid(descriptor); + assertThat( + new String( + AuthoredWorldReleaseAttestationEvidence.evidencePreimage(release), + StandardCharsets.UTF_8)) + .startsWith("49:game-design-authored-world-release-attestation/v4") + .contains("worldStartLocationEvidence.canonicalBytesBase64") + .endsWith(Base64.getEncoder().encodeToString(selector.canonicalBytes())); + + for (String mixedOwner : + List.of( + "WORLD_MANAGEMENT", + "ENTITY_MANAGEMENT", + "AUTOMATION_SCRIPTING", + "GAME_DESIGN_CONTROL_PLANE")) { + var mixedParticipants = + release.participantDigests().stream() + .map( + participant -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionIdPresent(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + mixedOwner.equals(participant.participantKey()) + ? participant.digestSchemaVersion() - 1 + : participant.digestSchemaVersion(), + participant.abilitySchemaDigestPresent(), + participant.abilitySchemaDigest())) + .toList(); + assertThatThrownBy( + () -> + AuthoredWorldReleaseAttestationEvidence.createSelectedFull( + release.targetNamespace(), + release.descriptorResultDigest(), + release.canonicalTenantId(), + release.canonicalVersionId(), + release.worldSlug(), + release.authoredWorldSourceOperationId(), + release.authoredWorldSourceEvidenceDigest(), + release.launchDescriptorId(), + release.publishedReleaseBundleRef(), + release.versionStateEpoch(), + release.publishWorkflowId(), + release.commitId(), + mixedParticipants, + release.manifestHash(), + release.manifestSchemaVersion(), + release.requiredManifestAssetKeys(), + release.artifactDigests(), + release.commandDefinitions(), + release.generationConfigRevision(), + selector)) + .as("selected-full refuses retained participant schema for %s", mixedOwner) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Participant digest schema is unsupported"); + } + } + @Test void terminalReleaseProjectionAcceptsExactV2AndV3OwnerSchemasAndRejectsMixedSchemas() throws Exception { @@ -179,6 +258,19 @@ private static GameDesignPublicationTerminalEvidence.ReleaseContent terminalRele attestation.worldStartLocationEvidence()); } + @Test + void retainedV1CanonicalByteVectorKeepsItsOriginalDigest() { + var evidence = retainedV1EvidenceVector(); + + assertThat(evidence.evidenceDigest()) + .isEqualTo("sha256:54d38e2af416b25c0c3d05495853124eedd885ed725046052a71e3cc0a6d87e5"); + assertThat( + new String( + AuthoredWorldReleaseAttestationEvidence.evidencePreimage(evidence), + StandardCharsets.UTF_8)) + .startsWith("49:game-design-authored-world-release-attestation/v1"); + } + @Test void v1BytesAndDigestRemainUnchangedAndCannotBePromotedBySupplyingASelector() throws Exception { var selector = selectorEvidence(); @@ -311,6 +403,57 @@ void selectedAttestationRejectsRetainedSchemaOneControlPlaneEvidence() throws Ex .hasMessageContaining("Participant digest schema is unsupported"); } + private static AuthoredWorldReleaseAttestationEvidence retainedV1EvidenceVector() { + var participants = + List.of( + new AuthoredWorldReleaseAttestationEvidence.Participant( + "WORLD_MANAGEMENT", "7", false, null, "commit", "1".repeat(64), 3, false, null), + new AuthoredWorldReleaseAttestationEvidence.Participant( + "ENTITY_MANAGEMENT", "7", false, null, "commit", "2".repeat(64), 2, false, null), + new AuthoredWorldReleaseAttestationEvidence.Participant( + "GAME_LOGIC", + "7", + false, + null, + "commit", + "3".repeat(64), + 1, + true, + "sha256:" + "c".repeat(64)), + new AuthoredWorldReleaseAttestationEvidence.Participant( + "AUTOMATION_SCRIPTING", "7", false, null, "commit", "4".repeat(64), 5, false, null), + new AuthoredWorldReleaseAttestationEvidence.Participant( + "GAME_DESIGN_CONTROL_PLANE", + "7", + false, + null, + "commit", + "5".repeat(64), + 1, + false, + null)); + return AuthoredWorldReleaseAttestationEvidence.create( + "test", + "sha256:" + "a".repeat(64), + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + "synthetic-world", + UUID.fromString("33333333-3333-4333-8333-333333333333"), + "sha256:" + "b".repeat(64), + "descriptor", + "release", + 42L, + "workflow", + "commit", + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + "generation"); + } + private static List retainedV1Participants( List selected) { // Stipulated historical evidence, independently scoped to the retained-v1 contract. @@ -448,6 +591,30 @@ private static AuthoredWorldReleaseAttestationEvidence release( descriptor.generationConfigRevision(), selector); } + if (attestationSchemaVersion + == AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION) { + return AuthoredWorldReleaseAttestationEvidence.createSelectedFull( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + selector.request().canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selector.request().publishWorkflowId(), + selector.request().appliedCommitId(), + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of("LOOK"), + descriptor.generationConfigRevision(), + selector); + } return AuthoredWorldReleaseAttestationEvidence.create( descriptor.targetNamespace(), descriptor.resultDigest(), diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/TemplateConfigSourceSnapshotTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/TemplateConfigSourceSnapshotTest.java new file mode 100644 index 0000000000..64bdbfedad --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/TemplateConfigSourceSnapshotTest.java @@ -0,0 +1,456 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; + +class TemplateConfigSourceSnapshotTest { + private static final UUID TENANT = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID GENESIS = UUID.fromString("33333333-3333-4333-8333-333333333333"); + + @Test + void directDecoderPreservesV1BytesAndMissingDeclarationEvidence() throws Exception { + var config = new TemplateConfigSourceValues.Config(config()); + var original = binding(TemplateConfigSourceValues.createPayload("Starter", config)); + var entry = entry(original, "7", "Starter", config); + var selected = binding(); + String json = canonical(snapshotObject(selected, List.of(entry.object()), null)); + var decoded = TemplateConfigSourceSnapshot.fromStored(json); + assertThat(decoded.binding()).isEqualTo(selected); + assertThat(decoded.entries().getFirst().sourceBinding()).isEqualTo(original); + assertThat(decoded.ownerSourceInventoryDeclarations()).isEmpty(); + assertThat(decoded.canonicalJson()).isEqualTo(json); + assertThat(decoded.canonicalBytes()).isEqualTo(json.getBytes(StandardCharsets.UTF_8)); + assertThat(decoded.digest()).isEqualTo(digest(json)); + } + + @Test + void directV2DecoderKeepsOriginalDeclarationsSeparateFromSelectedIdentity() throws Exception { + var automation = AutomationAuthoredSourceInventoryDeclaration.parse(automationInventory()); + var entity = EntityAuthoredSourceInventoryDeclaration.parse(entityInventory()); + var authored = + binding( + TemplateConfigSourceValues.ownerInventoryPayload( + Owner.AUTOMATION_SCRIPTING, automation), + TemplateConfigSourceValues.ownerInventoryPayload(Owner.ENTITY_MANAGEMENT, entity)); + var declarations = + TemplateConfigSourceValues.mutations(authored).stream() + .map(TemplateConfigSourceValues.Mutation::ownerInventoryDeclaration) + .toList(); + var selected = binding(); + String json = + canonical( + snapshotObject( + selected, + List.of(), + declarations.stream() + .map(TemplateConfigOwnerSourceInventoryDeclaration::object) + .toList())); + var decoded = TemplateConfigSourceSnapshot.fromStored(json); + assertThat(decoded.binding()).isEqualTo(selected); + assertThat(decoded.ownerSourceInventoryDeclarations()).hasSize(2); + assertThat(decoded.ownerSourceInventoryDeclarations()) + .extracting(TemplateConfigOwnerSourceInventoryDeclaration::sourceBinding) + .containsExactly(authored, authored); + assertThat(decoded.ownerSourceInventoryDeclarations().get(0).inventory()).isEqualTo(automation); + assertThat(decoded.ownerSourceInventoryDeclarations().get(1).entityInventory()) + .isEqualTo(entity); + assertThat(decoded.canonicalJson()).isEqualTo(json); + assertThat(decoded.digest()).isEqualTo(digest(json)); + } + + @Test + void configRejectsIncompleteAmbiguousAndUnsupportedGrammar() { + String valid = config(); + for (String invalid : + List.of( + valid.replace("\"rooms\":[]", "\"rooms\":null"), + valid.replace("\"rooms\":[]", "\"unknown\":[]"), + valid.replace("\"inputs\":[]", "\"inputs\":[],\"receipt\":{}"), + valid.replace("\"inputs\":[]", "\"inputs\":[],\"commitDigest\":\"recursive\""), + valid.replace("\"inputs\":[]", "\"inputs\":[],\"bindingJson\":\"recursive\""), + valid.replace("\"schemaVersion\":1", "\"schemaVersion\":1,\"schemaVersion\":1"), + valid.replace("\"schemaVersion\":1", "\"schemaVersion\":2"), + valid.replace(VERSION.toString(), "00000000-0000-0000-0000-000000000000"), + valid.replace("\"items\":[]", "\"items\":[{\"entityTemplateId\":\"7\"}]"), + valid.replace("\"supportedSettings\":[]", "\"supportedSettings\":[{}]"), + valid.replace("\"presence\":\"ABSENT\"", "\"presence\":\"UNKNOWN\""), + valid.replace("\"presence\":\"ABSENT\"", "\"presence\":\"PRESENT\""), + valid + "{}")) { + assertThatThrownBy(() -> new TemplateConfigSourceValues.Config(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void ownerReferencePredicatesInspectEveryCollectionAndPresentPatchWithoutQualification() { + var empty = new TemplateConfigSourceValues.Config(config()); + assertThat(empty.hasWorldReferences()).isFalse(); + assertThat(empty.hasEntityReferences()).isFalse(); + assertThat(empty.hasAutomationReferences()).isFalse(); + for (String collection : List.of("regions", "rooms")) { + String key = collection.equals("regions") ? "regionTemplateId" : "roomTemplateId"; + assertThat( + new TemplateConfigSourceValues.Config( + config() + .replace( + "\"" + collection + "\":[]", + "\"" + collection + "\":[{\"" + key + "\":\"" + GENESIS + "\"}]")) + .hasWorldReferences()) + .isTrue(); + } + for (String collection : List.of("items", "npcs")) + assertThat( + new TemplateConfigSourceValues.Config( + config() + .replace( + "\"" + collection + "\":[]", + "\"" + + collection + + "\":[{\"entityTemplateId\":\"" + + GENESIS + + "\"}]")) + .hasEntityReferences()) + .isTrue(); + assertThat( + new TemplateConfigSourceValues.Config( + config() + .replace( + "\"scripts\":[]", + "\"scripts\":[{\"scriptId\":\"raw-script\",\"eventBindings\":[]}]")) + .hasAutomationReferences()) + .isTrue(); + assertThat( + new TemplateConfigSourceValues.Config( + config() + .replace( + "\"presence\":\"ABSENT\"", + "\"presence\":\"PRESENT\",\"scriptPatchVersion\":\" raw-patch \"")) + .hasAutomationReferences()) + .isTrue(); + } + + @Test + void configRejectsDuplicateReferencesInputsScriptsAndBindings() { + String item = "{\"entityTemplateId\":\"" + GENESIS + "\"}"; + String region = "{\"regionTemplateId\":\"" + GENESIS + "\"}"; + String input = + "{\"family\":\"ADMISSION_TAGS\",\"key\":\"entry\",\"revisionId\":\"" + GENESIS + "\"}"; + String event = + "{\"eventType\":\"onEnter\",\"eventSchemaVersion\":\"1\"," + + "\"bindingId\":\"binding-1\",\"targetScopeType\":\"ROOM\",\"targetScopeId\":\"\"}"; + String script = "{\"scriptId\":\"onEnter\",\"eventBindings\":[]}"; + String duplicateEvents = + "{\"scriptId\":\"onEnter\",\"eventBindings\":[" + event + "," + event + "]}"; + for (String invalid : + List.of( + config().replace("\"items\":[]", "\"items\":[" + item + "," + item + "]"), + config().replace("\"regions\":[]", "\"regions\":[" + region + "," + region + "]"), + config().replace("\"inputs\":[]", "\"inputs\":[" + input + "," + input + "]"), + config().replace("\"scripts\":[]", "\"scripts\":[" + script + "," + script + "]"), + config().replace("\"scripts\":[]", "\"scripts\":[" + duplicateEvents + "]"), + config() + .replace( + "\"scripts\":[]", "\"scripts\":[{\"scriptId\":\"x\",\"eventBindings\":null}]"), + config() + .replace( + "\"inputs\":[]", + "\"inputs\":[{\"family\":\"UNKNOWN\",\"key\":\"entry\",\"revisionId\":\"" + + GENESIS + + "\"}]"))) { + assertThatThrownBy(() -> new TemplateConfigSourceValues.Config(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + // The existing grammar permits an empty targetScopeId with nonempty binding and scope keys. + var valid = + new TemplateConfigSourceValues.Config( + config() + .replace( + "\"scripts\":[]", + "\"scripts\":[{\"scriptId\":\"onEnter\",\"eventBindings\":[" + event + "]}]")); + assertThat(valid.hasAutomationReferences()).isTrue(); + } + + @Test + void storedSnapshotRejectsClosedFieldsCollectionsCanonicalFormAndSchemaMismatch() + throws Exception { + var selected = binding(); + var value = snapshotObject(selected, List.of(), null); + String valid = canonical(value); + List invalid = + new ArrayList<>( + List.of( + valid + "{}", + " " + valid, + valid.replace("\"sourceEpoch\":\"1\"", "\"sourceEpoch\":\"01\""), + valid.replace("\"entries\":[]", "\"entries\":null"), + valid.replace("\"inheritedCommitId\":\"\"", "\"inheritedCommitId\":null"), + valid.replace(GENESIS.toString(), "00000000-0000-0000-0000-000000000000"), + valid.replace(TemplateConfigSourceSnapshot.SCHEMA, "unknown/v1"), + valid.replace("\"schema\":", "\"unknown\":0,\"schema\":"), + valid.replace( + "\"sourceEpoch\":\"1\"", "\"sourceEpoch\":\"1\",\"sourceEpoch\":\"1\""))); + var missing = new LinkedHashMap<>(value); + missing.remove("genesisReceiptId"); + invalid.add(canonical(missing)); + var emptyV2 = snapshotObject(selected, List.of(), List.of()); + invalid.add(canonical(emptyV2)); + var malformedV2 = new LinkedHashMap<>(emptyV2); + malformedV2.put("ownerSourceInventoryDeclarations", Map.of()); + invalid.add(canonical(malformedV2)); + var v1WithDeclarations = new LinkedHashMap<>(emptyV2); + v1WithDeclarations.put("schema", TemplateConfigSourceSnapshot.SCHEMA); + invalid.add(canonical(v1WithDeclarations)); + var wrongDigest = new LinkedHashMap<>(value); + wrongDigest.put("bindingDigest", "sha256:" + "0".repeat(64)); + String corruptBinding = canonical(wrongDigest); + assertThatThrownBy(() -> TemplateConfigSourceSnapshot.fromStored(corruptBinding)) + .isInstanceOf(IllegalStateException.class); + for (String json : invalid) + assertThatThrownBy(() -> TemplateConfigSourceSnapshot.fromStored(json)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void storedEntryRejectsOrderingDuplicatesTargetAndRevisionSubstitution() throws Exception { + var config = new TemplateConfigSourceValues.Config(config()); + var original = binding(TemplateConfigSourceValues.createPayload("Starter", config)); + var first = entry(original, "7", "Starter", config); + var second = entry(original, "8", "Starter", config); + var selected = binding(); + for (List> entries : + List.of( + List.of(first.object(), first.object()), List.of(second.object(), first.object()))) { + String json = canonical(snapshotObject(selected, entries, null)); + assertThatThrownBy(() -> TemplateConfigSourceSnapshot.fromStored(json)) + .isInstanceOf(IllegalArgumentException.class); + } + var altered = new LinkedHashMap<>(first.object()); + altered.put("revisionId", GENESIS.toString()); + String wrongRevision = canonical(snapshotObject(selected, List.of(altered), null)); + assertThatThrownBy(() -> TemplateConfigSourceSnapshot.fromStored(wrongRevision)) + .isInstanceOf(IllegalArgumentException.class); + altered.put("revisionId", first.revisionId().toString()); + altered.put("createdName", "Substituted"); + String wrongPayload = canonical(snapshotObject(selected, List.of(altered), null)); + assertThatThrownBy(() -> TemplateConfigSourceSnapshot.fromStored(wrongPayload)) + .isInstanceOf(IllegalArgumentException.class); + for (String key : + List.of( + "templateId", + "configJson", + "sourceBindingJson", + "sourceBindingDigest", + "revisionOrder", + "revisionId", + "createdName")) { + var missing = new LinkedHashMap<>(first.object()); + missing.remove(key); + String missingField = canonical(snapshotObject(selected, List.of(missing), null)); + assertThatThrownBy(() -> TemplateConfigSourceSnapshot.fromStored(missingField)) + .isInstanceOf(IllegalArgumentException.class); + } + var missingOperation = new LinkedHashMap<>(first.object()); + missingOperation.put("createdName", 1); + String nontextOperation = canonical(snapshotObject(selected, List.of(missingOperation), null)); + assertThatThrownBy(() -> TemplateConfigSourceSnapshot.fromStored(nontextOperation)) + .isInstanceOf(IllegalArgumentException.class); + var foreign = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + GENESIS, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit-0", + original.revisions(), + original.affectedUnits()); + altered = new LinkedHashMap<>(first.object()); + altered.put("sourceBindingJson", foreign.canonicalJson()); + altered.put("sourceBindingDigest", foreign.digest()); + String wrongTarget = canonical(snapshotObject(selected, List.of(altered), null)); + assertThatThrownBy(() -> TemplateConfigSourceSnapshot.fromStored(wrongTarget)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void declarationsRejectOwnerSchemaContentRevisionAndOrderSubstitution() throws Exception { + var inventory = AutomationAuthoredSourceInventoryDeclaration.parse(automationInventory()); + String payload = + TemplateConfigSourceValues.ownerInventoryPayload(Owner.AUTOMATION_SCRIPTING, inventory); + var authored = binding(payload); + var declaration = + TemplateConfigSourceValues.mutations(authored).getFirst().ownerInventoryDeclaration(); + var selected = binding(); + for (String invalid : + List.of( + payload.replace("\"schemaVersion\":2", "\"schemaVersion\":3"), + payload.replace("AUTOMATION_SCRIPTING", "ENTITY_MANAGEMENT"), + payload.replace("\"inventory\":", "\"unknown\":"), + payload.replace("\"SCRIPT_DEFINITIONS\":[]", "\"SCRIPT_DEFINITIONS\":[{}]"), + payload.replace( + "\"operation\":\"DECLARE_OWNER_SOURCE_INVENTORY\"", "\"operation\":\"UNKNOWN\""))) { + assertThatThrownBy(() -> TemplateConfigSourceValues.mutations(binding(invalid))) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy(() -> TemplateConfigSourceValues.mutations(binding(payload, payload))) + .isInstanceOf(IllegalArgumentException.class); + String duplicate = + canonical( + snapshotObject( + selected, List.of(), List.of(declaration.object(), declaration.object()))); + assertThatThrownBy(() -> TemplateConfigSourceSnapshot.fromStored(duplicate)) + .isInstanceOf(IllegalArgumentException.class); + var changed = new LinkedHashMap<>(declaration.object()); + changed.put("inventoryJson", entityInventory()); + String substituted = canonical(snapshotObject(selected, List.of(), List.of(changed))); + assertThatThrownBy(() -> TemplateConfigSourceSnapshot.fromStored(substituted)) + .isInstanceOf(IllegalArgumentException.class); + changed = new LinkedHashMap<>(declaration.object()); + changed.put("revisionOrder", "01"); + String wrongOrder = canonical(snapshotObject(selected, List.of(), List.of(changed))); + assertThatThrownBy(() -> TemplateConfigSourceSnapshot.fromStored(wrongOrder)) + .isInstanceOf(IllegalArgumentException.class); + changed = new LinkedHashMap<>(declaration.object()); + changed.put("revisionId", GENESIS.toString()); + String wrongRevision = canonical(snapshotObject(selected, List.of(), List.of(changed))); + assertThatThrownBy(() -> TemplateConfigSourceSnapshot.fromStored(wrongRevision)) + .isInstanceOf(IllegalArgumentException.class); + for (String key : + List.of( + "owner", + "inventoryJson", + "sourceBindingJson", + "sourceBindingDigest", + "revisionOrder", + "revisionId")) { + var missing = new LinkedHashMap<>(declaration.object()); + missing.remove(key); + String missingField = canonical(snapshotObject(selected, List.of(), List.of(missing))); + assertThatThrownBy(() -> TemplateConfigSourceSnapshot.fromStored(missingField)) + .isInstanceOf(IllegalArgumentException.class); + } + var entity = EntityAuthoredSourceInventoryDeclaration.parse(entityInventory()); + var both = + binding( + payload, + TemplateConfigSourceValues.ownerInventoryPayload(Owner.ENTITY_MANAGEMENT, entity)); + var declarations = + TemplateConfigSourceValues.mutations(both).stream() + .map(TemplateConfigSourceValues.Mutation::ownerInventoryDeclaration) + .toList(); + String reversed = + canonical( + snapshotObject( + selected, + List.of(), + List.of(declarations.get(1).object(), declarations.get(0).object()))); + assertThatThrownBy(() -> TemplateConfigSourceSnapshot.fromStored(reversed)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static TemplateConfigSourceValues.Entry entry( + DraftCommitBinding source, String id, String name, TemplateConfigSourceValues.Config config) { + var revision = source.revisions().getFirst(); + return new TemplateConfigSourceValues.Entry( + id, config, source, revision.revisionOrder(), revision.revisionId(), name); + } + + private static Map snapshotObject( + DraftCommitBinding selected, + List> entries, + List> declarations) { + var value = new LinkedHashMap(); + value.put( + "schema", + declarations == null + ? TemplateConfigSourceSnapshot.SCHEMA + : TemplateConfigSourceSnapshot.SCHEMA_V2); + value.put("bindingJson", selected.canonicalJson()); + value.put("bindingDigest", selected.digest()); + value.put("sourceEpoch", "1"); + value.put("inheritedCommitId", ""); + value.put("genesisReceiptId", GENESIS.toString()); + value.put("entries", entries); + if (declarations != null) value.put("ownerSourceInventoryDeclarations", declarations); + return value; + } + + private static String canonical(Object value) throws Exception { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(new ObjectMapper().writeValueAsString(value)), + StandardCharsets.UTF_8); + } + + private static String digest(String json) throws Exception { + return "sha256:" + + java.util.HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(json.getBytes(StandardCharsets.UTF_8))); + } + + private static String config() { + return "{\"schemaVersion\":1,\"baseVersionId\":\"" + + VERSION + + "\",\"world\":{\"regions\":[],\"rooms\":[]},\"entity\":{\"items\":[],\"npcs\":[]}," + + "\"gameLogic\":{\"inputs\":[]},\"automation\":{\"scripts\":[],\"scriptPatch\":{\"presence\":\"ABSENT\"}},\"supportedSettings\":[]}"; + } + + private static String automationInventory() { + return "{\"schema\":\"automation-authored-source-inventory/v1\",\"families\":" + + "{\"SCRIPT_DEFINITIONS\":[],\"EVENT_BINDINGS\":[],\"SCRIPT_PATCH_SOURCES\":[]}}"; + } + + private static String entityInventory() { + return "{\"schema\":\"entity-authored-source-inventory/v1\",\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":{" + + "\"ACTOR_BODY_LAYOUT_ASSIGNMENTS\":[],\"ARCHETYPE_ASSIGNMENTS\":[],\"ARCHETYPE_CONSTRAINTS\":[]," + + "\"ARCHETYPE_ROOTS\":[],\"BALANCE_CURVE_ATTACHMENTS\":[],\"BALANCE_CURVE_ROOTS\":[]," + + "\"BODY_LAYOUT_MEMBERSHIPS\":[],\"BODY_LAYOUT_ROOTS\":[],\"CRAFTING_INGREDIENT_BINDINGS\":[]," + + "\"CRAFTING_RECIPE_RESULT_BINDINGS\":[],\"CRAFTING_RECIPE_ROOTS\":[],\"EQUIPMENT_ATTACHMENT_RULES\":[]," + + "\"EQUIPMENT_CAPABILITIES\":[],\"EQUIPMENT_COMPATIBILITY_RULES\":[],\"EQUIPMENT_OCCUPANCY_RULES\":[]," + + "\"EQUIPMENT_SLOT_GROUPS\":[],\"EQUIPMENT_SLOT_ROOTS\":[],\"INBOUND_LOOT_BINDINGS\":[]," + + "\"ITEM_TEMPLATE_ROOTS\":[],\"LOOT_ITEM_MAPPINGS\":[],\"LOOT_TABLE_ROOTS\":[]," + + "\"NPC_TEMPLATE_ROOTS\":[],\"OTHER_ACTOR_TEMPLATE_ROOTS\":[]}}"; + } + + private static DraftCommitBinding binding(String... payloads) { + if (payloads.length == 0) payloads = new String[] {"{\"revisionKind\":\"COMMAND_DEFINITION\"}"}; + var revisions = new ArrayList(); + for (int i = 0; i < payloads.length; i++) + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(i), + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + payloads[i])); + return DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + TENANT, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit-0", + revisions, + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSourceValues.SCOPE, + VERSION.toString(), + TemplateConfigSourceValues.SCOPE, + TemplateConfigSourceValues.SCOPE_ID, + "0"))); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameDesignPublicationTerminalEvidenceCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameDesignPublicationTerminalEvidenceCodecTest.java index 6763a55fbe..413c70a3c6 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameDesignPublicationTerminalEvidenceCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameDesignPublicationTerminalEvidenceCodecTest.java @@ -9,6 +9,7 @@ import java.nio.charset.StandardCharsets; import java.util.Optional; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadRequest; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadResult; @@ -18,6 +19,128 @@ import org.junit.jupiter.api.Test; class GameDesignPublicationTerminalEvidenceCodecTest { + @Test + void selectedFullV4TerminalRoundTripsOnlyTheExactCompleteParticipantVector() throws Exception { + var fixture = PublishedRealmEntryPolicySetEvidenceTest.fixture(false); + var previous = fixture.terminal().releaseContent(); + var previousSelector = previous.worldStartLocationEvidence(); + var oldRequest = previousSelector.request(); + var selectorRequest = + new WorldPublishedStartLocationEvidence.Request( + oldRequest.targetNamespace(), + oldRequest.canonicalTenantId(), + oldRequest.canonicalVersionId(), + oldRequest.intakeRequestId(), + oldRequest.publicationFence(), + oldRequest.publicationRequestId(), + oldRequest.requestDigest(), + oldRequest.versionStateEpoch(), + oldRequest.publishWorkflowId(), + oldRequest.appliedCommitId(), + oldRequest.contentDigest(), + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION, + oldRequest.worldAffectedTuples()); + var selector = + new WorldPublishedStartLocationEvidence( + selectorRequest, + previousSelector.selectorReceiptBytes(), + previousSelector.originalAccountBindingBytes(), + previousSelector.appliedResultBytes()); + var operation = + new GameDesignPublicationOperationBinding( + fixture.operation().account(), + selector, + net.firedevops.firemud.test.IsolatedWorldPublicationInventoryFixtures.stipulated( + fixture.operation().account(), selector)); + var participants = + previous.participantDigests().stream() + .map( + participant -> + new GameDesignPublicationTerminalEvidence.Participant( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + participant.participantKey(), + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION), + participant.abilitySchemaDigest(), + participant.errorCode(), + participant.errorMessage())) + .toList(); + var release = + new GameDesignPublicationTerminalEvidence.ReleaseContent( + previous.canonicalTenantId(), + previous.canonicalVersionId(), + previous.publishedReleaseBundleRef(), + previous.versionNumber(), + "v4", + previous.publishWorkflowId(), + previous.manifestHash(), + previous.manifestSchemaVersion(), + previous.artifactDigests(), + previous.requiredManifestAssetKeys(), + participants, + previous.commandDefinitions(), + previous.generationConfigRevision(), + selector); + assertThat(participants) + .extracting(GameDesignPublicationTerminalEvidence.Participant::digestSchemaVersion) + .containsExactly(4, 3, 1, 6, 2); + + var terminal = + new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), + GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED, + release, + fixture.terminal().publicationVersionStateEpoch()); + var request = + new ReadRequest( + ReadRequest.SCHEMA_VERSION, + operation.world().request().targetNamespace(), + java.util.UUID.fromString("30303030-3030-4030-8030-303030303030"), + operation.canonicalBytes()); + var result = new ReadResult(request, Status.PUBLISHED, Optional.of(terminal)); + var response = GameDesignPublicationTerminalReadGrpcCodec.toResponse(request, result); + + assertThat(GameDesignPublicationTerminalReadGrpcCodec.fromResponse(request, response)) + .isEqualTo(result); + + var mixedParticipants = new java.util.ArrayList<>(participants); + mixedParticipants.set( + 3, + new GameDesignPublicationTerminalEvidence.Participant( + "AUTOMATION_SCRIPTING", + participants.get(3).scopeValue(), + null, + participants.get(3).appliedCommitId(), + participants.get(3).contentDigest(), + 5, + null, + null, + null)); + assertThatThrownBy( + () -> + new GameDesignPublicationTerminalEvidence.ReleaseContent( + previous.canonicalTenantId(), + previous.canonicalVersionId(), + previous.publishedReleaseBundleRef(), + previous.versionNumber(), + "v4", + previous.publishWorkflowId(), + previous.manifestHash(), + previous.manifestSchemaVersion(), + previous.artifactDigests(), + previous.requiredManifestAssetKeys(), + mixedParticipants, + previous.commandDefinitions(), + previous.generationConfigRevision(), + selector)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Incomplete or changed required participant proof"); + } + @Test void maximumFrozenEpochIsRejectedAsInvalidEvidenceAndOrdinaryEpochRoundTrips() throws Exception { var ordinary = PublishedRealmEntryPolicySetEvidenceTest.fixture(false); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClientMtlsTest.java new file mode 100644 index 0000000000..2fa794f011 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClientMtlsTest.java @@ -0,0 +1,546 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +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.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.Base64; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedSpawnRequirementsRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedSpawnRequirementsResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedSpawnRequirementsReadServiceGrpc; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Physical mTLS proof against a labeled transport-only World source double. */ +class WorldPublishedSpawnRequirementsClientMtlsTest { + private static final String NAMESPACE = "test"; + private static final String WORLD_URI = "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String OTHER_WORLD_URI = + "spiffe://firemud/ns/other-test/sa/world-management-service"; + private static final String WRONG_WORKLOAD_URI = + "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String ENTITY_URI = "spiffe://firemud/ns/test/sa/entity-management-service"; + private static final String WRONG_CLIENT_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + + @TempDir static Path tempDirectory; + private static TestPki pki; + private Server server; + private WorldPublishedSpawnRequirementsClient client; + private AtomicInteger headers; + private AtomicInteger bodies; + + @BeforeAll + static void createTrustedCertificates() throws Exception { + pki = TestPki.create(tempDirectory); + } + + @AfterEach + void stopTransport() throws Exception { + TransactionSynchronizationManager.clear(); + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void ambientTransactionAndSynchronizationAreRejectedBeforeTransport() throws Exception { + startServer(pki.worldServer(), Mode.EXACT); + client = newClient(server, pki.entityClient()); + client.init(); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.read(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("World spawn-requirements transport must run outside SQL"); + assertThat(headers).hasValue(0); + assertThat(bodies).hasValue(0); + + TransactionSynchronizationManager.clear(); + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> client.read(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("World spawn-requirements transport must run outside SQL"); + assertThat(headers).hasValue(0); + assertThat(bodies).hasValue(0); + } + + @Test + void exactWorldPeerReturnsUnchangedSourceCarrierAndExactRequestId() throws Exception { + var expected = WorldPublishedSpawnRequirementsGrpcCodecTest.evidence(); + startServer(pki.worldServer(), Mode.EXACT); + client = newClient(server, pki.entityClient()); + client.init(); + + var actual = client.read(expected.request()); + + assertThat(actual).isEqualTo(expected); + assertThat(actual.request().readRequestId()).isEqualTo(expected.request().readRequestId()); + assertThat(actual.familyCounts()).isEqualTo(expected.familyCounts()); + assertThat(actual.spawnRequirements()).isEqualTo(expected.spawnRequirements()); + assertThat(actual.generationRequirements()).isEqualTo(expected.generationRequirements()); + assertThat(headers).hasValue(1); + assertThat(bodies).hasValue(1); + } + + @Test + void trustedWrongWorldWorkloadAndNamespaceReleaseNoRequestMetadataOrBody() throws Exception { + var request = WorldPublishedSpawnRequirementsGrpcCodecTest.evidence().request(); + for (TestIdentity identity : List.of(pki.wrongWorkloadServer(), pki.otherNamespaceServer())) { + startServer(identity, Mode.EXACT); + client = newClient(server, pki.entityClient()); + client.init(); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + exception -> + assertThat(Status.fromThrowable(exception).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(headers).hasValue(0); + assertThat(bodies).hasValue(0); + stopTransport(); + } + } + + @Test + void rejectsChangedRequestReleaseGraphAndFamilyEvidenceAfterAuthenticatedRead() throws Exception { + var request = WorldPublishedSpawnRequirementsGrpcCodecTest.evidence().request(); + for (Mode mode : + List.of( + Mode.CHANGED_REQUEST, Mode.CHANGED_RELEASE, Mode.CHANGED_GRAPH, Mode.CHANGED_FAMILY)) { + startServer(pki.worldServer(), mode); + client = newClient(server, pki.entityClient()); + client.init(); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid published spawn-requirements evidence"); + assertThat(headers).hasValue(1); + assertThat(bodies).hasValue(1); + stopTransport(); + } + } + + @Test + void rejectsResponseAboveExplicitWireLimitAtGrpcTransport() throws Exception { + var request = WorldPublishedSpawnRequirementsGrpcCodecTest.evidence().request(); + startServer(pki.worldServer(), Mode.OVERSIZED); + client = newClient(server, pki.entityClient()); + client.init(); + + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + exception -> + assertThat(Status.fromThrowable(exception).getCode()) + .isEqualTo(Status.Code.RESOURCE_EXHAUSTED)); + assertThat(headers).hasValue(1); + assertThat(bodies).hasValue(1); + } + + @Test + void rejectsWrongLocalWorkloadPlaintextAndNonFileBackedTls() throws Exception { + var request = WorldPublishedSpawnRequirementsGrpcCodecTest.evidence().request(); + startServer(pki.worldServer(), Mode.EXACT); + + assertThatThrownBy(() -> newClient(server, pki.wrongClient())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact same-namespace Entity workload identity"); + + var plaintext = pki.clientProperties(tempDirectory, pki.entityClient()); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new WorldPublishedSpawnRequirementsClient( + endpoints(server), plaintext, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload mTLS"); + + var classpath = pki.clientProperties(tempDirectory, pki.entityClient()); + classpath.setCaCert("classpath:ca.crt"); + assertThatThrownBy( + () -> + new WorldPublishedSpawnRequirementsClient( + endpoints(server), classpath, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + client = newClient(server, pki.entityClient()); + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + client.init(); + client.close(); + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + assertThat(headers).hasValue(0); + } + + private enum Mode { + EXACT, + CHANGED_REQUEST, + CHANGED_RELEASE, + CHANGED_GRAPH, + CHANGED_FAMILY, + OVERSIZED + } + + private void startServer(TestIdentity identity, Mode mode) throws Exception { + headers = new AtomicInteger(); + bodies = new AtomicInteger(); + var service = + new WorldPublishedSpawnRequirementsReadServiceGrpc + .WorldPublishedSpawnRequirementsReadServiceImplBase() { + @Override + public void readWorldPublishedSpawnRequirements( + ReadWorldPublishedSpawnRequirementsRequest wire, + StreamObserver observer) { + bodies.incrementAndGet(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(ENTITY_URI); + var request = WorldPublishedSpawnRequirementsGrpcCodec.fromRequest(wire); + var evidence = WorldPublishedSpawnRequirementsGrpcCodecTest.evidence(); + var response = WorldPublishedSpawnRequirementsGrpcCodec.toResponse(request, evidence); + if (mode == Mode.CHANGED_REQUEST) { + response = + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setReadRequestId("ffffffff-ffff-4fff-8fff-ffffffffffff")) + .build(); + } else if (mode == Mode.CHANGED_RELEASE) { + response = + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setExpectedReleaseAttestationDigest("sha256:" + "f".repeat(64))) + .build(); + } else if (mode == Mode.CHANGED_GRAPH) { + response = response.toBuilder().setGraphDigest("sha256:" + "f".repeat(64)).build(); + } else if (mode == Mode.CHANGED_FAMILY) { + response = + response.toBuilder() + .setFamilyCounts( + 0, + response.getFamilyCounts(0).toBuilder() + .setFamily( + net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType + .WORLD_DESIGN_AGGREGATE_TYPE_UNSPECIFIED)) + .build(); + } else if (mode == Mode.OVERSIZED) { + response = + response.toBuilder() + .setGraphDigest( + "x" + .repeat( + WorldPublishedSpawnRequirementsGrpcCodec.MAX_RESPONSE_WIRE_BYTES + + 1)) + .build(); + } + observer.onNext(response); + observer.onCompleted(); + } + }; + ServerInterceptor countHeaders = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + headers.incrementAndGet(); + return next.startCall(call, metadata); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, countHeaders, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private WorldPublishedSpawnRequirementsClient newClient(Server target, TestIdentity local) + throws Exception { + return new WorldPublishedSpawnRequirementsClient( + endpoints(target), + pki.clientProperties(tempDirectory, local), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static ServiceEndpointsProperties endpoints(Server target) { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("localhost:" + target.getPort()); + return endpoints; + } + + private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity worldServer, + TestIdentity wrongWorkloadServer, + TestIdentity otherNamespaceServer, + TestIdentity entityClient, + TestIdentity wrongClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD spawn-requirements 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("test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + X509Certificate caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + issueIdentity(directory, caStore, caFile, "world-server", WORLD_URI, true), + issueIdentity( + directory, caStore, caFile, "wrong-workload-server", WRONG_WORKLOAD_URI, true), + issueIdentity( + directory, caStore, caFile, "wrong-namespace-server", OTHER_WORLD_URI, true), + issueIdentity(directory, caStore, caFile, "entity-client", ENTITY_URI, false), + issueIdentity(directory, caStore, caFile, "wrong-client", WRONG_CLIENT_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + Path certificate = + writePem( + directory.resolve( + "client-" + identity.certificate().getSerialNumber().toString(16) + ".crt"), + "CERTIFICATE", + identity.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve( + "client-" + identity.certificate().getSerialNumber().toString(16) + ".key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()); + Path caFile = + writePem( + directory.resolve("client-trust-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( + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new java.util.ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + 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[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClientTest.java new file mode 100644 index 0000000000..1e73376529 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClientTest.java @@ -0,0 +1,38 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; + +import java.nio.file.Path; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import org.junit.jupiter.api.Test; + +class WorldPublishedSpawnRequirementsClientTest { + @Test + void rejectsPlaintextAndInvalidNamespaceBeforeCreatingTransport() { + var plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new WorldPublishedSpawnRequirementsClient( + new ServiceEndpointsProperties(), + plaintext, + mock(GrpcChannelFactory.class), + "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload mTLS"); + + var tls = new CommonGrpcClientProperties(); + tls.setCertChain(Path.of("missing.crt").toString()); + tls.setPrivateKey(Path.of("missing.key").toString()); + tls.setCaCert(Path.of("missing-ca.crt").toString()); + assertThatThrownBy( + () -> + new WorldPublishedSpawnRequirementsClient( + new ServiceEndpointsProperties(), tls, mock(GrpcChannelFactory.class), "Test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical DNS label"); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsEvidenceTest.java new file mode 100644 index 0000000000..b2a8dcec71 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsEvidenceTest.java @@ -0,0 +1,90 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import org.junit.jupiter.api.Test; + +class WorldPublishedSpawnRequirementsEvidenceTest { + @Test + void retainsImmutableOriginalRequirementsAndArbitraryPrecisionRevisionOrder() { + var evidence = WorldPublishedSpawnRequirementsGrpcCodecTest.evidence(); + + assertThat(evidence.spawnRequirements()).hasSize(2); + assertThat(evidence.spawnRequirements().get(0).revisionOrder()).isEqualTo("9007199254740993"); + assertThat(evidence.spawnRequirements().get(0).spawnCount()).isEqualTo(7); + assertThat(evidence.spawnRequirements().get(0).respawnDelaySeconds()).isEqualTo(2700); + assertThat(evidence.spawnRequirements().get(0).roomTemplate().tenantId()) + .isEqualTo(evidence.launchBinding().releaseAttestation().canonicalTenantId()); + assertThat(evidence.spawnRequirements().get(0).entityTemplate().kind().name()) + .isEqualTo("ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM"); + assertThat(evidence.generationRequirements().get(0).revisionOrder()) + .isEqualTo("9007199254740992"); + assertThat(evidence.generationRequirements().get(0).value()).isEqualTo(" authored value "); + assertThatThrownBy(evidence.spawnRequirements()::clear) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(evidence.generationRequirements()::clear) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void deniesDuplicateIdentityAndNonIncreasingRevisionOrder() { + var evidence = WorldPublishedSpawnRequirementsGrpcCodecTest.evidence(); + var first = evidence.spawnRequirements().get(0); + var second = evidence.spawnRequirements().get(1); + + assertThatThrownBy( + () -> + new WorldPublishedSpawnRequirementsEvidence( + evidence.request(), + evidence.launchBinding(), + evidence.captureId(), + evidence.graphDigest(), + evidence.familyCounts(), + List.of( + first, + new WorldPublishedSpawnRequirementsEvidence.SpawnRequirement( + "9007199254740994", + second.revisionId(), + first.spawnBindingId(), + second.roomTemplate(), + second.entityTemplate(), + second.spawnCount(), + second.respawnDelaySeconds())), + evidence.generationRequirements())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("binding identity"); + + assertThatThrownBy( + () -> + new WorldPublishedSpawnRequirementsEvidence( + evidence.request(), + evidence.launchBinding(), + evidence.captureId(), + evidence.graphDigest(), + evidence.familyCounts(), + List.of(second, first), + evidence.generationRequirements())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("strictly increasing revision order"); + } + + @Test + void bindsGraphDigestToTheReleaseSelectorReceipt() { + var evidence = WorldPublishedSpawnRequirementsGrpcCodecTest.evidence(); + + assertThatThrownBy( + () -> + new WorldPublishedSpawnRequirementsEvidence( + evidence.request(), + evidence.launchBinding(), + evidence.captureId(), + "sha256:" + "f".repeat(64), + evidence.familyCounts(), + evidence.spawnRequirements(), + evidence.generationRequirements())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("graph digest"); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsGrpcCodecTest.java new file mode 100644 index 0000000000..bb83428378 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsGrpcCodecTest.java @@ -0,0 +1,502 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +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.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedSpawnRequirementsFamilyCount; +import org.junit.jupiter.api.Test; + +class WorldPublishedSpawnRequirementsGrpcCodecTest { + private static final UUID READ_ID = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID OTHER_ID = uuid("44444444-4444-4444-8444-444444444444"); + + @Test + void roundTripsExactRequestCompletePairAndOriginalRequirementValues() { + var expected = evidence(); + var request = WorldPublishedSpawnRequirementsGrpcCodec.toRequest(expected.request()); + assertThat(WorldPublishedSpawnRequirementsGrpcCodec.fromRequest(request)) + .isEqualTo(expected.request()); + + var response = + WorldPublishedSpawnRequirementsGrpcCodec.toResponse(expected.request(), expected); + var actual = + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse(expected.request(), response); + + assertThat(actual).isEqualTo(expected); + assertThat(actual.launchBinding().descriptor().requestedScriptPatchVersionPresent()).isTrue(); + assertThat(actual.launchBinding().descriptor().sourceVersionIdPresent()).isTrue(); + assertThat(actual.launchBinding().descriptor().targetVersionIdPresent()).isTrue(); + assertThat(actual.launchBinding().descriptor().requestedRuntimeFlagsJsonPresent()).isTrue(); + assertThat(actual.launchBinding().descriptor().scriptPatchVersionPresent()).isTrue(); + assertThat(actual.launchBinding().descriptor().remapSetIdPresent()).isTrue(); + assertThat(actual.spawnRequirements()).hasSize(2); + assertThat(actual.spawnRequirements().getFirst().revisionOrder()).isEqualTo("9007199254740993"); + assertThat(actual.spawnRequirements().getFirst().spawnCount()).isEqualTo(7); + assertThat(actual.spawnRequirements().getFirst().respawnDelaySeconds()).isEqualTo(2700); + assertThat(actual.spawnRequirements().getFirst().entityTemplate()) + .isEqualTo(expected.spawnRequirements().getFirst().entityTemplate()); + assertThat(actual.generationRequirements().getFirst().revisionOrder()) + .isEqualTo("9007199254740992"); + assertThat(actual.generationRequirements().getFirst().value()).isEqualTo(" authored value "); + } + + @Test + void acceptsTheMaximumResponseWireSizeAndRejectsOneByteOver() { + var expected = evidence(); + var response = + WorldPublishedSpawnRequirementsGrpcCodec.toResponse(expected.request(), expected); + var atLimit = + responseAtWireSize( + response, WorldPublishedSpawnRequirementsGrpcCodec.MAX_RESPONSE_WIRE_BYTES); + assertThat(atLimit.getSerializedSize()) + .isEqualTo(WorldPublishedSpawnRequirementsGrpcCodec.MAX_RESPONSE_WIRE_BYTES); + assertThat( + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse(expected.request(), atLimit) + .generationRequirements() + .getFirst() + .value()) + .isEqualTo(atLimit.getGenerationRequirements(0).getValue()); + + var overLimit = + responseAtWireSize( + response, WorldPublishedSpawnRequirementsGrpcCodec.MAX_RESPONSE_WIRE_BYTES + 1); + assertThat(overLimit.getSerializedSize()) + .isEqualTo(WorldPublishedSpawnRequirementsGrpcCodec.MAX_RESPONSE_WIRE_BYTES + 1); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), overLimit)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("maximum wire size"); + } + + @Test + void rejectsChangedRequestScopeReleaseAndMalformedCapture() { + var expected = evidence(); + var response = + WorldPublishedSpawnRequirementsGrpcCodec.toResponse(expected.request(), expected); + + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder() + .setRequest( + response.getRequest().toBuilder().setReadRequestId(OTHER_ID.toString())) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder().setGraphDigest("sha256:" + "f".repeat(64)).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("graph digest"); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setExpectedReleaseAttestationDigest("sha256:" + "f".repeat(64))) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed the exact source-read request"); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder() + .setCompleteLaunchBinding( + response.getCompleteLaunchBinding().toBuilder() + .setReleaseAttestation( + response + .getCompleteLaunchBinding() + .getReleaseAttestation() + .toBuilder() + .setCanonicalTenantId(OTHER_ID.toString()))) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder() + .setCaptureId("00000000-0000-0000-0000-000000000000") + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("captureId"); + } + + @Test + void rejectsMissingNestedEvidenceUnknownFieldsAndChangedAuthoredScope() { + var expected = evidence(); + var response = + WorldPublishedSpawnRequirementsGrpcCodec.toResponse(expected.request(), expected); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), response.toBuilder().clearRequest().build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), response.toBuilder().clearCompleteLaunchBinding().build())) + .isInstanceOf(IllegalArgumentException.class); + + UnknownFieldSet unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), response.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder() + .setRequest(response.getRequest().toBuilder().setUnknownFields(unknown)) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setLaunchBindingRequest( + response.getRequest().getLaunchBindingRequest().toBuilder() + .setUnknownFields(unknown))) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder() + .setSpawnRequirements( + 0, + response.getSpawnRequirements(0).toBuilder() + .setRoomTemplate( + response.getSpawnRequirements(0).getRoomTemplate().toBuilder() + .setTenantId(OTHER_ID.toString()))) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical tenant/version context"); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder() + .setSpawnRequirements( + 0, + response.getSpawnRequirements(0).toBuilder() + .setRoomTemplate( + response.getSpawnRequirements(0).getRoomTemplate().toBuilder() + .setUnknownFields(unknown))) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + } + + @Test + void requiresAllSixExplicitCountsAndRejectsCountListMismatch() { + var empty = emptyEvidence(); + var emptyResponse = WorldPublishedSpawnRequirementsGrpcCodec.toResponse(empty.request(), empty); + assertThat(emptyResponse.getFamilyCountsCount()).isEqualTo(6); + for (var count : emptyResponse.getFamilyCountsList()) { + assertThat(count.hasCount()).isTrue(); + assertThat(count.getCount()).isZero(); + } + assertThat( + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse(empty.request(), emptyResponse)) + .isEqualTo(empty); + + var populated = evidence(); + var response = + WorldPublishedSpawnRequirementsGrpcCodec.toResponse(populated.request(), populated); + var badCount = + WorldPublishedSpawnRequirementsFamilyCount.newBuilder() + .setFamily(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE) + .setCount(1) + .build(); + assertThatThrownBy( + () -> + new WorldPublishedSpawnRequirementsEvidence( + populated.request(), + populated.launchBinding(), + populated.captureId(), + populated.graphDigest(), + List.of( + populated.familyCounts().get(0), + populated.familyCounts().get(1), + populated.familyCounts().get(2), + populated.familyCounts().get(3), + new WorldPublishedSpawnRequirementsEvidence.FamilyCount( + badCount.getFamily(), badCount.getCount()), + populated.familyCounts().get(5)), + populated.spawnRequirements(), + populated.generationRequirements())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("count differs"); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + populated.request(), + response.toBuilder() + .setFamilyCounts(4, response.getFamilyCounts(4).toBuilder().setCount(1)) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("count differs"); + + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + empty.request(), + emptyResponse.toBuilder() + .setFamilyCounts( + 0, emptyResponse.getFamilyCounts(0).toBuilder().clearCount()) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not explicitly present"); + } + + static WorldPublishedSpawnRequirementsEvidence evidence() { + CompleteLaunchBindingEvidence binding = completeBinding(); + var request = request(binding); + UUID tenant = binding.releaseAttestation().canonicalTenantId(); + UUID version = binding.releaseAttestation().canonicalVersionId(); + var item = + new WorldPublishedSpawnRequirementsEvidence.EntityTemplateReference( + net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType + .ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM, + tenant, + version, + uuid("66666666-6666-4666-8666-666666666666")); + var npc = + new WorldPublishedSpawnRequirementsEvidence.EntityTemplateReference( + net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType + .ENTITY_TEMPLATE_REFERENCE_TYPE_NPC, + tenant, + version, + uuid("77777777-7777-4777-8777-777777777777")); + return new WorldPublishedSpawnRequirementsEvidence( + request, + binding, + uuid("88888888-8888-4888-8888-888888888888"), + graphDigest(binding), + counts(1, 2, 3, 4, 2, 2), + List.of( + new WorldPublishedSpawnRequirementsEvidence.SpawnRequirement( + "9007199254740993", + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + new RoomTemplateRef(tenant, version, uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc")), + item, + 7, + 2700), + new WorldPublishedSpawnRequirementsEvidence.SpawnRequirement( + "9007199254740994", + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + new RoomTemplateRef(tenant, version, uuid("ffffffff-ffff-4fff-8fff-ffffffffffff")), + npc, + 0, + 0)), + List.of( + new WorldPublishedSpawnRequirementsEvidence.GenerationRequirement( + "9007199254740992", + uuid("12345678-1234-4234-8234-123456789001"), + uuid("12345678-1234-4234-8234-123456789101"), + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION, + uuid("12345678-1234-4234-8234-123456789201"), + "difficulty.mode", + " authored value "), + new WorldPublishedSpawnRequirementsEvidence.GenerationRequirement( + "9007199254740995", + uuid("12345678-1234-4234-8234-123456789002"), + uuid("12345678-1234-4234-8234-123456789102"), + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, + uuid("12345678-1234-4234-8234-123456789202"), + "population.mode", + "sparse"))); + } + + private static net.firedevops.firemud.worldmanagement.v1 + .ReadWorldPublishedSpawnRequirementsResponse + responseAtWireSize( + net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedSpawnRequirementsResponse + response, + int targetSize) { + String value = response.getGenerationRequirements(0).getValue(); + int length = value.length() + targetSize - response.getSerializedSize(); + for (int attempt = 0; attempt < 4; attempt++) { + var sized = + response.toBuilder() + .setGenerationRequirements( + 0, response.getGenerationRequirements(0).toBuilder().setValue("x".repeat(length))) + .build(); + int difference = targetSize - sized.getSerializedSize(); + if (difference == 0) { + return sized; + } + length += difference; + } + throw new AssertionError("Could not size response to the requested wire length"); + } + + static WorldPublishedSpawnRequirementsEvidence emptyEvidence() { + CompleteLaunchBindingEvidence binding = completeBinding(); + return new WorldPublishedSpawnRequirementsEvidence( + request(binding), + binding, + uuid("88888888-8888-4888-8888-888888888888"), + graphDigest(binding), + counts(0, 0, 0, 0, 0, 0), + List.of(), + List.of()); + } + + private static List counts( + int region, int zone, int room, int exit, int generation, int spawn) { + return List.of( + new WorldPublishedSpawnRequirementsEvidence.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION, region), + new WorldPublishedSpawnRequirementsEvidence.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, zone), + new WorldPublishedSpawnRequirementsEvidence.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, room), + new WorldPublishedSpawnRequirementsEvidence.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT, exit), + new WorldPublishedSpawnRequirementsEvidence.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE, generation), + new WorldPublishedSpawnRequirementsEvidence.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING, + spawn)); + } + + private static WorldPublishedSpawnRequirementsEvidence.Request request( + CompleteLaunchBindingEvidence binding) { + var descriptor = binding.descriptor(); + GetLaunchDescriptorRequest selector = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId(READ_ID.toString()) + .setCanonicalTenantId(descriptor.canonicalTenantId().toString()) + .setWorldSlug(descriptor.worldSlug()) + .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) + .setExpectedRequestDigest(descriptor.requestDigest()) + .setExpectedResultDigest(descriptor.resultDigest()) + .build(); + return new WorldPublishedSpawnRequirementsEvidence.Request( + descriptor.targetNamespace(), + READ_ID, + selector, + binding.releaseAttestation().evidenceDigest()); + } + + private static String graphDigest(CompleteLaunchBindingEvidence binding) { + return WorldDraftStartLocationEvidence.fromStored( + binding.releaseAttestation().worldStartLocationEvidence().selectorReceiptBytes()) + .graphDigest(); + } + + private static CompleteLaunchBindingEvidence completeBinding() { + WorldPublishedStartLocationEvidence worldStart; + try { + worldStart = WorldPublishedStartLocationGrpcCodecTest.evidence(); + } catch (Exception impossible) { + throw new AssertionError(impossible); + } + var selection = worldStart.request(); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + selection.targetNamespace(), + "launch-control-request", + selection.canonicalTenantId(), + "synthetic-world", + uuid("99999999-9999-4999-8999-999999999999"), + "sha256:" + "a".repeat(64), + 19L, + true, + "script-patch", + true, + 17L, + true, + Long.MAX_VALUE, + true, + "{\"requested\":true}"); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "descriptor", + Long.MAX_VALUE, + true, + "script-patch", + "{}", + "generation-config", + 9L, + 7L, + "published-release", + true, + "remap-set"); + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selection.appliedCommitId(), + "b".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence release = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + selection.canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selection.publishWorkflowId(), + selection.appliedCommitId(), + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of("LOOK"), + descriptor.generationConfigRevision(), + worldStart); + return new CompleteLaunchBindingEvidence(descriptor, release); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundleTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundleTest.java index 892c733258..0c820e4388 100644 --- a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundleTest.java +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundleTest.java @@ -208,6 +208,19 @@ void rejectsInvalidExpiryAndReferenceOverflowOrMismatch() throws Exception { new StartSessionAuthorityEvidenceBundle.BundleReference( StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "24", "17")))) .isNull(); + assertThatThrownBy( + () -> + new StartSessionAuthorityEvidenceBundle.BundleReference( + "authorityEvidenceBundle/v2", "17", "23", "17")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "9223372036854775808", + "17")) + .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( () -> new StartSessionAuthorityEvidenceBundle.BundleReference( diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionLaunchDescriptorGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionLaunchDescriptorGrpcService.java new file mode 100644 index 0000000000..ec1f4dcb56 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionLaunchDescriptorGrpcService.java @@ -0,0 +1,144 @@ +package net.firedevops.firemud.gamedesign.draft; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; +import net.firedevops.firemud.gamedesign.publication.StartSessionLaunchDescriptorProducer; +import net.firedevops.firemud.gamedesign.v1.GameDesignStartSessionLaunchDescriptorServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveStartSessionLaunchDescriptorResponse; + +/** Standalone authenticated StartSession descriptor adapter; deliberately not registered. */ +public final class GameDesignStartSessionLaunchDescriptorGrpcService + extends GameDesignStartSessionLaunchDescriptorServiceGrpc + .GameDesignStartSessionLaunchDescriptorServiceImplBase { + private final StartSessionLaunchDescriptorProducer producer; + private final String workloadNamespace; + + public GameDesignStartSessionLaunchDescriptorGrpcService( + StartSessionLaunchDescriptorProducer producer, String workloadNamespace) { + this.producer = Objects.requireNonNull(producer, "producer"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Design workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + @Override + public void resolveStartSessionLaunchDescriptor( + ReadStartSessionTemplateAssociationRequest request, + StreamObserver observer) { + try { + requirePeer(); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + + final Request decoded; + try { + decoded = StartSessionLaunchDescriptorGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException malformed) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Exact StartSession template association replay required") + .asRuntimeException()); + return; + } + if (!workloadNamespace.equals(decoded.targetNamespace())) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription("StartSession target namespace differs from the Game Design peer") + .asRuntimeException()); + return; + } + + try { + StartSessionLaunchDescriptorProducer.ResolvedBinding binding = producer.resolve(decoded); + if (!decoded.equals(binding.request())) { + throw new IllegalArgumentException("Producer changed the exact StartSession request"); + } + ResolvedLaunchDescriptorDto descriptor = binding.descriptor(); + AuthoredWorldLaunchDescriptorEvidence evidence = descriptor.authoredWorldBinding(); + requireDtoMatchesEvidence(descriptor, evidence); + observer.onNext( + StartSessionLaunchDescriptorGrpcCodec.toDescriptorResponse( + decoded, binding.associationRead(), evidence)); + observer.onCompleted(); + } catch (StartSessionLaunchDescriptorProducer.StoredBusinessDenial denied) { + try { + observer.onNext( + StartSessionLaunchDescriptorGrpcCodec.toFailureResponse( + decoded, denied.associationRead(), denied.failureCode(), denied.getMessage())); + observer.onCompleted(); + } catch (RuntimeException invalidDenial) { + observer.onError( + Status.INTERNAL + .withDescription("Stored StartSession denial did not match its exact request") + .asRuntimeException()); + } + } catch (StatusRuntimeException failure) { + Status status = Status.fromThrowable(failure); + observer.onError( + Status.fromCode(status.getCode()) + .withDescription("StartSession launch descriptor owner read denied or unavailable") + .asRuntimeException()); + } catch (IllegalArgumentException invalidResult) { + observer.onError( + Status.INTERNAL + .withDescription("Game Design returned an invalid StartSession launch descriptor") + .asRuntimeException()); + } catch (RuntimeException unavailable) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Game Design StartSession launch descriptor is unavailable") + .asRuntimeException()); + } + } + + private void requirePeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified Game Session workload identity required") + .asRuntimeException(); + } + if (!("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service") + .equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Session workload required") + .asRuntimeException(); + } + } + + private static void requireDtoMatchesEvidence( + ResolvedLaunchDescriptorDto descriptor, AuthoredWorldLaunchDescriptorEvidence evidence) { + Objects.requireNonNull(descriptor, "descriptor"); + Objects.requireNonNull(evidence, "authoredWorldBinding"); + if (!Objects.equals(descriptor.launchDescriptorId(), evidence.launchDescriptorId()) + || !Objects.equals(descriptor.canonicalTenantId(), evidence.canonicalTenantId().toString()) + || descriptor.gameTemplateId() != evidence.gameTemplateId() + || !Objects.equals(descriptor.controlPlaneRequestId(), evidence.controlPlaneRequestId()) + || descriptor.versionId() != evidence.versionId() + || !Objects.equals( + descriptor.scriptPatchVersion(), + evidence.scriptPatchVersionPresent() ? evidence.scriptPatchVersion() : null) + || !Objects.equals(descriptor.runtimeFlagsJson(), evidence.runtimeFlagsJson()) + || !Objects.equals( + descriptor.generationConfigRevision(), evidence.generationConfigRevision()) + || descriptor.versionStateEpoch() != evidence.versionStateEpoch() + || descriptor.releaseBundleId() != evidence.releaseBundleId() + || !Objects.equals( + descriptor.publishedReleaseBundleRef(), evidence.publishedReleaseBundleRef()) + || !Objects.equals( + descriptor.remapSetId(), evidence.remapSetIdPresent() ? evidence.remapSetId() : null)) { + throw new IllegalArgumentException("Resolved descriptor DTO differs from closed evidence"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionTemplateAssociationReadGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionTemplateAssociationReadGrpcService.java new file mode 100644 index 0000000000..e647b5e69b --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionTemplateAssociationReadGrpcService.java @@ -0,0 +1,96 @@ +package net.firedevops.firemud.gamedesign.draft; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.publication.StartSessionTemplateAssociationReadService; +import net.firedevops.firemud.gamedesign.v1.GameDesignStartSessionTemplateAssociationReadServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationResponse; + +/** Standalone, deliberately unregistered authenticated Game Session association read endpoint. */ +public final class GameDesignStartSessionTemplateAssociationReadGrpcService + extends GameDesignStartSessionTemplateAssociationReadServiceGrpc + .GameDesignStartSessionTemplateAssociationReadServiceImplBase { + private final StartSessionTemplateAssociationReadService service; + private final String workloadNamespace; + + public GameDesignStartSessionTemplateAssociationReadGrpcService( + StartSessionTemplateAssociationReadService service, String workloadNamespace) { + this.service = Objects.requireNonNull(service, "service"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Design workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + @Override + public void readStartSessionTemplateAssociation( + ReadStartSessionTemplateAssociationRequest request, + StreamObserver observer) { + try { + requirePeer(); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + + final StartSessionTemplateAssociationReadEvidence.Request decoded; + try { + decoded = StartSessionTemplateAssociationReadGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException malformed) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical StartSession template association read required") + .asRuntimeException()); + return; + } + if (!workloadNamespace.equals(decoded.targetNamespace())) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription("StartSession association namespace differs from peer") + .asRuntimeException()); + return; + } + + try { + observer.onNext( + StartSessionTemplateAssociationReadGrpcCodec.toResponse(service.read(decoded))); + observer.onCompleted(); + } catch (StatusRuntimeException failure) { + observer.onError( + Status.fromCode(Status.fromThrowable(failure).getCode()) + .withDescription("Exact StartSession association read denied or unavailable") + .asRuntimeException()); + } catch (IllegalArgumentException invalidResult) { + observer.onError( + Status.INTERNAL + .withDescription("Game Design returned an invalid StartSession association") + .asRuntimeException()); + } catch (RuntimeException unavailable) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Game Design template association owner read unavailable") + .asRuntimeException()); + } + } + + private void requirePeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified Game Session workload identity required") + .asRuntimeException(); + } + if (!("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service") + .equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Session workload required") + .asRuntimeException(); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AuthoredInitialActorCoreReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AuthoredInitialActorCoreReadService.java new file mode 100644 index 0000000000..d1a75637c1 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AuthoredInitialActorCoreReadService.java @@ -0,0 +1,445 @@ +package net.firedevops.firemud.gamedesign.publication; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence.ReadRequest; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence.ReadResult; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreSourceBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Association; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.entity.LaunchDescriptor; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.LaunchDescriptorRepository; +import net.firedevops.firemud.gamedesign.repository.StartSessionAuthoredActorCoreProjectionRepository; +import net.firedevops.firemud.gamedesign.repository.StartSessionLaunchDescriptorRepository; +import net.firedevops.firemud.gamedesign.repository.StartSessionLaunchDescriptorRepository.Binding; +import org.jooq.DSLContext; +import org.jooq.exception.DataAccessException; +import tools.jackson.databind.ObjectMapper; + +/** + * Standalone, read-only authenticated authored-core projection. It never invokes descriptor + * resolution or repairs missing owner/projection rows. + */ +public final class AuthoredInitialActorCoreReadService { + private static final String EMPTY_RUNTIME_FLAGS = "{}"; + private static final String RUNTIME_SURFACE_EMPTY_V1 = "EMPTY_V1"; + + private final String workloadNamespace; + private final StartSessionTemplateAssociationReadService associationReader; + private final GameAuthoredWorldSourceRepository worldSources; + private final LaunchDescriptorRepository descriptors; + private final StartSessionLaunchDescriptorRepository descriptorBindings; + private final StartSessionAuthoredActorCoreProjectionRepository projections; + private final GameDesignPublicationOperationRepository publicationOperations; + private final GameDesignSourceRepository sourceRepository; + private final SelectedDraftTemplateWorldSourceAssociationRepository associations; + private final SelectedDraftGameLogicReceiptRepository gameLogicReceipts; + private final GameplayRuleSourceRepository gameplayRules; + private final ObjectMapper objectMapper; + + public AuthoredInitialActorCoreReadService( + DSLContext dsl, + String workloadNamespace, + StartSessionTemplateAssociationReadService associationReader, + ObjectMapper objectMapper) { + Objects.requireNonNull(dsl, "dsl"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Design workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + this.associationReader = Objects.requireNonNull(associationReader, "associationReader"); + this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper"); + worldSources = new GameAuthoredWorldSourceRepository(dsl); + descriptors = new LaunchDescriptorRepository(dsl); + descriptorBindings = new StartSessionLaunchDescriptorRepository(dsl); + projections = new StartSessionAuthoredActorCoreProjectionRepository(dsl); + publicationOperations = new GameDesignPublicationOperationRepository(dsl); + sourceRepository = new GameDesignSourceRepository(dsl); + associations = new SelectedDraftTemplateWorldSourceAssociationRepository(dsl); + gameLogicReceipts = new SelectedDraftGameLogicReceiptRepository(dsl); + gameplayRules = new GameplayRuleSourceRepository(dsl); + } + + /** Caller authorization occurs before request correlation checks or the local snapshot. */ + public ReadResult read(ReadRequest request) { + associationReader.requireAuthoredInitialActorCorePeer(); + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.associationRequest().targetNamespace())) { + throw Status.PERMISSION_DENIED + .withDescription("Authored-core request namespace differs from Game Design") + .asRuntimeException(); + } + try { + return associationReader.readForAuthoredInitialActorCore( + request.associationRequest(), exact -> readOwner(exact, request.associationRequest())); + } catch (StatusRuntimeException failure) { + throw failure; + } catch (DataAccessException unavailable) { + throw Status.UNAVAILABLE + .withDescription("Game Design authored-core owner storage unavailable") + .withCause(unavailable) + .asRuntimeException(); + } catch (RuntimeException invalid) { + throw Status.FAILED_PRECONDITION + .withDescription( + "Exact retained authored-core owner evidence is unavailable or conflicting") + .withCause(invalid) + .asRuntimeException(); + } + } + + private ReadResult readOwner(Result exact, Request request) { + StartSessionPostAuthorizationExecutionTuple tuple = request.decodedTuple(); + var action = tuple.preAuthorizationTuple().action(); + Association association = exact.association(); + if (!(request.selection() instanceof ExactReplay replay) + || !request.equals(exact.request()) + || !replay.canonicalVersionId().equals(association.canonicalVersionId()) + || !replay.selectedCommitId().equals(association.selectedCommitId()) + || !replay.publishWorkflowId().equals(association.publishWorkflowId()) + || !replay.associationDigest().equals(association.associationDigest()) + || !action.scope().tenantId().equals(association.canonicalTenantId()) + || action.target().gameTemplateId() != association.templateId()) { + throw conflict("Account-gated association differs from the exact original request"); + } + + AuthoredWorldSourceEvidence source = + worldSources + .read( + association.sourceOperationId(), + association.canonicalTenantId(), + association.worldSlug(), + workloadNamespace) + .orElseThrow(() -> conflict("Exact registered Game Design source is unavailable")); + requireSourceMatches(association, source); + + String requestId = tuple.controlPlaneRequestId(); + Binding owner = + descriptorBindings + .find(workloadNamespace, association.canonicalTenantId(), requestId) + .orElseThrow( + () -> conflict("Retained StartSession descriptor owner binding is missing")); + LaunchDescriptor descriptor = + descriptors + .findBoundByRequest(workloadNamespace, association.canonicalTenantId(), requestId) + .orElseThrow(() -> conflict("Retained StartSession descriptor row is missing")); + if (!Objects.equals(owner.descriptorRowId(), descriptor.getId())) { + throw conflict("Descriptor binding does not point at the actual immutable descriptor row"); + } + + AuthoredWorldLaunchDescriptorEvidence.Request descriptorRequest = + descriptorRequest(request, association); + String originalRequestJson = writeJson(descriptorRequest); + String sourceEvidenceJson = writeJson(source); + requireSuccessfulDescriptor( + descriptor, source, descriptorRequest, originalRequestJson, sourceEvidenceJson); + + CapturedSources captured = requireCapturedSources(exact, association.templateId()); + requireOwnerBinding(owner, descriptor, request, exact, source, captured.gameLogicReceipt()); + List retained = + projections.replayExact(owner, captured.actorCoreBindings()); + return new ReadResult(request, exact, evidence(descriptor, descriptorRequest), retained); + } + + private CapturedSources requireCapturedSources(Result exact, long templateId) { + Association association = exact.association(); + var readback = + publicationOperations + .read(association.publishWorkflowId()) + .orElseThrow(() -> conflict("Exact selected publication operation is unavailable")); + var operation = readback.operation(); + var selection = operation.account().input().selection(); + if (!"PUBLISHED".equals(readback.outcome()) + || !operation.workflowId().equals(association.publishWorkflowId()) + || !operation.tenantKey().equals(selection.target().gameDesignVersionTenantKey()) + || operation.versionId() != selection.target().gameDesignVersionRowId() + || !selection.target().canonicalTenantId().equals(association.canonicalTenantId()) + || !selection.target().canonicalVersionId().equals(association.canonicalVersionId()) + || !selection.selectedCommit().commitId().equals(association.selectedCommitId()) + || readback.terminalEvidenceBytes() == null) { + throw conflict("Published operation differs from the pinned association"); + } + GameDesignPublicationTerminalEvidence terminal = + GameDesignPublicationTerminalEvidence.fromStored(readback.terminalEvidenceBytes()); + if (terminal.outcome() != GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + || !Arrays.equals(terminal.operationBytes(), operation.canonicalBytes()) + || terminal.releaseContent() == null + || terminal.publicationVersionStateEpoch() <= 0L) { + throw conflict("Exact selected publication terminal evidence is incomplete"); + } + GameDesignSourceRepository.Capture capture = + sourceRepository + .readCapture(operation) + .orElseThrow(() -> conflict("Complete selected publication capture is unavailable")); + var templateCapture = + capture + .templateConfig() + .orElseThrow( + () -> conflict("Exact selected template configuration capture is unavailable")); + if (!templateCapture.snapshot().binding().equals(selection.selectedCommit())) { + throw conflict("Selected template capture differs from its publication commit"); + } + List templateEntries = + templateCapture.snapshot().entries().stream() + .filter(entry -> Long.parseLong(entry.templateId()) == templateId) + .toList(); + if (templateEntries.size() != 1 + || !templateEntries + .getFirst() + .config() + .baseVersionId() + .equals(association.canonicalVersionId())) { + throw conflict("Exact selected template entry is missing, duplicated or misbound"); + } + + SelectedGameplayRules selectedRules = + requireSelectedGameLogic( + operation, + capture + .gameplay() + .orElseThrow( + () -> conflict("Exact selected gameplay source capture is unavailable"))); + List associationRows = + associations.readExact(operation, templateCapture).stream() + .filter(value -> value.templateId() == templateId) + .toList(); + if (associationRows.size() != 1) { + throw conflict("Exact immutable template source association is missing or ambiguous"); + } + var row = associationRows.getFirst(); + if (!row.canonicalTenantId().equals(association.canonicalTenantId()) + || row.templateId() != association.templateId() + || !row.canonicalVersionId().equals(association.canonicalVersionId()) + || !row.selectedCommitId().equals(association.selectedCommitId()) + || !row.publishWorkflowId().equals(association.publishWorkflowId()) + || !row.digest().equals(association.associationDigest()) + || !row.targetNamespace().equals(association.targetNamespace()) + || !row.sourceOperationId().equals(association.sourceOperationId()) + || !row.sourceEvidenceDigest().equals(association.sourceEvidenceDigest()) + || !row.worldSlug().equals(association.worldSlug())) { + throw conflict("Retained private association differs from its public pinned result"); + } + List actorBindings = + StartSessionLaunchDescriptorProducer.resolveSelectedAuthoredInitialActorCoreSources( + association.sourceOperationId(), + association.sourceEvidenceDigest(), + association.worldSlug(), + operation.workflowId(), + operation.canonicalBytes(), + readback.terminalEvidenceBytes(), + selection.selectedCommit(), + net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot.fromStored( + capture.policy().snapshot().canonicalJson()), + selectedRules.snapshot()); + return new CapturedSources(actorBindings, selectedRules.receiptBinding()); + } + + private SelectedGameplayRules requireSelectedGameLogic( + GameDesignPublicationOperation operation, GameplayRuleSnapshot.Capture gameplayCapture) { + var selection = operation.account().input().selection(); + var target = selection.target(); + var publicationRequest = + PublicationDigestRequestBinding.full( + selection.intent().canonicalTenantId().toString(), + Long.toString(target.gameDesignVersionRowId()), + selection.intent().publishRequestId()); + SelectedDraftGameLogicReceipt receipt = + gameLogicReceipts + .readForPublication(publicationRequest) + .orElseThrow(() -> conflict("Exact retained Game Logic source receipt is unavailable")); + GameplayRuleSnapshot snapshot = + gameplayRules + .readSnapshot(target, selection.selectedCommit().commitId()) + .orElseThrow(() -> conflict("Exact selected Game Logic source is unavailable")); + if (!SelectedGameplayRuleSourceJoin.matches(operation, gameplayCapture, snapshot, receipt)) { + throw conflict("Retained Game Logic receipt differs from the selected source"); + } + return new SelectedGameplayRules( + snapshot, + new GameLogicReceiptBinding( + selection.intent().publishRequestId(), + selection.digest(), + receipt.authorization().digest(), + receipt.receipt().digest())); + } + + private void requireOwnerBinding( + Binding owner, + LaunchDescriptor descriptor, + Request request, + Result exact, + AuthoredWorldSourceEvidence source, + GameLogicReceiptBinding logic) { + Association association = exact.association(); + if (!Objects.equals(owner.targetNamespace(), workloadNamespace) + || !Objects.equals(owner.canonicalTenantId(), association.canonicalTenantId()) + || !Objects.equals( + owner.controlPlaneRequestId(), request.decodedTuple().controlPlaneRequestId()) + || !Objects.equals(owner.descriptorRowId(), descriptor.getId()) + || !Objects.equals(owner.releaseBundleId(), exact.releaseBundle().getId()) + || !Objects.equals(owner.versionStateEpoch(), descriptor.getVersionStateEpoch()) + || !Arrays.equals( + owner.canonicalPostAuthorizationTuple(), request.canonicalPostAuthorizationTuple()) + || !Objects.equals(owner.ownerAttemptId(), request.ownerAttemptId()) + || !Objects.equals(owner.ownerFence(), request.ownerFence()) + || !Objects.equals(owner.gameTemplateId(), association.templateId()) + || !Objects.equals(owner.canonicalVersionId(), association.canonicalVersionId()) + || !Objects.equals(owner.selectedCommitId(), association.selectedCommitId()) + || !Objects.equals(owner.publishWorkflowId(), association.publishWorkflowId()) + || !Objects.equals( + owner.publicationSelectionDigest(), association.publicationSelectionDigest()) + || !Objects.equals(owner.associationDigest(), association.associationDigest()) + || !Objects.equals(owner.sourceOperationId(), association.sourceOperationId()) + || !Objects.equals(owner.sourceEvidenceDigest(), association.sourceEvidenceDigest()) + || !Objects.equals(owner.worldSlug(), association.worldSlug()) + || !Objects.equals(owner.referencePhaseEpoch(), exact.phaseEpoch()) + || !Objects.equals(owner.runtimeSurface(), RUNTIME_SURFACE_EMPTY_V1) + || !Objects.equals(owner.gameLogicPublishRequestId(), logic.publishRequestId()) + || !Objects.equals(owner.gameLogicSelectionDigest(), logic.selectionDigest()) + || !Objects.equals(owner.gameLogicAuthorizationDigest(), logic.authorizationDigest()) + || !Objects.equals(owner.gameLogicReceiptDigest(), logic.receiptDigest()) + || !Arrays.equals( + owner.associationReadResponseBytes(), + StartSessionTemplateAssociationReadGrpcCodec.toResponse(exact).toByteArray()) + || !Objects.equals(source.operationId(), owner.sourceOperationId()) + || !Objects.equals(source.evidenceDigest(), owner.sourceEvidenceDigest())) { + throw conflict("Immutable StartSession descriptor owner binding differs from exact read"); + } + } + + private void requireSuccessfulDescriptor( + LaunchDescriptor descriptor, + AuthoredWorldSourceEvidence source, + AuthoredWorldLaunchDescriptorEvidence.Request request, + String requestJson, + String sourceJson) { + if (!LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus()) + || descriptor.getDescriptorSchemaVersion() == null + || descriptor.getDescriptorSchemaVersion() + != AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION + || !workloadNamespace.equals(descriptor.getTargetNamespace()) + || !request.canonicalTenantId().toString().equals(descriptor.getCanonicalTenantId()) + || !request.worldSlug().equals(descriptor.getWorldSlug()) + || !request + .authoredWorldSourceOperationId() + .toString() + .equals(descriptor.getAuthoredWorldSourceOperationId()) + || !request + .authoredWorldSourceEvidenceDigest() + .equals(descriptor.getAuthoredWorldSourceEvidenceDigest()) + || !request.controlPlaneRequestId().equals(descriptor.getControlPlaneRequestId()) + || !Objects.equals(descriptor.getTenantId(), source.sourceGameTenantKey()) + || request.gameTemplateId() != descriptor.getGameTemplateId() + || !requestJson.equals(descriptor.getOriginalRequestJson()) + || !sourceJson.equals(descriptor.getSourceEvidenceJson()) + || !request.requestDigest().equals(descriptor.getRequestDigest()) + || !request.requestDigest().equals(descriptor.getRequestHash()) + || descriptor.getScriptPatchVersion() != null + || descriptor.getRemapSetId() != null + || !EMPTY_RUNTIME_FLAGS.equals(descriptor.getRuntimeFlagsJson())) { + throw conflict("Stored descriptor is not the exact successful immutable binding"); + } + } + + private AuthoredWorldLaunchDescriptorEvidence evidence( + LaunchDescriptor descriptor, AuthoredWorldLaunchDescriptorEvidence.Request request) { + var evidence = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + descriptor.getLaunchDescriptorId(), + descriptor.getVersionId(), + descriptor.getScriptPatchVersion() != null, + descriptor.getScriptPatchVersion(), + descriptor.getRuntimeFlagsJson(), + descriptor.getGenerationConfigRevision(), + descriptor.getVersionStateEpoch(), + descriptor.getReleaseBundleId(), + descriptor.getPublishedReleaseBundleRef(), + descriptor.getRemapSetId() != null, + descriptor.getRemapSetId()); + evidence.requireValid(); + if (!evidence.resultDigest().equals(descriptor.getResultDigest())) { + throw conflict("Stored descriptor result digest differs from its complete content"); + } + return evidence; + } + + private AuthoredWorldLaunchDescriptorEvidence.Request descriptorRequest( + Request request, Association association) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + request.targetNamespace(), + request.decodedTuple().controlPlaneRequestId(), + association.canonicalTenantId(), + association.worldSlug(), + association.sourceOperationId(), + association.sourceEvidenceDigest(), + association.templateId(), + false, + null, + false, + null, + false, + null, + true, + EMPTY_RUNTIME_FLAGS); + } + + private String writeJson(Object value) { + try { + return objectMapper.writeValueAsString(value); + } catch (Exception invalid) { + throw new IllegalStateException("Cannot encode exact retained descriptor evidence", invalid); + } + } + + private void requireSourceMatches(Association association, AuthoredWorldSourceEvidence source) { + if (!workloadNamespace.equals(source.targetNamespace()) + || !association.targetNamespace().equals(source.targetNamespace()) + || !association.canonicalTenantId().equals(source.canonicalTenantId()) + || !association.sourceOperationId().equals(source.operationId()) + || !association.sourceEvidenceDigest().equals(source.evidenceDigest()) + || !association.worldSlug().equals(source.worldSlug()) + || !"NEW_GAME_ROW".equals(source.provenanceKind()) + || source.sourceGameRowId() <= 0L + || source.sourceGameTenantKey() == null + || source.sourceGameTenantKey().isBlank()) { + throw conflict("Exact association source differs from registered source evidence"); + } + } + + private static StatusRuntimeException conflict(String description) { + return Status.FAILED_PRECONDITION.withDescription(description).asRuntimeException(); + } + + private record CapturedSources( + List actorCoreBindings, + GameLogicReceiptBinding gameLogicReceipt) { + private CapturedSources { + actorCoreBindings = List.copyOf(actorCoreBindings); + Objects.requireNonNull(gameLogicReceipt, "gameLogicReceipt"); + } + } + + private record SelectedGameplayRules( + GameplayRuleSnapshot snapshot, GameLogicReceiptBinding receiptBinding) {} + + private record GameLogicReceiptBinding( + String publishRequestId, + String selectionDigest, + String authorizationDigest, + String receiptDigest) {} +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java index d04db8f1a1..5bb6b2e03e 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java @@ -143,9 +143,10 @@ public String digest() { } /** - * Converts the closed Draft owner payloads to command mutations. Realm policy and ordinary asset - * reference payloads are separate Game Design owner scopes and are left to their typed writers. - * Unknown kinds deny rather than being guessed from omitted or legacy rows. + * Converts the closed Draft owner payloads to command mutations. Realm policy, ordinary asset, + * gameplay-rule, and template-configuration payloads are separate Game Design owner scopes and + * are left to their typed writers. Unknown kinds deny rather than being guessed from omitted or + * legacy rows. */ public static List mutations(DraftCommitBinding binding) { Objects.requireNonNull(binding, "binding"); @@ -159,7 +160,8 @@ public static List mutations(DraftCommitBinding binding) { String revisionKind = payload.path("revisionKind").asText(); if (REALM_POLICY_REVISION_KIND.equals(revisionKind) || AssetSource.REVISION_KIND.equals(revisionKind) - || GameplayRuleSource.REVISION_KIND.equals(revisionKind)) continue; + || GameplayRuleSource.REVISION_KIND.equals(revisionKind) + || TemplateConfigSource.REVISION_KIND.equals(revisionKind)) continue; if (!REVISION_KIND.equals(revisionKind)) { throw new IllegalArgumentException("Unsupported Game Design command source revision kind"); } @@ -210,7 +212,8 @@ public static boolean hasRealmPolicyRevision(DraftCommitBinding binding) { found = true; } else if (!REVISION_KIND.equals(revisionKind) && !AssetSource.REVISION_KIND.equals(revisionKind) - && !GameplayRuleSource.REVISION_KIND.equals(revisionKind)) { + && !GameplayRuleSource.REVISION_KIND.equals(revisionKind) + && !TemplateConfigSource.REVISION_KIND.equals(revisionKind)) { throw new IllegalArgumentException("Unsupported Game Design command source revision kind"); } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java index bc0add3a2c..baebc91ae0 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java @@ -127,7 +127,9 @@ public Optional apply(DraftCommitBinding binding) { List mutations = CommandSource.mutations(binding); boolean policyMutation = CommandSource.hasRealmPolicyRevision(binding); boolean assetMutation = !AssetSource.mutations(binding).isEmpty(); - requireCompleteControlPlaneScopes(binding, mutations, policyMutation, assetMutation); + boolean templateConfigMutation = !TemplateConfigSource.mutations(binding).isEmpty(); + requireCompleteControlPlaneScopes( + binding, mutations, policyMutation, assetMutation, templateConfigMutation); Optional existing = application(binding); if (existing.isPresent()) return existing; if (mutations.isEmpty()) return Optional.empty(); @@ -222,7 +224,8 @@ public CommandSnapshot captureSynchronized(DraftCommitBinding binding) { binding, mutations, CommandSource.hasRealmPolicyRevision(binding), - !AssetSource.mutations(binding).isEmpty()); + !AssetSource.mutations(binding).isEmpty(), + !TemplateConfigSource.mutations(binding).isEmpty()); List definitions; if (!mutations.isEmpty()) { CommandApplication applied = @@ -547,7 +550,8 @@ private void requireCompleteControlPlaneScopes( DraftCommitBinding binding, List commandMutations, boolean policyMutation, - boolean assetMutation) { + boolean assetMutation, + boolean templateConfigMutation) { List units = binding.affectedUnits(Owner.GAME_DESIGN_CONTROL_PLANE); List commands = @@ -562,11 +566,18 @@ private void requireCompleteControlPlaneScopes( .toList(); boolean gameplayMutation = !net.firedevops.firemud.common.gamedesign.GameplayRuleSource.mutations(binding).isEmpty(); + var templateConfigs = units.stream().filter(TemplateConfigSource::isScope).toList(); if (commands.size() != (commandMutations.isEmpty() ? 0 : 1) || policies.size() != (policyMutation ? 1 : 0) || assets.size() != (assetMutation ? 1 : 0) || gameplay.size() != (gameplayMutation ? 1 : 0) - || commands.size() + policies.size() + assets.size() + gameplay.size() != units.size()) { + || templateConfigs.size() != (templateConfigMutation ? 1 : 0) + || commands.size() + + policies.size() + + assets.size() + + gameplay.size() + + templateConfigs.size() + != units.size()) { throw new IllegalArgumentException( "Complete supported Game Design control-plane scopes are required"); } @@ -574,6 +585,8 @@ private void requireCompleteControlPlaneScopes( if (!policies.isEmpty()) requireScopeTarget(policies.getFirst(), binding.target()); if (!assets.isEmpty()) requireScopeTarget(assets.getFirst(), binding.target()); if (!gameplay.isEmpty()) requireScopeTarget(gameplay.getFirst(), binding.target()); + if (!templateConfigs.isEmpty()) + requireScopeTarget(templateConfigs.getFirst(), binding.target()); } private boolean isCommandScope(DraftCommitBinding.AffectedUnit unit) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java index da6f3ddb2f..b57e93bb4b 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java @@ -7,6 +7,8 @@ import java.util.Optional; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; import org.jooq.DSLContext; import org.jooq.Record; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -95,6 +97,40 @@ public GameDesignPublicationOperation requirePending( return operation; } + public void requireExactSelection(GameDesignPublicationOperation operation) { + Objects.requireNonNull(operation, "operation"); + var selected = operation.account().input().selection(); + var retained = + new AuthoredDraftPublishSelectionRepository(dsl, new DraftCommitCoordinatorRepository(dsl)) + .read( + selected.intent().canonicalTenantId(), + selected.intent().canonicalVersionId(), + selected.intent().publishRequestId()) + .orElseThrow(() -> new IllegalStateException("PUBLICATION_SELECTION_UNAVAILABLE")) + .selection(); + if (!Arrays.equals(selected.canonicalBytes(), retained.canonicalBytes()) + || !selected.digest().equals(retained.digest())) { + throw new IllegalStateException("PUBLICATION_SELECTION_CHANGED"); + } + } + + /** Requires one exact operation and selection with the requested owner terminal state. */ + public GameDesignPublicationOperation requireOutcome( + String tenant, String workflow, long version, String digest, String outcome) { + var result = + read(workflow) + .orElseThrow(() -> new IllegalStateException("PUBLICATION_OPERATION_UNAVAILABLE")); + var operation = result.operation(); + if (!operation.tenantKey().equals(tenant) + || operation.versionId() != version + || !operation.selectionDigest().equals(digest) + || !Objects.equals(result.outcome(), outcome)) { + throw new IllegalStateException("PUBLICATION_OPERATION_SEALED_OR_CHANGED"); + } + requireExactSelection(operation); + return operation; + } + public void seal(String tenant, String workflow, long version, String digest, boolean published) { GameDesignPublicationOperation operation = requirePending(tenant, workflow, version, digest); Record release = diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java index 075ef956a0..d55529b7ca 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java @@ -39,6 +39,7 @@ public final class GameDesignSourceRepository { private final CommandSourceRepository commands; private final AssetSourceRepository assets; private final GameplayRuleSourceRepository gameplay; + private final TemplateConfigSourceRepository templateConfigs; private final DraftCommitCoordinatorRepository coordinator; public GameDesignSourceRepository(DSLContext dsl) { @@ -47,6 +48,7 @@ public GameDesignSourceRepository(DSLContext dsl) { commands = new CommandSourceRepository(dsl); assets = new AssetSourceRepository(dsl); gameplay = new GameplayRuleSourceRepository(dsl); + templateConfigs = new TemplateConfigSourceRepository(dsl); coordinator = new DraftCommitCoordinatorRepository(dsl); } @@ -71,7 +73,10 @@ public Genesis enrollFreshDraft(TargetProof target) { target, policy.receiptId(), policy.creationTransactionId())); AssetSnapshot.Genesis asset = assets.enrollFreshDraft(target); var rules = gameplay.enrollFreshDraft(target); - Genesis result = new Genesis(policy, command, Optional.of(asset), Optional.of(rules)); + var templateConfig = templateConfigs.enrollFreshDraft(target); + Genesis result = + new Genesis( + policy, command, Optional.of(asset), Optional.of(rules), Optional.of(templateConfig)); if (!result.equals( readGenesis(target) .orElseThrow( @@ -88,13 +93,18 @@ public Optional readGenesis(TargetProof target) { var policy = policies.readGenesis(target); var command = commands.readNewDraftGenesis(target); var asset = assets.readGenesis(target); - if (policy.isEmpty() && command.isEmpty() && asset.isEmpty()) return Optional.empty(); + var rules = gameplay.readGenesis(target); + var templateConfig = templateConfigs.readGenesis(target); + if (policy.isEmpty() + && command.isEmpty() + && asset.isEmpty() + && rules.isEmpty() + && templateConfig.isEmpty()) return Optional.empty(); if (policy.isEmpty() || command.isEmpty()) { throw new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_INCOMPLETE"); } return Optional.of( - new Genesis( - policy.orElseThrow(), command.orElseThrow(), asset, gameplay.readGenesis(target))); + new Genesis(policy.orElseThrow(), command.orElseThrow(), asset, rules, templateConfig)); } /** Pure typed owner/scope validation; this does not read storage or grant write authority. */ @@ -103,12 +113,14 @@ public void validateInput(DraftCommitBinding binding) { var commandMutations = CommandSource.mutations(binding); boolean policyMutation = CommandSource.hasRealmPolicyRevision(binding); boolean assetMutation = !AssetSource.mutations(binding).isEmpty(); + boolean templateConfigMutation = !TemplateConfigSource.mutations(binding).isEmpty(); requireCompleteScopes( binding, !commandMutations.isEmpty(), policyMutation, assetMutation, - !GameplayRuleSource.mutations(binding).isEmpty()); + !GameplayRuleSource.mutations(binding).isEmpty(), + templateConfigMutation); } /** Stage actual source writes and record exactly one complete local owner outcome. */ @@ -118,6 +130,7 @@ public Application apply(DraftCommitBinding binding) { List commandMutations = CommandSource.mutations(binding); boolean policyMutation = CommandSource.hasRealmPolicyRevision(binding); boolean assetMutation = !AssetSource.mutations(binding).isEmpty(); + boolean templateConfigMutation = !TemplateConfigSource.mutations(binding).isEmpty(); requireGenesis(binding.target()); requireReviewed(binding); Optional command = commands.apply(binding); @@ -131,18 +144,25 @@ public Application apply(DraftCommitBinding binding) { var rules = gameplay.apply(binding); if (rules.isPresent() != !GameplayRuleSource.mutations(binding).isEmpty()) throw new IllegalStateException("GAMEPLAY_RULE_APPLICATION_INCOMPLETE"); + Optional templateConfig = + templateConfigs.apply(binding); + if (templateConfig.isPresent() != templateConfigMutation) + throw new IllegalStateException("GAME_DESIGN_TEMPLATE_CONFIG_APPLICATION_INCOMPLETE"); Optional policy = Optional.empty(); if (policyMutation) { // The policy-only path retains its existing exact owner result. Mixed input stages policy // first, then records the combined result using actual sibling readback bytes. policy = Optional.of( - command.isPresent() || asset.isPresent() || rules.isPresent() + command.isPresent() + || asset.isPresent() + || rules.isPresent() + || templateConfig.isPresent() ? policies.applyMutation(binding) : policies.apply(binding)); } OwnerOutcome expected; - if (asset.isPresent() || rules.isPresent()) { + if (asset.isPresent() || rules.isPresent() || templateConfig.isPresent()) { ByteArrayOutputStream components = new ByteArrayOutputStream(); DraftAuthorizationFenceBinding.frame( components, "game-design-control-plane-sibling-components/v1"); @@ -162,6 +182,12 @@ public Application apply(DraftCommitBinding binding) { DraftAuthorizationFenceBinding.frame(components, rules.orElseThrow().canonicalBytes()); epochs.add(rules.orElseThrow().appliedEpoch()); } + if (templateConfig.isPresent()) { + DraftAuthorizationFenceBinding.frame(components, "TEMPLATE_CONFIG"); + DraftAuthorizationFenceBinding.frame( + components, templateConfig.orElseThrow().canonicalBytes()); + epochs.add(templateConfig.orElseThrow().appliedEpoch()); + } if (policy.isPresent()) { var policyResult = policy.orElseThrow(); epochs.add(policyResult.ownerOutcome().appliedEpochs().getFirst()); @@ -215,7 +241,7 @@ public Application apply(DraftCommitBinding binding) { if (!expected.equals(retained)) { throw new IllegalStateException("GAME_DESIGN_OWNER_RESULT_READBACK_CONFLICT"); } - return new Application(binding, command, policy, asset, rules, retained); + return new Application(binding, command, policy, asset, rules, templateConfig, retained); } /** Invoke after the actual coordinator fence advances, before releasing its application slot. */ @@ -236,7 +262,11 @@ public SynchronizedSources captureSynchronized(DraftCommitBinding binding) { gameplay.readGenesis(binding.target()).isPresent() ? Optional.of(gameplay.captureSynchronized(binding)) : Optional.empty(); - return new SynchronizedSources(command, policy, Optional.of(asset), rules); + var templateConfig = + templateConfigs.readGenesis(binding.target()).isPresent() + ? Optional.of(templateConfigs.captureSynchronized(binding)) + : Optional.empty(); + return new SynchronizedSources(command, policy, Optional.of(asset), rules, templateConfig); } /** Freeze complete selected source snapshots against the same current retained operation. */ @@ -257,7 +287,13 @@ public Capture freeze(GameDesignPublicationOperation operation) { CommandSnapshot.Capture command = commands.freeze(operation); AssetSnapshot.Capture asset = assets.freeze(operation); GameplayRuleSnapshot.Capture gameplayCapture = gameplay.freeze(operation); - Capture result = new Capture(command, policy, Optional.of(asset), Optional.of(gameplayCapture)); + var templateConfig = + templateConfigs.readGenesis(operation.account().input().selection().target()).isPresent() + ? Optional.of(templateConfigs.freeze(operation)) + : Optional.empty(); + Capture result = + new Capture( + command, policy, Optional.of(asset), Optional.of(gameplayCapture), templateConfig); Capture retained = readCapture(operation) .orElseThrow( @@ -271,7 +307,8 @@ public Capture freeze(GameDesignPublicationOperation operation) { || retained.gameplay().isEmpty() || !Arrays.equals( result.gameplay().orElseThrow().canonicalBytes(), - retained.gameplay().orElseThrow().canonicalBytes())) { + retained.gameplay().orElseThrow().canonicalBytes()) + || !optionalCaptureBytesEqual(result.templateConfig(), retained.templateConfig())) { throw new IllegalStateException("GAME_DESIGN_SOURCE_CAPTURE_READBACK_CONFLICT"); } return retained; @@ -286,23 +323,38 @@ public Optional readCapture(GameDesignPublicationOperation operation) { var command = commands.readCapture(operation); var policy = policies.readCapture(operation); var asset = assets.readCapture(operation); + var target = operation.account().input().selection().target(); + boolean templateSourceEnrolled = templateConfigs.readGenesis(target).isPresent(); + var templateConfig = templateConfigs.readCapture(operation); var gameplayCapture = gameplay.readCapture(operation); - if (command.isEmpty() && policy.isEmpty() && asset.isEmpty() && gameplayCapture.isEmpty()) + if (command.isEmpty() + && policy.isEmpty() + && asset.isEmpty() + && gameplayCapture.isEmpty() + && templateConfig.isEmpty()) { return Optional.empty(); + } if (historicalOperation) { new GameDesignReviewedBaseRepository(dsl) .requireRetained(operation.account().input().selection().selectedCommit()); } boolean historicalGameplay = !historicalOperation && gameplayCapture.isEmpty() && operationIsTerminal(operation); + boolean historicalTemplate = + historicalOperation + || (templateSourceEnrolled + && templateConfig.isEmpty() + && operationIsTerminal(operation)); if (command.isEmpty() || policy.isEmpty() || (asset.isEmpty() && !historicalOperation) - || (gameplayCapture.isEmpty() && !historicalOperation && !historicalGameplay)) { + || (gameplayCapture.isEmpty() && !historicalOperation && !historicalGameplay) + || (templateSourceEnrolled && templateConfig.isEmpty() && !historicalTemplate)) { throw new IllegalStateException("GAME_DESIGN_SOURCE_CAPTURE_INCOMPLETE"); } return Optional.of( - new Capture(command.orElseThrow(), policy.orElseThrow(), asset, gameplayCapture)); + new Capture( + command.orElseThrow(), policy.orElseThrow(), asset, gameplayCapture, templateConfig)); } public Optional readSynchronized(TargetProof target, UUID commitId) { @@ -325,8 +377,14 @@ public Optional readSynchronized(TargetProof target, UUID c && (gameplay.readGenesis(target).isPresent() || !GameplayRuleSource.mutations(binding).isEmpty())) throw new IllegalStateException("GAMEPLAY_RULE_SYNCHRONIZED_SOURCE_INCOMPLETE"); + var templateConfig = templateConfigs.readSnapshot(target, commitId); + if (templateConfig.isEmpty() + && (templateConfigs.readGenesis(target).isPresent() + || !TemplateConfigSource.mutations(binding).isEmpty())) + throw new IllegalStateException("TEMPLATE_CONFIG_SYNCHRONIZED_SOURCE_INCOMPLETE"); return Optional.of( - new SynchronizedSources(command.orElseThrow(), policy.orElseThrow(), asset, rules)); + new SynchronizedSources( + command.orElseThrow(), policy.orElseThrow(), asset, rules, templateConfig)); } private void requireGenesis(TargetProof target) { @@ -381,8 +439,9 @@ private static void requireCompleteScopes( boolean hasCommand, boolean hasPolicy, boolean hasAsset, - boolean hasGameplay) { - if (!hasCommand && !hasPolicy && !hasAsset && !hasGameplay + boolean hasGameplay, + boolean hasTemplateConfig) { + if (!hasCommand && !hasPolicy && !hasAsset && !hasGameplay && !hasTemplateConfig || !binding.requiredOwners().contains(Owner.GAME_DESIGN_CONTROL_PLANE)) { throw new IllegalArgumentException("Game Design owner requires typed source revisions"); } @@ -405,11 +464,14 @@ private static void requireCompleteScopes( .toList(); List assets = units.stream().filter(AssetSourceRepository::isScope).toList(); var rules = units.stream().filter(GameplayRuleSource::isScope).toList(); + var templateConfigs = units.stream().filter(TemplateConfigSource::isScope).toList(); if (commands.size() != (hasCommand ? 1 : 0) || policies.size() != (hasPolicy ? 1 : 0) || assets.size() != (hasAsset ? 1 : 0) || rules.size() != (hasGameplay ? 1 : 0) - || commands.size() + policies.size() + assets.size() + rules.size() != units.size() + || templateConfigs.size() != (hasTemplateConfig ? 1 : 0) + || commands.size() + policies.size() + assets.size() + rules.size() + templateConfigs.size() + != units.size() || units.stream() .anyMatch( unit -> @@ -438,12 +500,14 @@ public record Genesis( RealmPolicyGenesis policy, CommandSource.NewDraftGenesisReceipt command, Optional assetEvidence, - Optional gameplayEvidence) { + Optional gameplayEvidence, + Optional templateConfig) { public Genesis { Objects.requireNonNull(policy, "policy"); Objects.requireNonNull(command, "command"); assetEvidence = Objects.requireNonNull(assetEvidence, "assetEvidence"); gameplayEvidence = Objects.requireNonNull(gameplayEvidence, "gameplayEvidence"); + templateConfig = Objects.requireNonNull(templateConfig, "templateConfig"); if (gameplayEvidence.isPresent() && (!policy.target().equals(gameplayEvidence.orElseThrow().target()) || !policy @@ -460,17 +524,32 @@ public record Genesis( .equals(assetEvidence.orElseThrow().creationTransactionId()))) { throw new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_IDENTITY_CONFLICT"); } + if (templateConfig.isPresent() + && (!policy.target().equals(templateConfig.orElseThrow().target()) + || !policy + .creationTransactionId() + .equals(templateConfig.orElseThrow().creationTransactionId()))) { + throw new IllegalStateException("TEMPLATE_CONFIG_GENESIS_IDENTITY_CONFLICT"); + } + } + + public Genesis( + RealmPolicyGenesis policy, + CommandSource.NewDraftGenesisReceipt command, + Optional assetEvidence, + Optional gameplayEvidence) { + this(policy, command, assetEvidence, gameplayEvidence, Optional.empty()); } public Genesis( RealmPolicyGenesis policy, CommandSource.NewDraftGenesisReceipt command, Optional assetEvidence) { - this(policy, command, assetEvidence, Optional.empty()); + this(policy, command, assetEvidence, Optional.empty(), Optional.empty()); } public Genesis(RealmPolicyGenesis policy, CommandSource.NewDraftGenesisReceipt command) { - this(policy, command, Optional.empty()); + this(policy, command, Optional.empty(), Optional.empty(), Optional.empty()); } public AssetSnapshot.Genesis asset() { @@ -485,6 +564,7 @@ public record Application( Optional policy, Optional asset, Optional gameplay, + Optional templateConfig, OwnerOutcome ownerOutcome) { public Application { Objects.requireNonNull(binding, "binding"); @@ -492,12 +572,18 @@ public record Application( policy = Objects.requireNonNull(policy, "policy"); asset = Objects.requireNonNull(asset, "asset"); gameplay = Objects.requireNonNull(gameplay, "gameplay"); + templateConfig = Objects.requireNonNull(templateConfig, "templateConfig"); Objects.requireNonNull(ownerOutcome, "ownerOutcome"); - if (command.isEmpty() && policy.isEmpty() && asset.isEmpty() && gameplay.isEmpty() + if (command.isEmpty() + && policy.isEmpty() + && asset.isEmpty() + && gameplay.isEmpty() + && templateConfig.isEmpty() || command.isPresent() && !binding.equals(command.orElseThrow().binding()) || policy.isPresent() && !binding.equals(policy.orElseThrow().snapshot().binding()) || asset.isPresent() && !binding.equals(asset.orElseThrow().binding()) || gameplay.isPresent() && !binding.equals(gameplay.orElseThrow().binding()) + || templateConfig.isPresent() && !binding.equals(templateConfig.orElseThrow().binding()) || ownerOutcome.owner() != Owner.GAME_DESIGN_CONTROL_PLANE || ownerOutcome.status() != OwnerStatus.APPLIED || !binding.commitId().equals(ownerOutcome.commitId()) @@ -506,13 +592,23 @@ public record Application( } } + public Application( + DraftCommitBinding binding, + Optional command, + Optional policy, + Optional asset, + Optional gameplay, + OwnerOutcome ownerOutcome) { + this(binding, command, policy, asset, gameplay, Optional.empty(), ownerOutcome); + } + public Application( DraftCommitBinding binding, Optional command, Optional policy, Optional asset, OwnerOutcome ownerOutcome) { - this(binding, command, policy, asset, Optional.empty(), ownerOutcome); + this(binding, command, policy, asset, Optional.empty(), Optional.empty(), ownerOutcome); } } @@ -520,15 +616,20 @@ public record SynchronizedSources( CommandSnapshot command, RealmPolicySnapshot policy, Optional assetEvidence, - Optional gameplayEvidence) { + Optional gameplayEvidence, + Optional templateConfig) { public SynchronizedSources { Objects.requireNonNull(command, "command"); Objects.requireNonNull(policy, "policy"); assetEvidence = Objects.requireNonNull(assetEvidence, "assetEvidence"); gameplayEvidence = Objects.requireNonNull(gameplayEvidence, "gameplayEvidence"); + templateConfig = Objects.requireNonNull(templateConfig, "templateConfig"); if (gameplayEvidence.isPresent() && !command.binding().equals(gameplayEvidence.orElseThrow().binding())) throw new IllegalStateException("GAMEPLAY_RULE_SOURCE_SNAPSHOT_BINDING_CONFLICT"); + if (templateConfig.isPresent() + && !command.binding().equals(templateConfig.orElseThrow().binding())) + throw new IllegalStateException("TEMPLATE_CONFIG_SOURCE_SNAPSHOT_BINDING_CONFLICT"); if (!command.binding().equals(policy.binding()) || assetEvidence.isPresent() && !command.binding().equals(assetEvidence.orElseThrow().binding())) { @@ -540,7 +641,15 @@ public SynchronizedSources( CommandSnapshot command, RealmPolicySnapshot policy, Optional assetEvidence) { - this(command, policy, assetEvidence, Optional.empty()); + this(command, policy, assetEvidence, Optional.empty(), Optional.empty()); + } + + public SynchronizedSources( + CommandSnapshot command, + RealmPolicySnapshot policy, + Optional assetEvidence, + Optional gameplayEvidence) { + this(command, policy, assetEvidence, gameplayEvidence, Optional.empty()); } public AssetSnapshot asset() { @@ -553,12 +662,14 @@ public record Capture( CommandSnapshot.Capture command, RealmPolicySnapshot.Capture policy, Optional asset, - Optional gameplay) { + Optional gameplay, + Optional templateConfig) { public Capture { Objects.requireNonNull(command, "command"); Objects.requireNonNull(policy, "policy"); asset = Objects.requireNonNull(asset, "asset"); gameplay = Objects.requireNonNull(gameplay, "gameplay"); + templateConfig = Objects.requireNonNull(templateConfig, "templateConfig"); if (!Arrays.equals(command.operation().canonicalBytes(), policy.operation().canonicalBytes()) || !command.snapshot().binding().equals(policy.snapshot().binding()) || asset.isPresent() @@ -576,6 +687,30 @@ public record Capture( .equals(gameplay.orElseThrow().snapshot().binding()))) { throw new IllegalStateException("GAME_DESIGN_SOURCE_CAPTURE_BINDING_CONFLICT"); } + if (templateConfig.isPresent() + && (!Arrays.equals( + command.operation().canonicalBytes(), + templateConfig.orElseThrow().operation().canonicalBytes()) + || !command + .snapshot() + .binding() + .equals(templateConfig.orElseThrow().snapshot().binding()))) { + throw new IllegalStateException("GAME_DESIGN_TEMPLATE_CONFIG_CAPTURE_BINDING_CONFLICT"); + } } + + public Capture( + CommandSnapshot.Capture command, + RealmPolicySnapshot.Capture policy, + Optional asset) { + this(command, policy, asset, Optional.empty(), Optional.empty()); + } + } + + private static boolean optionalCaptureBytesEqual( + Optional left, + Optional right) { + if (left.isEmpty() || right.isEmpty()) return left.isEmpty() && right.isEmpty(); + return Arrays.equals(left.orElseThrow().canonicalBytes(), right.orElseThrow().canonicalBytes()); } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GrpcAuthoredInitialActorCoreReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GrpcAuthoredInitialActorCoreReadService.java new file mode 100644 index 0000000000..2bacabbbd0 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GrpcAuthoredInitialActorCoreReadService.java @@ -0,0 +1,116 @@ +package net.firedevops.firemud.gamedesign.publication; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence.ReadRequest; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamedesign.v1.GameDesignAuthoredInitialActorCoreReadServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.ReadAuthoredInitialActorCoreRequest; +import net.firedevops.firemud.gamedesign.v1.ReadAuthoredInitialActorCoreResponse; + +/** + * Standalone, unregistered workload-authenticated authored-core projection endpoint. + * + *

The handler's 128 KiB request check runs after gRPC has received and buffered the message. Any + * future receiving server composition must enforce the same inbound limit before registering this + * adapter; the handler guard remains defense in depth. + */ +public final class GrpcAuthoredInitialActorCoreReadService + extends GameDesignAuthoredInitialActorCoreReadServiceGrpc + .GameDesignAuthoredInitialActorCoreReadServiceImplBase { + public static final int MAX_REQUEST_WIRE_BYTES = 128 * 1024; + private final AuthoredInitialActorCoreReadService service; + private final String workloadNamespace; + + public GrpcAuthoredInitialActorCoreReadService( + AuthoredInitialActorCoreReadService service, String workloadNamespace) { + this.service = Objects.requireNonNull(service, "service"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Design workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + @Override + public void readAuthoredInitialActorCore( + ReadAuthoredInitialActorCoreRequest request, + StreamObserver observer) { + try { + requirePeer(); + if (SessionContext.hasAuthenticatedCallerContext()) { + throw Status.PERMISSION_DENIED + .withDescription("Workload-only authored-core read required") + .asRuntimeException(); + } + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + if (request.getSerializedSize() > MAX_REQUEST_WIRE_BYTES) { + observer.onError( + Status.RESOURCE_EXHAUSTED + .withDescription("Authored-core request exceeds its bounded wire size") + .asRuntimeException()); + return; + } + + final ReadRequest decoded; + try { + decoded = AuthoredInitialActorCoreReadGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException malformed) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Exact canonical authored-core replay request required") + .asRuntimeException()); + return; + } + if (!workloadNamespace.equals(decoded.associationRequest().targetNamespace())) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription("Authored-core target namespace differs from peer") + .asRuntimeException()); + return; + } + try { + observer.onNext(AuthoredInitialActorCoreReadGrpcCodec.toResponse(service.read(decoded))); + observer.onCompleted(); + } catch (StatusRuntimeException failure) { + observer.onError( + Status.fromCode(Status.fromThrowable(failure).getCode()) + .withDescription("Exact authored-core owner read denied or unavailable") + .asRuntimeException()); + } catch (IllegalArgumentException invalidResult) { + observer.onError( + Status.INTERNAL + .withDescription("Game Design returned invalid authored-core owner evidence") + .asRuntimeException()); + } catch (RuntimeException unavailable) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Game Design authored-core owner read unavailable") + .asRuntimeException()); + } + } + + private void requirePeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified same-namespace Game Session or Entity workload required") + .asRuntimeException(); + } + String expectedPrefix = "spiffe://firemud/ns/" + workloadNamespace + "/sa/"; + if (!workloadNamespace.equals(peer.namespace()) + || !("game-session-service".equals(peer.service()) + || "entity-management-service".equals(peer.service())) + || !(expectedPrefix + peer.service()).equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Session or Entity workload required") + .asRuntimeException(); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/PublishedReleaseEvidenceEncoding.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/PublishedReleaseEvidenceEncoding.java new file mode 100644 index 0000000000..1a8f7beaee --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/PublishedReleaseEvidenceEncoding.java @@ -0,0 +1,133 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.util.List; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; +import net.firedevops.firemud.gamedesign.v1.ParticipantDigest; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; + +/** Shared canonical conversion from the published release DTO into retained read evidence. */ +final class PublishedReleaseEvidenceEncoding { + private PublishedReleaseEvidenceEncoding() {} + + static PublishedReleaseBundle toPublishedReleaseBundle(PublishedReleaseBundleDto dto) { + Objects.requireNonNull(dto, "dto"); + var builder = + PublishedReleaseBundle.newBuilder() + .setId(dto.id()) + .setVersionId(dto.versionId()) + .setVersionNumber(dto.versionNumber()) + .setAttestationSchemaVersion(dto.attestationSchemaVersion()) + .setPublishWorkflowId(dto.publishWorkflowId()) + .setManifestHash(dto.manifestHash()) + .addAllRequiredManifestAssetKeys(dto.requiredManifestAssetKeys()) + .setIsScriptOnly(dto.scriptOnly()) + .setScriptPatchVersion(Objects.requireNonNullElse(dto.scriptPatchVersion(), "")) + .setPublishedAt(dto.publishedAt().toString()) + .setGenerationConfigRevision(dto.generationConfigRevision()) + .addAllCommandDefinitions(dto.commandDefinitions()) + .setPublishedReleaseBundleRef(dto.publishedReleaseBundleRef()) + .setCanonicalTenantId(dto.canonicalTenantId().toString()) + .setCanonicalVersionId(dto.canonicalVersionId().toString()); + for (PublishParticipantDigestDto participant : dto.participantDigests()) { + if (!participant.succeeded()) throw new FailedParticipantException(); + var value = + ParticipantDigest.newBuilder() + .setParticipantKey(participant.participantKey()) + .setScopeValue(participant.scopeValue()) + .setAppliedCommitId(Objects.requireNonNull(participant.appliedCommitId())) + .setContentDigest(Objects.requireNonNull(participant.contentDigest())) + .setDigestSchemaVersion(Objects.requireNonNull(participant.digestSchemaVersion())); + if (participant.abilitySchemaDigest() != null) { + value.setAbilitySchemaDigest(participant.abilitySchemaDigest()); + } + builder.addParticipantDigests(value); + } + if (dto.manifestSchemaVersion() != null) { + builder.setManifestSchemaVersion(dto.manifestSchemaVersion()); + } + if (dto.artifactDigests() != null) { + for (PublishedArtifactDigest artifact : dto.artifactDigests()) { + builder.addArtifactDigests( + net.firedevops.firemud.gamedesign.v1.PublishedArtifactDigest.newBuilder() + .setUsageKey(artifact.usageKey()) + .setArtifactKind(artifact.artifactKind()) + .setImmutableObjectKey(artifact.immutableObjectKey()) + .setContentDigest(artifact.contentDigest()) + .setContentType(artifact.contentType()) + .setArtifactSchemaVersion(artifact.artifactSchemaVersion())); + } + } + return builder.build(); + } + + static GameDesignPublicationTerminalEvidence.ReleaseContent releaseContent( + PublishedReleaseBundleDto dto) { + Objects.requireNonNull(dto, "dto"); + if (dto.manifestSchemaVersion() == null || dto.artifactDigests() == null) { + throw new IncompleteArtifactProofException(); + } + List participants = + dto.participantDigests().stream() + .map( + value -> + new GameDesignPublicationTerminalEvidence.Participant( + value.participantKey(), + value.scopeValue(), + value.baseVersionId(), + value.appliedCommitId(), + value.contentDigest(), + Objects.requireNonNull(value.digestSchemaVersion()), + value.abilitySchemaDigest(), + value.errorCode(), + value.errorMessage())) + .toList(); + List artifacts = + dto.artifactDigests().stream() + .map( + value -> + new AuthoredWorldReleaseAttestationEvidence.Artifact( + value.usageKey(), + value.artifactKind(), + value.immutableObjectKey(), + value.contentDigest(), + value.contentType(), + value.artifactSchemaVersion())) + .toList(); + return new GameDesignPublicationTerminalEvidence.ReleaseContent( + dto.canonicalTenantId(), + dto.canonicalVersionId(), + dto.publishedReleaseBundleRef(), + dto.versionNumber(), + dto.attestationSchemaVersion(), + dto.publishWorkflowId(), + dto.manifestHash(), + dto.manifestSchemaVersion(), + artifacts, + dto.requiredManifestAssetKeys(), + participants, + dto.commandDefinitions(), + dto.generationConfigRevision(), + dto.worldPublishedStartLocationEvidence()); + } + + static final class FailedParticipantException extends IllegalStateException { + private static final long serialVersionUID = 1L; + + private FailedParticipantException() { + super("Published release participant did not succeed"); + } + } + + static final class IncompleteArtifactProofException extends IllegalStateException { + private static final long serialVersionUID = 1L; + + private IncompleteArtifactProofException() { + super("Immutable release content evidence is incomplete"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java index 817f81d15e..2278d90f05 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java @@ -74,8 +74,8 @@ public static boolean isPolicyRevision(DraftCommitBinding.RevisionPayload input) if (RealmEntryPolicy.REVISION_KIND.equals(kind)) return true; if ("COMMAND_DEFINITION".equals(kind) || AssetSource.REVISION_KIND.equals(kind) - || net.firedevops.firemud.common.gamedesign.GameplayRuleSource.REVISION_KIND.equals(kind)) - return false; + || net.firedevops.firemud.common.gamedesign.GameplayRuleSource.REVISION_KIND.equals(kind) + || TemplateConfigSource.REVISION_KIND.equals(kind)) return false; throw new IllegalArgumentException("Unsupported Game Design owner revision kind"); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationOwner.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationOwner.java new file mode 100644 index 0000000000..3b774a371a --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationOwner.java @@ -0,0 +1,258 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import net.firedevops.firemud.gamedesign.entity.PublishAttempt; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; +import net.firedevops.firemud.gamedesign.model.PublishType; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import org.jooq.DSLContext; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered Game Design owner entry for reserving publication of one existing synchronized + * Draft. It persists exact local selection/attempt/source state; supplied Account, World, and + * World-source objects are structured evidence, not proof that either remote owner authenticated + * its producer. A production caller must obtain them from the authenticated Account publication + * producer and protected World reads. Isolated fixtures may supply synthetic values only to test + * this owner-local boundary. + */ +public final class SelectedDraftPublicationOwner { + private final GameRepository games; + private final VersionRepository versions; + private final AuthoredDraftPublishSelectionRepository selections; + private final PublishAttemptRepository attempts; + private final GameDesignPublicationOperationRepository operations; + private final SelectedDraftTemplateWorldSourceAssociationRepository templateWorldSources; + + public SelectedDraftPublicationOwner(DSLContext dsl) { + Objects.requireNonNull(dsl, "dsl"); + var coordinator = new DraftCommitCoordinatorRepository(dsl); + games = new GameRepository(dsl); + versions = new VersionRepository(dsl); + selections = new AuthoredDraftPublishSelectionRepository(dsl, coordinator); + attempts = new PublishAttemptRepository(dsl); + operations = new GameDesignPublicationOperationRepository(dsl); + templateWorldSources = new SelectedDraftTemplateWorldSourceAssociationRepository(dsl); + } + + /** + * Retains a first selection and its original external publication inputs in one caller-owned + * writable READ_COMMITTED transaction. Existing operations only exact-read their original source + * relation; an old full-publish digest is never rewritten or upgraded here. + */ + public Reservation reserve( + AuthoredDraftPublishSelection.PublishIntent intent, + AccountPublicationAuthorizationBinding account, + WorldPublishedStartLocationEvidence world, + WorldSelectedPublicationArtifactInventoryEvidence inventory, + SelectedDraftTemplateWorldSourceAssociation.SourceRead worldSourceRead) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(intent, "intent"); + Objects.requireNonNull(account, "account"); + Objects.requireNonNull(world, "world"); + Objects.requireNonNull(worldSourceRead, "worldSourceRead"); + + Version identityCandidate = + versions + .findByCanonicalTenantIdAndCanonicalVersionId( + intent.canonicalTenantId(), intent.canonicalVersionId()) + .orElseThrow( + () -> new IllegalStateException("SELECTED_PUBLICATION_VERSION_UNAVAILABLE")); + String tenantKey = identityCandidate.getTenantId(); + var game = games.findByTenantIdForUpdate(tenantKey); + if (game == null + || !intent.canonicalTenantId().equals(game.getCanonicalTenantId()) + || !intent.canonicalTenantId().equals(identityCandidate.getCanonicalTenantId())) { + throw new IllegalStateException("SELECTED_PUBLICATION_GAME_IDENTITY_CHANGED"); + } + + var selectionSnapshot = selections.reserve(intent); + var selection = selectionSnapshot.selection(); + var selectedBinding = account.input().selection(); + if (!Arrays.equals(selection.canonicalBytes(), selectedBinding.canonicalBytes()) + || !selection.digest().equals(selectedBinding.digest())) { + throw new IllegalStateException("SELECTED_PUBLICATION_SELECTION_CHANGED"); + } + + var operation = new GameDesignPublicationOperation(account, world, inventory); + String workflowId = + PublicationDigestRequestBinding.full( + selection.target().canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + intent.publishRequestId()) + .derivedWorkflowIdentity(); + if (!workflowId.equals(operation.workflowId()) + || !selection.target().canonicalTenantId().equals(world.request().canonicalTenantId()) + || !selection.target().canonicalVersionId().equals(world.request().canonicalVersionId()) + || !intent.publishRequestId().equals(world.request().publicationRequestId()) + || !intent + .expectedVersionStateEpoch() + .equals(Long.toString(world.request().versionStateEpoch())) + || !selection + .selectedCommit() + .commitId() + .toString() + .equals(world.request().appliedCommitId()) + || !selection.digest().equals("sha256:" + world.request().requestDigest())) { + throw new IllegalStateException("SELECTED_PUBLICATION_OPERATION_BINDING_CHANGED"); + } + + var priorOperation = operations.read(operation.workflowId()); + if (priorOperation.isPresent() + && !Arrays.equals( + operation.canonicalBytes(), + priorOperation.orElseThrow().operation().canonicalBytes())) { + throw new IllegalStateException("SELECTED_PUBLICATION_OPERATION_IDENTITY_CONFLICT"); + } + + if (!tenantKey.equals(selection.target().gameDesignVersionTenantKey())) { + throw new IllegalStateException("SELECTED_PUBLICATION_TENANT_KEY_CHANGED"); + } + Version version = + versions + .findByTenantIdAndIdForUpdate(tenantKey, selection.target().gameDesignVersionRowId()) + .orElseThrow( + () -> new IllegalStateException("SELECTED_PUBLICATION_VERSION_UNAVAILABLE")); + requireExactSelectedVersion(selection, version); + + PublishAttempt attempt = + attempts.findByPublishWorkflowIdForUpdate(operation.workflowId()).orElse(null); + if (attempt == null) { + attempt = new PublishAttempt(); + attempt.setTenantId(tenantKey); + attempt.setPublishWorkflowId(operation.workflowId()); + attempt.setPublishType(PublishType.FULL_VERSION); + attempt.setVersionId(version.getId()); + attempt.setVersionNumber(version.getVersionNumber()); + attempt.setRequestDigest(selection.digest()); + attempt = attempts.save(attempt); + } else { + requireExactSelectedAttempt(attempt, operation, version, selection.digest()); + if (attempt.getStatus() != PublishAttemptStatus.PENDING) { + throw new IllegalStateException("SELECTED_PUBLICATION_ATTEMPT_TERMINAL"); + } + } + + var capture = operations.reserveSourceBacked(operation); + var gameplayCapture = + capture + .gameplay() + .orElseThrow( + () -> + new IllegalStateException( + "SELECTED_PUBLICATION_GAMEPLAY_SOURCE_CAPTURE_UNAVAILABLE")); + var templateCapture = + capture + .templateConfig() + .orElseThrow( + () -> + new IllegalStateException( + "SELECTED_PUBLICATION_TEMPLATE_SOURCE_CAPTURE_UNAVAILABLE")); + templateWorldSources.retainOrRead( + operation, templateCapture, worldSourceRead, priorOperation.isEmpty()); + var retained = + operations + .read(operation.workflowId()) + .orElseThrow( + () -> new IllegalStateException("SELECTED_PUBLICATION_READBACK_UNAVAILABLE")); + var retainedSelection = + selections + .read( + intent.canonicalTenantId(), intent.canonicalVersionId(), intent.publishRequestId()) + .orElseThrow( + () -> + new IllegalStateException( + "SELECTED_PUBLICATION_SELECTION_READBACK_UNAVAILABLE")) + .selection(); + if (!Arrays.equals(operation.canonicalBytes(), retained.operation().canonicalBytes()) + || !"PENDING".equals(retained.outcome()) + || !Arrays.equals(selection.canonicalBytes(), retainedSelection.canonicalBytes()) + || !capture.command().operation().equals(operation) + || !capture.policy().operation().equals(operation) + || !Arrays.equals(gameplayCapture.operation().canonicalBytes(), operation.canonicalBytes()) + || !selection.selectedCommit().equals(gameplayCapture.snapshot().binding())) { + throw new IllegalStateException("SELECTED_PUBLICATION_RESERVATION_READBACK_CONFLICT"); + } + long attemptId = + Objects.requireNonNull(attempt.getId(), "reserved publication attempt must be persisted"); + return new Reservation(selection, operation, attemptId, capture); + } + + private static void requireExactSelectedVersion( + net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection selection, + Version version) { + var target = selection.target(); + var actualTarget = + new net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + if (!target.equals(actualTarget) + || version.getVersionState() != VersionLifecycleState.DRAFT + || version.isScriptOnly() + || version.getBaseVersionId() != null + || version.getScriptPatchVersion() != null + || !Long.toString(version.getVersionStateEpoch()) + .equals(selection.intent().expectedVersionStateEpoch())) { + throw new IllegalStateException("SELECTED_PUBLICATION_VERSION_CHANGED"); + } + } + + private static void requireExactSelectedAttempt( + PublishAttempt attempt, + GameDesignPublicationOperation operation, + Version version, + String selectionDigest) { + if (!Objects.equals(attempt.getTenantId(), operation.tenantKey()) + || !Objects.equals(attempt.getPublishWorkflowId(), operation.workflowId()) + || attempt.getPublishType() != PublishType.FULL_VERSION + || !Objects.equals(attempt.getVersionId(), version.getId()) + || attempt.getVersionNumber() != version.getVersionNumber() + || !Objects.equals(attempt.getRequestDigest(), selectionDigest)) { + throw new IllegalStateException("SELECTED_PUBLICATION_ATTEMPT_IDENTITY_CONFLICT"); + } + } + + private static void requireWritableReadCommittedTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isSynchronizationActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Selected Draft publication reservation requires caller-owned writable READ_COMMITTED transaction"); + } + } + + public record Reservation( + net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection selection, + GameDesignPublicationOperation operation, + long attemptId, + GameDesignSourceRepository.Capture sourceCapture) { + public Reservation { + Objects.requireNonNull(selection); + Objects.requireNonNull(operation); + if (attemptId <= 0) { + throw new IllegalArgumentException("reserved publication attempt ID must be positive"); + } + Objects.requireNonNull(sourceCapture); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftTemplateWorldSourceAssociation.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftTemplateWorldSourceAssociation.java new file mode 100644 index 0000000000..39eecd5852 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftTemplateWorldSourceAssociation.java @@ -0,0 +1,294 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; + +/** + * Immutable relation between one captured selected template and the exact World-authored source + * returned for the original publication freeze. Structured evidence is not producer authority; + * production admission obtains it from authenticated World and owner-local reads. + */ +public final class SelectedDraftTemplateWorldSourceAssociation { + private static final String SCHEMA = "game-design-selected-template-world-source-association/v1"; + + private SelectedDraftTemplateWorldSourceAssociation() {} + + /** + * Exact by-ID request and complete public World response, including the independent read echo. + */ + public record SourceRead(ByIdReadRequest request, PublicReceipt receipt) { + public SourceRead { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(receipt, "receipt"); + WorldAuthoredSourceIntakeGrpcCodec.toReadByIdResponse(request, receipt); + } + + public byte[] requestBytes() { + return WorldAuthoredSourceIntakeGrpcCodec.toReadByIdRequest(request).toByteArray(); + } + + public byte[] responseBytes() { + return WorldAuthoredSourceIntakeGrpcCodec.toReadByIdResponse(request, receipt).toByteArray(); + } + } + + /** Canonical frozen row to retain; the public World response contains no World-private keys. */ + public static final class Association { + private final UUID canonicalTenantId; + private final UUID canonicalVersionId; + private final UUID selectedCommitId; + private final long templateId; + private final String publishWorkflowId; + private final String targetNamespace; + private final UUID intakeRequestId; + private final UUID worldOperationId; + private final UUID sourceOperationId; + private final String worldSlug; + private final String sourceEvidenceDigest; + private final byte[] operationBytes; + private final byte[] captureBytes; + private final byte[] templateSnapshotBytes; + private final byte[] templateEntryBytes; + private final byte[] worldReadRequestBytes; + private final byte[] worldReadResponseBytes; + private final byte[] canonicalBytes; + private final String digest; + + private Association( + UUID canonicalTenantId, + UUID canonicalVersionId, + UUID selectedCommitId, + long templateId, + String publishWorkflowId, + String targetNamespace, + UUID intakeRequestId, + UUID worldOperationId, + UUID sourceOperationId, + String worldSlug, + String sourceEvidenceDigest, + byte[] operationBytes, + byte[] captureBytes, + byte[] templateSnapshotBytes, + byte[] templateEntryBytes, + byte[] worldReadRequestBytes, + byte[] worldReadResponseBytes) { + this.canonicalTenantId = Objects.requireNonNull(canonicalTenantId); + this.canonicalVersionId = Objects.requireNonNull(canonicalVersionId); + this.selectedCommitId = Objects.requireNonNull(selectedCommitId); + if (templateId <= 0) + throw new IllegalArgumentException("Positive template identity required"); + this.templateId = templateId; + this.publishWorkflowId = Objects.requireNonNull(publishWorkflowId); + this.targetNamespace = Objects.requireNonNull(targetNamespace); + this.intakeRequestId = Objects.requireNonNull(intakeRequestId); + this.worldOperationId = Objects.requireNonNull(worldOperationId); + this.sourceOperationId = Objects.requireNonNull(sourceOperationId); + this.worldSlug = Objects.requireNonNull(worldSlug); + this.sourceEvidenceDigest = Objects.requireNonNull(sourceEvidenceDigest); + this.operationBytes = copy(operationBytes); + this.captureBytes = copy(captureBytes); + this.templateSnapshotBytes = copy(templateSnapshotBytes); + this.templateEntryBytes = copy(templateEntryBytes); + this.worldReadRequestBytes = copy(worldReadRequestBytes); + this.worldReadResponseBytes = copy(worldReadResponseBytes); + this.canonicalBytes = buildCanonicalBytes(); + this.digest = CommandSource.sha256(this.canonicalBytes); + } + + public UUID canonicalTenantId() { + return canonicalTenantId; + } + + public UUID canonicalVersionId() { + return canonicalVersionId; + } + + public UUID selectedCommitId() { + return selectedCommitId; + } + + public long templateId() { + return templateId; + } + + public String publishWorkflowId() { + return publishWorkflowId; + } + + public String targetNamespace() { + return targetNamespace; + } + + public UUID intakeRequestId() { + return intakeRequestId; + } + + public UUID worldOperationId() { + return worldOperationId; + } + + public UUID sourceOperationId() { + return sourceOperationId; + } + + public String worldSlug() { + return worldSlug; + } + + public String sourceEvidenceDigest() { + return sourceEvidenceDigest; + } + + public byte[] operationBytes() { + return copy(operationBytes); + } + + public byte[] captureBytes() { + return copy(captureBytes); + } + + public byte[] templateSnapshotBytes() { + return copy(templateSnapshotBytes); + } + + public byte[] templateEntryBytes() { + return copy(templateEntryBytes); + } + + public byte[] worldReadRequestBytes() { + return copy(worldReadRequestBytes); + } + + public byte[] worldReadResponseBytes() { + return copy(worldReadResponseBytes); + } + + public byte[] canonicalBytes() { + return copy(canonicalBytes); + } + + public String digest() { + return digest; + } + + public boolean sameStoredValue(Association other) { + return other != null + && canonicalTenantId.equals(other.canonicalTenantId) + && canonicalVersionId.equals(other.canonicalVersionId) + && selectedCommitId.equals(other.selectedCommitId) + && templateId == other.templateId + && publishWorkflowId.equals(other.publishWorkflowId) + && targetNamespace.equals(other.targetNamespace) + && intakeRequestId.equals(other.intakeRequestId) + && worldOperationId.equals(other.worldOperationId) + && sourceOperationId.equals(other.sourceOperationId) + && worldSlug.equals(other.worldSlug) + && sourceEvidenceDigest.equals(other.sourceEvidenceDigest) + && Arrays.equals(operationBytes, other.operationBytes) + && Arrays.equals(captureBytes, other.captureBytes) + && Arrays.equals(templateSnapshotBytes, other.templateSnapshotBytes) + && Arrays.equals(templateEntryBytes, other.templateEntryBytes) + && Arrays.equals(worldReadRequestBytes, other.worldReadRequestBytes) + && Arrays.equals(worldReadResponseBytes, other.worldReadResponseBytes) + && Arrays.equals(canonicalBytes, other.canonicalBytes) + && digest.equals(other.digest); + } + + private byte[] buildCanonicalBytes() { + var output = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(output, SCHEMA); + DraftAuthorizationFenceBinding.frame(output, canonicalTenantId.toString()); + DraftAuthorizationFenceBinding.frame(output, canonicalVersionId.toString()); + DraftAuthorizationFenceBinding.frame(output, selectedCommitId.toString()); + DraftAuthorizationFenceBinding.frame(output, Long.toString(templateId)); + DraftAuthorizationFenceBinding.frame(output, publishWorkflowId); + DraftAuthorizationFenceBinding.frame(output, targetNamespace); + DraftAuthorizationFenceBinding.frame(output, intakeRequestId.toString()); + DraftAuthorizationFenceBinding.frame(output, worldOperationId.toString()); + DraftAuthorizationFenceBinding.frame(output, sourceOperationId.toString()); + DraftAuthorizationFenceBinding.frame(output, worldSlug); + DraftAuthorizationFenceBinding.frame(output, sourceEvidenceDigest); + DraftAuthorizationFenceBinding.frame(output, operationBytes); + DraftAuthorizationFenceBinding.frame(output, captureBytes); + DraftAuthorizationFenceBinding.frame(output, templateSnapshotBytes); + DraftAuthorizationFenceBinding.frame(output, templateEntryBytes); + DraftAuthorizationFenceBinding.frame(output, worldReadRequestBytes); + DraftAuthorizationFenceBinding.frame(output, worldReadResponseBytes); + return output.toByteArray(); + } + } + + public static Association create( + GameDesignPublicationOperation operation, + TemplateConfigSourceSnapshot.Capture capture, + TemplateConfigSource.Entry entry, + SourceRead worldSourceRead) { + Objects.requireNonNull(operation, "operation"); + Objects.requireNonNull(capture, "capture"); + Objects.requireNonNull(entry, "entry"); + Objects.requireNonNull(worldSourceRead, "worldSourceRead"); + if (!Arrays.equals(operation.canonicalBytes(), capture.operation().canonicalBytes()) + || !capture + .snapshot() + .binding() + .equals(operation.account().input().selection().selectedCommit()) + || !capture.snapshot().entries().contains(entry)) { + throw new IllegalArgumentException("Association requires the exact captured template entry"); + } + var target = operation.account().input().selection().target(); + WorldPublishedStartLocationEvidence.Request selectedWorld = operation.world().request(); + ByIdReadRequest request = worldSourceRead.request(); + PublicReceipt receipt = worldSourceRead.receipt(); + if (!target.canonicalTenantId().equals(selectedWorld.canonicalTenantId()) + || receipt.source().sourceGameRowId() != target.sourceGameRowId() + || !receipt.source().sourceGameTenantKey().equals(target.sourceGameTenantKey()) + || !receipt.source().provenanceKind().equals(target.sourceProvenanceKind()) + || !selectedWorld.targetNamespace().equals(request.targetNamespace()) + || !selectedWorld.intakeRequestId().equals(request.intakeRequestId()) + || !selectedWorld.canonicalTenantId().equals(request.canonicalTenantId()) + || !selectedWorld.targetNamespace().equals(receipt.targetNamespace()) + || !selectedWorld.canonicalTenantId().equals(receipt.canonicalTenantId()) + || !selectedWorld.intakeRequestId().equals(receipt.intakeRequestId())) { + throw new IllegalArgumentException( + "World source receipt differs from the original selected publication freeze"); + } + long templateId; + try { + templateId = Long.parseLong(entry.templateId()); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException( + "Captured template identity is not a stored row ID", invalid); + } + return new Association( + target.canonicalTenantId(), + target.canonicalVersionId(), + capture.snapshot().binding().commitId(), + templateId, + operation.workflowId(), + receipt.targetNamespace(), + receipt.intakeRequestId(), + receipt.operationId(), + receipt.sourceOperationId(), + receipt.worldSlug(), + receipt.sourceEvidenceDigest(), + operation.canonicalBytes(), + capture.canonicalBytes(), + capture.snapshot().canonicalBytes(), + CommandSource.canonical(entry.object()).getBytes(StandardCharsets.UTF_8), + worldSourceRead.requestBytes(), + worldSourceRead.responseBytes()); + } + + private static byte[] copy(byte[] value) { + return Objects.requireNonNull(value, "value").clone(); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftTemplateWorldSourceAssociationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftTemplateWorldSourceAssociationRepository.java new file mode 100644 index 0000000000..fff0ef7fff --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftTemplateWorldSourceAssociationRepository.java @@ -0,0 +1,273 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftTemplateWorldSourceAssociation.Association; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftTemplateWorldSourceAssociation.SourceRead; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeByIdRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeByIdResponse; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Immutable per-template relation to the exact selected publication's original World source. */ +public final class SelectedDraftTemplateWorldSourceAssociationRepository { + private static final String TABLE = "game_design_selected_template_world_source_association"; + private final DSLContext dsl; + + public SelectedDraftTemplateWorldSourceAssociationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + /** + * Persists first-time associations in the publication reservation transaction, or exact-reads + * them for an already retained operation. Replay never allocates a row or replaces its original + * read identity. + */ + public List retainOrRead( + GameDesignPublicationOperation operation, + TemplateConfigSourceSnapshot.Capture capture, + SourceRead currentSourceRead, + boolean allowCreate) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(currentSourceRead, "currentSourceRead"); + List expected = associations(operation, capture, currentSourceRead); + List rows = rows(operation, capture); + List inserted = new ArrayList<>(expected.size()); + if (allowCreate) { + if (!rows.isEmpty()) { + throw new IllegalStateException( + "SELECTED_TEMPLATE_WORLD_SOURCE_ASSOCIATION_PREEXISTS_WITHOUT_OPERATION"); + } + for (Association association : expected) inserted.add(insert(association)); + } + List retained = readExact(operation, capture); + if (retained.size() != expected.size()) { + throw new IllegalStateException("SELECTED_TEMPLATE_WORLD_SOURCE_ASSOCIATION_INCOMPLETE"); + } + for (int index = 0; index < retained.size(); index++) { + Association old = retained.get(index); + Association current = expected.get(index); + // A competing exact first reservation may have committed the same durable operation from a + // separately authenticated by-ID read. Keep its original read correlation; only that + // correlation/echo may differ, never the receipt, selected capture, or source identity. + boolean matches = + allowCreate && inserted.get(index) + ? old.sameStoredValue(current) + : sameOriginalSource(old, current, currentSourceRead); + if (!matches) { + throw new IllegalStateException( + allowCreate + ? "SELECTED_TEMPLATE_WORLD_SOURCE_ASSOCIATION_READBACK_CONFLICT" + : "SELECTED_TEMPLATE_WORLD_SOURCE_ASSOCIATION_CONFLICT"); + } + } + return retained; + } + + /** Exact read-only completeness proof for an already retained source-backed operation. */ + public List readExact( + GameDesignPublicationOperation operation, TemplateConfigSourceSnapshot.Capture capture) { + Objects.requireNonNull(operation, "operation"); + Objects.requireNonNull(capture, "capture"); + if (!Arrays.equals(operation.canonicalBytes(), capture.operation().canonicalBytes())) { + throw new IllegalArgumentException("Association read requires its exact captured operation"); + } + List rows = rows(operation, capture); + List entries = capture.snapshot().entries(); + if (rows.size() != entries.size()) { + throw new IllegalStateException("SELECTED_TEMPLATE_WORLD_SOURCE_ASSOCIATION_INCOMPLETE"); + } + List result = new ArrayList<>(entries.size()); + for (TemplateConfigSource.Entry entry : entries) { + long templateId = parseTemplateId(entry.templateId()); + Record row = + rows.stream() + .filter(value -> Objects.equals(value.get("template_id", Long.class), templateId)) + .findFirst() + .orElseThrow( + () -> + new IllegalStateException( + "SELECTED_TEMPLATE_WORLD_SOURCE_ASSOCIATION_ENTRY_MISSING")); + Association retained = decode(operation, capture, entry, row); + requireRowMatches(retained, row); + result.add(retained); + } + return List.copyOf(result); + } + + private List associations( + GameDesignPublicationOperation operation, + TemplateConfigSourceSnapshot.Capture capture, + SourceRead sourceRead) { + Objects.requireNonNull(operation, "operation"); + Objects.requireNonNull(capture, "capture"); + return capture.snapshot().entries().stream() + .map( + entry -> + SelectedDraftTemplateWorldSourceAssociation.create( + operation, capture, entry, sourceRead)) + .toList(); + } + + private boolean insert(Association value) { + return dsl.execute( + "INSERT INTO " + + TABLE + + " (canonical_tenant_id, canonical_version_id, commit_id, template_id, publish_workflow_id, " + + "target_namespace, intake_request_id, world_operation_id, source_operation_id, world_slug, " + + "source_evidence_digest, operation_bytes, capture_bytes, template_snapshot_bytes, template_entry_bytes, " + + "world_read_request_bytes, world_read_response_bytes, association_bytes, association_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING", + value.canonicalTenantId(), + value.canonicalVersionId(), + value.selectedCommitId(), + value.templateId(), + value.publishWorkflowId(), + value.targetNamespace(), + value.intakeRequestId(), + value.worldOperationId(), + value.sourceOperationId(), + value.worldSlug(), + value.sourceEvidenceDigest(), + value.operationBytes(), + value.captureBytes(), + value.templateSnapshotBytes(), + value.templateEntryBytes(), + value.worldReadRequestBytes(), + value.worldReadResponseBytes(), + value.canonicalBytes(), + value.digest()) + == 1; + } + + private List rows( + GameDesignPublicationOperation operation, TemplateConfigSourceSnapshot.Capture capture) { + var selection = operation.account().input().selection(); + return dsl.fetch( + "SELECT * FROM " + + TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ? ORDER BY template_id", + selection.target().canonicalTenantId(), + selection.target().canonicalVersionId(), + capture.snapshot().binding().commitId()); + } + + private Association decode( + GameDesignPublicationOperation operation, + TemplateConfigSourceSnapshot.Capture capture, + TemplateConfigSource.Entry entry, + Record row) { + try { + byte[] requestBytes = row.get("world_read_request_bytes", byte[].class); + byte[] responseBytes = row.get("world_read_response_bytes", byte[].class); + var requestMessage = ReadAuthoredWorldSourceIntakeByIdRequest.parseFrom(requestBytes); + var request = WorldAuthoredSourceIntakeGrpcCodec.fromReadByIdRequest(requestMessage); + var responseMessage = ReadAuthoredWorldSourceIntakeByIdResponse.parseFrom(responseBytes); + var receipt = + WorldAuthoredSourceIntakeGrpcCodec.fromReadByIdResponse(request, responseMessage); + var sourceRead = new SourceRead(request, receipt); + if (!Arrays.equals(requestBytes, sourceRead.requestBytes()) + || !Arrays.equals(responseBytes, sourceRead.responseBytes())) { + throw new IllegalStateException("noncanonical retained World source read"); + } + return SelectedDraftTemplateWorldSourceAssociation.create( + operation, capture, entry, sourceRead); + } catch (IOException | IllegalArgumentException | IllegalStateException failure) { + throw new IllegalStateException( + "SELECTED_TEMPLATE_WORLD_SOURCE_ASSOCIATION_EVIDENCE_CORRUPT", failure); + } + } + + private static void requireRowMatches(Association value, Record row) { + if (!value.canonicalTenantId().equals(row.get("canonical_tenant_id", java.util.UUID.class)) + || !value.canonicalVersionId().equals(row.get("canonical_version_id", java.util.UUID.class)) + || !value.selectedCommitId().equals(row.get("commit_id", java.util.UUID.class)) + || value.templateId() != row.get("template_id", Long.class) + || !value.publishWorkflowId().equals(row.get("publish_workflow_id", String.class)) + || !value.targetNamespace().equals(row.get("target_namespace", String.class)) + || !value.intakeRequestId().equals(row.get("intake_request_id", java.util.UUID.class)) + || !value.worldOperationId().equals(row.get("world_operation_id", java.util.UUID.class)) + || !value.sourceOperationId().equals(row.get("source_operation_id", java.util.UUID.class)) + || !value.worldSlug().equals(row.get("world_slug", String.class)) + || !value.sourceEvidenceDigest().equals(row.get("source_evidence_digest", String.class)) + || !Arrays.equals(value.operationBytes(), row.get("operation_bytes", byte[].class)) + || !Arrays.equals(value.captureBytes(), row.get("capture_bytes", byte[].class)) + || !Arrays.equals( + value.templateSnapshotBytes(), row.get("template_snapshot_bytes", byte[].class)) + || !Arrays.equals(value.templateEntryBytes(), row.get("template_entry_bytes", byte[].class)) + || !Arrays.equals( + value.worldReadRequestBytes(), row.get("world_read_request_bytes", byte[].class)) + || !Arrays.equals( + value.worldReadResponseBytes(), row.get("world_read_response_bytes", byte[].class)) + || !Arrays.equals(value.canonicalBytes(), row.get("association_bytes", byte[].class)) + || !value.digest().equals(row.get("association_digest", String.class))) { + throw new IllegalStateException( + "SELECTED_TEMPLATE_WORLD_SOURCE_ASSOCIATION_READBACK_CONFLICT"); + } + } + + private static boolean sameOriginalSource( + Association retained, Association candidate, SourceRead currentRead) { + return retained.canonicalTenantId().equals(candidate.canonicalTenantId()) + && retained.canonicalVersionId().equals(candidate.canonicalVersionId()) + && retained.selectedCommitId().equals(candidate.selectedCommitId()) + && retained.templateId() == candidate.templateId() + && retained.publishWorkflowId().equals(candidate.publishWorkflowId()) + && retained.targetNamespace().equals(candidate.targetNamespace()) + && retained.intakeRequestId().equals(candidate.intakeRequestId()) + && retained.worldOperationId().equals(candidate.worldOperationId()) + && retained.sourceOperationId().equals(candidate.sourceOperationId()) + && retained.worldSlug().equals(candidate.worldSlug()) + && retained.sourceEvidenceDigest().equals(candidate.sourceEvidenceDigest()) + && Arrays.equals(retained.operationBytes(), candidate.operationBytes()) + && Arrays.equals(retained.captureBytes(), candidate.captureBytes()) + && Arrays.equals(retained.templateSnapshotBytes(), candidate.templateSnapshotBytes()) + && Arrays.equals(retained.templateEntryBytes(), candidate.templateEntryBytes()) + && currentRead.request().targetNamespace().equals(retained.targetNamespace()) + && currentRead.request().intakeRequestId().equals(retained.intakeRequestId()) + && currentRead.request().canonicalTenantId().equals(retained.canonicalTenantId()) + && currentRead.receipt().equals(retainedReceipt(retained)); + } + + private static WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt retainedReceipt( + Association association) { + try { + var request = + WorldAuthoredSourceIntakeGrpcCodec.fromReadByIdRequest( + ReadAuthoredWorldSourceIntakeByIdRequest.parseFrom( + association.worldReadRequestBytes())); + return WorldAuthoredSourceIntakeGrpcCodec.fromReadByIdResponse( + request, + ReadAuthoredWorldSourceIntakeByIdResponse.parseFrom( + association.worldReadResponseBytes())); + } catch (IOException | IllegalArgumentException invalid) { + throw new IllegalStateException( + "SELECTED_TEMPLATE_WORLD_SOURCE_ASSOCIATION_EVIDENCE_CORRUPT", invalid); + } + } + + private static long parseTemplateId(String templateId) { + try { + return Long.parseLong(templateId); + } catch (NumberFormatException invalid) { + throw new IllegalStateException("TEMPLATE_CONFIG_CAPTURE_ID_INVALID", invalid); + } + } + + private static void requireWritableReadCommittedTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isSynchronizationActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Template/world source association requires writable READ_COMMITTED transaction"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedGameplayRuleSourceJoin.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedGameplayRuleSourceJoin.java new file mode 100644 index 0000000000..ff7e0720aa --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedGameplayRuleSourceJoin.java @@ -0,0 +1,33 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.util.Arrays; +import java.util.Objects; + +/** + * Canonical byte equality for the selected Gameplay capture, source read and Game Logic receipt. + */ +final class SelectedGameplayRuleSourceJoin { + private SelectedGameplayRuleSourceJoin() {} + + static boolean matches( + GameDesignPublicationOperation operation, + GameplayRuleSnapshot.Capture capture, + GameplayRuleSnapshot selectedSnapshot, + SelectedDraftGameLogicReceipt receipt) { + Objects.requireNonNull(operation, "operation"); + Objects.requireNonNull(capture, "capture"); + Objects.requireNonNull(selectedSnapshot, "selectedSnapshot"); + Objects.requireNonNull(receipt, "receipt"); + + var selection = operation.account().input().selection(); + return Arrays.equals(capture.operation().canonicalBytes(), operation.canonicalBytes()) + && selection.selectedCommit().equals(capture.snapshot().binding()) + && Arrays.equals(capture.snapshot().canonicalBytes(), selectedSnapshot.canonicalBytes()) + && Arrays.equals( + capture.snapshot().canonicalBytes(), receipt.authorization().source().canonicalBytes()) + && Arrays.equals(selection.canonicalBytes(), receipt.selection().canonicalBytes()) + && selection.selectedCommit().equals(selectedSnapshot.binding()) + && Arrays.equals( + selectedSnapshot.canonicalBytes(), receipt.authorization().source().canonicalBytes()); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java new file mode 100644 index 0000000000..b7174e27b6 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java @@ -0,0 +1,1269 @@ +package net.firedevops.firemud.gamedesign.publication; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreSourceBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Association; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; +import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; +import net.firedevops.firemud.gamedesign.entity.LaunchDescriptor; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.LaunchDescriptorRepository; +import net.firedevops.firemud.gamedesign.repository.StartSessionAuthoredActorCoreProjectionRepository; +import net.firedevops.firemud.gamedesign.repository.StartSessionLaunchDescriptorRepository; +import net.firedevops.firemud.gamedesign.repository.StartSessionLaunchDescriptorRepository.Binding; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.databind.ObjectMapper; + +/** + * Standalone fresh StartSession descriptor producer. It is intentionally not a Spring bean or a + * runtime selector: the only accepted input is an exact association replay already pinned by Game + * Session, and the Account-gated owner reader runs before the descriptor write transaction. + */ +public final class StartSessionLaunchDescriptorProducer { + private static final String RUNTIME_SURFACE_EMPTY_V1 = "EMPTY_V1"; + private static final String RUNTIME_SURFACE_UNSUPPORTED_CAPTURE_V1 = "UNSUPPORTED_CAPTURE_V1"; + private static final String EMPTY_RUNTIME_FLAGS = "{}"; + private static final String INVALID_TEMPLATE_CONFIGURATION = "INVALID_TEMPLATE_CONFIGURATION"; + private static final String UNSUPPORTED_CAPTURE_MESSAGE = + "INVALID_TEMPLATE_CONFIGURATION: captured template has unsupported World, Entity, or Automation references"; + + private final DSLContext dsl; + private final String workloadNamespace; + private final StartSessionTemplateAssociationReadService associationReader; + private final GameAuthoredWorldSourceRepository authoredWorldSources; + private final LaunchDescriptorRepository descriptors; + private final StartSessionLaunchDescriptorRepository bindings; + private final StartSessionAuthoredActorCoreProjectionRepository actorCoreProjections; + private final VersionRepository versions; + private final TemplateReferenceRepository templateReferences; + private final GameDesignPublicationOperationRepository publicationOperations; + private final GameDesignSourceRepository sourceRepository; + private final SelectedDraftTemplateWorldSourceAssociationRepository associations; + private final PublishedReleaseBundleService releases; + private final ObjectMapper objectMapper; + private final TransactionTemplate writeTransaction; + + /** + * Production construction accepts only the concrete Account-gated same-namespace owner reader. No + * caller-supplied association, Version, or release can enter this path. + */ + public StartSessionLaunchDescriptorProducer( + DSLContext dsl, + PlatformTransactionManager transactions, + String workloadNamespace, + StartSessionTemplateAssociationReadService associationReader, + PublishedReleaseBundleService releases, + ObjectMapper objectMapper) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Design workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + this.associationReader = Objects.requireNonNull(associationReader, "associationReader"); + this.releases = Objects.requireNonNull(releases, "releases"); + this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper"); + authoredWorldSources = new GameAuthoredWorldSourceRepository(dsl); + descriptors = new LaunchDescriptorRepository(dsl); + bindings = new StartSessionLaunchDescriptorRepository(dsl); + actorCoreProjections = new StartSessionAuthoredActorCoreProjectionRepository(dsl); + versions = new VersionRepository(dsl); + templateReferences = new TemplateReferenceRepository(dsl); + publicationOperations = new GameDesignPublicationOperationRepository(dsl); + sourceRepository = new GameDesignSourceRepository(dsl); + associations = new SelectedDraftTemplateWorldSourceAssociationRepository(dsl); + writeTransaction = + new TransactionTemplate(Objects.requireNonNull(transactions, "transactions")); + writeTransaction.setName("game-design-start-session-launch-descriptor"); + writeTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + writeTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + writeTransaction.setReadOnly(false); + } + + /** Reads the current Account projection, then stores or exactly replays one pinned descriptor. */ + public ResolvedBinding resolve(Request request) { + requirePeer(); + Objects.requireNonNull(request, "request"); + if (!(request.selection() instanceof ExactReplay)) { + throw Status.INVALID_ARGUMENT + .withDescription("An exact Game Session-pinned association replay is required") + .asRuntimeException(); + } + if (!workloadNamespace.equals(request.targetNamespace())) { + throw Status.PERMISSION_DENIED + .withDescription("StartSession target namespace differs from the Game Design peer") + .asRuntimeException(); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription( + "Account projection and owner descriptor writes require independent transactions") + .asRuntimeException(); + } + + // This call performs the independent Account projection read before any local write + // transaction. + Result exact = associationReader.read(request); + requireExactAssociationRead(request, exact); + StartSessionPostAuthorizationExecutionTuple tuple = request.decodedTuple(); + var action = tuple.preAuthorizationTuple().action(); + UUID canonicalTenantId = action.scope().tenantId(); + long templateId = action.target().gameTemplateId(); + Association association = exact.association(); + AuthoredWorldSourceEvidence source = + authoredWorldSources + .read( + association.sourceOperationId(), + canonicalTenantId, + association.worldSlug(), + request.targetNamespace()) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription( + "Exact registered Game Design source for the association is unavailable") + .asRuntimeException()); + requireSourceMatches(association, source); + AuthoredWorldLaunchDescriptorEvidence.Request descriptorRequest = + descriptorRequest(tuple, association); + String requestJson = writeJson(descriptorRequest); + String sourceJson = writeJson(source); + + OwnerOutcome outcome = + Objects.requireNonNull( + writeTransaction.execute( + ignored -> + writeOrRead( + request, + exact, + descriptorRequest, + requestJson, + source, + sourceJson, + canonicalTenantId, + templateId)), + "StartSession launch descriptor transaction returned no binding"); + if (outcome.failure() != null) { + throw new StoredBusinessDenial(exact, outcome.failure()); + } + return Objects.requireNonNull( + outcome.resolvedBinding(), "Successful descriptor binding is missing"); + } + + private OwnerOutcome writeOrRead( + Request exactRequest, + Result exact, + AuthoredWorldLaunchDescriptorEvidence.Request descriptorRequest, + String requestJson, + AuthoredWorldSourceEvidence source, + String sourceJson, + UUID canonicalTenantId, + long templateId) { + String controlPlaneRequestId = descriptorRequest.controlPlaneRequestId(); + descriptors.lockBoundRequest(workloadNamespace, canonicalTenantId, controlPlaneRequestId); + Optional storedDescriptor = + descriptors.findBoundByRequest(workloadNamespace, canonicalTenantId, controlPlaneRequestId); + Optional storedBinding = + bindings.find(workloadNamespace, canonicalTenantId, controlPlaneRequestId); + if (storedDescriptor.isPresent() || storedBinding.isPresent()) { + if (storedDescriptor.isEmpty() || storedBinding.isEmpty()) { + throw conflict("Stored descriptor is missing its exact StartSession association binding"); + } + LaunchDescriptor descriptor = storedDescriptor.orElseThrow(); + CapturedTemplate capturedTemplate = requireCapturedTemplate(exact, templateId); + requireBindingMatches( + storedBinding.orElseThrow(), + descriptor, + exactRequest, + exact, + descriptorRequest, + source, + capturedTemplate.gameLogicReceipt()); + List retainedActorCoreProjections = + replayActorCoreProjections(storedBinding.orElseThrow(), capturedTemplate); + if (LaunchDescriptor.OUTCOME_FAILED.equals(descriptor.getOutcomeStatus())) { + if (capturedTemplate.failureMessage() == null) { + throw conflict( + "Stored failed descriptor no longer matches its immutable captured configuration"); + } + FrozenFailure failure = + requireStoredFailure(descriptor, descriptorRequest, requestJson, source, sourceJson); + return OwnerOutcome.failed(failure); + } + if (capturedTemplate.failureMessage() != null) { + throw conflict( + "Stored successful descriptor differs from its immutable captured configuration"); + } + requireSuccessfulDescriptor(descriptor); + ResolvedLaunchDescriptorDto resolved = + readStored(descriptor, descriptorRequest, requestJson, source, sourceJson); + return OwnerOutcome.succeeded( + new ResolvedBinding(exactRequest, exact, resolved, retainedActorCoreProjections)); + } + + if (descriptors + .findByPrivateRequest(source.sourceGameTenantKey(), controlPlaneRequestId) + .isPresent()) { + throw conflict( + "Retained private-owner descriptor history is unbound or bound to another canonical identity"); + } + + TemplateReferenceRepository.PhaseSnapshot phase = + templateReferences + .readPhase(canonicalTenantId) + .filter(value -> value.phase() == TemplateReferenceRepository.Phase.ENFORCED) + .filter(value -> value.phaseEpoch() == exact.phaseEpoch()) + .filter( + value -> value.inventoryDigest() != null && value.inventoryTemplateCount() != null) + .filter(value -> value.inventoryTemplateCount() > 0L) + .orElseThrow( + () -> conflict("Current explicit enforced template-reference phase changed")); + if (phase.sourceGameRowId() != source.sourceGameRowId() + || !phase.sourceGameTenantKey().equals(source.sourceGameTenantKey()) + || !"NEW_GAME_ROW".equals(phase.provenanceKind()) + || !"NEW_GAME_ROW".equals(source.provenanceKind())) { + throw conflict("Exact source and fresh tenant phase provenance differ"); + } + + Version selectedVersion = + versions + .findByCanonicalTenantIdAndCanonicalVersionId( + canonicalTenantId, exact.association().canonicalVersionId()) + .orElseThrow(() -> conflict("Exact selected canonical Version is unavailable")); + lockAndReloadSelectedVersion( + selectedVersion, canonicalTenantId, exact.association().canonicalVersionId()); + Version version = + versions + .findByCanonicalTenantIdAndCanonicalVersionId( + canonicalTenantId, exact.association().canonicalVersionId()) + .orElseThrow( + () -> conflict("Exact selected canonical Version disappeared after locking")); + if (!Objects.equals(selectedVersion.getId(), version.getId())) { + throw conflict("Canonical Version row identity changed while locking the exact selection"); + } + requireLaunchableVersion(version, source, phase, exact.association()); + PublishedReleaseBundleDto release = + releases + .findPublishedReleaseBundle(version.getTenantId(), version.getId()) + .orElseThrow(() -> conflict("Exact selected immutable release bundle is unavailable")); + requireReleaseMatches(exact, release, version); + CapturedTemplate capturedTemplate = requireCapturedTemplate(exact, templateId); + String unsupportedCapture = capturedTemplate.failureMessage(); + long versionStateEpoch = + Objects.requireNonNull(version.getVersionStateEpoch(), "versionStateEpoch"); + + boolean deterministicFailure = unsupportedCapture != null; + LaunchDescriptor candidate; + if (deterministicFailure) { + candidate = + frozenFailure( + descriptorRequest, + source, + requestJson, + sourceJson, + INVALID_TEMPLATE_CONFIGURATION, + UNSUPPORTED_CAPTURE_MESSAGE); + } else { + AuthoredWorldLaunchDescriptorEvidence evidence = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "ld-" + UUID.randomUUID(), + version.getId(), + false, + null, + EMPTY_RUNTIME_FLAGS, + release.generationConfigRevision(), + versionStateEpoch, + release.id(), + release.publishedReleaseBundleRef(), + false, + null); + candidate = descriptorRow(evidence, source, requestJson, sourceJson); + } + LaunchDescriptor persisted = descriptors.insertImmutable(candidate); + if (deterministicFailure) { + requireStoredFailure(persisted, descriptorRequest, requestJson, source, sourceJson); + } else { + requireSuccessfulDescriptor(persisted); + } + String runtimeSurface = + deterministicFailure ? RUNTIME_SURFACE_UNSUPPORTED_CAPTURE_V1 : RUNTIME_SURFACE_EMPTY_V1; + Binding inserted = + binding( + exactRequest, + exact, + persisted.getId(), + Objects.requireNonNull(release.id(), "release.id"), + versionStateEpoch, + runtimeSurface, + capturedTemplate.gameLogicReceipt()); + Binding persistedBinding = bindings.insertImmutable(inserted); + requireBindingMatches( + persistedBinding, + persisted, + exactRequest, + exact, + descriptorRequest, + source, + capturedTemplate.gameLogicReceipt()); + List retainedActorCoreProjections = + insertActorCoreProjections(persistedBinding, capturedTemplate); + if (deterministicFailure) { + return OwnerOutcome.failed( + new FrozenFailure(INVALID_TEMPLATE_CONFIGURATION, UNSUPPORTED_CAPTURE_MESSAGE)); + } + ResolvedLaunchDescriptorDto resolved = + readStored(persisted, descriptorRequest, requestJson, source, sourceJson); + return OwnerOutcome.succeeded( + new ResolvedBinding(exactRequest, exact, resolved, retainedActorCoreProjections)); + } + + private List replayActorCoreProjections( + Binding binding, CapturedTemplate capturedTemplate) { + try { + return actorCoreProjections.replayExact(binding, capturedTemplate.actorCoreBindings()); + } catch ( + StartSessionAuthoredActorCoreProjectionRepository.RetainedProjectionConflictException + invalid) { + throw conflict("Retained authored actor-core projection differs from exact source"); + } + } + + private List insertActorCoreProjections( + Binding binding, CapturedTemplate capturedTemplate) { + try { + return actorCoreProjections.insertForNewOwner(binding, capturedTemplate.actorCoreBindings()); + } catch ( + StartSessionAuthoredActorCoreProjectionRepository.RetainedProjectionConflictException + invalid) { + throw conflict("New authored actor-core projection conflicts with retained owner storage"); + } + } + + private CapturedTemplate requireCapturedTemplate(Result exact, long templateId) { + var readback = + publicationOperations + .read(exact.association().publishWorkflowId()) + .orElseThrow(() -> conflict("Exact selected publication operation is unavailable")); + var operation = readback.operation(); + var selection = operation.account().input().selection(); + if (!"PUBLISHED".equals(readback.outcome()) + || !operation.workflowId().equals(exact.association().publishWorkflowId()) + || !operation.tenantKey().equals(selection.target().gameDesignVersionTenantKey()) + || operation.versionId() != selection.target().gameDesignVersionRowId() + || !selection.target().canonicalTenantId().equals(exact.association().canonicalTenantId()) + || !selection.target().canonicalVersionId().equals(exact.association().canonicalVersionId()) + || !selection.selectedCommit().commitId().equals(exact.association().selectedCommitId()) + || readback.terminalEvidenceBytes() == null) { + throw conflict("Published owner operation differs from the pinned association"); + } + GameDesignPublicationTerminalEvidence terminal = + GameDesignPublicationTerminalEvidence.fromStored(readback.terminalEvidenceBytes()); + if (terminal.outcome() != GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + || !Arrays.equals(terminal.operationBytes(), operation.canonicalBytes()) + || terminal.releaseContent() == null + || terminal.publicationVersionStateEpoch() <= 0L) { + throw conflict("Exact selected publication terminal evidence is incomplete"); + } + requireTerminalMatchesExactRelease(exact, terminal); + GameDesignSourceRepository.Capture capture = + sourceRepository + .readCapture(operation) + .orElseThrow( + () -> conflict("Complete exact publication source capture is unavailable")); + var templateCapture = + capture + .templateConfig() + .orElseThrow( + () -> conflict("Exact selected template configuration capture is unavailable")); + if (!templateCapture.snapshot().binding().equals(selection.selectedCommit())) { + throw conflict("Selected template capture differs from the original committed source"); + } + List entries = + templateCapture.snapshot().entries().stream() + .filter(entry -> Long.parseLong(entry.templateId()) == templateId) + .toList(); + if (entries.size() != 1) { + throw conflict("Exact selected template is missing or duplicated in the committed capture"); + } + SelectedGameplayRules selectedGameplayRules = + requireSelectedGameLogicReceipt( + operation, + capture + .gameplay() + .orElseThrow( + () -> conflict("Exact selected gameplay source capture is unavailable"))); + TemplateConfigSource.Entry entry = entries.getFirst(); + if (!entry.config().baseVersionId().equals(exact.association().canonicalVersionId())) { + throw conflict("Original captured template base differs from the pinned selected Version"); + } + String unsupported = null; + try { + entry.config().requireAvailableOwnerReads(); + } catch (IllegalStateException unavailableOwner) { + if (!List.of( + "TEMPLATE_CONFIG_WORLD_EXACT_OWNER_READ_UNAVAILABLE", + "TEMPLATE_CONFIG_ENTITY_EXACT_OWNER_READ_UNAVAILABLE", + "TEMPLATE_CONFIG_AUTOMATION_EXACT_OWNER_READ_UNAVAILABLE") + .contains(unavailableOwner.getMessage())) { + throw conflict("Captured template owner-reference validation is unavailable"); + } + unsupported = UNSUPPORTED_CAPTURE_MESSAGE; + } + + List exactRows = + associations.readExact(operation, templateCapture).stream() + .filter(value -> value.templateId() == templateId) + .toList(); + if (exactRows.size() != 1) { + throw conflict("Exact immutable selected template/source association is unavailable"); + } + var row = exactRows.getFirst(); + Association publicAssociation = exact.association(); + if (!row.canonicalTenantId().equals(publicAssociation.canonicalTenantId()) + || row.templateId() != publicAssociation.templateId() + || !row.canonicalVersionId().equals(publicAssociation.canonicalVersionId()) + || !row.selectedCommitId().equals(publicAssociation.selectedCommitId()) + || !row.publishWorkflowId().equals(publicAssociation.publishWorkflowId()) + || !row.digest().equals(publicAssociation.associationDigest()) + || !row.targetNamespace().equals(publicAssociation.targetNamespace()) + || !row.sourceOperationId().equals(publicAssociation.sourceOperationId()) + || !row.sourceEvidenceDigest().equals(publicAssociation.sourceEvidenceDigest()) + || !row.worldSlug().equals(publicAssociation.worldSlug())) { + throw conflict("Retained association row differs from the public pinned association"); + } + var policySnapshot = + net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot.fromStored( + capture.policy().snapshot().canonicalJson()); + var gameplayRules = selectedGameplayRules.snapshot(); + List actorCoreBindings; + try { + actorCoreBindings = + resolveSelectedAuthoredInitialActorCoreSources( + exact.association().sourceOperationId(), + exact.association().sourceEvidenceDigest(), + exact.association().worldSlug(), + operation.workflowId(), + operation.canonicalBytes(), + readback.terminalEvidenceBytes(), + selection.selectedCommit(), + policySnapshot, + gameplayRules); + } catch (IllegalArgumentException invalidActorCoreSource) { + throw conflict("Selected authored initial actor core differs from exact published source"); + } + return new CapturedTemplate( + unsupported, + selectedGameplayRules.receiptBinding(), + selection.selectedCommit(), + policySnapshot, + gameplayRules, + operation.workflowId(), + operation.canonicalBytes(), + readback.terminalEvidenceBytes(), + actorCoreBindings); + } + + static List resolveSelectedAuthoredInitialActorCoreSources( + UUID worldSourceOperationId, + String worldSourceEvidenceDigest, + String expectedWorldSlug, + String publicationWorkflowId, + byte[] publicationOperationBytes, + byte[] publicationTerminalEvidenceBytes, + net.firedevops.firemud.common.authoring.DraftCommitBinding selectedCommit, + net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot policySnapshot, + GameplayRuleSnapshot gameplayRules) { + Objects.requireNonNull(gameplayRules, "gameplayRules"); + return AuthoredInitialActorCoreSourceBinding.resolveAll( + worldSourceOperationId, + worldSourceEvidenceDigest, + expectedWorldSlug, + publicationWorkflowId, + publicationOperationBytes, + publicationTerminalEvidenceBytes, + selectedCommit, + policySnapshot, + new GameplayRuleSelectedSource(gameplayRules.canonicalJson())); + } + + /** + * Exact Game Logic receipt/source join already required by the selected-publication inventory. + */ + private SelectedGameplayRules requireSelectedGameLogicReceipt( + GameDesignPublicationOperation operation, GameplayRuleSnapshot.Capture gameplayCapture) { + var selection = operation.account().input().selection(); + var target = selection.target(); + var publicationRequest = + PublicationDigestRequestBinding.full( + selection.intent().canonicalTenantId().toString(), + Long.toString(target.gameDesignVersionRowId()), + selection.intent().publishRequestId()); + SelectedDraftGameLogicReceipt receipt = + new SelectedDraftGameLogicReceiptRepository(dsl) + .readForPublication(publicationRequest) + .orElseThrow(() -> conflict("Exact retained Game Logic source receipt is unavailable")); + GameplayRuleSnapshot selectedRules = + new GameplayRuleSourceRepository(dsl) + .readSnapshot(target, selection.selectedCommit().commitId()) + .orElseThrow( + () -> conflict("Exact selected Game Logic source snapshot is unavailable")); + if (!SelectedGameplayRuleSourceJoin.matches( + operation, gameplayCapture, selectedRules, receipt)) { + throw conflict("Retained Game Logic receipt differs from the exact selected source"); + } + return new SelectedGameplayRules( + selectedRules, + new GameLogicReceiptBinding( + selection.intent().publishRequestId(), + selection.digest(), + receipt.authorization().digest(), + receipt.receipt().digest())); + } + + private void requireReleaseMatches( + Result exact, PublishedReleaseBundleDto release, Version version) { + var selected = exact.releaseBundle(); + var current = toPublishedReleaseBundle(release); + if (!selected.equals(current) + || release.id() == null + || release.id() <= 0L + || !Objects.equals(release.id(), selected.getId()) + || !Objects.equals(release.versionId(), version.getId()) + || !Objects.equals(release.canonicalTenantId(), exact.association().canonicalTenantId()) + || !Objects.equals(release.canonicalVersionId(), exact.association().canonicalVersionId()) + || !Objects.equals(release.publishWorkflowId(), exact.association().publishWorkflowId()) + || !"v2".equals(release.attestationSchemaVersion()) + || !Objects.equals( + release.worldPublishedStartLocationEvidence(), + exact.worldPublishedStartLocationEvidence()) + || release.scriptOnly() + || release.scriptPatchVersion() != null && !release.scriptPatchVersion().isBlank()) { + throw conflict("Current release row differs from the exact committed published release"); + } + var releaseContent = releaseContent(release); + var readback = + publicationOperations + .read(exact.association().publishWorkflowId()) + .orElseThrow(() -> conflict("Exact selected publication operation is unavailable")); + if (readback.terminalEvidenceBytes() == null) { + throw conflict("Exact published terminal evidence is unavailable"); + } + var terminal = + GameDesignPublicationTerminalEvidence.fromStored(readback.terminalEvidenceBytes()); + if (terminal.releaseContent() == null + || terminal.publicationVersionStateEpoch() > version.getVersionStateEpoch() + || !Arrays.equals( + terminal.releaseContent().canonicalBytes(), releaseContent.canonicalBytes())) { + throw conflict( + "Current release content differs from the original published terminal evidence"); + } + } + + private void lockAndReloadSelectedVersion( + Version version, UUID canonicalTenantId, UUID canonicalVersionId) { + Record row = + dsl.fetchOne( + "SELECT id FROM version WHERE id = ? AND canonical_tenant_id = ? " + + "AND canonical_version_id = ? FOR UPDATE", + version.getId(), + canonicalTenantId, + canonicalVersionId); + if (row == null || !Objects.equals(row.get("id", Long.class), version.getId())) { + throw conflict("Exact canonical Version row could not be locked for descriptor creation"); + } + } + + private void requireLaunchableVersion( + Version version, + AuthoredWorldSourceEvidence source, + TemplateReferenceRepository.PhaseSnapshot phase, + Association association) { + if (!Objects.equals(version.getCanonicalTenantId(), association.canonicalTenantId()) + || !Objects.equals(version.getCanonicalVersionId(), association.canonicalVersionId()) + || !Objects.equals(version.getTenantId(), source.sourceGameTenantKey()) + || !Objects.equals(version.getIdentitySourceGameRowId(), phase.sourceGameRowId()) + || !Objects.equals(version.getIdentitySourceGameTenantKey(), phase.sourceGameTenantKey()) + || !Objects.equals(version.getIdentitySourceProvenanceKind(), phase.provenanceKind()) + || version.getVersionStateEpoch() == null + || version.getVersionStateEpoch() <= 0L + || !(version.getVersionState() == VersionLifecycleState.PUBLISHED + || version.getVersionState() == VersionLifecycleState.ACTIVE) + || version.isScriptOnly() + || version.getBaseVersionId() != null + || version.getScriptPatchVersion() != null) { + throw conflict("Exact fresh published full Version is not launchable"); + } + } + + private void requireSourceMatches(Association association, AuthoredWorldSourceEvidence source) { + if (!workloadNamespace.equals(source.targetNamespace()) + || !association.targetNamespace().equals(source.targetNamespace()) + || !association.canonicalTenantId().equals(source.canonicalTenantId()) + || !association.sourceOperationId().equals(source.operationId()) + || !association.sourceEvidenceDigest().equals(source.evidenceDigest()) + || !association.worldSlug().equals(source.worldSlug()) + || !"NEW_GAME_ROW".equals(source.provenanceKind()) + || source.sourceGameRowId() <= 0L + || source.sourceGameTenantKey() == null + || source.sourceGameTenantKey().isBlank()) { + throw conflict("Exact association source does not match fresh Game Design source evidence"); + } + } + + private void requireExactAssociationRead(Request request, Result result) { + if (result == null + || !request.equals(result.request()) + || !(result.request().selection() instanceof ExactReplay replay) + || !replay.canonicalVersionId().equals(result.association().canonicalVersionId()) + || !replay.selectedCommitId().equals(result.association().selectedCommitId()) + || !replay.publishWorkflowId().equals(result.association().publishWorkflowId()) + || !replay.associationDigest().equals(result.association().associationDigest())) { + throw conflict("Account-gated association read differs from the exact Game Session replay"); + } + var tuple = request.decodedTuple(); + var action = tuple.preAuthorizationTuple().action(); + if (!action.scope().tenantId().equals(result.association().canonicalTenantId()) + || action.target().gameTemplateId() != result.association().templateId() + || !request.targetNamespace().equals(result.association().targetNamespace())) { + throw conflict( + "Exact association read differs from the original authorized StartSession target"); + } + } + + private AuthoredWorldLaunchDescriptorEvidence.Request descriptorRequest( + StartSessionPostAuthorizationExecutionTuple tuple, Association association) { + var action = tuple.preAuthorizationTuple().action(); + if (!action.scope().tenantId().equals(association.canonicalTenantId()) + || action.target().gameTemplateId() != association.templateId()) { + throw conflict("Association source differs from the original StartSession tenant/template"); + } + return new AuthoredWorldLaunchDescriptorEvidence.Request( + workloadNamespace, + tuple.controlPlaneRequestId(), + association.canonicalTenantId(), + association.worldSlug(), + association.sourceOperationId(), + association.sourceEvidenceDigest(), + association.templateId(), + false, + null, + false, + null, + false, + null, + true, + EMPTY_RUNTIME_FLAGS); + } + + private LaunchDescriptor descriptorRow( + AuthoredWorldLaunchDescriptorEvidence evidence, + AuthoredWorldSourceEvidence source, + String requestJson, + String sourceJson) { + LaunchDescriptor descriptor = new LaunchDescriptor(); + descriptor.setLaunchDescriptorId(evidence.launchDescriptorId()); + descriptor.setTenantId(source.sourceGameTenantKey()); + descriptor.setGameTemplateId(evidence.gameTemplateId()); + descriptor.setControlPlaneRequestId(evidence.controlPlaneRequestId()); + descriptor.setRequestHash(evidence.requestDigest()); + descriptor.setVersionId(evidence.versionId()); + descriptor.setScriptPatchVersion(null); + descriptor.setRuntimeFlagsJson(evidence.runtimeFlagsJson()); + descriptor.setGenerationConfigRevision(evidence.generationConfigRevision()); + descriptor.setVersionStateEpoch(evidence.versionStateEpoch()); + descriptor.setReleaseBundleId(evidence.releaseBundleId()); + descriptor.setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()); + descriptor.setRemapSetId(null); + descriptor.setDescriptorSchemaVersion(evidence.schemaVersion()); + descriptor.setTargetNamespace(evidence.targetNamespace()); + descriptor.setCanonicalTenantId(evidence.canonicalTenantId().toString()); + descriptor.setWorldSlug(evidence.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId( + evidence.authoredWorldSourceOperationId().toString()); + descriptor.setAuthoredWorldSourceEvidenceDigest(evidence.authoredWorldSourceEvidenceDigest()); + descriptor.setRequestDigest(evidence.requestDigest()); + descriptor.setResultDigest(evidence.resultDigest()); + descriptor.setOriginalRequestJson(requestJson); + descriptor.setSourceEvidenceJson(sourceJson); + return descriptor; + } + + private Binding binding( + Request request, + Result result, + Long descriptorRowId, + Long releaseBundleId, + Long versionStateEpoch, + String runtimeSurface, + GameLogicReceiptBinding gameLogicReceipt) { + Association association = result.association(); + var tuple = request.decodedTuple(); + return new Binding( + workloadNamespace, + association.canonicalTenantId(), + tuple.controlPlaneRequestId(), + descriptorRowId, + releaseBundleId, + versionStateEpoch, + request.canonicalPostAuthorizationTuple(), + request.ownerAttemptId(), + request.ownerFence(), + association.templateId(), + association.canonicalVersionId(), + association.selectedCommitId(), + association.publishWorkflowId(), + association.publicationSelectionDigest(), + association.associationDigest(), + association.sourceOperationId(), + association.sourceEvidenceDigest(), + association.worldSlug(), + result.phaseEpoch(), + runtimeSurface, + gameLogicReceipt.publishRequestId(), + gameLogicReceipt.selectionDigest(), + gameLogicReceipt.authorizationDigest(), + gameLogicReceipt.receiptDigest(), + StartSessionTemplateAssociationReadGrpcCodec.toResponse(result).toByteArray(), + java.time.LocalDateTime.now()); + } + + private void requireBindingMatches( + Binding binding, + LaunchDescriptor descriptor, + Request request, + Result result, + AuthoredWorldLaunchDescriptorEvidence.Request descriptorRequest, + AuthoredWorldSourceEvidence source, + GameLogicReceiptBinding gameLogicReceipt) { + Association association = result.association(); + if (!Objects.equals(binding.targetNamespace(), workloadNamespace) + || !Objects.equals(binding.canonicalTenantId(), association.canonicalTenantId()) + || !Objects.equals( + binding.controlPlaneRequestId(), descriptorRequest.controlPlaneRequestId()) + || !Objects.equals(binding.descriptorRowId(), descriptor.getId()) + || !Objects.equals(binding.releaseBundleId(), result.releaseBundle().getId()) + || (LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus()) + && !Objects.equals(binding.versionStateEpoch(), descriptor.getVersionStateEpoch())) + || !Arrays.equals( + binding.canonicalPostAuthorizationTuple(), request.canonicalPostAuthorizationTuple()) + || !Objects.equals(binding.ownerAttemptId(), request.ownerAttemptId()) + || !Objects.equals(binding.ownerFence(), request.ownerFence()) + || !Objects.equals(binding.gameTemplateId(), association.templateId()) + || !Objects.equals(binding.canonicalVersionId(), association.canonicalVersionId()) + || !Objects.equals(binding.selectedCommitId(), association.selectedCommitId()) + || !Objects.equals(binding.publishWorkflowId(), association.publishWorkflowId()) + || !Objects.equals( + binding.publicationSelectionDigest(), association.publicationSelectionDigest()) + || !Objects.equals(binding.associationDigest(), association.associationDigest()) + || !Objects.equals(binding.sourceOperationId(), association.sourceOperationId()) + || !Objects.equals(binding.sourceEvidenceDigest(), association.sourceEvidenceDigest()) + || !Objects.equals(binding.worldSlug(), association.worldSlug()) + || !Objects.equals(binding.referencePhaseEpoch(), result.phaseEpoch()) + || !Objects.equals(binding.gameLogicPublishRequestId(), gameLogicReceipt.publishRequestId()) + || !Objects.equals(binding.gameLogicSelectionDigest(), gameLogicReceipt.selectionDigest()) + || !Objects.equals( + binding.gameLogicAuthorizationDigest(), gameLogicReceipt.authorizationDigest()) + || !Objects.equals(binding.gameLogicReceiptDigest(), gameLogicReceipt.receiptDigest()) + || !(LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus()) + && Objects.equals(binding.runtimeSurface(), RUNTIME_SURFACE_EMPTY_V1) + || LaunchDescriptor.OUTCOME_FAILED.equals(descriptor.getOutcomeStatus()) + && Objects.equals(binding.runtimeSurface(), RUNTIME_SURFACE_UNSUPPORTED_CAPTURE_V1)) + || !source.operationId().equals(binding.sourceOperationId()) + || !source.evidenceDigest().equals(binding.sourceEvidenceDigest()) + || !sameAssociationReadResponse(binding.associationReadResponseBytes(), request, result)) { + throw conflict("Immutable StartSession descriptor association binding changed or conflicts"); + } + } + + private boolean sameAssociationReadResponse( + byte[] storedBytes, Request currentRequest, Result current) { + try { + var stored = + net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationResponse + .parseFrom(storedBytes); + Request storedRequest = + StartSessionTemplateAssociationReadGrpcCodec.fromRequest(stored.getRequest()); + Result previous = + StartSessionTemplateAssociationReadGrpcCodec.fromResponse(storedRequest, stored); + return sameLogicalRequest(storedRequest, currentRequest) + && previous.association().equals(current.association()) + && previous.releaseBundle().equals(current.releaseBundle()) + && previous + .worldPublishedStartLocationEvidence() + .equals(current.worldPublishedStartLocationEvidence()) + && previous.phaseEpoch() == current.phaseEpoch(); + } catch (IOException | IllegalArgumentException invalid) { + throw conflict("Stored exact StartSession association evidence is corrupt"); + } + } + + private boolean sameLogicalRequest(Request left, Request right) { + return left.schemaVersion() == right.schemaVersion() + && left.targetNamespace().equals(right.targetNamespace()) + && Arrays.equals( + left.canonicalPostAuthorizationTuple(), right.canonicalPostAuthorizationTuple()) + && left.ownerAttemptId().equals(right.ownerAttemptId()) + && left.ownerFence() == right.ownerFence() + && left.selection().equals(right.selection()); + } + + private ResolvedLaunchDescriptorDto readStored( + LaunchDescriptor descriptor, + AuthoredWorldLaunchDescriptorEvidence.Request request, + String requestJson, + AuthoredWorldSourceEvidence source, + String sourceJson) { + if (!LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus()) + || descriptor.getDescriptorSchemaVersion() == null + || descriptor.getDescriptorSchemaVersion() + != AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION + || !workloadNamespace.equals(descriptor.getTargetNamespace()) + || !request.canonicalTenantId().toString().equals(descriptor.getCanonicalTenantId()) + || !request.worldSlug().equals(descriptor.getWorldSlug()) + || !request + .authoredWorldSourceOperationId() + .toString() + .equals(descriptor.getAuthoredWorldSourceOperationId()) + || !request + .authoredWorldSourceEvidenceDigest() + .equals(descriptor.getAuthoredWorldSourceEvidenceDigest()) + || !request.controlPlaneRequestId().equals(descriptor.getControlPlaneRequestId()) + || !Objects.equals(descriptor.getTenantId(), source.sourceGameTenantKey()) + || request.gameTemplateId() != descriptor.getGameTemplateId() + || !requestJson.equals(descriptor.getOriginalRequestJson()) + || !sourceJson.equals(descriptor.getSourceEvidenceJson()) + || !request.requestDigest().equals(descriptor.getRequestHash()) + || !request.requestDigest().equals(descriptor.getRequestDigest())) { + throw conflict("Stored descriptor is not the exact immutable StartSession request"); + } + AuthoredWorldLaunchDescriptorEvidence evidence = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + descriptor.getLaunchDescriptorId(), + descriptor.getVersionId(), + descriptor.getScriptPatchVersion() != null, + descriptor.getScriptPatchVersion(), + descriptor.getRuntimeFlagsJson(), + descriptor.getGenerationConfigRevision(), + descriptor.getVersionStateEpoch(), + descriptor.getReleaseBundleId(), + descriptor.getPublishedReleaseBundleRef(), + descriptor.getRemapSetId() != null, + descriptor.getRemapSetId()); + evidence.requireValid(); + if (!evidence.resultDigest().equals(descriptor.getResultDigest())) { + throw conflict("Stored launch descriptor result digest is inconsistent"); + } + if (descriptor.getScriptPatchVersion() != null + || descriptor.getRemapSetId() != null + || !EMPTY_RUNTIME_FLAGS.equals(descriptor.getRuntimeFlagsJson())) { + throw conflict("Stored descriptor exceeds the explicitly empty launch runtime surface"); + } + return new ResolvedLaunchDescriptorDto( + evidence.launchDescriptorId(), + evidence.canonicalTenantId().toString(), + evidence.gameTemplateId(), + evidence.controlPlaneRequestId(), + evidence.versionId(), + evidence.scriptPatchVersion(), + evidence.runtimeFlagsJson(), + evidence.generationConfigRevision(), + evidence.versionStateEpoch(), + evidence.releaseBundleId(), + evidence.publishedReleaseBundleRef(), + evidence.remapSetId(), + evidence); + } + + private void requireSuccessfulDescriptor(LaunchDescriptor descriptor) { + if (!LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus()) + || descriptor.getDescriptorSchemaVersion() == null) { + throw conflict("Retained descriptor history is not an exact successful bound descriptor"); + } + } + + private FrozenFailure requireStoredFailure( + LaunchDescriptor descriptor, + AuthoredWorldLaunchDescriptorEvidence.Request request, + String requestJson, + AuthoredWorldSourceEvidence source, + String sourceJson) { + if (!LaunchDescriptor.OUTCOME_FAILED.equals(descriptor.getOutcomeStatus()) + || !Objects.equals( + descriptor.getDescriptorSchemaVersion(), + AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION) + || !workloadNamespace.equals(descriptor.getTargetNamespace()) + || !request.canonicalTenantId().toString().equals(descriptor.getCanonicalTenantId()) + || !request.worldSlug().equals(descriptor.getWorldSlug()) + || !request + .authoredWorldSourceOperationId() + .toString() + .equals(descriptor.getAuthoredWorldSourceOperationId()) + || !request + .authoredWorldSourceEvidenceDigest() + .equals(descriptor.getAuthoredWorldSourceEvidenceDigest()) + || !request.controlPlaneRequestId().equals(descriptor.getControlPlaneRequestId()) + || !request.requestDigest().equals(descriptor.getRequestHash()) + || !request.requestDigest().equals(descriptor.getRequestDigest()) + || !requestJson.equals(descriptor.getOriginalRequestJson()) + || !sourceJson.equals(descriptor.getSourceEvidenceJson()) + || !Objects.equals(source.sourceGameTenantKey(), descriptor.getTenantId()) + || descriptor.getLaunchDescriptorId() != null + || descriptor.getGameTemplateId() != null + || descriptor.getVersionId() != null + || descriptor.getScriptPatchVersion() != null + || descriptor.getRuntimeFlagsJson() != null + || descriptor.getGenerationConfigRevision() != null + || descriptor.getVersionStateEpoch() != null + || descriptor.getReleaseBundleId() != null + || descriptor.getPublishedReleaseBundleRef() != null + || descriptor.getRemapSetId() != null + || descriptor.getResultDigest() != null + || !INVALID_TEMPLATE_CONFIGURATION.equals(descriptor.getFailureCode()) + || !UNSUPPORTED_CAPTURE_MESSAGE.equals(descriptor.getFailureMessage())) { + throw conflict( + "Stored failed descriptor is not the exact immutable unsupported-capture outcome"); + } + return new FrozenFailure(descriptor.getFailureCode(), descriptor.getFailureMessage()); + } + + private LaunchDescriptor frozenFailure( + AuthoredWorldLaunchDescriptorEvidence.Request request, + AuthoredWorldSourceEvidence source, + String requestJson, + String sourceJson, + String failureCode, + String failureMessage) { + LaunchDescriptor descriptor = new LaunchDescriptor(); + descriptor.setTenantId(source.sourceGameTenantKey()); + descriptor.setControlPlaneRequestId(request.controlPlaneRequestId()); + descriptor.setRequestHash(request.requestDigest()); + descriptor.setDescriptorSchemaVersion(AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION); + descriptor.setTargetNamespace(workloadNamespace); + descriptor.setCanonicalTenantId(request.canonicalTenantId().toString()); + descriptor.setWorldSlug(request.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId( + request.authoredWorldSourceOperationId().toString()); + descriptor.setAuthoredWorldSourceEvidenceDigest(request.authoredWorldSourceEvidenceDigest()); + descriptor.setRequestDigest(request.requestDigest()); + descriptor.setOriginalRequestJson(requestJson); + descriptor.setSourceEvidenceJson(sourceJson); + descriptor.setOutcomeStatus(LaunchDescriptor.OUTCOME_FAILED); + descriptor.setFailureCode(failureCode); + descriptor.setFailureMessage(failureMessage); + return descriptor; + } + + private String writeJson(Object value) { + try { + return objectMapper.writeValueAsString(value); + } catch (Exception failure) { + throw new IllegalStateException("Could not encode exact immutable owner evidence", failure); + } + } + + net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle toPublishedReleaseBundle( + PublishedReleaseBundleDto dto) { + try { + return PublishedReleaseEvidenceEncoding.toPublishedReleaseBundle(dto); + } catch (PublishedReleaseEvidenceEncoding.FailedParticipantException failure) { + throw conflict("Published release participant did not succeed"); + } + } + + GameDesignPublicationTerminalEvidence.ReleaseContent releaseContent( + PublishedReleaseBundleDto dto) { + try { + return PublishedReleaseEvidenceEncoding.releaseContent(dto); + } catch (PublishedReleaseEvidenceEncoding.IncompleteArtifactProofException missingProof) { + throw conflict("Immutable release content evidence is incomplete"); + } + } + + private GameDesignPublicationTerminalEvidence.ReleaseContent releaseContent(Result exact) { + var bundle = exact.releaseBundle(); + if (!bundle.hasManifestSchemaVersion()) { + throw conflict("Exact Account-pinned release bundle lacks its manifest schema"); + } + List participants = + bundle.getParticipantDigestsList().stream() + .map( + value -> + new GameDesignPublicationTerminalEvidence.Participant( + value.getParticipantKey(), + value.getScopeValue(), + null, + value.getAppliedCommitId(), + value.getContentDigest(), + value.getDigestSchemaVersion(), + value.hasAbilitySchemaDigest() ? value.getAbilitySchemaDigest() : null, + null, + null)) + .toList(); + List + artifacts = + bundle.getArtifactDigestsList().stream() + .map( + value -> + new net.firedevops.firemud.common.gamedesign + .AuthoredWorldReleaseAttestationEvidence.Artifact( + value.getUsageKey(), + value.getArtifactKind(), + value.getImmutableObjectKey(), + value.getContentDigest(), + value.getContentType(), + value.getArtifactSchemaVersion())) + .toList(); + return new GameDesignPublicationTerminalEvidence.ReleaseContent( + UUID.fromString(bundle.getCanonicalTenantId()), + UUID.fromString(bundle.getCanonicalVersionId()), + bundle.getPublishedReleaseBundleRef(), + bundle.getVersionNumber(), + bundle.getAttestationSchemaVersion(), + bundle.getPublishWorkflowId(), + bundle.getManifestHash(), + bundle.getManifestSchemaVersion(), + artifacts, + bundle.getRequiredManifestAssetKeysList(), + participants, + bundle.getCommandDefinitionsList(), + bundle.getGenerationConfigRevision(), + exact.worldPublishedStartLocationEvidence()); + } + + private void requireTerminalMatchesExactRelease( + Result exact, GameDesignPublicationTerminalEvidence terminal) { + if (terminal.releaseContent() == null + || !Arrays.equals( + terminal.releaseContent().canonicalBytes(), releaseContent(exact).canonicalBytes())) { + throw conflict("Private source binding release differs from exact pinned Account release"); + } + } + + private void requirePeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified same-namespace Game Session workload identity required") + .asRuntimeException(); + } + if (!("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service") + .equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Session workload required") + .asRuntimeException(); + } + } + + private static StatusRuntimeException conflict(String description) { + return Status.FAILED_PRECONDITION.withDescription(description).asRuntimeException(); + } + + /** + * Internal result pairing an exact selected-release descriptor with minimal retained projections. + * Projection construction validates canonical integrity, not producer authentication; the + * producer returns this result only after its owner path cross-checks the private source proofs. + */ + public record ResolvedBinding( + Request request, + Result associationRead, + ResolvedLaunchDescriptorDto descriptor, + List actorCoreProjections) { + public ResolvedBinding { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(associationRead, "associationRead"); + Objects.requireNonNull(descriptor, "descriptor"); + actorCoreProjections = + List.copyOf(Objects.requireNonNull(actorCoreProjections, "actorCoreProjections")); + if (!request.equals(associationRead.request()) + || !request + .decodedTuple() + .controlPlaneRequestId() + .equals(descriptor.controlPlaneRequestId()) + || !request + .decodedTuple() + .preAuthorizationTuple() + .action() + .scope() + .tenantId() + .toString() + .equals(descriptor.canonicalTenantId()) + || request.decodedTuple().preAuthorizationTuple().action().target().gameTemplateId() + != descriptor.gameTemplateId()) { + throw new IllegalArgumentException( + "Resolved descriptor differs from exact StartSession binding"); + } + var association = associationRead.association(); + var authoredWorld = descriptor.authoredWorldBinding(); + if (actorCoreProjections.stream() + .map(AuthoredInitialActorCoreProjection::bindingId) + .distinct() + .count() + != actorCoreProjections.size()) { + throw new IllegalArgumentException( + "Authored actor-core projection identities must be unique"); + } + for (var actorCore : actorCoreProjections) { + if (!actorCore.worldSourceOperationId().equals(association.sourceOperationId()) + || !actorCore.worldSourceEvidenceDigest().equals(association.sourceEvidenceDigest()) + || !actorCore.worldSlug().equals(association.worldSlug()) + || !actorCore.publicationWorkflowId().equals(association.publishWorkflowId()) + || !actorCore.canonicalTenantId().equals(association.canonicalTenantId()) + || !actorCore.canonicalVersionId().equals(association.canonicalVersionId()) + || !actorCore.selectedCommitId().equals(association.selectedCommitId()) + || !actorCore.worldSlug().equals(authoredWorld.worldSlug()) + || !actorCore + .worldSourceOperationId() + .equals(authoredWorld.authoredWorldSourceOperationId()) + || !actorCore + .worldSourceEvidenceDigest() + .equals(authoredWorld.authoredWorldSourceEvidenceDigest()) + || !actorCore.canonicalTenantId().equals(authoredWorld.canonicalTenantId()) + || !actorCore.canonicalVersionId().equals(association.canonicalVersionId()) + || association.templateId() != authoredWorld.gameTemplateId()) { + throw new IllegalArgumentException( + "Authored actor core differs from the exact selected StartSession release"); + } + } + } + } + + /** + * A proved immutable business result, exposed only after its owner transaction commits. RPC + * failures and missing evidence never become this type, so transport adapters need not guess + * whether a FAILED_PRECONDITION represents a retained result. + */ + public static final class StoredBusinessDenial extends RuntimeException { + private static final long serialVersionUID = 1L; + private final Result associationRead; + private final String failureCode; + + private StoredBusinessDenial(Result associationRead, FrozenFailure failure) { + super(failure.message()); + this.associationRead = Objects.requireNonNull(associationRead, "associationRead"); + this.failureCode = failure.code(); + } + + public Result associationRead() { + return associationRead; + } + + public String failureCode() { + return failureCode; + } + } + + private record FrozenFailure(String code, String message) { + private FrozenFailure { + Objects.requireNonNull(code, "code"); + Objects.requireNonNull(message, "message"); + } + } + + private record CapturedTemplate( + String failureMessage, + GameLogicReceiptBinding gameLogicReceipt, + net.firedevops.firemud.common.authoring.DraftCommitBinding selectedCommit, + net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot policySnapshot, + GameplayRuleSnapshot gameplayRules, + String publicationWorkflowId, + byte[] publicationOperationBytes, + byte[] publicationTerminalEvidenceBytes, + List actorCoreBindings) { + private CapturedTemplate { + Objects.requireNonNull(gameLogicReceipt, "gameLogicReceipt"); + Objects.requireNonNull(selectedCommit, "selectedCommit"); + Objects.requireNonNull(policySnapshot, "policySnapshot"); + Objects.requireNonNull(gameplayRules, "gameplayRules"); + Objects.requireNonNull(publicationWorkflowId, "publicationWorkflowId"); + publicationOperationBytes = + Objects.requireNonNull(publicationOperationBytes, "publicationOperationBytes").clone(); + publicationTerminalEvidenceBytes = + Objects.requireNonNull( + publicationTerminalEvidenceBytes, "publicationTerminalEvidenceBytes") + .clone(); + actorCoreBindings = + List.copyOf(Objects.requireNonNull(actorCoreBindings, "actorCoreBindings")); + if (!selectedCommit.equals(policySnapshot.binding()) + || !selectedCommit.equals(gameplayRules.binding())) { + throw new IllegalArgumentException("Captured source differs from selected commit"); + } + } + + @Override + public byte[] publicationOperationBytes() { + return publicationOperationBytes.clone(); + } + + @Override + public byte[] publicationTerminalEvidenceBytes() { + return publicationTerminalEvidenceBytes.clone(); + } + } + + private record SelectedGameplayRules( + GameplayRuleSnapshot snapshot, GameLogicReceiptBinding receiptBinding) { + private SelectedGameplayRules { + Objects.requireNonNull(snapshot, "snapshot"); + Objects.requireNonNull(receiptBinding, "receiptBinding"); + } + } + + private record GameLogicReceiptBinding( + String publishRequestId, + String selectionDigest, + String authorizationDigest, + String receiptDigest) { + private GameLogicReceiptBinding { + Objects.requireNonNull(publishRequestId, "publishRequestId"); + Objects.requireNonNull(selectionDigest, "selectionDigest"); + Objects.requireNonNull(authorizationDigest, "authorizationDigest"); + Objects.requireNonNull(receiptDigest, "receiptDigest"); + } + } + + private record OwnerOutcome(ResolvedBinding resolvedBinding, FrozenFailure failure) { + private OwnerOutcome { + if ((resolvedBinding == null) == (failure == null)) { + throw new IllegalArgumentException("Exactly one descriptor outcome is required"); + } + } + + static OwnerOutcome succeeded(ResolvedBinding binding) { + return new OwnerOutcome(Objects.requireNonNull(binding), null); + } + + static OwnerOutcome failed(FrozenFailure failure) { + return new OwnerOutcome(null, Objects.requireNonNull(failure)); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java new file mode 100644 index 0000000000..8e21ac2adb --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java @@ -0,0 +1,642 @@ +package net.firedevops.firemud.gamedesign.publication; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Function; +import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionResponse; +import net.firedevops.firemud.common.account.StartSessionRedeemedOperationProjectionClient; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Association; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.InitialConfigured; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; +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.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeByIdRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeByIdResponse; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.exception.DataAccessException; +import org.springframework.transaction.CannotCreateTransactionException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionSystemException; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Standalone, unregistered exact StartSession template-association read. It verifies Account's + * original redeemed operation before any local query and returns only immutable public evidence. + */ +public final class StartSessionTemplateAssociationReadService { + private final DSLContext dsl; + private final TemplateReferenceRepository templateReferences; + private final TemplateConfigSourceRepository templateSources; + private final VersionRepository versions; + private final GameDesignPublicationOperationRepository publicationOperations; + private final GameDesignSourceRepository sourceRepository; + private final SelectedDraftTemplateWorldSourceAssociationRepository associations; + private final PublishedReleaseBundleService releases; + private final TransactionTemplate snapshot; + private final String workloadNamespace; + private final AccountProjectionReader accountProjectionReader; + + /** + * Production construction always delegates to the explicit same-namespace Account mTLS client. + */ + public StartSessionTemplateAssociationReadService( + DSLContext dsl, + PlatformTransactionManager transactions, + String workloadNamespace, + StartSessionRedeemedOperationProjectionClient accountProjectionClient, + PublishedReleaseBundleService releases) { + this( + dsl, + transactions, + workloadNamespace, + Objects.requireNonNull(accountProjectionClient, "accountProjectionClient")::read, + releases); + } + + StartSessionTemplateAssociationReadService( + DSLContext dsl, + PlatformTransactionManager transactions, + String workloadNamespace, + AccountProjectionReader accountProjectionReader, + PublishedReleaseBundleService releases) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.templateReferences = new TemplateReferenceRepository(dsl); + this.templateSources = new TemplateConfigSourceRepository(dsl); + this.versions = new VersionRepository(dsl); + this.publicationOperations = new GameDesignPublicationOperationRepository(dsl); + this.sourceRepository = new GameDesignSourceRepository(dsl); + this.associations = new SelectedDraftTemplateWorldSourceAssociationRepository(dsl); + this.releases = Objects.requireNonNull(releases, "releases"); + this.accountProjectionReader = + Objects.requireNonNull(accountProjectionReader, "accountProjectionReader"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Design workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + snapshot = new TransactionTemplate(Objects.requireNonNull(transactions, "transactions")); + snapshot.setName("game-design-start-session-template-association-read"); + snapshot.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + snapshot.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + snapshot.setReadOnly(true); + } + + /** + * The typed request is untrusted. This checks the peer, independently verifies Account's exact + * operation/attempt projection, and only then opens a new local repeatable-read snapshot. + */ + public Result read(Request request) { + requirePeer(); + return readAuthorized(request, Function.identity()); + } + + /** + * Core-read-only qualification for one same-namespace Game Session or Entity caller. The exact + * Account operation is still verified by this Game Design workload before opening the snapshot; + * the callback runs within that same read-only snapshot with the exact association result. + */ + T readForAuthoredInitialActorCore(Request request, Function ownerRead) { + requireAuthoredInitialActorCorePeer(); + Objects.requireNonNull(ownerRead, "ownerRead"); + return readAuthorized(request, ownerRead); + } + + private T readAuthorized(Request request, Function ownerRead) { + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw Status.PERMISSION_DENIED + .withDescription("StartSession association namespace differs from peer") + .asRuntimeException(); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Independent StartSession association snapshot required") + .asRuntimeException(); + } + + final StartSessionPostAuthorizationExecutionTuple tuple; + try { + tuple = request.decodedTuple(); + requireAuthorizedTarget(request, tuple); + ReadRedeemedOperationProjectionResponse projection = + accountProjectionReader.read(tuple, request.ownerAttemptId(), request.ownerFence()); + requireAccountProjection(request, tuple, projection); + } catch (StatusRuntimeException failure) { + throw failure; + } catch (RuntimeException unavailableOrInvalid) { + throw Status.UNAVAILABLE + .withDescription("Exact redeemed StartSession projection unavailable") + .withCause(unavailableOrInvalid) + .asRuntimeException(); + } + + try { + return Objects.requireNonNull( + snapshot.execute( + ignored -> ownerRead.apply(Objects.requireNonNull(readSnapshot(request, tuple)))), + "StartSession association snapshot returned no result"); + } catch (StatusRuntimeException failure) { + throw failure; + } catch (DataAccessException unavailable) { + throw Status.UNAVAILABLE + .withDescription("Game Design association owner storage unavailable") + .withCause(unavailable) + .asRuntimeException(); + } catch (org.springframework.dao.TransientDataAccessException + | org.springframework.dao.DataAccessResourceFailureException unavailable) { + throw Status.UNAVAILABLE + .withDescription("Game Design association owner storage unavailable") + .withCause(unavailable) + .asRuntimeException(); + } catch (CannotCreateTransactionException | TransactionSystemException unavailable) { + throw Status.UNAVAILABLE + .withDescription("Game Design association owner storage unavailable") + .withCause(unavailable) + .asRuntimeException(); + } catch (RuntimeException invalid) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact StartSession template association is unavailable or conflicting") + .withCause(invalid) + .asRuntimeException(); + } + } + + private Result readSnapshot(Request request, StartSessionPostAuthorizationExecutionTuple tuple) { + var preTuple = tuple.preAuthorizationTuple(); + UUID canonicalTenantId = preTuple.action().scope().tenantId(); + long templateId = preTuple.action().target().gameTemplateId(); + + var phase = + templateReferences + .readPhase(canonicalTenantId) + .filter(value -> value.phase() == TemplateReferenceRepository.Phase.ENFORCED) + .filter(value -> value.phaseEpoch() > 0L) + .filter( + value -> + value.inventoryTemplateCount() != null && value.inventoryTemplateCount() > 0L) + .filter(value -> value.inventoryDigest() != null) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Explicit enforced template reference phase unavailable") + .asRuntimeException()); + + UUID canonicalVersionId; + UUID selectedCommitId = null; + TemplateReferenceRepository.BaseReference configuredReference = null; + TemplateConfigSource.Entry configuredEntry = null; + if (request.selection() instanceof InitialConfigured) { + configuredReference = + templateReferences + .readExactBaseReference(canonicalTenantId, templateId) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Current normalized template reference unavailable") + .asRuntimeException()); + canonicalVersionId = configuredReference.canonicalVersionId(); + if (!canonicalTenantId.equals(configuredReference.canonicalTenantId()) + || templateId != configuredReference.templateId()) { + throw new IllegalStateException("TEMPLATE_REFERENCE_INITIAL_SELECTOR_SCOPE_CONFLICT"); + } + } else if (request.selection() instanceof ExactReplay replay) { + canonicalVersionId = replay.canonicalVersionId(); + selectedCommitId = replay.selectedCommitId(); + } else { + throw Status.INVALID_ARGUMENT + .withDescription("Explicit initial or exact replay selection required") + .asRuntimeException(); + } + + Version version = + versions + .findByCanonicalTenantIdAndCanonicalVersionId(canonicalTenantId, canonicalVersionId) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Exact canonical published Version unavailable") + .asRuntimeException()); + requireLaunchableVersion(version, canonicalTenantId, canonicalVersionId, phase); + if (configuredReference != null) { + configuredEntry = + readCurrentConfiguredEntry( + configuredReference, targetProof(version), version, templateId); + } + StartSessionTemplateAssociationReadEvidence.ExactReplay replay = + request.selection() instanceof ExactReplay value ? value : null; + String workflowId = replay == null ? null : replay.publishWorkflowId(); + if (workflowId == null) { + // The canonical version has one exact immutable release row; its workflow ID, not a + // workflow-list/latest query, selects the original publication operation. + PublishedReleaseBundleDto configuredRelease = + releases + .findPublishedReleaseBundle(version.getTenantId(), version.getId()) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Exact published release bundle unavailable") + .asRuntimeException()); + if (!canonicalTenantId.equals(configuredRelease.canonicalTenantId()) + || !canonicalVersionId.equals(configuredRelease.canonicalVersionId()) + || !"v2".equals(configuredRelease.attestationSchemaVersion())) { + throw new IllegalStateException("START_SESSION_CONFIGURED_RELEASE_IDENTITY_CONFLICT"); + } + workflowId = configuredRelease.publishWorkflowId(); + } + return readExactPublication( + request, + canonicalTenantId, + templateId, + canonicalVersionId, + selectedCommitId, + workflowId, + replay, + configuredEntry, + version, + phase.phaseEpoch()); + } + + private Result readExactPublication( + Request request, + UUID canonicalTenantId, + long templateId, + UUID canonicalVersionId, + UUID selectedCommitId, + String workflowId, + ExactReplay replay, + TemplateConfigSource.Entry configuredEntry, + Version version, + long phaseEpoch) { + GameDesignPublicationOperationRepository.Readback operationReadback = + publicationOperations + .read(workflowId) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Exact original publication operation unavailable") + .asRuntimeException()); + GameDesignPublicationOperation operation = operationReadback.operation(); + if (!"PUBLISHED".equals(operationReadback.outcome()) + || operationReadback.terminalEvidenceBytes() == null + || !workflowId.equals(operation.workflowId()) + || !version.getTenantId().equals(operation.tenantKey()) + || !Objects.equals(version.getId(), operation.versionId())) { + throw new IllegalStateException("START_SESSION_PUBLICATION_OPERATION_NOT_PUBLISHED"); + } + GameDesignPublicationOperation exactOperation = + publicationOperations.requireOutcome( + operation.tenantKey(), + workflowId, + operation.versionId(), + operation.selectionDigest(), + "PUBLISHED"); + if (!Arrays.equals(exactOperation.canonicalBytes(), operation.canonicalBytes())) { + throw new IllegalStateException("START_SESSION_PUBLICATION_SELECTION_CHANGED"); + } + + GameDesignPublicationTerminalEvidence terminal = + GameDesignPublicationTerminalEvidence.fromStored(operationReadback.terminalEvidenceBytes()); + if (terminal.outcome() != GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + || !Arrays.equals(terminal.operationBytes(), operation.canonicalBytes()) + || terminal.releaseContent() == null + || terminal.publicationVersionStateEpoch() <= 0L) { + throw new IllegalStateException("START_SESSION_PUBLICATION_TERMINAL_CONFLICT"); + } + var selected = operation.account().input().selection(); + UUID actualSelectedCommitId = selected.selectedCommit().commitId(); + if (selectedCommitId != null && !selectedCommitId.equals(actualSelectedCommitId)) { + throw new IllegalStateException("START_SESSION_REPLAY_SELECTION_CONFLICT"); + } + selectedCommitId = actualSelectedCommitId; + if (!canonicalTenantId.equals(selected.target().canonicalTenantId()) + || !canonicalVersionId.equals(selected.target().canonicalVersionId()) + || !Objects.equals(version.getId(), selected.target().gameDesignVersionRowId()) + || !targetProof(version).equals(selected.target()) + || !selectedCommitId.equals(selected.selectedCommit().commitId()) + || !workflowId.equals(operation.world().request().publishWorkflowId()) + || !canonicalTenantId.equals(operation.world().request().canonicalTenantId()) + || !canonicalVersionId.equals(operation.world().request().canonicalVersionId()) + || !request.targetNamespace().equals(operation.world().request().targetNamespace())) { + throw new IllegalStateException("START_SESSION_OPERATION_COMMON_COMMIT_CONFLICT"); + } + + GameDesignSourceRepository.Capture capture = + sourceRepository + .readCapture(operation) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Complete original selected source capture unavailable") + .asRuntimeException()); + TemplateConfigSourceSnapshot.Capture templateCapture = + capture + .templateConfig() + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Exact template source capture unavailable") + .asRuntimeException()); + if (!templateCapture.snapshot().binding().equals(selected.selectedCommit())) { + throw new IllegalStateException("START_SESSION_CAPTURE_SOURCE_ENTRY_CONFLICT"); + } + List capturedTemplateEntries = + templateCapture.snapshot().entries().stream() + .filter(entry -> Long.parseLong(entry.templateId()) == templateId) + .toList(); + if (capturedTemplateEntries.size() != 1) { + throw new IllegalStateException("START_SESSION_CAPTURE_TEMPLATE_ENTRY_UNAVAILABLE"); + } + TemplateConfigSource.Entry selectedTemplateEntry = capturedTemplateEntries.getFirst(); + if (!selectedTemplateEntry.config().baseVersionId().equals(canonicalVersionId) + || replay == null + && (configuredEntry == null || !configuredEntry.equals(selectedTemplateEntry))) { + throw new IllegalStateException("START_SESSION_CAPTURE_SOURCE_ENTRY_CONFLICT"); + } + var retainedAssociations = associations.readExact(operation, templateCapture); + List templateAssociations = + retainedAssociations.stream().filter(value -> value.templateId() == templateId).toList(); + if (templateAssociations.size() != 1) { + throw new IllegalStateException("START_SESSION_TEMPLATE_ASSOCIATION_NOT_UNIQUE"); + } + var retained = templateAssociations.getFirst(); + if (!canonicalTenantId.equals(retained.canonicalTenantId()) + || !canonicalVersionId.equals(retained.canonicalVersionId()) + || !selectedCommitId.equals(retained.selectedCommitId()) + || !workflowId.equals(retained.publishWorkflowId()) + || !retained.targetNamespace().equals(request.targetNamespace())) { + throw new IllegalStateException("START_SESSION_TEMPLATE_ASSOCIATION_SELECTION_CONFLICT"); + } + + ReadAuthoredWorldSourceIntakeByIdRequest worldRequest; + ReadAuthoredWorldSourceIntakeByIdResponse worldResponse; + try { + worldRequest = + ReadAuthoredWorldSourceIntakeByIdRequest.parseFrom(retained.worldReadRequestBytes()); + worldResponse = + ReadAuthoredWorldSourceIntakeByIdResponse.parseFrom(retained.worldReadResponseBytes()); + } catch (IOException malformed) { + throw new IllegalStateException("START_SESSION_WORLD_SOURCE_RECEIPT_CORRUPT", malformed); + } + Association association = + Association.fromStoredProjection( + retained.canonicalTenantId(), + retained.templateId(), + retained.canonicalVersionId(), + retained.selectedCommitId(), + retained.publishWorkflowId(), + operation.selectionDigest(), + retained.digest(), + retained.targetNamespace(), + retained.intakeRequestId(), + retained.worldOperationId(), + retained.sourceOperationId(), + retained.worldSlug(), + retained.sourceEvidenceDigest(), + worldRequest, + worldResponse); + + if (replay != null + && (!replay.canonicalVersionId().equals(association.canonicalVersionId()) + || !replay.selectedCommitId().equals(association.selectedCommitId()) + || !replay.publishWorkflowId().equals(association.publishWorkflowId()) + || !replay.associationDigest().equals(association.associationDigest()))) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact retry differs from the first pinned association") + .asRuntimeException(); + } + + PublishedReleaseBundleDto release = + releases + .findPublishedReleaseBundle(version.getTenantId(), version.getId()) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Exact published release bundle unavailable") + .asRuntimeException()); + if (!workflowId.equals(release.publishWorkflowId()) + || !canonicalTenantId.equals(release.canonicalTenantId()) + || !canonicalVersionId.equals(release.canonicalVersionId()) + || !release.worldPublishedStartLocationEvidence().equals(operation.world())) { + throw new IllegalStateException("START_SESSION_RELEASE_OWNER_EVIDENCE_CONFLICT"); + } + var releaseContent = releaseContent(release); + if (!Arrays.equals( + terminal.releaseContent().canonicalBytes(), releaseContent.canonicalBytes())) { + throw new IllegalStateException("START_SESSION_RELEASE_TERMINAL_CONTENT_CONFLICT"); + } + WorldPublishedStartLocationEvidence worldEvidence = + WorldPublishedStartLocationEvidence.fromStored( + terminal.releaseContent().worldStartLocationEvidence().canonicalBytes()); + return new Result( + request, association, toPublishedReleaseBundle(release), worldEvidence, phaseEpoch); + } + + private TemplateConfigSource.Entry readCurrentConfiguredEntry( + TemplateReferenceRepository.BaseReference ref, + DraftCommitBinding.TargetProof target, + Version version, + long templateId) { + if (ref == null + || !ref.canonicalTenantId().equals(version.getCanonicalTenantId()) + || !ref.canonicalVersionId().equals(version.getCanonicalVersionId()) + || ref.templateId() != templateId) { + throw new IllegalStateException("TEMPLATE_REFERENCE_ENTRY_PROJECTION_CONFLICT"); + } + Record head = + dsl.fetchOne( + "SELECT visible_commit_id FROM game_design_template_config_source_head " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + ref.canonicalTenantId(), + ref.canonicalVersionId()); + UUID visibleCommitId = head == null ? null : head.get("visible_commit_id", UUID.class); + if (visibleCommitId == null) { + throw new IllegalStateException("TEMPLATE_REFERENCE_SOURCE_HEAD_PROJECTION_CONFLICT"); + } + TemplateConfigSourceSnapshot currentSource = + templateSources + .readSnapshot(target, visibleCommitId) + .orElseThrow( + () -> new IllegalStateException("TEMPLATE_REFERENCE_CURRENT_SOURCE_UNAVAILABLE")); + List currentEntries = + currentSource.entries().stream() + .filter(entry -> Long.parseLong(entry.templateId()) == templateId) + .toList(); + if (!currentSource.binding().commitId().equals(visibleCommitId) || currentEntries.size() != 1) { + throw new IllegalStateException("TEMPLATE_REFERENCE_CURRENT_SOURCE_CONFLICT"); + } + TemplateConfigSource.Entry currentEntry = currentEntries.getFirst(); + if (!currentEntry.sourceBinding().target().equals(target) + || !currentEntry.sourceBinding().commitId().equals(ref.sourceCommitId()) + || !currentEntry.revisionId().equals(ref.sourceRevisionId()) + || !currentEntry.config().baseVersionId().equals(ref.canonicalVersionId())) { + throw new IllegalStateException("TEMPLATE_REFERENCE_ENTRY_PROJECTION_CONFLICT"); + } + var privateTemplate = + dsl.fetchOne( + "SELECT tenant_id, default_version_id, config::TEXT AS config_json " + + "FROM game_templates WHERE id = ?", + templateId); + if (privateTemplate == null + || !version.getTenantId().equals(privateTemplate.get("tenant_id", String.class)) + || !Objects.equals(version.getId(), privateTemplate.get("default_version_id", Long.class)) + || !currentEntry + .config() + .canonicalJson() + .equals( + new TemplateConfigSource.Config(privateTemplate.get("config_json", String.class)) + .canonicalJson())) { + throw new IllegalStateException("TEMPLATE_REFERENCE_CURRENT_SOURCE_PROJECTION_CONFLICT"); + } + return currentEntry; + } + + private void requireLaunchableVersion( + Version version, + UUID canonicalTenantId, + UUID canonicalVersionId, + TemplateReferenceRepository.PhaseSnapshot phase) { + if (!Objects.equals(version.getCanonicalTenantId(), canonicalTenantId) + || !Objects.equals(version.getCanonicalVersionId(), canonicalVersionId) + || !(version.getVersionState() == VersionLifecycleState.PUBLISHED + || version.getVersionState() == VersionLifecycleState.ACTIVE) + || !"NEW_GAME_ROW".equals(phase.provenanceKind()) + || !Objects.equals(version.getIdentitySourceGameRowId(), phase.sourceGameRowId()) + || !Objects.equals(version.getIdentitySourceGameTenantKey(), phase.sourceGameTenantKey()) + || !Objects.equals(version.getIdentitySourceProvenanceKind(), phase.provenanceKind()) + || !Objects.equals(version.getTenantId(), phase.sourceGameTenantKey())) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact fresh published or active template Version unavailable") + .asRuntimeException(); + } + } + + private DraftCommitBinding.TargetProof targetProof(Version version) { + return new DraftCommitBinding.TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + } + + private void requireAuthorizedTarget( + Request request, StartSessionPostAuthorizationExecutionTuple tuple) { + var action = tuple.preAuthorizationTuple().action(); + if (!request.targetNamespace().equals(action.scope().targetNamespace()) + || !workloadNamespace.equals(action.scope().targetNamespace())) { + throw Status.PERMISSION_DENIED + .withDescription("StartSession target namespace differs from verified owner") + .asRuntimeException(); + } + } + + private void requireAccountProjection( + Request request, + StartSessionPostAuthorizationExecutionTuple tuple, + ReadRedeemedOperationProjectionResponse projection) { + byte[] canonicalPreTuple = + tuple.preAuthorizationTuple().canonicalJson().getBytes(StandardCharsets.UTF_8); + String expectedRedeemer = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"; + if (projection == null + || !tuple.controlPlaneRequestId().equals(projection.getControlPlaneRequestId()) + || !MessageDigest.isEqual( + canonicalPreTuple, projection.getCanonicalPreAuthorizationTupleBytes().toByteArray()) + || !tuple.preAuthorizationTuple().mutationDigest().equals(projection.getMutationDigest()) + || !request.ownerAttemptId().toString().equals(projection.getOwnerAttemptId()) + || request.ownerFence() != projection.getOwnerFence() + || !expectedRedeemer.equals(projection.getAuthenticatedRedeemerWorkloadIdentity())) { + throw Status.FAILED_PRECONDITION + .withDescription( + "Account projection differs from the exact original StartSession attempt") + .asRuntimeException(); + } + } + + GameDesignPublicationTerminalEvidence.ReleaseContent releaseContent( + PublishedReleaseBundleDto dto) { + try { + return PublishedReleaseEvidenceEncoding.releaseContent(dto); + } catch (PublishedReleaseEvidenceEncoding.IncompleteArtifactProofException missingProof) { + throw new IllegalStateException( + "START_SESSION_IMMUTABLE_RELEASE_ARTIFACT_PROOF_MISSING", missingProof); + } + } + + net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle toPublishedReleaseBundle( + PublishedReleaseBundleDto dto) { + try { + return PublishedReleaseEvidenceEncoding.toPublishedReleaseBundle(dto); + } catch (PublishedReleaseEvidenceEncoding.FailedParticipantException failure) { + throw new IllegalStateException("START_SESSION_PUBLISHED_PARTICIPANT_FAILURE", failure); + } + } + + private void requirePeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified Game Session workload identity required") + .asRuntimeException(); + } + if (!("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service") + .equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Session workload required") + .asRuntimeException(); + } + } + + void requireAuthoredInitialActorCorePeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified same-namespace Game Session or Entity workload required") + .asRuntimeException(); + } + String expectedPrefix = "spiffe://firemud/ns/" + workloadNamespace + "/sa/"; + if (!workloadNamespace.equals(peer.namespace()) + || !("game-session-service".equals(peer.service()) + || "entity-management-service".equals(peer.service())) + || !(expectedPrefix + peer.service()).equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Session or Entity workload required") + .asRuntimeException(); + } + if (SessionContext.hasAuthenticatedCallerContext()) { + throw Status.PERMISSION_DENIED + .withDescription("Workload-only authored-core read required") + .asRuntimeException(); + } + } + + @FunctionalInterface + interface AccountProjectionReader { + ReadRedeemedOperationProjectionResponse read( + StartSessionPostAuthorizationExecutionTuple tuple, UUID ownerAttemptId, long ownerFence); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSource.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSource.java new file mode 100644 index 0000000000..0f3a934feb --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSource.java @@ -0,0 +1,298 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.math.BigInteger; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.gamedesign.TemplateConfigOwnerSourceInventoryDeclaration; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family; + +/** Closed authored wiring. Syntax validation never qualifies an external owner's reference. */ +public final class TemplateConfigSource { + public static final String REVISION_KIND = TemplateConfigSourceValues.REVISION_KIND; + public static final String SCOPE = TemplateConfigSourceValues.SCOPE; + public static final String SCOPE_ID = TemplateConfigSourceValues.SCOPE_ID; + + private TemplateConfigSource() {} + + public enum OperationKind { + CREATE, + UPSERT, + DELETE, + DECLARE_OWNER_SOURCE_INVENTORY + } + + public record GameplayInput(Family family, String key, UUID revisionId) { + public GameplayInput { + new TemplateConfigSourceValues.GameplayInput(family, key, revisionId); + } + } + + /** Canonical config remains the actual authored document, without derived commit evidence. */ + public record Config(String canonicalJson) { + public Config { + canonicalJson = new TemplateConfigSourceValues.Config(canonicalJson).canonicalJson(); + } + + TemplateConfigSourceValues.Config shared() { + return new TemplateConfigSourceValues.Config(canonicalJson); + } + + public UUID baseVersionId() { + return shared().baseVersionId(); + } + + public List gameplayInputs() { + return shared().gameplayInputs().stream() + .map(value -> new GameplayInput(value.family(), value.key(), value.revisionId())) + .toList(); + } + + /** These missing authenticated owner boundaries deliberately prevent qualification. */ + public void requireAvailableOwnerReads() { + var value = shared(); + if (value.hasWorldReferences()) + throw new IllegalStateException("TEMPLATE_CONFIG_WORLD_EXACT_OWNER_READ_UNAVAILABLE"); + if (value.hasEntityReferences()) + throw new IllegalStateException("TEMPLATE_CONFIG_ENTITY_EXACT_OWNER_READ_UNAVAILABLE"); + if (value.hasAutomationReferences()) + throw new IllegalStateException("TEMPLATE_CONFIG_AUTOMATION_EXACT_OWNER_READ_UNAVAILABLE"); + } + } + + public record Mutation( + DraftCommitBinding binding, + String revisionOrder, + UUID revisionId, + OperationKind operation, + String templateId, + String templateName, + Config config, + Owner declaredOwner, + AutomationAuthoredSourceInventoryDeclaration inventory, + EntityAuthoredSourceInventoryDeclaration entityInventory) { + public Mutation( + DraftCommitBinding binding, + String revisionOrder, + UUID revisionId, + OperationKind operation, + String templateId, + String templateName, + Config config) { + this( + binding, + revisionOrder, + revisionId, + operation, + templateId, + templateName, + config, + null, + null, + null); + } + + public Mutation { + new TemplateConfigSourceValues.Mutation( + binding, + revisionOrder, + revisionId, + operation == null + ? null + : TemplateConfigSourceValues.OperationKind.valueOf(operation.name()), + templateId, + templateName, + config == null ? null : config.shared(), + declaredOwner, + inventory, + entityInventory); + } + + public String payload() { + return shared().payload(); + } + + public boolean changesTemplateRow() { + return shared().changesTemplateRow(); + } + + public TemplateConfigOwnerSourceInventoryDeclaration ownerInventoryDeclaration() { + return shared().ownerInventoryDeclaration(); + } + + public String inventoryJson() { + return shared().inventoryJson(); + } + + TemplateConfigSourceValues.Mutation shared() { + return new TemplateConfigSourceValues.Mutation( + binding, + revisionOrder, + revisionId, + TemplateConfigSourceValues.OperationKind.valueOf(operation.name()), + templateId, + templateName, + config == null ? null : config.shared(), + declaredOwner, + inventory, + entityInventory); + } + + static Mutation fromShared(TemplateConfigSourceValues.Mutation value) { + return new Mutation( + value.binding(), + value.revisionOrder(), + value.revisionId(), + OperationKind.valueOf(value.operation().name()), + value.templateId(), + value.templateName(), + value.config() == null ? null : new Config(value.config().canonicalJson()), + value.declaredOwner(), + value.inventory(), + value.entityInventory()); + } + } + + public record Entry( + String templateId, + Config config, + DraftCommitBinding sourceBinding, + String revisionOrder, + UUID revisionId, + String createdName) { + public Entry { + new TemplateConfigSourceValues.Entry( + templateId, + config == null ? null : config.shared(), + sourceBinding, + revisionOrder, + revisionId, + createdName); + } + + Map object() { + return shared().object(); + } + + TemplateConfigSourceValues.Entry shared() { + return new TemplateConfigSourceValues.Entry( + templateId, config.shared(), sourceBinding, revisionOrder, revisionId, createdName); + } + + static Entry fromShared(TemplateConfigSourceValues.Entry value) { + return new Entry( + value.templateId(), + new Config(value.config().canonicalJson()), + value.sourceBinding(), + value.revisionOrder(), + value.revisionId(), + value.createdName()); + } + } + + public static List mutations(DraftCommitBinding binding) { + return TemplateConfigSourceValues.mutations(binding).stream() + .map(Mutation::fromShared) + .toList(); + } + + public static String upsertPayload(String templateId, Config config) { + return TemplateConfigSourceValues.upsertPayload(templateId, config.shared()); + } + + public static String createPayload(String templateName, Config config) { + return TemplateConfigSourceValues.createPayload(templateName, config.shared()); + } + + public static String deletePayload(String templateId) { + return TemplateConfigSourceValues.deletePayload(templateId); + } + + public static String ownerInventoryPayload( + Owner owner, AutomationAuthoredSourceInventoryDeclaration inventory) { + return TemplateConfigSourceValues.ownerInventoryPayload(owner, inventory); + } + + public static String ownerInventoryPayload( + Owner owner, EntityAuthoredSourceInventoryDeclaration inventory) { + return TemplateConfigSourceValues.ownerInventoryPayload(owner, inventory); + } + + public static List + replayOwnerInventoryDeclarations( + List inherited, + DraftCommitBinding binding) { + Map declarations = + new java.util.EnumMap<>(Owner.class); + for (var declaration : inherited) { + if (!binding.target().equals(declaration.sourceBinding().target()) + || declarations.put(declaration.owner(), declaration) != null) + throw new IllegalArgumentException("Invalid inherited owner inventory declarations"); + } + for (Mutation mutation : mutations(binding)) { + if (mutation.operation() == OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) { + declarations.put(mutation.declaredOwner(), mutation.ownerInventoryDeclaration()); + } + } + return declarations.values().stream() + .sorted(Comparator.comparing(value -> value.owner().name())) + .toList(); + } + + public static List replay( + List inherited, DraftCommitBinding binding, Map createdRows) { + Map entries = new java.util.HashMap<>(); + for (Entry entry : inherited) { + if (!binding.target().equals(entry.sourceBinding().target()) + || entries.put(entry.templateId(), entry) != null) + throw new IllegalArgumentException("Invalid inherited template config inventory"); + } + for (Mutation mutation : mutations(binding)) { + if (!mutation.changesTemplateRow()) continue; + if (mutation.operation() == OperationKind.DELETE) { + if (entries.remove(mutation.templateId()) == null) + throw new IllegalArgumentException("Template DELETE requires an authored entry"); + } else { + String id = + mutation.operation() == OperationKind.CREATE + ? Objects.requireNonNull( + createdRows.get(mutation.revisionId()), + "Actual generated template row required") + : mutation.templateId(); + if (mutation.operation() == OperationKind.CREATE && entries.containsKey(id) + || mutation.operation() == OperationKind.UPSERT && !entries.containsKey(id)) + throw new IllegalArgumentException( + "Template source identity is not an existing qualified entry"); + entries.put( + id, + new Entry( + id, + mutation.config(), + binding, + mutation.revisionOrder(), + mutation.revisionId(), + mutation.templateName())); + } + } + return entries.values().stream() + .sorted(Comparator.comparing(e -> new BigInteger(e.templateId()))) + .toList(); + } + + public static boolean isScope(DraftCommitBinding.AffectedUnit unit) { + return SCOPE.equals(unit.aggregateType()) + && SCOPE.equals(unit.scopeType()) + && SCOPE_ID.equals(unit.scopeId()); + } + + static UUID uuid(String value) { + return TemplateConfigSourceValues.uuid(value); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceRepository.java new file mode 100644 index 0000000000..fe1a8d202e --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceRepository.java @@ -0,0 +1,869 @@ +package net.firedevops.firemud.gamedesign.publication; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.TemplateConfigOwnerSourceInventoryDeclaration; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Actual coordinated author history. Account mutation authority must be supplied by its owner. */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Owner-local persistence collaborator") +public final class TemplateConfigSourceRepository { + private final DSLContext dsl; + private final DraftCommitCoordinatorRepository coordinator; + private final TemplateReferenceRepository templateReferences; + + public TemplateConfigSourceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + coordinator = new DraftCommitCoordinatorRepository(dsl); + templateReferences = new TemplateReferenceRepository(dsl); + } + + public TemplateConfigSourceSnapshot.Genesis enrollFreshDraft(TargetProof target) { + write(); + lock(target); + var existing = readGenesis(target); + if (existing.isPresent()) return existing.orElseThrow(); + Record witness = + dsl.fetchOne( + "SELECT creation_transaction_id FROM game_design_realm_policy_version_insert " + + "WHERE version_id = ? AND creation_transaction_id = pg_current_xact_id()::TEXT", + target.gameDesignVersionRowId()); + if (witness == null) + throw new IllegalStateException("TEMPLATE_CONFIG_FRESH_INSERT_UNAVAILABLE"); + var result = + new TemplateConfigSourceSnapshot.Genesis( + target, UUID.randomUUID(), witness.get(0, String.class)); + dsl.execute( + "INSERT INTO game_design_template_config_source_genesis (canonical_tenant_id, canonical_version_id, " + + "version_id, receipt_id, creation_transaction_id, target_json) VALUES (?, ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + target.gameDesignVersionRowId(), + result.receiptId(), + result.creationTransactionId(), + CommandSource.canonical(CommandSource.targetObject(target))); + dsl.execute( + "INSERT INTO game_design_template_config_source_head (canonical_tenant_id, canonical_version_id, source_epoch, genesis_receipt_id) " + + "VALUES (?, ?, '0', ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + result.receiptId()); + if (!result.equals(readGenesis(target).orElseThrow())) + throw new IllegalStateException("TEMPLATE_CONFIG_GENESIS_READBACK_CONFLICT"); + return result; + } + + public Optional readGenesis(TargetProof target) { + var row = + dsl.fetchOne( + "SELECT * FROM game_design_template_config_source_genesis WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (row == null) return Optional.empty(); + if (!CommandSource.canonical(CommandSource.targetObject(target)) + .equals(row.get("target_json", String.class)) + || target.gameDesignVersionRowId() != row.get("version_id", Long.class)) + throw new IllegalStateException("TEMPLATE_CONFIG_GENESIS_TARGET_CONFLICT"); + return Optional.of( + new TemplateConfigSourceSnapshot.Genesis( + target, + row.get("receipt_id", UUID.class), + row.get("creation_transaction_id", String.class))); + } + + public Optional apply(DraftCommitBinding binding) { + write(); + lock(binding.target()); + exact(binding); + var prior = application(binding); + if (prior.isPresent()) return prior; + var mutations = TemplateConfigSource.mutations(binding); + if (mutations.isEmpty()) return Optional.empty(); + open(binding.target()); + var slot = coordinator.readApplicationSlot(binding.target()).orElseThrow(); + var owner = + coordinator + .read(binding.target(), binding.requestId()) + .orElseThrow() + .ownerStates() + .get(Owner.GAME_DESIGN_CONTROL_PLANE); + if (!slot.commitId().equals(binding.commitId()) + || !slot.requestId().equals(binding.requestId()) + || owner == null + || owner.status() != DraftCommitCoordinatorRepository.OwnerStatus.IN_PROGRESS + && owner.status() != DraftCommitCoordinatorRepository.OwnerStatus.UNKNOWN) + throw new IllegalStateException("TEMPLATE_CONFIG_COORDINATOR_APPLICATION_UNAVAILABLE"); + Record head = head(binding.target()); + String epoch = head.get("source_epoch", String.class); + var units = + binding.affectedUnits(Owner.GAME_DESIGN_CONTROL_PLANE).stream() + .filter(TemplateConfigSource::isScope) + .toList(); + if (units.size() != 1 + || !units.getFirst().aggregateId().equals(binding.target().canonicalVersionId().toString()) + || !epoch.equals(units.getFirst().expectedEpoch())) + throw new IllegalStateException("TEMPLATE_CONFIG_EPOCH_CONFLICT"); + UUID inherited = head.get("visible_commit_id", UUID.class); + var fence = coordinator.readVisibilityFence(binding.target()); + if (inherited == null + ? fence.isPresent() || !"0".equals(epoch) + : fence.isEmpty() || !inherited.equals(fence.orElseThrow().commitId())) + throw new IllegalStateException("TEMPLATE_CONFIG_PREVIOUS_FENCE_CHANGED"); + var previousSnapshot = + inherited == null + ? Optional.empty() + : Optional.of(readSnapshot(binding.target(), inherited).orElseThrow()); + List previous = + previousSnapshot.map(TemplateConfigSourceSnapshot::entries).orElseGet(List::of); + List previousDeclarations = + previousSnapshot + .map(TemplateConfigSourceSnapshot::ownerSourceInventoryDeclarations) + .orElseGet(List::of); + var createdRows = new java.util.HashMap(); + for (var mutation : mutations) { + if (mutation.operation() + == TemplateConfigSource.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) { + dsl.execute( + "INSERT INTO game_design_template_config_owner_source_inventory_declaration " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, revision_id, revision_order, owner, inventory_json, payload_json) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + mutation.revisionId(), + Integer.parseInt(mutation.revisionOrder()), + mutation.declaredOwner().name(), + mutation.inventoryJson(), + mutation.payload()); + continue; + } + if (mutation.config() != null) { + mutation.config().requireAvailableOwnerReads(); + requireGameplayInputs(binding, mutation.config()); + } + String templateId = mutation.templateId(); + if (mutation.operation() == TemplateConfigSource.OperationKind.CREATE) { + var row = + dsl.fetchOne( + "INSERT INTO game_templates (tenant_id, name, config, default_version_id, template_reference_phase) " + + "VALUES (?, ?, CAST(? AS JSONB), ?, 'LEGACY') RETURNING id", + binding.target().gameDesignVersionTenantKey(), + mutation.templateName(), + mutation.config().canonicalJson(), + binding.target().gameDesignVersionRowId()); + templateId = Objects.requireNonNull(row).get("id", Long.class).toString(); + createdRows.put(mutation.revisionId(), templateId); + dsl.execute( + "INSERT INTO game_design_template_config_source_qualification " + + "(template_id, canonical_tenant_id, canonical_version_id, request_id, commit_id, revision_id, revision_order) " + + "VALUES (?, ?, ?, ?, ?, ?, ?)", + Long.parseLong(templateId), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + mutation.revisionId(), + Integer.parseInt(mutation.revisionOrder())); + } else { + requireQualified(binding.target(), templateId, true); + if (mutation.operation() == TemplateConfigSource.OperationKind.UPSERT) + dsl.execute( + "UPDATE game_templates SET config = CAST(? AS JSONB) WHERE id = ? AND tenant_id = ?", + mutation.config().canonicalJson(), + Long.parseLong(templateId), + binding.target().gameDesignVersionTenantKey()); + } + dsl.execute( + "INSERT INTO game_design_template_config_source_revision " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, revision_id, revision_order, operation_kind, template_id, payload_json) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + mutation.revisionId(), + Integer.parseInt(mutation.revisionOrder()), + mutation.operation().name(), + Long.parseLong(templateId), + mutation.payload()); + if (mutation.config() != null) { + dsl.execute( + "INSERT INTO game_design_template_config_source_ref " + + "(canonical_tenant_id, canonical_version_id, revision_id, ref_kind, ref_key, referenced_revision_id) " + + "VALUES (?, ?, ?, 'BASE_VERSION', ?, NULL)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + mutation.revisionId(), + mutation.config().baseVersionId().toString()); + for (var input : mutation.config().gameplayInputs()) + dsl.execute( + "INSERT INTO game_design_template_config_source_ref " + + "(canonical_tenant_id, canonical_version_id, revision_id, ref_kind, ref_key, referenced_revision_id) " + + "VALUES (?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + mutation.revisionId(), + input.family().name(), + input.key(), + input.revisionId()); + } + } + var snapshot = + new TemplateConfigSourceSnapshot( + binding, + new BigInteger(epoch).add(BigInteger.ONE).toString(), + inherited, + head.get("genesis_receipt_id", UUID.class), + TemplateConfigSource.replay(previous, binding, createdRows), + TemplateConfigSource.replayOwnerInventoryDeclarations(previousDeclarations, binding)); + var result = new TemplateConfigSourceSnapshot.Application(binding, epoch, snapshot); + dsl.execute( + "INSERT INTO game_design_template_config_source_application (canonical_tenant_id, canonical_version_id, request_id, commit_id, " + + "expected_epoch, snapshot_json, result_bytes) VALUES (?, ?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + epoch, + snapshot.canonicalJson(), + result.canonicalBytes()); + if (dsl.execute( + "UPDATE game_design_template_config_source_head SET source_epoch = ?, applied_commit_id = ? " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND source_epoch = ? AND visible_commit_id IS NOT DISTINCT FROM CAST(? AS UUID)", + snapshot.sourceEpoch(), + binding.commitId(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + epoch, + inherited) + != 1) throw new IllegalStateException("TEMPLATE_CONFIG_EPOCH_CONFLICT"); + templateReferences.synchronizeCurrentProjection( + binding.target(), + binding, + snapshot, + mutations.stream().filter(TemplateConfigSource.Mutation::changesTemplateRow).toList(), + createdRows); + return Optional.of(application(binding).orElseThrow()); + } + + public TemplateConfigSourceSnapshot captureSynchronized(DraftCommitBinding binding) { + write(); + lock(binding.target()); + exact(binding); + var existing = readSnapshot(binding.target(), binding.commitId()); + if (existing.isPresent()) { + if (!existing.orElseThrow().binding().equals(binding)) + throw new IllegalStateException("TEMPLATE_CONFIG_SNAPSHOT_BINDING_CONFLICT"); + return existing.orElseThrow(); + } + open(binding.target()); + requireFence(binding); + var head = head(binding.target()); + UUID inherited = head.get("visible_commit_id", UUID.class); + var applied = application(binding); + TemplateConfigSourceSnapshot snapshot; + if (!TemplateConfigSource.mutations(binding).isEmpty()) { + snapshot = applied.orElseThrow().snapshot(); + if (!Objects.equals(inherited, snapshot.inheritedCommitId())) + throw new IllegalStateException("TEMPLATE_CONFIG_PREDECESSOR_CHANGED"); + } else { + if (applied.isPresent()) + throw new IllegalStateException("TEMPLATE_CONFIG_UNDECLARED_APPLICATION"); + var inheritedSnapshot = + inherited == null + ? Optional.empty() + : Optional.of(readSnapshot(binding.target(), inherited).orElseThrow()); + var entries = + inheritedSnapshot.map(TemplateConfigSourceSnapshot::entries).orElseGet(List::of); + var declarations = + inheritedSnapshot + .map(TemplateConfigSourceSnapshot::ownerSourceInventoryDeclarations) + .orElseGet(List::of); + if (inherited == null && !"0".equals(head.get("source_epoch", String.class))) + throw new IllegalStateException("TEMPLATE_CONFIG_GENESIS_NOT_CURRENT"); + snapshot = + new TemplateConfigSourceSnapshot( + binding, + head.get("source_epoch", String.class), + inherited, + head.get("genesis_receipt_id", UUID.class), + entries, + declarations); + } + requireSelectedReferences(snapshot); + requireCurrentInventory(snapshot); + if (!snapshot.sourceEpoch().equals(head.get("source_epoch", String.class))) + throw new IllegalStateException("TEMPLATE_CONFIG_PARTIAL_WRITE_NOT_VISIBLE"); + dsl.execute( + "INSERT INTO game_design_template_config_source_snapshot (canonical_tenant_id, canonical_version_id, request_id, commit_id, " + + "snapshot_json, snapshot_digest) VALUES (?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + snapshot.canonicalJson(), + snapshot.digest()); + if (dsl.execute( + "UPDATE game_design_template_config_source_head SET visible_commit_id = ? WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND visible_commit_id IS NOT DISTINCT FROM CAST(? AS UUID) AND source_epoch = ?", + binding.commitId(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + inherited, + snapshot.sourceEpoch()) + != 1) throw new IllegalStateException("TEMPLATE_CONFIG_VISIBILITY_CONFLICT"); + return readSnapshot(binding.target(), binding.commitId()).orElseThrow(); + } + + public Optional readSnapshot(TargetProof target, UUID commitId) { + var row = + dsl.fetchOne( + "SELECT * FROM game_design_template_config_source_snapshot WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + commitId); + if (row == null) return Optional.empty(); + var snapshot = TemplateConfigSourceSnapshot.fromStored(row.get("snapshot_json", String.class)); + if (!snapshot.binding().target().equals(target) + || !snapshot.binding().commitId().equals(commitId) + || !snapshot.binding().requestId().equals(row.get("request_id", UUID.class)) + || !snapshot.digest().equals(row.get("snapshot_digest", String.class))) + throw new IllegalStateException("TEMPLATE_CONFIG_SNAPSHOT_READBACK_CONFLICT"); + exact(snapshot.binding()); + var genesis = readGenesis(target).orElseThrow(); + if (!snapshot.genesisReceiptId().equals(genesis.receiptId())) + throw new IllegalStateException("TEMPLATE_CONFIG_GENESIS_CHANGED"); + var fence = + dsl.fetchOne( + "SELECT input_digest FROM game_design_draft_commit_visibility_fence WHERE canonical_tenant_id = ? " + + "AND canonical_version_id = ? AND request_id = ? AND commit_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + snapshot.binding().requestId(), + commitId); + if (fence == null || !snapshot.binding().digest().equals(fence.get(0, String.class))) + throw new IllegalStateException("TEMPLATE_CONFIG_SNAPSHOT_FENCE_CONFLICT"); + verifyEntries(snapshot); + verifyOwnerInventoryDeclarations(snapshot); + requireSelectedReferences(snapshot); + return Optional.of(snapshot); + } + + public TemplateConfigSourceSnapshot.Capture freeze(GameDesignPublicationOperation operation) { + write(); + var selection = operation.account().input().selection(); + lock(selection.target()); + var prior = readCapture(operation); + if (prior.isPresent()) return prior.orElseThrow(); + var retained = + new GameDesignPublicationOperationRepository(dsl) + .read(operation.workflowId()) + .orElseThrow(); + GameDesignPublicationOperationRepository.exact(retained.operation(), operation); + if (!"PENDING".equals(retained.outcome())) + throw new IllegalStateException("TEMPLATE_CONFIG_OPERATION_SEALED"); + requireFence(selection.selectedCommit()); + var selected = + dsl.fetchOne( + "SELECT selection_json FROM game_design_authored_draft_publish_selection WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + selection.target().canonicalTenantId(), + selection.target().canonicalVersionId()); + if (selected == null || !selection.canonicalJson().equals(selected.get(0, String.class))) + throw new IllegalStateException("TEMPLATE_CONFIG_SELECTION_CHANGED"); + var snapshot = + readSnapshot(selection.target(), selection.selectedCommit().commitId()).orElseThrow(); + var head = head(selection.target()); + if (!snapshot.binding().equals(selection.selectedCommit()) + || !snapshot.sourceEpoch().equals(head.get("source_epoch", String.class)) + || !snapshot.binding().commitId().equals(head.get("visible_commit_id", UUID.class))) + throw new IllegalStateException("TEMPLATE_CONFIG_NOT_SYNCHRONIZED"); + requireSelectedReferences(snapshot); + requireCurrentInventory(snapshot); + for (var entry : snapshot.entries()) { + var row = + dsl.fetchOne( + "SELECT config::TEXT, default_version_id, default_script_patch_version, default_runtime_flags_json " + + "FROM game_templates WHERE id = ? AND tenant_id = ? FOR UPDATE", + Long.parseLong(entry.templateId()), + selection.target().gameDesignVersionTenantKey()); + if (row == null + || !entry + .config() + .canonicalJson() + .equals(CommandSource.canonical(CommandSource.tree(row.get(0, String.class)))) + || !Long.valueOf(selection.target().gameDesignVersionRowId()) + .equals(row.get(1, Long.class)) + || row.get(2, String.class) != null + || !"{}".equals(CommandSource.canonical(CommandSource.tree(row.get(3, String.class))))) + throw new IllegalStateException("TEMPLATE_CONFIG_LIVE_ROW_DIFFERS_FROM_SELECTED_SOURCE"); + } + var capture = new TemplateConfigSourceSnapshot.Capture(operation, snapshot); + dsl.execute( + "INSERT INTO game_design_template_config_source_capture (canonical_tenant_id, canonical_version_id, publish_workflow_id, commit_id, operation_bytes, capture_bytes, capture_digest) VALUES (?, ?, ?, ?, ?, ?, ?)", + selection.target().canonicalTenantId(), + selection.target().canonicalVersionId(), + operation.workflowId(), + snapshot.binding().commitId(), + operation.canonicalBytes(), + capture.canonicalBytes(), + capture.digest()); + return readCapture(operation).orElseThrow(); + } + + public Optional readCapture( + GameDesignPublicationOperation operation) { + var target = operation.account().input().selection().target(); + var row = + dsl.fetchOne( + "SELECT * FROM game_design_template_config_source_capture WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (row == null) return Optional.empty(); + var capture = + new TemplateConfigSourceSnapshot.Capture( + operation, readSnapshot(target, row.get("commit_id", UUID.class)).orElseThrow()); + if (!operation.workflowId().equals(row.get("publish_workflow_id", String.class)) + || !Arrays.equals(operation.canonicalBytes(), row.get("operation_bytes", byte[].class)) + || !Arrays.equals(capture.canonicalBytes(), row.get("capture_bytes", byte[].class)) + || !capture.digest().equals(row.get("capture_digest", String.class))) + throw new IllegalStateException("TEMPLATE_CONFIG_CAPTURE_READBACK_CONFLICT"); + return Optional.of(capture); + } + + private void requireCurrentInventory(TemplateConfigSourceSnapshot snapshot) { + var target = snapshot.binding().target(); + Boolean complete = + dsl.fetchSingle( + "SELECT template_config_current_inventory(?, ?, ?, ?, CAST(? AS JSONB))", + target.canonicalTenantId(), + target.canonicalVersionId(), + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + snapshot.canonicalJson()) + .get(0, Boolean.class); + if (!Boolean.TRUE.equals(complete)) + throw new IllegalStateException("TEMPLATE_CONFIG_EXPLICIT_TARGET_INVENTORY_UNQUALIFIED"); + } + + private void requireSelectedReferences(TemplateConfigSourceSnapshot snapshot) { + var gameplay = + new GameplayRuleSourceRepository(dsl) + .readSnapshot(snapshot.binding().target(), snapshot.binding().commitId()) + .orElseThrow(); + if (!snapshot.binding().equals(gameplay.binding())) + throw new IllegalStateException("TEMPLATE_CONFIG_GAMEPLAY_SELECTION_CHANGED"); + for (var entry : snapshot.entries()) + for (var input : entry.config().gameplayInputs()) + if (gameplay.entries().stream() + .noneMatch( + e -> + e.family() == input.family() + && e.definition().key().equals(input.key()) + && e.revisionId().equals(input.revisionId()))) + throw new IllegalStateException("TEMPLATE_CONFIG_GAMEPLAY_INPUT_CHANGED"); + } + + private Optional application( + DraftCommitBinding binding) { + var row = + dsl.fetchOne( + "SELECT * FROM game_design_template_config_source_application WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId()); + if (row == null) return Optional.empty(); + var result = + new TemplateConfigSourceSnapshot.Application( + binding, + row.get("expected_epoch", String.class), + TemplateConfigSourceSnapshot.fromStored(row.get("snapshot_json", String.class))); + if (!binding.requestId().equals(row.get("request_id", UUID.class)) + || !Arrays.equals(result.canonicalBytes(), row.get("result_bytes", byte[].class))) + throw new IllegalStateException("TEMPLATE_CONFIG_APPLICATION_READBACK_CONFLICT"); + var stored = + dsl.fetch( + "SELECT payload_json FROM game_design_template_config_source_revision WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND commit_id = ? ORDER BY revision_order", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId()) + .getValues("payload_json", String.class); + if (!stored.equals( + TemplateConfigSource.mutations(binding).stream() + .filter(TemplateConfigSource.Mutation::changesTemplateRow) + .map(TemplateConfigSource.Mutation::payload) + .toList())) + throw new IllegalStateException("TEMPLATE_CONFIG_REVISION_READBACK_CONFLICT"); + verifyOwnerInventoryApplication(binding); + verifyEntries(result.snapshot()); + verifyOwnerInventoryDeclarations(result.snapshot()); + return Optional.of(result); + } + + private void verifyOwnerInventoryApplication(DraftCommitBinding binding) { + var expected = + TemplateConfigSource.mutations(binding).stream() + .filter( + mutation -> + mutation.operation() + == TemplateConfigSource.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) + .toList(); + var rows = + dsl.fetch( + "SELECT revision_id, revision_order, owner, inventory_json, payload_json " + + "FROM game_design_template_config_owner_source_inventory_declaration " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND request_id = ? AND commit_id = ? " + + "ORDER BY revision_order", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()); + if (rows.size() != expected.size()) + throw new IllegalStateException("TEMPLATE_CONFIG_OWNER_INVENTORY_READBACK_CONFLICT"); + for (int i = 0; i < expected.size(); i++) { + var mutation = expected.get(i); + var row = rows.get(i); + if (!mutation.revisionId().equals(row.get("revision_id", UUID.class)) + || Integer.parseInt(mutation.revisionOrder()) != row.get("revision_order", Integer.class) + || !mutation.declaredOwner().name().equals(row.get("owner", String.class)) + || !mutation.inventoryJson().equals(row.get("inventory_json", String.class)) + || !mutation.payload().equals(row.get("payload_json", String.class))) + throw new IllegalStateException("TEMPLATE_CONFIG_OWNER_INVENTORY_READBACK_CONFLICT"); + } + } + + private void verifyOwnerInventoryDeclarations(TemplateConfigSourceSnapshot snapshot) { + var target = snapshot.binding().target(); + var effectiveRows = + dsl.fetch( + "SELECT DISTINCT ON (d.owner) d.request_id, d.commit_id, d.revision_id, d.revision_order, " + + "d.owner, d.inventory_json, d.payload_json, c.binding_json, c.input_digest " + + "FROM game_design_template_config_owner_source_inventory_declaration d " + + "JOIN game_design_template_config_source_application a ON a.canonical_tenant_id = d.canonical_tenant_id " + + "AND a.canonical_version_id = d.canonical_version_id AND a.request_id = d.request_id AND a.commit_id = d.commit_id " + + "JOIN game_design_draft_commit c ON c.canonical_tenant_id = d.canonical_tenant_id " + + "AND c.canonical_version_id = d.canonical_version_id AND c.request_id = d.request_id AND c.commit_id = d.commit_id " + + "WHERE d.canonical_tenant_id = ? AND d.canonical_version_id = ? AND a.expected_epoch::NUMERIC < CAST(? AS NUMERIC) " + + "ORDER BY d.owner, a.expected_epoch::NUMERIC DESC, d.revision_order DESC", + target.canonicalTenantId(), + target.canonicalVersionId(), + snapshot.sourceEpoch()); + var effectiveDeclarations = + new java.util.ArrayList(); + for (var row : effectiveRows) { + var sourceBinding = + DraftCommitBinding.fromStored( + row.get("binding_json", String.class), row.get("input_digest", String.class)); + exact(sourceBinding); + var mutation = + TemplateConfigSource.mutations(sourceBinding).stream() + .filter(m -> m.revisionId().equals(row.get("revision_id", UUID.class))) + .filter( + m -> + Integer.parseInt(m.revisionOrder()) + == row.get("revision_order", Integer.class)) + .filter( + m -> + m.operation() + == TemplateConfigSource.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) + .findFirst() + .orElseThrow( + () -> + new IllegalStateException( + "TEMPLATE_CONFIG_OWNER_INVENTORY_SOURCE_UNAVAILABLE")); + if (!sourceBinding.requestId().equals(row.get("request_id", UUID.class)) + || !sourceBinding.commitId().equals(row.get("commit_id", UUID.class)) + || !mutation.declaredOwner().name().equals(row.get("owner", String.class)) + || !mutation.inventoryJson().equals(row.get("inventory_json", String.class)) + || !mutation.payload().equals(row.get("payload_json", String.class))) + throw new IllegalStateException("TEMPLATE_CONFIG_OWNER_INVENTORY_SOURCE_CHANGED"); + effectiveDeclarations.add(mutation.ownerInventoryDeclaration()); + } + if (!effectiveDeclarations.equals(snapshot.ownerSourceInventoryDeclarations())) + throw new IllegalStateException("TEMPLATE_CONFIG_OWNER_INVENTORY_SNAPSHOT_CONFLICT"); + + for (var declaration : snapshot.ownerSourceInventoryDeclarations()) { + exact(declaration.sourceBinding()); + var mutation = + TemplateConfigSource.mutations(declaration.sourceBinding()).stream() + .filter(m -> m.revisionId().equals(declaration.revisionId())) + .filter(m -> m.revisionOrder().equals(declaration.revisionOrder())) + .filter( + m -> + m.operation() + == TemplateConfigSource.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) + .findFirst() + .orElseThrow( + () -> + new IllegalStateException( + "TEMPLATE_CONFIG_OWNER_INVENTORY_SOURCE_UNAVAILABLE")); + var row = + dsl.fetchOne( + "SELECT request_id, commit_id, owner, inventory_json, payload_json " + + "FROM game_design_template_config_owner_source_inventory_declaration " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND request_id = ? " + + "AND commit_id = ? AND revision_id = ? AND revision_order = ? AND owner = ?", + snapshot.binding().target().canonicalTenantId(), + snapshot.binding().target().canonicalVersionId(), + declaration.sourceBinding().requestId(), + declaration.sourceBinding().commitId(), + declaration.revisionId(), + Integer.parseInt(declaration.revisionOrder()), + declaration.owner().name()); + if (row == null + || !declaration.sourceBinding().requestId().equals(row.get("request_id", UUID.class)) + || !declaration.sourceBinding().commitId().equals(row.get("commit_id", UUID.class)) + || !declaration.owner().name().equals(row.get("owner", String.class)) + || !declaration.inventoryJson().equals(row.get("inventory_json", String.class)) + || !mutation.payload().equals(row.get("payload_json", String.class))) + throw new IllegalStateException("TEMPLATE_CONFIG_OWNER_INVENTORY_SOURCE_CHANGED"); + } + for (var mutation : TemplateConfigSource.mutations(snapshot.binding())) + if (mutation.operation() == TemplateConfigSource.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY + && snapshot.ownerSourceInventoryDeclarations().stream() + .noneMatch(d -> d.revisionId().equals(mutation.revisionId()))) + throw new IllegalStateException("TEMPLATE_CONFIG_OWNER_INVENTORY_SNAPSHOT_MISSING"); + } + + private void verifyEntries(TemplateConfigSourceSnapshot snapshot) { + for (var entry : snapshot.entries()) { + exact(entry.sourceBinding()); + requireQualified(snapshot.binding().target(), entry.templateId(), false); + var mutation = + new TemplateConfigSource.Mutation( + entry.sourceBinding(), + entry.revisionOrder(), + entry.revisionId(), + entry.createdName() == null + ? TemplateConfigSource.OperationKind.UPSERT + : TemplateConfigSource.OperationKind.CREATE, + entry.createdName() == null ? entry.templateId() : null, + entry.createdName(), + entry.config()); + var row = + dsl.fetchOne( + "SELECT payload_json FROM game_design_template_config_source_revision WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ? AND revision_id = ? AND revision_order = ? AND template_id = ?", + snapshot.binding().target().canonicalTenantId(), + snapshot.binding().target().canonicalVersionId(), + entry.sourceBinding().requestId(), + entry.sourceBinding().commitId(), + entry.revisionId(), + Integer.parseInt(entry.revisionOrder()), + Long.parseLong(entry.templateId())); + if (row == null || !mutation.payload().equals(row.get(0, String.class))) + throw new IllegalStateException("TEMPLATE_CONFIG_ENTRY_PROVENANCE_CHANGED"); + entry.config().requireAvailableOwnerReads(); + verifyNormalizedReferences(snapshot.binding().target(), entry); + } + } + + private void requireQualified(TargetProof target, String templateId, boolean lock) { + var row = + dsl.fetchOne( + "SELECT t.id, q.request_id, q.commit_id, q.revision_id, q.revision_order, c.binding_json, c.input_digest " + + "FROM game_templates t JOIN game_design_template_config_source_qualification q ON q.template_id = t.id " + + "JOIN game_design_draft_commit c ON c.canonical_tenant_id = q.canonical_tenant_id " + + "AND c.canonical_version_id = q.canonical_version_id AND c.request_id = q.request_id AND c.commit_id = q.commit_id " + + "WHERE t.id = ? AND t.tenant_id = ? AND q.canonical_tenant_id = ? AND q.canonical_version_id = ?" + + (lock ? " FOR UPDATE OF t" : ""), + Long.parseLong(templateId), + target.gameDesignVersionTenantKey(), + target.canonicalTenantId(), + target.canonicalVersionId()); + if (row == null) + throw new IllegalStateException("TEMPLATE_CONFIG_TEMPLATE_OWNER_PROVENANCE_UNAVAILABLE"); + var original = + DraftCommitBinding.fromStored( + row.get("binding_json", String.class), row.get("input_digest", String.class)); + if (!target.equals(original.target())) + throw new IllegalStateException("TEMPLATE_CONFIG_TEMPLATE_OWNER_PROVENANCE_CHANGED"); + exact(original); + var create = + TemplateConfigSource.mutations(original).stream() + .filter(m -> m.revisionId().equals(row.get("revision_id", UUID.class))) + .filter( + m -> m.revisionOrder().equals(row.get("revision_order", Integer.class).toString())) + .filter(m -> m.operation() == TemplateConfigSource.OperationKind.CREATE) + .findFirst() + .orElseThrow(); + var retained = + dsl.fetchOne( + "SELECT payload_json FROM game_design_template_config_source_revision " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND revision_id = ? AND template_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + create.revisionId(), + Long.parseLong(templateId)); + if (retained == null || !create.payload().equals(retained.get(0, String.class))) + throw new IllegalStateException("TEMPLATE_CONFIG_TEMPLATE_CREATE_READBACK_UNAVAILABLE"); + } + + private void requireGameplayInputs( + DraftCommitBinding binding, TemplateConfigSource.Config config) { + var head = + dsl.fetchOne( + "SELECT visible_commit_id, applied_commit_id FROM game_design_gameplay_rule_head " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId()); + if (head == null) + throw new IllegalStateException("TEMPLATE_CONFIG_GAMEPLAY_SOURCE_UNAVAILABLE"); + String json; + if (binding.commitId().equals(head.get("applied_commit_id", UUID.class))) { + var row = + dsl.fetchOne( + "SELECT snapshot_json FROM game_design_gameplay_rule_application " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId()); + json = + Objects.requireNonNull(row, "TEMPLATE_CONFIG_GAMEPLAY_APPLICATION_UNAVAILABLE") + .get(0, String.class); + } else { + UUID visible = head.get("visible_commit_id", UUID.class); + var fence = coordinator.readVisibilityFence(binding.target()); + if (visible == null && fence.isEmpty()) { + new GameplayRuleSourceRepository(dsl).readGenesis(binding.target()).orElseThrow(); + if (!config.gameplayInputs().isEmpty()) + throw new IllegalStateException("TEMPLATE_CONFIG_GAMEPLAY_INPUT_UNAVAILABLE"); + return; + } + if (fence.isEmpty() || !Objects.equals(visible, fence.orElseThrow().commitId())) + throw new IllegalStateException("TEMPLATE_CONFIG_GAMEPLAY_SOURCE_NOT_SYNCHRONIZED"); + json = + new GameplayRuleSourceRepository(dsl) + .readSnapshot(binding.target(), visible) + .orElseThrow() + .canonicalJson(); + } + var rules = GameplayRuleSnapshot.fromStored(json); + for (var input : config.gameplayInputs()) + if (rules.entries().stream() + .noneMatch( + e -> + e.family() == input.family() + && e.definition().key().equals(input.key()) + && e.revisionId().equals(input.revisionId()))) + throw new IllegalStateException("TEMPLATE_CONFIG_GAMEPLAY_INPUT_UNAVAILABLE"); + } + + private void verifyNormalizedReferences(TargetProof target, TemplateConfigSource.Entry entry) { + var refs = + dsl.fetch( + "SELECT ref_kind, ref_key, referenced_revision_id FROM game_design_template_config_source_ref " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND revision_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + entry.revisionId()); + var expected = new java.util.HashSet(); + expected.add("BASE_VERSION:" + entry.config().baseVersionId() + ":"); + for (var input : entry.config().gameplayInputs()) + expected.add(input.family().name() + ":" + input.key() + ":" + input.revisionId()); + var actual = new java.util.HashSet(); + for (var ref : refs) + actual.add( + ref.get("ref_kind", String.class) + + ":" + + ref.get("ref_key", String.class) + + ":" + + (ref.get("referenced_revision_id", UUID.class) == null + ? "" + : ref.get("referenced_revision_id", UUID.class))); + if (!expected.equals(actual) || refs.size() != expected.size()) + throw new IllegalStateException("TEMPLATE_CONFIG_NORMALIZED_REFERENCE_READBACK_CONFLICT"); + } + + private Record head(TargetProof target) { + readGenesis(target) + .orElseThrow(() -> new IllegalStateException("TEMPLATE_CONFIG_GENESIS_UNAVAILABLE")); + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM game_design_template_config_source_head WHERE canonical_tenant_id = ? AND canonical_version_id = ? FOR UPDATE", + target.canonicalTenantId(), + target.canonicalVersionId()), + "TEMPLATE_CONFIG_HEAD_UNAVAILABLE"); + } + + private void exact(DraftCommitBinding binding) { + if (!coordinator + .read(binding.target(), binding.requestId()) + .orElseThrow() + .binding() + .equals(binding)) throw new IllegalStateException("TEMPLATE_CONFIG_BINDING_CHANGED"); + } + + private void requireFence(DraftCommitBinding binding) { + var fence = coordinator.readVisibilityFence(binding.target()).orElseThrow(); + if (!binding.commitId().equals(fence.commitId()) + || !binding.requestId().equals(fence.requestId()) + || !binding.digest().equals(fence.inputDigest()) + || coordinator.read(binding.target(), binding.requestId()).orElseThrow().workflowState() + != DraftCommitCoordinatorRepository.WorkflowState.SYNCHRONIZED) + throw new IllegalStateException("TEMPLATE_CONFIG_SYNCHRONIZED_FENCE_UNAVAILABLE"); + } + + private void open(TargetProof target) { + if (dsl.fetchOne( + "SELECT id FROM version WHERE id = ? AND version_state = 'DRAFT' AND NOT is_script_only " + + "AND base_version_id IS NULL AND script_patch_version IS NULL", + target.gameDesignVersionRowId()) + == null + || dsl.fetchOne( + "SELECT 1 FROM game_design_authored_draft_publish_selection WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()) + != null) throw new IllegalStateException("TEMPLATE_CONFIG_FROZEN_OR_NOT_DRAFT"); + } + + private void lock(TargetProof target) { + var repository = new net.firedevops.firemud.gamedesign.repository.VersionRepository(dsl); + var qualified = + repository + .findByCanonicalTenantIdAndCanonicalVersionId( + target.canonicalTenantId(), target.canonicalVersionId()) + .orElseThrow(); + var version = + repository + .findByTenantIdAndIdForUpdate( + target.gameDesignVersionTenantKey(), target.gameDesignVersionRowId()) + .orElseThrow(); + var actual = + new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + if (!target.equals(actual) || !qualified.getId().equals(version.getId())) + throw new IllegalStateException("TEMPLATE_CONFIG_TARGET_CHANGED"); + } + + private static void write() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) + throw new IllegalStateException( + "Template config source requires writable READ_COMMITTED transaction"); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceSnapshot.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceSnapshot.java new file mode 100644 index 0000000000..b4a994eade --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceSnapshot.java @@ -0,0 +1,154 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.math.BigInteger; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.TemplateConfigOwnerSourceInventoryDeclaration; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; + +/** Actual template wiring history only; no Game Logic receipt or total-release completeness. */ +public record TemplateConfigSourceSnapshot( + DraftCommitBinding binding, + String sourceEpoch, + UUID inheritedCommitId, + UUID genesisReceiptId, + List entries, + List ownerSourceInventoryDeclarations) { + public static final String SCHEMA = + net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot.SCHEMA; + public static final String SCHEMA_V2 = + net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot.SCHEMA_V2; + + public TemplateConfigSourceSnapshot( + DraftCommitBinding binding, + String sourceEpoch, + UUID inheritedCommitId, + UUID genesisReceiptId, + List entries) { + this(binding, sourceEpoch, inheritedCommitId, genesisReceiptId, entries, List.of()); + } + + public TemplateConfigSourceSnapshot { + entries = List.copyOf(entries); + ownerSourceInventoryDeclarations = List.copyOf(ownerSourceInventoryDeclarations); + new net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot( + binding, + sourceEpoch, + inheritedCommitId, + genesisReceiptId, + entries.stream().map(TemplateConfigSource.Entry::shared).toList(), + ownerSourceInventoryDeclarations); + } + + public String canonicalJson() { + return shared().canonicalJson(); + } + + public byte[] canonicalBytes() { + return shared().canonicalBytes(); + } + + public String digest() { + return shared().digest(); + } + + public static TemplateConfigSourceSnapshot fromStored(String json) { + return fromShared( + net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot.fromStored(json)); + } + + net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot shared() { + return new net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot( + binding, + sourceEpoch, + inheritedCommitId, + genesisReceiptId, + entries.stream().map(TemplateConfigSource.Entry::shared).toList(), + ownerSourceInventoryDeclarations); + } + + static TemplateConfigSourceSnapshot fromShared( + net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot value) { + return new TemplateConfigSourceSnapshot( + value.binding(), + value.sourceEpoch(), + value.inheritedCommitId(), + value.genesisReceiptId(), + value.entries().stream().map(TemplateConfigSource.Entry::fromShared).toList(), + value.ownerSourceInventoryDeclarations()); + } + + public record Genesis(TargetProof target, UUID receiptId, String creationTransactionId) { + public Genesis { + Objects.requireNonNull(target); + DraftAuthorizationFenceBinding.requireUuid(receiptId); + if (creationTransactionId == null || !creationTransactionId.matches("[1-9][0-9]*")) + throw new IllegalArgumentException( + "Actual fresh template source creation witness required"); + } + } + + public record Application( + DraftCommitBinding binding, String expectedEpoch, TemplateConfigSourceSnapshot snapshot) { + public Application { + Objects.requireNonNull(binding); + if (expectedEpoch == null + || !expectedEpoch.matches("0|[1-9][0-9]*") + || !binding.equals(snapshot.binding()) + || TemplateConfigSource.mutations(binding).isEmpty() + || !new BigInteger(expectedEpoch) + .add(BigInteger.ONE) + .toString() + .equals(snapshot.sourceEpoch())) + throw new IllegalArgumentException( + "Exact template source application must advance its epoch"); + } + + public AppliedEpoch appliedEpoch() { + return new AppliedEpoch( + TemplateConfigSource.SCOPE, + binding.target().canonicalVersionId().toString(), + TemplateConfigSource.SCOPE, + TemplateConfigSource.SCOPE_ID, + expectedEpoch, + snapshot.sourceEpoch()); + } + + public byte[] canonicalBytes() { + var out = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + out, "game-design-template-config-source-application/v1"); + DraftAuthorizationFenceBinding.frame(out, expectedEpoch); + DraftAuthorizationFenceBinding.frame(out, snapshot.canonicalBytes()); + return out.toByteArray(); + } + } + + public record Capture( + GameDesignPublicationOperation operation, TemplateConfigSourceSnapshot snapshot) { + public Capture { + Objects.requireNonNull(operation); + Objects.requireNonNull(snapshot); + if (!operation.account().input().selection().selectedCommit().equals(snapshot.binding())) + throw new IllegalArgumentException( + "Template source differs from exact publication selection"); + } + + public byte[] canonicalBytes() { + var out = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "game-design-template-config-source-capture/v1"); + DraftAuthorizationFenceBinding.frame(out, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, snapshot.canonicalBytes()); + return out.toByteArray(); + } + + public String digest() { + return CommandSource.sha256(canonicalBytes()); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateReferenceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateReferenceRepository.java new file mode 100644 index 0000000000..537443fa54 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateReferenceRepository.java @@ -0,0 +1,603 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.TreeMap; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Owner-local normalized template base references and explicit tenant cutover authority. */ +public final class TemplateReferenceRepository { + private final DSLContext dsl; + + public TemplateReferenceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + /** + * Creates the non-launchable initial phase only from the exact completed fresh Game operation. + * Retained tenants and rows discovered by inventory scans are never initialized here. + */ + public PhaseSnapshot initializeFreshTenant(FreshTenantCreationEvidence evidence) { + requireWritableTransaction(); + Objects.requireNonNull(evidence, "evidence"); + if (!"NEW_GAME_ROW".equals(evidence.provenanceKind())) { + throw new IllegalArgumentException("Fresh Game tenant creation evidence is required"); + } + Record owner = + dsl.fetchOne( + "SELECT g.id AS game_row_id, g.tenant_id, g.canonical_tenant_id, " + + "g.tenant_identity_provenance_kind, c.target_namespace, c.request_digest, " + + "c.operation_id, c.creation_request_id, " + + "c.status, c.source_game_row_id, c.source_game_tenant_key, c.provenance_kind, " + + "c.evidence_digest FROM game_tenant_creation_operations c JOIN game g " + + "ON g.id = c.source_game_row_id AND g.tenant_id = c.source_game_tenant_key " + + "AND g.canonical_tenant_id = c.canonical_tenant_id " + + "WHERE c.operation_id = ? FOR UPDATE OF g", + evidence.operationId()); + Long sourceGameRowId = owner == null ? null : owner.get("source_game_row_id", Long.class); + if (owner == null + || !"COMPLETED".equals(owner.get("status", String.class)) + || !evidence.operationId().equals(owner.get("operation_id", UUID.class)) + || !evidence.targetNamespace().equals(owner.get("target_namespace", String.class)) + || !evidence.creationRequestId().equals(owner.get("creation_request_id", UUID.class)) + || !evidence.requestDigest().equals(owner.get("request_digest", String.class)) + || !evidence.canonicalTenantId().equals(owner.get("canonical_tenant_id", UUID.class)) + || sourceGameRowId == null + || evidence.sourceGameRowId() != sourceGameRowId + || !evidence.sourceGameTenantKey().equals(owner.get("source_game_tenant_key", String.class)) + || !evidence.sourceGameTenantKey().equals(owner.get("tenant_id", String.class)) + || !"NEW_GAME_ROW".equals(owner.get("provenance_kind", String.class)) + || !"NEW_GAME_ROW".equals(owner.get("tenant_identity_provenance_kind", String.class)) + || !evidence.evidenceDigest().equals(owner.get("evidence_digest", String.class))) { + throw new IllegalStateException("TEMPLATE_REFERENCE_FRESH_CREATION_EVIDENCE_UNAVAILABLE"); + } + + Record existing = + dsl.fetchOne( + "SELECT * FROM game_template_reference_phase WHERE canonical_tenant_id = ? FOR UPDATE", + evidence.canonicalTenantId()); + if (existing != null) { + PhaseSnapshot snapshot = phaseSnapshot(existing); + requireSameCreation(snapshot, evidence); + return snapshot; + } + + if (dsl.execute( + "INSERT INTO game_template_reference_phase (canonical_tenant_id, source_game_row_id, " + + "source_game_tenant_key, creation_operation_id, creation_request_id, " + + "creation_evidence_digest, phase, phase_epoch) " + + "VALUES (?, ?, ?, ?, ?, ?, 'BACKFILLING', 1)", + evidence.canonicalTenantId(), + evidence.sourceGameRowId(), + evidence.sourceGameTenantKey(), + evidence.operationId(), + evidence.creationRequestId(), + evidence.evidenceDigest()) + != 1) { + throw new IllegalStateException("TEMPLATE_REFERENCE_PHASE_GENESIS_WRITE_CONFLICT"); + } + PhaseSnapshot persisted = readPhaseForUpdate(evidence.canonicalTenantId()).orElseThrow(); + requireSameCreation(persisted, evidence); + if (persisted.phase() != Phase.BACKFILLING || persisted.phaseEpoch() != 1) { + throw new IllegalStateException("TEMPLATE_REFERENCE_PHASE_GENESIS_READBACK_CONFLICT"); + } + return persisted; + } + + /** + * Reads explicit phase state. An absent row remains absent and is never interpreted as ENFORCED. + */ + public Optional readPhase(UUID canonicalTenantId) { + requireCanonicalTenantId(canonicalTenantId); + Record row = + dsl.fetchOne( + "SELECT * FROM game_template_reference_phase WHERE canonical_tenant_id = ?", + canonicalTenantId); + return row == null ? Optional.empty() : Optional.of(phaseSnapshot(row)); + } + + public PhaseSnapshot requireEnforced(UUID canonicalTenantId) { + return readPhase(canonicalTenantId) + .filter(snapshot -> snapshot.phase() == Phase.ENFORCED) + .orElseThrow(() -> new IllegalStateException("TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED")); + } + + /** + * Validates the complete physical tenant inventory under the Game-row mutex, then performs both + * monotonic CAS transitions using the same exact inventory/source digest. This is an internal + * owner primitive, not a public or read-side repair operation. + */ + public PhaseSnapshot validateAndEnforce(UUID canonicalTenantId) { + requireWritableReadCommittedTransaction(); + requireCanonicalTenantId(canonicalTenantId); + GameOwner owner = lockGameOwner(canonicalTenantId); + PhaseSnapshot phase = + readPhaseForUpdate(canonicalTenantId) + .orElseThrow( + () -> new IllegalStateException("TEMPLATE_REFERENCE_PHASE_NOT_INITIALIZED")); + requirePhaseOwnerMatches(phase, owner); + if (phase.phase() == Phase.ENFORCED) return phase; + + InventoryEvidence evidence = readCompleteInventory(owner); + if (phase.phase() == Phase.BACKFILLING) { + if (dsl.execute( + "UPDATE game_template_reference_phase SET phase = 'VALIDATED', phase_epoch = phase_epoch + 1, " + + "inventory_digest = ?, inventory_template_count = ? " + + "WHERE canonical_tenant_id = ? AND phase = 'BACKFILLING' AND phase_epoch = ?", + evidence.digest(), + evidence.templateCount(), + canonicalTenantId, + phase.phaseEpoch()) + != 1) { + throw new IllegalStateException("TEMPLATE_REFERENCE_PHASE_CAS_CONFLICT"); + } + phase = readPhaseForUpdate(canonicalTenantId).orElseThrow(); + if (phase.phase() != Phase.VALIDATED + || !evidence.digest().equals(phase.inventoryDigest()) + || evidence.templateCount() != phase.inventoryTemplateCount()) { + throw new IllegalStateException("TEMPLATE_REFERENCE_PHASE_VALIDATION_READBACK_CONFLICT"); + } + } else if (phase.phase() == Phase.VALIDATED + && (!evidence.digest().equals(phase.inventoryDigest()) + || evidence.templateCount() != phase.inventoryTemplateCount())) { + throw new IllegalStateException("TEMPLATE_REFERENCE_PHASE_VALIDATION_EVIDENCE_STALE"); + } + + if (phase.phase() != Phase.VALIDATED + || dsl.execute( + "UPDATE game_template_reference_phase SET phase = 'ENFORCED', phase_epoch = phase_epoch + 1 " + + "WHERE canonical_tenant_id = ? AND phase = 'VALIDATED' AND phase_epoch = ? " + + "AND inventory_digest = ? AND inventory_template_count = ?", + canonicalTenantId, + phase.phaseEpoch(), + evidence.digest(), + evidence.templateCount()) + != 1) { + throw new IllegalStateException("TEMPLATE_REFERENCE_PHASE_CAS_CONFLICT"); + } + PhaseSnapshot enforced = readPhaseForUpdate(canonicalTenantId).orElseThrow(); + if (enforced.phase() != Phase.ENFORCED + || enforced.phaseEpoch() != phase.phaseEpoch() + 1 + || !evidence.digest().equals(enforced.inventoryDigest()) + || evidence.templateCount() != enforced.inventoryTemplateCount()) { + throw new IllegalStateException("TEMPLATE_REFERENCE_PHASE_ENFORCEMENT_READBACK_CONFLICT"); + } + return enforced; + } + + /** Applies one authorized source mutation to the current canonical base projection. */ + void synchronizeCurrentProjection( + TargetProof target, + DraftCommitBinding binding, + TemplateConfigSourceSnapshot snapshot, + List mutations, + Map createdRows) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(target, "target"); + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(snapshot, "snapshot"); + if (!binding.target().equals(target) || !snapshot.binding().equals(binding)) { + throw new IllegalStateException("TEMPLATE_REFERENCE_SOURCE_BINDING_CONFLICT"); + } + Map finalMutationByTemplate = + new java.util.LinkedHashMap<>(); + for (TemplateConfigSource.Mutation mutation : mutations) { + String templateId = + mutation.operation() == TemplateConfigSource.OperationKind.CREATE + ? createdRows.get(mutation.revisionId()) + : mutation.templateId(); + if (templateId == null) { + throw new IllegalStateException("TEMPLATE_REFERENCE_SOURCE_TEMPLATE_ID_UNAVAILABLE"); + } + finalMutationByTemplate.put(templateId, mutation); + } + for (var mutationEntry : finalMutationByTemplate.entrySet()) { + String templateId = mutationEntry.getKey(); + TemplateConfigSource.Mutation mutation = mutationEntry.getValue(); + TemplateConfigSource.Entry current = + snapshot.entries().stream() + .filter(entry -> entry.templateId().equals(templateId)) + .findFirst() + .orElse(null); + if (current == null) { + if (mutation.operation() != TemplateConfigSource.OperationKind.DELETE) { + throw new IllegalStateException("TEMPLATE_REFERENCE_SOURCE_ENTRY_MISSING"); + } + dsl.execute( + "DELETE FROM game_template_version_ref WHERE canonical_tenant_id = ? AND template_id = ?", + target.canonicalTenantId(), + Long.parseLong(templateId)); + continue; + } + if (mutation.operation() == TemplateConfigSource.OperationKind.DELETE + || !current.sourceBinding().equals(binding) + || !current.config().baseVersionId().equals(target.canonicalVersionId())) { + throw new IllegalStateException("TEMPLATE_REFERENCE_SOURCE_ENTRY_PROVENANCE_CONFLICT"); + } + int written = + dsl.execute( + "INSERT INTO game_template_version_ref (canonical_tenant_id, template_id, canonical_version_id, " + + "source_commit_id, source_revision_id) VALUES (?, ?, ?, ?, ?) " + + "ON CONFLICT (canonical_tenant_id, template_id) DO UPDATE SET " + + "source_commit_id = EXCLUDED.source_commit_id, " + + "source_revision_id = EXCLUDED.source_revision_id", + target.canonicalTenantId(), + Long.parseLong(templateId), + target.canonicalVersionId(), + current.sourceBinding().commitId(), + current.revisionId()); + if (written != 1) { + throw new IllegalStateException("TEMPLATE_REFERENCE_BASE_PROJECTION_WRITE_CONFLICT"); + } + Record readback = + dsl.fetchOne( + "SELECT canonical_version_id, source_commit_id, source_revision_id " + + "FROM game_template_version_ref WHERE canonical_tenant_id = ? AND template_id = ?", + target.canonicalTenantId(), + Long.parseLong(templateId)); + if (readback == null + || !target.canonicalVersionId().equals(readback.get("canonical_version_id", UUID.class)) + || !current + .sourceBinding() + .commitId() + .equals(readback.get("source_commit_id", UUID.class)) + || !current.revisionId().equals(readback.get("source_revision_id", UUID.class))) { + throw new IllegalStateException("TEMPLATE_REFERENCE_BASE_PROJECTION_READBACK_CONFLICT"); + } + } + } + + /** + * Exact current projection read for later launch-consumer integration; no fallback is provided. + */ + public Optional readExactBaseReference(UUID canonicalTenantId, long templateId) { + requireCanonicalTenantId(canonicalTenantId); + if (templateId <= 0) throw new IllegalArgumentException("Positive template row id required"); + Record row = + dsl.fetchOne( + "SELECT r.canonical_tenant_id, r.template_id, r.canonical_version_id, " + + "r.source_commit_id, r.source_revision_id, t.tenant_id " + + "FROM game_template_version_ref r JOIN game_templates t ON t.id = r.template_id " + + "JOIN game g ON g.tenant_id = t.tenant_id AND g.canonical_tenant_id = r.canonical_tenant_id " + + "WHERE r.canonical_tenant_id = ? AND r.template_id = ?", + canonicalTenantId, + templateId); + if (row == null) return Optional.empty(); + if (!canonicalTenantId.equals(row.get("canonical_tenant_id", UUID.class)) + || templateId != row.get("template_id", Long.class)) { + throw new IllegalStateException("TEMPLATE_REFERENCE_BASE_READBACK_SCOPE_CONFLICT"); + } + return Optional.of( + new BaseReference( + canonicalTenantId, + templateId, + row.get("canonical_version_id", UUID.class), + row.get("source_commit_id", UUID.class), + row.get("source_revision_id", UUID.class))); + } + + private InventoryEvidence readCompleteInventory(GameOwner owner) { + List rows = + dsl.fetch( + "SELECT t.id, t.tenant_id, t.config::TEXT AS config_json, t.default_version_id, " + + "q.canonical_tenant_id, q.canonical_version_id " + + "FROM game_templates t LEFT JOIN game_design_template_config_source_qualification q " + + "ON q.template_id = t.id LEFT JOIN LATERAL (" + + "SELECT r.operation_kind FROM game_design_template_config_source_revision r " + + "JOIN game_design_template_config_source_application a " + + "ON a.canonical_tenant_id = r.canonical_tenant_id " + + "AND a.canonical_version_id = r.canonical_version_id AND a.commit_id = r.commit_id " + + "WHERE r.canonical_tenant_id = q.canonical_tenant_id " + + "AND r.canonical_version_id = q.canonical_version_id AND r.template_id = t.id " + + "AND q.canonical_tenant_id = ? " + + "ORDER BY a.expected_epoch::NUMERIC DESC, r.revision_order DESC LIMIT 1" + + ") latest ON TRUE " + + "WHERE t.tenant_id = ? AND latest.operation_kind IS DISTINCT FROM 'DELETE' " + + "ORDER BY t.id", + owner.canonicalTenantId(), + owner.tenantKey()); + if (rows.isEmpty()) { + throw new IllegalStateException("TEMPLATE_REFERENCE_INVENTORY_EMPTY"); + } + + Map scopes = new TreeMap<>(); + Map> templatesByVersion = new HashMap<>(); + List completeTemplates = new ArrayList<>(); + for (Record row : rows) { + Long templateId = row.get("id", Long.class); + Long privateVersionId = row.get("default_version_id", Long.class); + UUID rowTenantId = row.get("canonical_tenant_id", UUID.class); + UUID canonicalVersionId = row.get("canonical_version_id", UUID.class); + if (templateId == null + || privateVersionId == null + || !owner.canonicalTenantId().equals(rowTenantId) + || canonicalVersionId == null) { + throw new IllegalStateException("TEMPLATE_REFERENCE_INVENTORY_UNQUALIFIED"); + } + VersionScope scope = scopes.get(canonicalVersionId); + if (scope == null) { + scope = findVersionScope(owner, canonicalVersionId, privateVersionId); + scopes.put(canonicalVersionId, scope); + } else if (scope.privateVersionId() != privateVersionId) { + throw new IllegalStateException("TEMPLATE_REFERENCE_INVENTORY_VERSION_CONFLICT"); + } + TemplateRow template = + new TemplateRow( + templateId, + privateVersionId, + canonicalVersionId, + row.get("config_json", String.class)); + completeTemplates.add(template); + if (templatesByVersion + .computeIfAbsent(canonicalVersionId, ignored -> new HashMap<>()) + .put(templateId, template) + != null) { + throw new IllegalStateException("TEMPLATE_REFERENCE_INVENTORY_DUPLICATE_TEMPLATE"); + } + } + + List> evidenceTemplates = new ArrayList<>(); + Set sourceEntryTemplateIds = new HashSet<>(); + TemplateConfigSourceRepository sourceRepository = new TemplateConfigSourceRepository(dsl); + for (var scopeEntry : scopes.entrySet()) { + UUID canonicalVersionId = scopeEntry.getKey(); + VersionScope scope = scopeEntry.getValue(); + Record head = + dsl.fetchOne( + "SELECT visible_commit_id FROM game_design_template_config_source_head " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + owner.canonicalTenantId(), + canonicalVersionId); + UUID visibleCommitId = head == null ? null : head.get("visible_commit_id", UUID.class); + if (visibleCommitId == null) { + throw new IllegalStateException("TEMPLATE_REFERENCE_SOURCE_SNAPSHOT_UNAVAILABLE"); + } + TemplateConfigSourceSnapshot snapshot = + sourceRepository + .readSnapshot(scope.target(), visibleCommitId) + .orElseThrow( + () -> + new IllegalStateException("TEMPLATE_REFERENCE_SOURCE_SNAPSHOT_UNAVAILABLE")); + Map versionTemplates = templatesByVersion.get(canonicalVersionId); + if (snapshot.entries().size() != versionTemplates.size()) { + throw new IllegalStateException("TEMPLATE_REFERENCE_INVENTORY_SOURCE_SET_CONFLICT"); + } + for (TemplateConfigSource.Entry entry : snapshot.entries()) { + long templateId = Long.parseLong(entry.templateId()); + TemplateRow template = versionTemplates.get(templateId); + if (template == null + || !entry.sourceBinding().target().equals(scope.target()) + || !entry.config().baseVersionId().equals(canonicalVersionId) + || !new TemplateConfigSource.Config(template.configJson()) + .canonicalJson() + .equals(entry.config().canonicalJson()) + || !sourceEntryTemplateIds.add(templateId)) { + throw new IllegalStateException("TEMPLATE_REFERENCE_INVENTORY_SOURCE_SET_CONFLICT"); + } + entry.config().requireAvailableOwnerReads(); + requireExactProjection(owner.canonicalTenantId(), template, snapshot, entry); + evidenceTemplates.add( + Map.of( + "templateId", Long.toString(templateId), + "canonicalVersionId", canonicalVersionId.toString(), + "sourceCommitId", entry.sourceBinding().commitId().toString(), + "sourceRevisionId", entry.revisionId().toString(), + "sourceSnapshotDigest", snapshot.digest(), + "configJson", entry.config().canonicalJson())); + } + } + if (sourceEntryTemplateIds.size() != completeTemplates.size()) { + throw new IllegalStateException("TEMPLATE_REFERENCE_INVENTORY_SOURCE_SET_CONFLICT"); + } + String canonicalEvidence = + CommandSource.canonical( + Map.of( + "schema", "game-design-template-reference-inventory/v1", + "canonicalTenantId", owner.canonicalTenantId().toString(), + "sourceGameRowId", Long.toString(owner.gameRowId()), + "sourceGameTenantKey", owner.tenantKey(), + "templates", evidenceTemplates)); + return new InventoryEvidence( + CommandSource.sha256(canonicalEvidence.getBytes(StandardCharsets.UTF_8)), + completeTemplates.size()); + } + + private VersionScope findVersionScope( + GameOwner owner, UUID canonicalVersionId, long expectedPrivateVersionId) { + Record version = + dsl.fetchOne( + "SELECT v.id, v.tenant_id, v.canonical_tenant_id, v.canonical_version_id, " + + "v.identity_source_game_row_id, v.identity_source_game_tenant_key, " + + "v.identity_source_provenance_kind FROM version v JOIN game g " + + "ON g.id = v.identity_source_game_row_id " + + "AND g.tenant_id = v.identity_source_game_tenant_key " + + "AND g.canonical_tenant_id = v.canonical_tenant_id " + + "AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind " + + "WHERE v.canonical_tenant_id = ? AND v.canonical_version_id = ?", + owner.canonicalTenantId(), + canonicalVersionId); + if (version == null + || expectedPrivateVersionId != version.get("id", Long.class) + || !owner.tenantKey().equals(version.get("tenant_id", String.class)) + || owner.gameRowId() != version.get("identity_source_game_row_id", Long.class) + || !owner.tenantKey().equals(version.get("identity_source_game_tenant_key", String.class)) + || !owner + .provenanceKind() + .equals(version.get("identity_source_provenance_kind", String.class))) { + throw new IllegalStateException("TEMPLATE_REFERENCE_INVENTORY_VERSION_PROVENANCE_CONFLICT"); + } + TargetProof target = + new TargetProof( + version.get("canonical_tenant_id", UUID.class), + version.get("canonical_version_id", UUID.class), + version.get("id", Long.class), + version.get("tenant_id", String.class), + version.get("identity_source_game_row_id", Long.class), + version.get("identity_source_game_tenant_key", String.class), + version.get("identity_source_provenance_kind", String.class)); + return new VersionScope(target, expectedPrivateVersionId); + } + + private void requireExactProjection( + UUID canonicalTenantId, + TemplateRow template, + TemplateConfigSourceSnapshot snapshot, + TemplateConfigSource.Entry entry) { + Record projection = + dsl.fetchOne( + "SELECT canonical_version_id, source_commit_id, source_revision_id " + + "FROM game_template_version_ref WHERE canonical_tenant_id = ? AND template_id = ?", + canonicalTenantId, + template.templateId()); + if (projection == null + || !template.canonicalVersionId().equals(projection.get("canonical_version_id", UUID.class)) + || !entry.sourceBinding().commitId().equals(projection.get("source_commit_id", UUID.class)) + || !entry.revisionId().equals(projection.get("source_revision_id", UUID.class)) + || !snapshot.binding().target().canonicalTenantId().equals(canonicalTenantId)) { + throw new IllegalStateException("TEMPLATE_REFERENCE_BASE_PROJECTION_UNAVAILABLE"); + } + } + + private GameOwner lockGameOwner(UUID canonicalTenantId) { + Record game = + dsl.fetchOne( + "SELECT id, tenant_id, canonical_tenant_id, tenant_identity_provenance_kind, " + + "tenant_identity_source_game_id, tenant_identity_source_legacy_tenant_id " + + "FROM game WHERE canonical_tenant_id = ? FOR UPDATE", + canonicalTenantId); + if (game == null + || game.get("id", Long.class) == null + || game.get("id", Long.class) <= 0 + || !canonicalTenantId.equals(game.get("canonical_tenant_id", UUID.class)) + || !game.get("id", Long.class) + .equals(game.get("tenant_identity_source_game_id", Long.class)) + || !game.get("tenant_id", String.class) + .equals(game.get("tenant_identity_source_legacy_tenant_id", String.class))) { + throw new IllegalStateException("TEMPLATE_REFERENCE_GAME_OWNER_UNAVAILABLE"); + } + return new GameOwner( + game.get("id", Long.class), + game.get("tenant_id", String.class), + canonicalTenantId, + game.get("tenant_identity_provenance_kind", String.class)); + } + + private void requirePhaseOwnerMatches(PhaseSnapshot phase, GameOwner owner) { + if (phase.sourceGameRowId() != owner.gameRowId() + || !phase.sourceGameTenantKey().equals(owner.tenantKey()) + || !"NEW_GAME_ROW".equals(owner.provenanceKind()) + || !"NEW_GAME_ROW".equals(phase.provenanceKind())) { + throw new IllegalStateException("TEMPLATE_REFERENCE_PHASE_GAME_OWNER_CONFLICT"); + } + } + + private Optional readPhaseForUpdate(UUID canonicalTenantId) { + Record row = + dsl.fetchOne( + "SELECT * FROM game_template_reference_phase WHERE canonical_tenant_id = ? FOR UPDATE", + canonicalTenantId); + return row == null ? Optional.empty() : Optional.of(phaseSnapshot(row)); + } + + private PhaseSnapshot phaseSnapshot(Record row) { + return new PhaseSnapshot( + row.get("canonical_tenant_id", UUID.class), + Phase.valueOf(row.get("phase", String.class)), + row.get("phase_epoch", Long.class), + row.get("inventory_digest", String.class), + row.get("inventory_template_count", Long.class), + row.get("creation_operation_id", UUID.class), + row.get("creation_request_id", UUID.class), + row.get("source_game_row_id", Long.class), + row.get("source_game_tenant_key", String.class), + row.get("creation_evidence_digest", String.class), + "NEW_GAME_ROW"); + } + + private void requireSameCreation(PhaseSnapshot phase, FreshTenantCreationEvidence evidence) { + if (!phase.canonicalTenantId().equals(evidence.canonicalTenantId()) + || !phase.creationOperationId().equals(evidence.operationId()) + || !phase.creationRequestId().equals(evidence.creationRequestId()) + || phase.sourceGameRowId() != evidence.sourceGameRowId() + || !phase.sourceGameTenantKey().equals(evidence.sourceGameTenantKey()) + || !phase.creationEvidenceDigest().equals(evidence.evidenceDigest())) { + throw new IllegalStateException("TEMPLATE_REFERENCE_PHASE_CREATION_READBACK_CONFLICT"); + } + } + + private void requireCanonicalTenantId(UUID canonicalTenantId) { + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + if (canonicalTenantId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Canonical tenant identity is required"); + } + } + + private static void requireWritableReadCommittedTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Template reference writes require a writable READ_COMMITTED owner transaction"); + } + } + + private static void requireWritableTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Template reference creation requires a writable Game Design owner transaction"); + } + } + + public enum Phase { + BACKFILLING, + VALIDATED, + ENFORCED + } + + public record PhaseSnapshot( + UUID canonicalTenantId, + Phase phase, + long phaseEpoch, + String inventoryDigest, + Long inventoryTemplateCount, + UUID creationOperationId, + UUID creationRequestId, + long sourceGameRowId, + String sourceGameTenantKey, + String creationEvidenceDigest, + String provenanceKind) {} + + public record BaseReference( + UUID canonicalTenantId, + long templateId, + UUID canonicalVersionId, + UUID sourceCommitId, + UUID sourceRevisionId) {} + + private record GameOwner( + long gameRowId, String tenantKey, UUID canonicalTenantId, String provenanceKind) {} + + private record VersionScope(TargetProof target, long privateVersionId) {} + + private record TemplateRow( + long templateId, long privateVersionId, UUID canonicalVersionId, String configJson) {} + + private record InventoryEvidence(String digest, long templateCount) {} +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTemplateRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTemplateRepository.java index baa68c9523..5d1f848f5a 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTemplateRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTemplateRepository.java @@ -122,18 +122,21 @@ public GameTemplate save(GameTemplate template) { .fetchOne(ID); return findByTenantIdAndId(template.getTenantId(), generatedId).orElseThrow(); } - dsl.update(TABLE_REF) - .set(TENANT_ID, template.getTenantId()) - .set(NAME, template.getName()) - .set(DESCRIPTION, template.getDescription()) - .set(CONFIG, jsonbParam(template.getConfig())) - .set(DEFAULT_VERSION_ID, template.getDefaultVersionId()) - .set(DEFAULT_SCRIPT_PATCH_VERSION, template.getDefaultScriptPatchVersion()) - .set(DEFAULT_RUNTIME_FLAGS_JSON, template.getDefaultRuntimeFlagsJson()) - .set(TEMPLATE_REFERENCE_PHASE, template.getTemplateReferencePhase().name()) - .set(CREATED_AT, Timestamp.valueOf(createdAt)) - .where(ID.eq(template.getId())) - .execute(); + int updatedRows = + dsl.update(TABLE_REF) + .set(NAME, template.getName()) + .set(DESCRIPTION, template.getDescription()) + .set(CONFIG, jsonbParam(template.getConfig())) + .set(DEFAULT_VERSION_ID, template.getDefaultVersionId()) + .set(DEFAULT_SCRIPT_PATCH_VERSION, template.getDefaultScriptPatchVersion()) + .set(DEFAULT_RUNTIME_FLAGS_JSON, template.getDefaultRuntimeFlagsJson()) + .set(TEMPLATE_REFERENCE_PHASE, template.getTemplateReferencePhase().name()) + .set(CREATED_AT, Timestamp.valueOf(createdAt)) + .where(ID.eq(template.getId()).and(TENANT_ID.eq(template.getTenantId()))) + .execute(); + if (updatedRows != 1) { + throw new IllegalArgumentException("game template not found for tenant"); + } return findByTenantIdAndId(template.getTenantId(), template.getId()).orElseThrow(); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepository.java index 06dce12e46..0e9d012343 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepository.java @@ -8,6 +8,7 @@ import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.publication.TemplateReferenceRepository; import org.jooq.DSLContext; import org.jooq.Field; import org.jooq.Record; @@ -156,7 +157,9 @@ public FreshTenantCreationEvidence createCandidate( if (completedRecord == null) { throw new IllegalStateException("Completed fresh tenant creation operation is missing"); } - return toReceipt(completedRecord); + FreshTenantCreationEvidence receipt = toReceipt(completedRecord); + new TemplateReferenceRepository(dsl).initializeFreshTenant(receipt); + return receipt; } /** Reads only a complete operation whose persisted source tuple still matches its game row. */ diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionRepository.java new file mode 100644 index 0000000000..7ec3e62e2e --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionRepository.java @@ -0,0 +1,322 @@ +package net.firedevops.firemud.gamedesign.repository; + +import java.sql.Timestamp; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreSourceBinding; +import net.firedevops.firemud.gamedesign.repository.StartSessionLaunchDescriptorRepository.Binding; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Insert-only authored actor-core proofs owned by one retained StartSession descriptor binding. */ +public final class StartSessionAuthoredActorCoreProjectionRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Table TABLE = + DSL.table(DSL.name("game_design_start_session_authored_actor_core_projection")); + private static final Field TARGET_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field CONTROL_PLANE_REQUEST_ID = + DSL.field(DSL.name("control_plane_request_id"), String.class); + private static final Field DESCRIPTOR_ROW_ID = + DSL.field(DSL.name("launch_descriptor_row_id"), Long.class); + private static final Field POLICY_ORDER = + DSL.field(DSL.name("policy_order"), Integer.class); + private static final Field BINDING_ID = DSL.field(DSL.name("binding_id"), UUID.class); + private static final Field SOURCE_BINDING_BYTES = + DSL.field(DSL.name("source_binding_bytes"), byte[].class); + private static final Field SOURCE_BINDING_DIGEST = + DSL.field(DSL.name("source_binding_digest"), String.class); + private static final Field PROJECTION_BYTES = + DSL.field(DSL.name("projection_bytes"), byte[].class); + private static final Field PROJECTION_DIGEST = + DSL.field(DSL.name("projection_digest"), String.class); + private static final Field CREATED_AT = + DSL.field(DSL.name("created_at"), Timestamp.class); + + private final DSLContext dsl; + + public StartSessionAuthoredActorCoreProjectionRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + /** + * Allocates each Game Design binding identity only for a new owner row, inside its transaction. + * The caller must first complete its exact retained-owner retry check. + */ + public List insertForNewOwner( + Binding owner, List sourceBindings) { + requireTransaction(); + requireOwner(owner); + List sources = + List.copyOf(Objects.requireNonNull(sourceBindings, "sourceBindings")); + if (!findByOwner(owner).isEmpty()) { + throw new RetainedProjectionConflictException( + "Authored actor-core projection rows already exist for a new descriptor owner"); + } + + for (int index = 0; index < sources.size(); index++) { + AuthoredInitialActorCoreSourceBinding source = + requireSourceMatchesOwner(owner, sources.get(index)); + UUID bindingId = UUID.randomUUID(); + AuthoredInitialActorCoreProjection projection = + AuthoredInitialActorCoreProjection.fromValidatedBinding(bindingId, source); + byte[] sourceBytes = source.canonicalBytes(); + String sourceDigest = source.digest(); + byte[] projectionBytes = projection.canonicalBytes(); + + int inserted = + dsl.insertInto(TABLE) + .set(TARGET_NAMESPACE, owner.targetNamespace()) + .set(CANONICAL_TENANT_ID, owner.canonicalTenantId()) + .set(CONTROL_PLANE_REQUEST_ID, owner.controlPlaneRequestId()) + .set(DESCRIPTOR_ROW_ID, owner.descriptorRowId()) + .set(POLICY_ORDER, index) + .set(BINDING_ID, bindingId) + .set(SOURCE_BINDING_BYTES, sourceBytes) + .set(SOURCE_BINDING_DIGEST, sourceDigest) + .set(PROJECTION_BYTES, projectionBytes) + .set(PROJECTION_DIGEST, projection.digest()) + .onConflictDoNothing() + .execute(); + if (inserted != 1) { + throw new RetainedProjectionConflictException( + "Authored actor-core projection identity conflicted during new owner insertion"); + } + } + + return validateReplay(findByOwner(owner), sources, owner); + } + + /** Replays only a complete exact retained proof set; this method never repairs missing rows. */ + public List replayExact( + Binding owner, List sourceBindings) { + requireOwner(owner); + return validateReplay( + findByOwner(owner), + List.copyOf(Objects.requireNonNull(sourceBindings, "sourceBindings")), + owner); + } + + public List findByOwner(Binding owner) { + requireOwner(owner); + return List.copyOf( + dsl.selectFrom(TABLE) + .where( + TARGET_NAMESPACE + .eq(owner.targetNamespace()) + .and(CANONICAL_TENANT_ID.eq(owner.canonicalTenantId())) + .and(CONTROL_PLANE_REQUEST_ID.eq(owner.controlPlaneRequestId())) + .and(DESCRIPTOR_ROW_ID.eq(owner.descriptorRowId()))) + .orderBy(POLICY_ORDER.asc()) + .fetch(this::toRetainedProjection)); + } + + static List validateReplay( + List retained, + List sourceBindings, + Binding owner) { + Objects.requireNonNull(retained, "retained"); + List sources = + List.copyOf(Objects.requireNonNull(sourceBindings, "sourceBindings")); + requireOwner(owner); + if (sources.isEmpty()) { + if (!retained.isEmpty()) { + throw new RetainedProjectionConflictException( + "Retained authored actor-core proofs differ from the exact source policy set"); + } + return List.of(); + } + if (retained.isEmpty()) { + throw new MissingRetainedProjectionException( + "Retained descriptor has no authored actor-core proof for its applicable policies"); + } + if (retained.size() != sources.size()) { + throw new RetainedProjectionConflictException( + "Retained authored actor-core proof count differs from the exact source policy set"); + } + + Set bindingIds = new HashSet<>(); + List result = new ArrayList<>(sources.size()); + for (int index = 0; index < sources.size(); index++) { + RetainedProjection row = retained.get(index); + AuthoredInitialActorCoreSourceBinding source = + requireSourceMatchesOwner(owner, sources.get(index)); + if (row.policyOrder() != index + || !owner.targetNamespace().equals(row.targetNamespace()) + || !owner.canonicalTenantId().equals(row.canonicalTenantId()) + || !owner.controlPlaneRequestId().equals(row.controlPlaneRequestId()) + || !owner.descriptorRowId().equals(row.descriptorRowId()) + || !bindingIds.add(row.bindingId())) { + throw new RetainedProjectionConflictException( + "Retained authored actor-core proof owner identity or order changed"); + } + + AuthoredInitialActorCoreSourceBinding storedSource; + AuthoredInitialActorCoreProjection projection; + try { + storedSource = + AuthoredInitialActorCoreSourceBinding.fromStored( + row.sourceBindingBytes(), row.sourceBindingDigest()); + projection = + AuthoredInitialActorCoreProjection.fromStored( + row.projectionBytes(), row.projectionDigest()); + } catch (IllegalArgumentException | IllegalStateException corrupt) { + throw new RetainedProjectionConflictException( + "Retained authored actor-core proof bytes or digests are corrupt", corrupt); + } + if (!Arrays.equals(storedSource.canonicalBytes(), source.canonicalBytes()) + || !storedSource.digest().equals(source.digest()) + || !projection.bindingId().equals(row.bindingId()) + || !projection.bindingDigest().equals(source.digest())) { + throw new RetainedProjectionConflictException( + "Retained authored actor-core private source proof differs from the exact source"); + } + + AuthoredInitialActorCoreProjection expected = + AuthoredInitialActorCoreProjection.fromValidatedBinding(row.bindingId(), source); + if (!Arrays.equals(expected.canonicalBytes(), row.projectionBytes()) + || !expected.digest().equals(row.projectionDigest()) + || !Arrays.equals(projection.canonicalBytes(), expected.canonicalBytes())) { + throw new RetainedProjectionConflictException( + "Retained authored actor-core projection differs from the exact private source"); + } + result.add(projection); + } + return List.copyOf(result); + } + + private RetainedProjection toRetainedProjection(Record row) { + Timestamp createdAt = row.get(CREATED_AT, Timestamp.class); + return new RetainedProjection( + row.get(TARGET_NAMESPACE), + row.get(CANONICAL_TENANT_ID), + row.get(CONTROL_PLANE_REQUEST_ID), + row.get(DESCRIPTOR_ROW_ID), + row.get(POLICY_ORDER), + row.get(BINDING_ID), + row.get(SOURCE_BINDING_BYTES), + row.get(SOURCE_BINDING_DIGEST), + row.get(PROJECTION_BYTES), + row.get(PROJECTION_DIGEST), + createdAt == null ? null : createdAt.toLocalDateTime()); + } + + private static AuthoredInitialActorCoreSourceBinding requireSourceMatchesOwner( + Binding owner, AuthoredInitialActorCoreSourceBinding source) { + Objects.requireNonNull(source, "source binding"); + AuthoredInitialActorCoreSourceBinding decoded; + try { + decoded = + AuthoredInitialActorCoreSourceBinding.fromStored( + source.canonicalBytes(), source.digest()); + } catch (IllegalArgumentException | IllegalStateException corrupt) { + throw new RetainedProjectionConflictException( + "Authored actor-core source binding failed complete canonical reconstruction", corrupt); + } + var selected = decoded.selectedCommit(); + if (!Objects.equals(owner.canonicalTenantId(), selected.target().canonicalTenantId()) + || !Objects.equals(owner.canonicalVersionId(), selected.target().canonicalVersionId()) + || !Objects.equals(owner.selectedCommitId(), selected.commitId()) + || !Objects.equals(owner.sourceOperationId(), decoded.worldSourceOperationId()) + || !Objects.equals(owner.sourceEvidenceDigest(), decoded.worldSourceEvidenceDigest()) + || !Objects.equals(owner.worldSlug(), decoded.expectedWorldSlug()) + || !Objects.equals(owner.publishWorkflowId(), decoded.publicationWorkflowId()) + || owner.releaseBundleId() == null + || owner.releaseBundleId() <= 0L + || !Arrays.equals(decoded.canonicalBytes(), source.canonicalBytes()) + || !decoded.digest().equals(source.digest())) { + throw new RetainedProjectionConflictException( + "Authored actor-core source binding differs from the exact descriptor owner identity"); + } + return decoded; + } + + private static void requireOwner(Binding owner) { + Objects.requireNonNull(owner, "owner binding"); + if (owner.targetNamespace() == null + || owner.targetNamespace().isBlank() + || owner.canonicalTenantId() == null + || owner.controlPlaneRequestId() == null + || owner.controlPlaneRequestId().isBlank() + || owner.descriptorRowId() == null + || owner.descriptorRowId() <= 0L + || owner.releaseBundleId() == null + || owner.releaseBundleId() <= 0L) { + throw new IllegalArgumentException("Exact retained descriptor owner binding required"); + } + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Authored actor-core identity allocation requires the descriptor owner transaction"); + } + } + + /** Complete immutable source and projection proof keyed to the actual descriptor owner row. */ + public record RetainedProjection( + String targetNamespace, + UUID canonicalTenantId, + String controlPlaneRequestId, + Long descriptorRowId, + Integer policyOrder, + UUID bindingId, + byte[] sourceBindingBytes, + String sourceBindingDigest, + byte[] projectionBytes, + String projectionDigest, + LocalDateTime createdAt) { + public RetainedProjection { + sourceBindingBytes = cloneBytes(sourceBindingBytes); + projectionBytes = cloneBytes(projectionBytes); + } + + @Override + public byte[] sourceBindingBytes() { + return cloneBytes(sourceBindingBytes); + } + + @Override + public byte[] projectionBytes() { + return cloneBytes(projectionBytes); + } + + private static byte[] cloneBytes(byte[] value) { + return value == null ? null : value.clone(); + } + } + + public static class RetainedProjectionConflictException extends IllegalStateException { + private static final long serialVersionUID = 1L; + + public RetainedProjectionConflictException(String message) { + super(message); + } + + public RetainedProjectionConflictException(String message, Throwable cause) { + super(message, cause); + } + } + + public static final class MissingRetainedProjectionException + extends RetainedProjectionConflictException { + private static final long serialVersionUID = 1L; + + public MissingRetainedProjectionException(String message) { + super(message); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/StartSessionLaunchDescriptorRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/StartSessionLaunchDescriptorRepository.java new file mode 100644 index 0000000000..a5495578ae --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/StartSessionLaunchDescriptorRepository.java @@ -0,0 +1,201 @@ +package net.firedevops.firemud.gamedesign.repository; + +import java.sql.Timestamp; +import java.time.LocalDateTime; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; + +/** Immutable binding from an owner-produced descriptor to its original StartSession evidence. */ +public final class StartSessionLaunchDescriptorRepository { + private static final Table TABLE = + DSL.table(DSL.name("game_design_start_session_launch_descriptor_binding")); + private static final Field TARGET_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field CONTROL_PLANE_REQUEST_ID = + DSL.field(DSL.name("control_plane_request_id"), String.class); + private static final Field DESCRIPTOR_ROW_ID = + DSL.field(DSL.name("launch_descriptor_row_id"), Long.class); + private static final Field RELEASE_BUNDLE_ID = + DSL.field(DSL.name("release_bundle_id"), Long.class); + private static final Field VERSION_STATE_EPOCH = + DSL.field(DSL.name("version_state_epoch"), Long.class); + private static final Field CANONICAL_TUPLE = + DSL.field(DSL.name("canonical_post_authorization_tuple"), byte[].class); + private static final Field OWNER_ATTEMPT_ID = + DSL.field(DSL.name("owner_attempt_id"), UUID.class); + private static final Field OWNER_FENCE = DSL.field(DSL.name("owner_fence"), Long.class); + private static final Field GAME_TEMPLATE_ID = + DSL.field(DSL.name("game_template_id"), Long.class); + private static final Field CANONICAL_VERSION_ID = + DSL.field(DSL.name("canonical_version_id"), UUID.class); + private static final Field SELECTED_COMMIT_ID = + DSL.field(DSL.name("selected_commit_id"), UUID.class); + private static final Field PUBLISH_WORKFLOW_ID = + DSL.field(DSL.name("publish_workflow_id"), String.class); + private static final Field PUBLICATION_SELECTION_DIGEST = + DSL.field(DSL.name("publication_selection_digest"), String.class); + private static final Field ASSOCIATION_DIGEST = + DSL.field(DSL.name("association_digest"), String.class); + private static final Field SOURCE_OPERATION_ID = + DSL.field(DSL.name("source_operation_id"), UUID.class); + private static final Field SOURCE_EVIDENCE_DIGEST = + DSL.field(DSL.name("source_evidence_digest"), String.class); + private static final Field WORLD_SLUG = DSL.field(DSL.name("world_slug"), String.class); + private static final Field REFERENCE_PHASE_EPOCH = + DSL.field(DSL.name("reference_phase_epoch"), Long.class); + private static final Field RUNTIME_SURFACE = + DSL.field(DSL.name("runtime_surface"), String.class); + private static final Field GAME_LOGIC_PUBLISH_REQUEST_ID = + DSL.field(DSL.name("game_logic_publish_request_id"), String.class); + private static final Field GAME_LOGIC_SELECTION_DIGEST = + DSL.field(DSL.name("game_logic_selection_digest"), String.class); + private static final Field GAME_LOGIC_AUTHORIZATION_DIGEST = + DSL.field(DSL.name("game_logic_authorization_digest"), String.class); + private static final Field GAME_LOGIC_RECEIPT_DIGEST = + DSL.field(DSL.name("game_logic_receipt_digest"), String.class); + private static final Field ASSOCIATION_READ_RESPONSE = + DSL.field(DSL.name("association_read_response_bytes"), byte[].class); + private static final Field CREATED_AT = + DSL.field(DSL.name("created_at"), Timestamp.class); + + private final DSLContext dsl; + + public StartSessionLaunchDescriptorRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + public Optional find(String targetNamespace, UUID canonicalTenantId, String requestId) { + return Optional.ofNullable( + dsl.selectFrom(TABLE) + .where( + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(CONTROL_PLANE_REQUEST_ID.eq(requestId))) + .fetchOne(this::toBinding)); + } + + /** Insert-only; the caller must compare the complete readback before returning it. */ + public Binding insertImmutable(Binding binding) { + Objects.requireNonNull(binding, "binding"); + dsl.insertInto(TABLE) + .set(TARGET_NAMESPACE, binding.targetNamespace()) + .set(CANONICAL_TENANT_ID, binding.canonicalTenantId()) + .set(CONTROL_PLANE_REQUEST_ID, binding.controlPlaneRequestId()) + .set(DESCRIPTOR_ROW_ID, binding.descriptorRowId()) + .set(RELEASE_BUNDLE_ID, binding.releaseBundleId()) + .set(VERSION_STATE_EPOCH, binding.versionStateEpoch()) + .set(CANONICAL_TUPLE, binding.canonicalPostAuthorizationTuple()) + .set(OWNER_ATTEMPT_ID, binding.ownerAttemptId()) + .set(OWNER_FENCE, binding.ownerFence()) + .set(GAME_TEMPLATE_ID, binding.gameTemplateId()) + .set(CANONICAL_VERSION_ID, binding.canonicalVersionId()) + .set(SELECTED_COMMIT_ID, binding.selectedCommitId()) + .set(PUBLISH_WORKFLOW_ID, binding.publishWorkflowId()) + .set(PUBLICATION_SELECTION_DIGEST, binding.publicationSelectionDigest()) + .set(ASSOCIATION_DIGEST, binding.associationDigest()) + .set(SOURCE_OPERATION_ID, binding.sourceOperationId()) + .set(SOURCE_EVIDENCE_DIGEST, binding.sourceEvidenceDigest()) + .set(WORLD_SLUG, binding.worldSlug()) + .set(REFERENCE_PHASE_EPOCH, binding.referencePhaseEpoch()) + .set(RUNTIME_SURFACE, binding.runtimeSurface()) + .set(GAME_LOGIC_PUBLISH_REQUEST_ID, binding.gameLogicPublishRequestId()) + .set(GAME_LOGIC_SELECTION_DIGEST, binding.gameLogicSelectionDigest()) + .set(GAME_LOGIC_AUTHORIZATION_DIGEST, binding.gameLogicAuthorizationDigest()) + .set(GAME_LOGIC_RECEIPT_DIGEST, binding.gameLogicReceiptDigest()) + .set(ASSOCIATION_READ_RESPONSE, binding.associationReadResponseBytes()) + .set(CREATED_AT, Timestamp.valueOf(binding.createdAt())) + .onConflictDoNothing() + .execute(); + return find( + binding.targetNamespace(), binding.canonicalTenantId(), binding.controlPlaneRequestId()) + .orElseThrow( + () -> new IllegalStateException("START_SESSION_DESCRIPTOR_BINDING_READBACK_MISSING")); + } + + private Binding toBinding(Record row) { + Timestamp createdAt = row.get(CREATED_AT, Timestamp.class); + return new Binding( + row.get(TARGET_NAMESPACE), + row.get(CANONICAL_TENANT_ID), + row.get(CONTROL_PLANE_REQUEST_ID), + row.get(DESCRIPTOR_ROW_ID), + row.get(RELEASE_BUNDLE_ID), + row.get(VERSION_STATE_EPOCH), + row.get(CANONICAL_TUPLE), + row.get(OWNER_ATTEMPT_ID), + row.get(OWNER_FENCE), + row.get(GAME_TEMPLATE_ID), + row.get(CANONICAL_VERSION_ID), + row.get(SELECTED_COMMIT_ID), + row.get(PUBLISH_WORKFLOW_ID), + row.get(PUBLICATION_SELECTION_DIGEST), + row.get(ASSOCIATION_DIGEST), + row.get(SOURCE_OPERATION_ID), + row.get(SOURCE_EVIDENCE_DIGEST), + row.get(WORLD_SLUG), + row.get(REFERENCE_PHASE_EPOCH), + row.get(RUNTIME_SURFACE), + row.get(GAME_LOGIC_PUBLISH_REQUEST_ID), + row.get(GAME_LOGIC_SELECTION_DIGEST), + row.get(GAME_LOGIC_AUTHORIZATION_DIGEST), + row.get(GAME_LOGIC_RECEIPT_DIGEST), + row.get(ASSOCIATION_READ_RESPONSE), + createdAt == null ? null : createdAt.toLocalDateTime()); + } + + public record Binding( + String targetNamespace, + UUID canonicalTenantId, + String controlPlaneRequestId, + Long descriptorRowId, + Long releaseBundleId, + Long versionStateEpoch, + byte[] canonicalPostAuthorizationTuple, + UUID ownerAttemptId, + Long ownerFence, + Long gameTemplateId, + UUID canonicalVersionId, + UUID selectedCommitId, + String publishWorkflowId, + String publicationSelectionDigest, + String associationDigest, + UUID sourceOperationId, + String sourceEvidenceDigest, + String worldSlug, + Long referencePhaseEpoch, + String runtimeSurface, + String gameLogicPublishRequestId, + String gameLogicSelectionDigest, + String gameLogicAuthorizationDigest, + String gameLogicReceiptDigest, + byte[] associationReadResponseBytes, + LocalDateTime createdAt) { + public Binding { + canonicalPostAuthorizationTuple = cloneBytes(canonicalPostAuthorizationTuple); + associationReadResponseBytes = cloneBytes(associationReadResponseBytes); + } + + @Override + public byte[] canonicalPostAuthorizationTuple() { + return cloneBytes(canonicalPostAuthorizationTuple); + } + + @Override + public byte[] associationReadResponseBytes() { + return cloneBytes(associationReadResponseBytes); + } + + private static byte[] cloneBytes(byte[] value) { + return value == null ? null : value.clone(); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameTemplateServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameTemplateServiceImpl.java index 04054e31c1..9214fca496 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameTemplateServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameTemplateServiceImpl.java @@ -27,6 +27,10 @@ public class GameTemplateServiceImpl implements GameTemplateService { @Transactional @Timed(value = "gamedesign.template.create") public GameTemplateDto createTemplate(GameTemplateDto dto) { + if (dto.id() != null) { + throw new IllegalArgumentException( + "INVALID_ARGUMENT: template id must not be supplied on create"); + } logger.info("Creating game template {}", dto.name()); GameTemplate entity = mapper.toEntity(dto); if (entity.getDefaultRuntimeFlagsJson() == null diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java index 7dac9d7d3b..a5d2f5812e 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java @@ -46,6 +46,10 @@ public RevisionDto saveRevision(RevisionDto dto) { dto.tenantId(), dto.versionId(), dto.revisionKind()); + if ("GAMEPLAY_RULE".equals(dto.revisionKind())) { + throw new IllegalArgumentException( + "INVALID_ARGUMENT: GAMEPLAY_RULE requires authorized coordinated source authoring"); + } Game game = Optional.ofNullable(gameRepository.findByTenantId(dto.tenantId())) .orElseThrow(() -> new IllegalArgumentException("game not found")); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java index c6c8417c94..f2149b0038 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java @@ -43,6 +43,7 @@ import net.firedevops.firemud.gamedesign.publication.GameplayRuleSourceRepository; import net.firedevops.firemud.gamedesign.publication.RealmPolicySource; import net.firedevops.firemud.gamedesign.publication.RealmPolicySourceRepository; +import net.firedevops.firemud.gamedesign.publication.TemplateConfigSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; @@ -1052,6 +1053,7 @@ void terminalV2CaptureWithMissingAssetAndGameplayIsIncomplete() { () -> { new CommandSourceRepository(fixture.dsl()).freeze(operation); new RealmPolicySourceRepository(fixture.dsl()).freeze(operation); + new TemplateConfigSourceRepository(fixture.dsl()).freeze(operation); var attempts = new PublishAttemptRepository(fixture.dsl()); var attempt = attempts.findByPublishWorkflowIdForUpdate(operation.workflowId()).orElseThrow(); @@ -1073,6 +1075,66 @@ void terminalV2CaptureWithMissingAssetAndGameplayIsIncomplete() { .hasMessage("GAME_DESIGN_SOURCE_CAPTURE_INCOMPLETE"); } + @Test + void terminalV2RetainsMissingTemplateCaptureButPendingV2RequiresIt() { + Fixture fixture = fixture(); + var authored = + binding( + fixture.target(), + "genesis:" + + fixture + .sources() + .readGenesis(fixture.target()) + .orElseThrow() + .policy() + .receiptId(), + "0", + null, + "main", + true); + synchronize(fixture, authored, apply(fixture, authored)); + var operation = retainSelectedOperation(fixture); + + fixture.tx( + () -> { + new CommandSourceRepository(fixture.dsl()).freeze(operation); + new RealmPolicySourceRepository(fixture.dsl()).freeze(operation); + new net.firedevops.firemud.gamedesign.publication.AssetSourceRepository(fixture.dsl()) + .freeze(operation); + new GameplayRuleSourceRepository(fixture.dsl()).freeze(operation); + return null; + }); + + assertThatThrownBy(() -> fixture.sources().readCapture(operation)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("GAME_DESIGN_SOURCE_CAPTURE_INCOMPLETE"); + + fixture.tx( + () -> { + var attempts = new PublishAttemptRepository(fixture.dsl()); + var attempt = + attempts.findByPublishWorkflowIdForUpdate(operation.workflowId()).orElseThrow(); + attempt.setStatus(PublishAttemptStatus.FAILED); + attempt.setFailureCode("ISOLATED_TERMINAL_CAPTURE_WITHOUT_TEMPLATE"); + attempts.save(attempt); + new GameDesignPublicationOperationRepository(fixture.dsl()) + .seal( + operation.tenantKey(), + operation.workflowId(), + operation.versionId(), + operation.selectionDigest(), + false); + return null; + }); + + var retained = fixture.sources().readCapture(operation).orElseThrow(); + assertThat(retained.command()).isNotNull(); + assertThat(retained.policy()).isNotNull(); + assertThat(retained.asset()).isPresent(); + assertThat(retained.gameplay()).isPresent(); + assertThat(retained.templateConfig()).isEmpty(); + } + @Test void preGameplayTerminalCaptureStaysUnknownAndCannotBeExtendedAfterV1032() throws Exception { Fixture fixture = fixture(false, "1031"); @@ -1112,6 +1174,7 @@ void preGameplayTerminalCaptureStaysUnknownAndCannotBeExtendedAfterV1032() throw new RealmPolicySourceRepository(fixture.dsl()).freeze(operation); new net.firedevops.firemud.gamedesign.publication.AssetSourceRepository(fixture.dsl()) .freeze(operation); + new TemplateConfigSourceRepository(fixture.dsl()).freeze(operation); var attempts = new PublishAttemptRepository(fixture.dsl()); var attempt = attempts.findByPublishWorkflowIdForUpdate(operation.workflowId()).orElseThrow(); @@ -1142,6 +1205,8 @@ void preGameplayTerminalCaptureStaysUnknownAndCannotBeExtendedAfterV1032() throw var commandBefore = retainedCapture(fixture, "game_design_command_source_capture"); var policyBefore = retainedCapture(fixture, "game_design_realm_policy_capture"); var assetBefore = retainedCapture(fixture, "game_design_asset_source_capture"); + var templateConfigBefore = + retainedCapture(fixture, "game_design_template_config_source_capture"); var migrationDataSource = new DriverManagerDataSource( @@ -1176,6 +1241,8 @@ void preGameplayTerminalCaptureStaysUnknownAndCannotBeExtendedAfterV1032() throw assertCaptureRetained(fixture, "game_design_command_source_capture", commandBefore); assertCaptureRetained(fixture, "game_design_realm_policy_capture", policyBefore); assertCaptureRetained(fixture, "game_design_asset_source_capture", assetBefore); + assertCaptureRetained( + fixture, "game_design_template_config_source_capture", templateConfigBefore); var historical = fixture.sources().readCapture(operation).orElseThrow(); assertThat(historical.gameplay()).isEmpty(); @@ -1192,6 +1259,8 @@ void preGameplayTerminalCaptureStaysUnknownAndCannotBeExtendedAfterV1032() throw assertCaptureRetained(fixture, "game_design_command_source_capture", commandBefore); assertCaptureRetained(fixture, "game_design_realm_policy_capture", policyBefore); assertCaptureRetained(fixture, "game_design_asset_source_capture", assetBefore); + assertCaptureRetained( + fixture, "game_design_template_config_source_capture", templateConfigBefore); } private static void assertInvalidGameplayCaptureInsert( diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java new file mode 100644 index 0000000000..b7443ebae6 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java @@ -0,0 +1,1583 @@ +package net.firedevops.firemud.gamedesign.draft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.authoring.DraftBaseReference; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import net.firedevops.firemud.gamedesign.publication.GameplayRuleSourceRepository; +import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; +import net.firedevops.firemud.gamedesign.publication.RealmPolicySource; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationOwner; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftTemplateWorldSourceAssociation; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftTemplateWorldSourceAssociationRepository; +import net.firedevops.firemud.gamedesign.publication.TemplateConfigSource; +import net.firedevops.firemud.gamedesign.publication.TemplateConfigSourceRepository; +import net.firedevops.firemud.gamedesign.publication.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +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.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Local coordinator/storage definitions; upstream Account authority and GL intake are not mocked + * proof. + */ +@Testcontainers(disabledWithoutDocker = true) +class TemplateConfigSourcePostgresIntegrationTest { + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void authoredAutomationInventoryHasExactRetryInheritanceAndFrozenOriginalProvenance() { + var f = fixture(); + var inventory = AutomationAuthoredSourceInventoryDeclaration.parse(automationInventory()); + var declaration = + binding( + f, + TemplateConfigSource.ownerInventoryPayload( + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, inventory), + TemplateConfigSource.SCOPE, + "0"); + apply(f, declaration); + + var first = source(f, declaration); + assertThat(first.sourceEpoch()).isEqualTo("1"); + assertThat(first.entries()).isEmpty(); + assertThat(first.ownerSourceInventoryDeclarations()).hasSize(1); + assertThat(first.ownerSourceInventoryDeclarations().getFirst().sourceBinding()) + .isEqualTo(declaration); + assertThat(first.ownerSourceInventoryDeclarations().getFirst().revisionOrder()).isEqualTo("0"); + assertThat(first.ownerSourceInventoryDeclarations().getFirst().revisionId()) + .isEqualTo(declaration.revisions().getFirst().revisionId()); + assertThat(f.dsl.fetchSingle("SELECT count(*) FROM game_templates").get(0, Long.class)) + .isZero(); + assertThat( + f.dsl + .fetchSingle( + "SELECT count(*) FROM game_design_template_config_owner_source_inventory_declaration") + .get(0, Long.class)) + .isEqualTo(1L); + + f.tx.executeWithoutResult( + ignored -> + assertThat(new TemplateConfigSourceRepository(f.dsl).apply(declaration).orElseThrow()) + .isEqualTo(new TemplateConfigSourceSnapshot.Application(declaration, "0", first))); + assertThat(f.dsl.fetchSingle("SELECT count(*) FROM game_templates").get(0, Long.class)) + .isZero(); + + var unrelated = + binding( + f, + GameplayRuleSource.upsertPayload(new GameplayRuleManifest.AdmissionTag("unrelated")), + GameplayRuleSource.SCOPE, + "0"); + apply(f, unrelated); + var inherited = source(f, unrelated); + assertThat(inherited.sourceEpoch()).isEqualTo("1"); + assertThat(inherited.ownerSourceInventoryDeclarations()) + .containsExactly(first.ownerSourceInventoryDeclarations().getFirst()); + assertThat(inherited.ownerSourceInventoryDeclarations().getFirst().sourceBinding()) + .isEqualTo(declaration); + + var actualTemplate = + binding( + f, + TemplateConfigSource.createPayload("Starter", config(f, "[]")), + TemplateConfigSource.SCOPE, + "1"); + apply(f, actualTemplate); + assertThat(source(f, actualTemplate).entries()).hasSize(1); + assertThat(source(f, actualTemplate).ownerSourceInventoryDeclarations()) + .containsExactly(first.ownerSourceInventoryDeclarations().getFirst()); + assertThat(f.dsl.fetchSingle("SELECT count(*) FROM game_templates").get(0, Long.class)) + .isEqualTo(1L); + + var operation = + f.tx.execute( + ignored -> { + try { + return IsolatedPublicationOwnerSetup.retainSourceBacked( + f.dsl, + f.target, + 1L, + "Automation inventory declaration source freeze", + actualTemplate.commitId().toString()); + } catch (Exception e) { + throw new IllegalStateException("Unable to retain source-backed publication", e); + } + }); + var capture = + Objects.requireNonNull( + f.tx.execute( + ignored -> new TemplateConfigSourceRepository(f.dsl).freeze(operation))) + .snapshot(); + assertThat(capture.ownerSourceInventoryDeclarations()) + .containsExactly(first.ownerSourceInventoryDeclarations().getFirst()); + assertThat(capture.ownerSourceInventoryDeclarations().getFirst().sourceBinding()) + .isEqualTo(declaration); + assertThat(capture.binding()) + .isEqualTo(operation.account().input().selection().selectedCommit()); + assertThat(capture.entries().getFirst().sourceBinding()).isEqualTo(actualTemplate); + } + + @Test + void latestSameOrderAutomationDeclarationRetainsItsExactBindingAcrossRetryAndInheritance() { + var f = fixture(); + var inventory = AutomationAuthoredSourceInventoryDeclaration.parse(automationInventory()); + String identicalContent = + TemplateConfigSource.ownerInventoryPayload( + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, inventory); + var first = binding(f, identicalContent, TemplateConfigSource.SCOPE, "0"); + apply(f, first); + var firstSnapshot = source(f, first); + assertThat(firstSnapshot.ownerSourceInventoryDeclarations().getFirst().sourceBinding()) + .isEqualTo(first); + assertThat(firstSnapshot.ownerSourceInventoryDeclarations().getFirst().revisionOrder()) + .isEqualTo("0"); + + var second = binding(f, identicalContent, TemplateConfigSource.SCOPE, "1"); + assertThat(second.revisions().getFirst().revisionOrder()).isEqualTo("0"); + assertThat(second.revisions().getFirst().payload()).isEqualTo(identicalContent); + apply(f, second); + var secondSnapshot = source(f, second); + var latest = secondSnapshot.ownerSourceInventoryDeclarations().getFirst(); + assertThat(secondSnapshot.sourceEpoch()).isEqualTo("2"); + assertThat(secondSnapshot.ownerSourceInventoryDeclarations()).hasSize(1); + assertThat(latest.sourceBinding()).isEqualTo(second); + assertThat(latest.revisionOrder()).isEqualTo("0"); + assertThat(latest.revisionId()).isEqualTo(second.revisions().getFirst().revisionId()); + assertThat(latest.inventory()).isEqualTo(inventory); + + f.tx.executeWithoutResult( + ignored -> + assertThat(new TemplateConfigSourceRepository(f.dsl).apply(second).orElseThrow()) + .isEqualTo( + new TemplateConfigSourceSnapshot.Application(second, "1", secondSnapshot))); + var unrelated = + binding( + f, + GameplayRuleSource.upsertPayload(new GameplayRuleManifest.AdmissionTag("unrelated")), + GameplayRuleSource.SCOPE, + "0"); + apply(f, unrelated); + var inherited = source(f, unrelated); + assertThat(inherited.sourceEpoch()).isEqualTo("2"); + assertThat(inherited.ownerSourceInventoryDeclarations()).containsExactly(latest); + assertThat(inherited.ownerSourceInventoryDeclarations().getFirst().sourceBinding()) + .isEqualTo(second); + assertThat( + f.dsl + .fetchSingle( + "SELECT count(*) FROM game_design_template_config_owner_source_inventory_declaration") + .get(0, Long.class)) + .isEqualTo(2L); + assertThat(f.dsl.fetchSingle("SELECT count(*) FROM game_templates").get(0, Long.class)) + .isZero(); + } + + @Test + void v1025RetainsV1AndV2SourceHistoryAcrossLatestUpgradeAndExactBindingRetry() { + var f = fixture("1025"); + var initialTemplate = + binding( + f, + TemplateConfigSource.createPayload("Starter", config(f, "[]")), + TemplateConfigSource.SCOPE, + "0"); + apply(f, initialTemplate); + String v1SnapshotJson = + f.dsl + .fetchSingle( + "SELECT snapshot_json FROM game_design_template_config_source_snapshot " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + initialTemplate.commitId()) + .get("snapshot_json", String.class); + String v1SnapshotDigest = + f.dsl + .fetchSingle( + "SELECT snapshot_digest FROM game_design_template_config_source_snapshot " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + initialTemplate.commitId()) + .get("snapshot_digest", String.class); + var originalV1Snapshot = + new TemplateConfigSourceRepository(f.dsl) + .readSnapshot(f.target, initialTemplate.commitId()) + .orElseThrow(); + assertThat(originalV1Snapshot.canonicalJson()).isEqualTo(v1SnapshotJson); + assertThat(originalV1Snapshot.digest()).isEqualTo(v1SnapshotDigest); + String originalV1SnapshotXmin = + f.dsl + .fetchSingle( + "SELECT xmin::text AS row_xmin FROM game_design_template_config_source_snapshot " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + initialTemplate.commitId()) + .get("row_xmin", String.class); + + var automationInventory = + AutomationAuthoredSourceInventoryDeclaration.parse(automationInventory()); + String automationPayload = + TemplateConfigSource.ownerInventoryPayload( + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, automationInventory); + var automation = binding(f, automationPayload, TemplateConfigSource.SCOPE, "1"); + apply(f, automation); + var automationSource = source(f, automation); + assertThat(automationSource.ownerSourceInventoryDeclarations()).hasSize(1); + assertThat(automationSource.ownerSourceInventoryDeclarations().getFirst().sourceBinding()) + .isEqualTo(automation); + + var retainedDeclaration = + f.dsl.fetchSingle( + "SELECT request_id, commit_id, revision_order, owner, inventory_json, payload_json, " + + "xmin::text AS row_xmin FROM game_design_template_config_owner_source_inventory_declaration " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND revision_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + automation.revisions().getFirst().revisionId()); + String originalInventoryJson = retainedDeclaration.get("inventory_json", String.class); + String originalPayloadJson = retainedDeclaration.get("payload_json", String.class); + String originalDeclarationXmin = retainedDeclaration.get("row_xmin", String.class); + assertThat(retainedDeclaration.get("request_id", UUID.class)).isEqualTo(automation.requestId()); + assertThat(retainedDeclaration.get("commit_id", UUID.class)).isEqualTo(automation.commitId()); + assertThat(retainedDeclaration.get("revision_order", Integer.class)).isZero(); + assertThat(retainedDeclaration.get("owner", String.class)).isEqualTo("AUTOMATION_SCRIPTING"); + var originalCommit = + f.dsl.fetchSingle( + "SELECT binding_json, input_digest, xmin::text AS row_xmin FROM game_design_draft_commit " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + automation.requestId(), + automation.commitId()); + String originalBindingJson = originalCommit.get("binding_json", String.class); + String originalBindingDigest = originalCommit.get("input_digest", String.class); + String originalCommitXmin = originalCommit.get("row_xmin", String.class); + var originalAutomationApplication = + f.dsl.fetchSingle( + "SELECT snapshot_json, result_bytes, xmin::text AS row_xmin FROM game_design_template_config_source_application " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + automation.commitId()); + String v2SnapshotJson = originalAutomationApplication.get("snapshot_json", String.class); + byte[] originalApplicationBytes = + originalAutomationApplication.get("result_bytes", byte[].class); + String originalApplicationXmin = originalAutomationApplication.get("row_xmin", String.class); + String v2SnapshotDigest = + f.dsl + .fetchSingle( + "SELECT snapshot_digest FROM game_design_template_config_source_snapshot " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + automation.commitId()) + .get("snapshot_digest", String.class); + String originalV2SnapshotXmin = + f.dsl + .fetchSingle( + "SELECT xmin::text AS row_xmin FROM game_design_template_config_source_snapshot " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + automation.commitId()) + .get("row_xmin", String.class); + assertThat(v2SnapshotJson) + .contains("AUTOMATION_SCRIPTING") + .contains(automation.requestId().toString()) + .contains(automation.commitId().toString()); + var v1025MigrationHistory = + f.dsl + .fetch( + "SELECT version || ':' || script || ':' || checksum || ':' || success AS history_entry " + + "FROM flyway_schema_history_game_design_service " + + "WHERE version IS NOT NULL ORDER BY installed_rank") + .getValues("history_entry", String.class); + + migrateToLatest(f); + assertThat( + f.dsl + .fetch( + "SELECT version || ':' || script || ':' || checksum || ':' || success AS history_entry " + + "FROM flyway_schema_history_game_design_service " + + "WHERE version IS NOT NULL ORDER BY installed_rank LIMIT ?", + v1025MigrationHistory.size()) + .getValues("history_entry", String.class)) + .containsExactlyElementsOf(v1025MigrationHistory); + f.tx.executeWithoutResult( + ignored -> + assertThat(new TemplateConfigSourceRepository(f.dsl).apply(automation).orElseThrow()) + .isEqualTo( + new TemplateConfigSourceSnapshot.Application( + automation, "1", automationSource))); + + var migratedDeclaration = + f.dsl.fetchSingle( + "SELECT request_id, commit_id, revision_order, owner, inventory_json, payload_json, " + + "xmin::text AS row_xmin FROM game_design_template_config_owner_source_inventory_declaration " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND revision_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + automation.revisions().getFirst().revisionId()); + assertThat(migratedDeclaration.get("request_id", UUID.class)) + .isEqualTo(retainedDeclaration.get("request_id", UUID.class)); + assertThat(migratedDeclaration.get("commit_id", UUID.class)) + .isEqualTo(retainedDeclaration.get("commit_id", UUID.class)); + assertThat(migratedDeclaration.get("revision_order", Integer.class)) + .isEqualTo(retainedDeclaration.get("revision_order", Integer.class)); + assertThat(migratedDeclaration.get("owner", String.class)) + .isEqualTo(retainedDeclaration.get("owner", String.class)); + assertThat(migratedDeclaration.get("inventory_json", String.class)) + .isEqualTo(originalInventoryJson); + assertThat(migratedDeclaration.get("payload_json", String.class)) + .isEqualTo(originalPayloadJson); + assertThat(migratedDeclaration.get("row_xmin", String.class)) + .isEqualTo(originalDeclarationXmin); + var migratedCommit = + f.dsl.fetchSingle( + "SELECT binding_json, input_digest, xmin::text AS row_xmin FROM game_design_draft_commit " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + automation.requestId(), + automation.commitId()); + assertThat(migratedCommit.get("binding_json", String.class)).isEqualTo(originalBindingJson); + assertThat(migratedCommit.get("input_digest", String.class)).isEqualTo(originalBindingDigest); + assertThat(migratedCommit.get("row_xmin", String.class)).isEqualTo(originalCommitXmin); + var migratedApplication = + f.dsl.fetchSingle( + "SELECT snapshot_json, result_bytes, xmin::text AS row_xmin FROM game_design_template_config_source_application " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + automation.commitId()); + assertThat(migratedApplication.get("snapshot_json", String.class)).isEqualTo(v2SnapshotJson); + assertThat(migratedApplication.get("result_bytes", byte[].class)) + .isEqualTo(originalApplicationBytes); + assertThat(migratedApplication.get("row_xmin", String.class)) + .isEqualTo(originalApplicationXmin); + assertThat( + f.dsl + .fetchSingle( + "SELECT snapshot_digest FROM game_design_template_config_source_snapshot " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + automation.commitId()) + .get("snapshot_digest", String.class)) + .isEqualTo(v2SnapshotDigest); + assertThat( + f.dsl + .fetchSingle( + "SELECT xmin::text AS row_xmin FROM game_design_template_config_source_snapshot " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + automation.commitId()) + .get("row_xmin", String.class)) + .isEqualTo(originalV2SnapshotXmin); + assertThat( + f.dsl + .fetchSingle( + "SELECT snapshot_json FROM game_design_template_config_source_snapshot " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + initialTemplate.commitId()) + .get("snapshot_json", String.class)) + .isEqualTo(v1SnapshotJson); + assertThat( + f.dsl + .fetchSingle( + "SELECT snapshot_digest FROM game_design_template_config_source_snapshot " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + initialTemplate.commitId()) + .get("snapshot_digest", String.class)) + .isEqualTo(v1SnapshotDigest); + assertThat( + f.dsl + .fetchSingle( + "SELECT xmin::text AS row_xmin FROM game_design_template_config_source_snapshot " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + initialTemplate.commitId()) + .get("row_xmin", String.class)) + .isEqualTo(originalV1SnapshotXmin); + var upgradedTemplateSources = new TemplateConfigSourceRepository(f.dsl); + assertThat( + upgradedTemplateSources + .readSnapshot(f.target, initialTemplate.commitId()) + .orElseThrow() + .canonicalJson()) + .isEqualTo(v1SnapshotJson); + assertThat( + upgradedTemplateSources + .readSnapshot(f.target, automation.commitId()) + .orElseThrow() + .canonicalJson()) + .isEqualTo(v2SnapshotJson); + + var entityInventory = EntityAuthoredSourceInventoryDeclaration.parse(entityInventory()); + var entity = + binding( + f, + TemplateConfigSource.ownerInventoryPayload( + DraftCommitBinding.Owner.ENTITY_MANAGEMENT, entityInventory), + TemplateConfigSource.SCOPE, + "2"); + apply(f, entity); + var entitySource = source(f, entity); + assertThat(entitySource.sourceEpoch()).isEqualTo("3"); + assertThat(entitySource.ownerSourceInventoryDeclarations()).hasSize(2); + assertThat(entitySource.ownerSourceInventoryDeclarations().get(0)) + .isEqualTo(automationSource.ownerSourceInventoryDeclarations().getFirst()); + assertThat(entitySource.ownerSourceInventoryDeclarations().get(0).owner()) + .isEqualTo(DraftCommitBinding.Owner.AUTOMATION_SCRIPTING); + assertThat(entitySource.ownerSourceInventoryDeclarations().get(0).sourceBinding()) + .isEqualTo(automation); + assertThat(entitySource.ownerSourceInventoryDeclarations().get(1).owner()) + .isEqualTo(DraftCommitBinding.Owner.ENTITY_MANAGEMENT); + assertThat(entitySource.ownerSourceInventoryDeclarations().get(1).sourceBinding()) + .isEqualTo(entity); + assertThat(entitySource.entries()).hasSize(1); + assertThat(f.dsl.fetchSingle("SELECT count(*) FROM game_templates").get(0, Long.class)) + .isEqualTo(1L); + f.tx.executeWithoutResult( + ignored -> + assertThat(new TemplateConfigSourceRepository(f.dsl).apply(entity).orElseThrow()) + .isEqualTo( + new TemplateConfigSourceSnapshot.Application(entity, "2", entitySource))); + + var unrelated = + binding( + f, + GameplayRuleSource.upsertPayload(new GameplayRuleManifest.AdmissionTag("after-entity")), + GameplayRuleSource.SCOPE, + "0"); + apply(f, unrelated); + var inherited = source(f, unrelated); + assertThat(inherited.ownerSourceInventoryDeclarations()) + .containsExactlyElementsOf(entitySource.ownerSourceInventoryDeclarations()); + assertThat(inherited.ownerSourceInventoryDeclarations().getFirst().sourceBinding()) + .isEqualTo(automation); + assertThat(inherited.ownerSourceInventoryDeclarations().get(1).sourceBinding()) + .isEqualTo(entity); + var postEntityReadback = new TemplateConfigSourceRepository(f.dsl); + var retainedV1 = + postEntityReadback.readSnapshot(f.target, initialTemplate.commitId()).orElseThrow(); + assertThat(retainedV1.canonicalJson()).isEqualTo(v1SnapshotJson); + assertThat(retainedV1.digest()).isEqualTo(v1SnapshotDigest); + var retainedAutomation = + postEntityReadback.readSnapshot(f.target, automation.commitId()).orElseThrow(); + assertThat(retainedAutomation.canonicalJson()).isEqualTo(v2SnapshotJson); + assertThat(retainedAutomation.digest()).isEqualTo(v2SnapshotDigest); + var retainedInherited = + postEntityReadback.readSnapshot(f.target, unrelated.commitId()).orElseThrow(); + assertThat(retainedInherited.ownerSourceInventoryDeclarations()) + .containsExactlyElementsOf(entitySource.ownerSourceInventoryDeclarations()); + var postEntityAutomationApplication = + f.dsl.fetchSingle( + "SELECT snapshot_json, result_bytes FROM game_design_template_config_source_application " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + automation.commitId()); + assertThat(postEntityAutomationApplication.get("snapshot_json", String.class)) + .isEqualTo(v2SnapshotJson); + assertThat(postEntityAutomationApplication.get("result_bytes", byte[].class)) + .isEqualTo(originalApplicationBytes); + var postEntityAutomationDeclaration = + f.dsl.fetchSingle( + "SELECT request_id, commit_id, revision_order, owner, inventory_json, payload_json FROM " + + "game_design_template_config_owner_source_inventory_declaration " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND revision_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + automation.revisions().getFirst().revisionId()); + assertThat(postEntityAutomationDeclaration.get("request_id", UUID.class)) + .isEqualTo(automation.requestId()); + assertThat(postEntityAutomationDeclaration.get("commit_id", UUID.class)) + .isEqualTo(automation.commitId()); + assertThat(postEntityAutomationDeclaration.get("revision_order", Integer.class)).isZero(); + assertThat(postEntityAutomationDeclaration.get("owner", String.class)) + .isEqualTo("AUTOMATION_SCRIPTING"); + assertThat(postEntityAutomationDeclaration.get("inventory_json", String.class)) + .isEqualTo(originalInventoryJson); + assertThat(postEntityAutomationDeclaration.get("payload_json", String.class)) + .isEqualTo(originalPayloadJson); + } + + @Test + void deferredTemplateApplicationGuardRejectsMissingOrChangedAtomicOwnerResult() { + var f = fixture(); + var automationInventory = + AutomationAuthoredSourceInventoryDeclaration.parse(automationInventory()); + var missingResult = + binding( + f, + TemplateConfigSource.ownerInventoryPayload( + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, automationInventory), + TemplateConfigSource.SCOPE, + "0"); + assertThatThrownBy( + () -> + f.tx.executeWithoutResult( + ignored -> { + stageInProgressTemplateApplication(f, missingResult); + f.dsl.execute( + "SET CONSTRAINTS template_config_application_commit_guard IMMEDIATE"); + })) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasStackTraceContaining("template config application requires exact atomic owner result"); + + var entityInventory = EntityAuthoredSourceInventoryDeclaration.parse(entityInventory()); + var changedResult = + binding( + f, + TemplateConfigSource.ownerInventoryPayload( + DraftCommitBinding.Owner.ENTITY_MANAGEMENT, entityInventory), + TemplateConfigSource.SCOPE, + "0"); + assertThatThrownBy( + () -> + f.tx.executeWithoutResult( + ignored -> { + var application = stageInProgressTemplateApplication(f, changedResult); + byte[] alteredResultBytes = application.canonicalBytes(); + alteredResultBytes[0] ^= 1; + new DraftCommitCoordinatorRepository(f.dsl) + .recordOwnerOutcome( + changedResult, + new DraftCommitCoordinatorRepository.OwnerOutcome( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, + changedResult.commitId(), + changedResult.digest(), + "ordinary-source:" + changedResult.commitId(), + alteredResultBytes, + List.of(application.appliedEpoch()))); + f.dsl.execute( + "SET CONSTRAINTS template_config_application_commit_guard IMMEDIATE"); + })) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasStackTraceContaining( + "template config owner result must contain exact complete tagged source bytes"); + } + + @Test + void actualCreateAndSameCommitGameplayInputHaveDurableGeneratedIdentityAndExactRetry() { + var f = fixture(); + UUID ruleRevision = UUID.randomUUID(); + var rule = + new DraftCommitBinding.RevisionPayload( + "0", + ruleRevision, + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload(new GameplayRuleManifest.AdmissionTag("ordinary"))); + var config = + config( + f, + "[{\"family\":\"ADMISSION_TAGS\",\"key\":\"ordinary\",\"revisionId\":\"" + + ruleRevision + + "\"}]"); + var create = + new DraftCommitBinding.RevisionPayload( + "1", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSource.createPayload("Starter", config)); + var binding = + binding( + f, + List.of(rule, create), + Map.of(GameplayRuleSource.SCOPE, "0", TemplateConfigSource.SCOPE, "0")); + apply(f, binding); + var first = source(f, binding); + String templateId = first.entries().getFirst().templateId(); + assertThat(first.entries().getFirst().sourceBinding()).isEqualTo(binding); + var initialBaseReference = + f.dsl.fetchSingle( + "SELECT canonical_tenant_id, template_id, canonical_version_id, source_commit_id, source_revision_id " + + "FROM game_template_version_ref WHERE canonical_tenant_id = ? AND template_id = ?", + f.target.canonicalTenantId(), + Long.parseLong(templateId)); + assertThat(initialBaseReference).isNotNull(); + assertThat(initialBaseReference.get("canonical_version_id", UUID.class)) + .isEqualTo(f.target.canonicalVersionId()); + assertThat(initialBaseReference.get("source_commit_id", UUID.class)) + .isEqualTo(binding.commitId()); + assertThat(initialBaseReference.get("source_revision_id", UUID.class)) + .isEqualTo(create.revisionId()); + assertThat( + f.dsl + .fetchSingle( + "SELECT count(*) FROM game_design_template_config_source_ref WHERE revision_id = ?", + create.revisionId()) + .get(0, Long.class)) + .isEqualTo(2L); + assertThat( + f.dsl + .fetchSingle( + "SELECT template_reference_phase FROM game_templates WHERE id = ?", + Long.parseLong(templateId)) + .get(0, String.class)) + .isEqualTo("LEGACY"); + // Replay reads the actual original stored application, not a second CREATE or current name + // lookup. + f.tx.executeWithoutResult( + ignored -> + assertThat( + new GameDesignSourceRepository(f.dsl) + .apply(binding) + .templateConfig() + .orElseThrow() + .snapshot()) + .isEqualTo(first)); + assertThat(f.dsl.fetchSingle("SELECT count(*) FROM game_templates").get(0, Long.class)) + .isEqualTo(1L); + var sibling = binding(f, commandUpsertPayload(), CommandSource.SCOPE, "0"); + apply(f, sibling); + assertThat(source(f, sibling).entries()).isEqualTo(first.entries()); + assertThat(source(f, sibling).sourceEpoch()).isEqualTo("1"); + + var update = + binding( + f, + TemplateConfigSource.upsertPayload(templateId, config(f, "[]")), + TemplateConfigSource.SCOPE, + "1"); + apply(f, update); + assertThat(source(f, update).entries().getFirst().sourceBinding()).isEqualTo(update); + var updatedBaseReference = + f.dsl.fetchSingle( + "SELECT canonical_version_id, source_commit_id, source_revision_id " + + "FROM game_template_version_ref WHERE canonical_tenant_id = ? AND template_id = ?", + f.target.canonicalTenantId(), + Long.parseLong(templateId)); + assertThat(updatedBaseReference).isNotNull(); + assertThat(updatedBaseReference.get("canonical_version_id", UUID.class)) + .isEqualTo(f.target.canonicalVersionId()); + assertThat(updatedBaseReference.get("source_commit_id", UUID.class)) + .isEqualTo(update.commitId()); + assertThat(updatedBaseReference.get("source_revision_id", UUID.class)) + .isEqualTo(TemplateConfigSource.mutations(update).getFirst().revisionId()); + assertThat(source(f, binding)).isEqualTo(first); + var delete = + binding(f, TemplateConfigSource.deletePayload(templateId), TemplateConfigSource.SCOPE, "2"); + apply(f, delete); + assertThat(source(f, delete).entries()).isEmpty(); + assertThat( + f.dsl.fetchOne( + "SELECT 1 FROM game_template_version_ref WHERE canonical_tenant_id = ? AND template_id = ?", + f.target.canonicalTenantId(), + Long.parseLong(templateId))) + .isNull(); + assertThat( + f.dsl + .fetchSingle( + "SELECT count(*) FROM game_templates WHERE id = ?", Long.parseLong(templateId)) + .get(0, Long.class)) + .isEqualTo(1L); + assertThat(source(f, binding)).isEqualTo(first); + assertThatThrownBy( + () -> + f.dsl.execute( + "UPDATE game_design_template_config_source_revision SET payload_json = '{}'")) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy(() -> f.dsl.execute("DELETE FROM game_design_template_config_source_ref")) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy( + () -> + f.dsl.execute( + "UPDATE game_templates SET config = '{}' WHERE id = ?", + Long.parseLong(templateId))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + + @Test + void unsupportedExternalOwnerReferencesRollbackWithoutInventingQualifiedRows() { + var f = fixture(); + var unsupported = + new TemplateConfigSource.Config( + config(f, "[]") + .canonicalJson() + .replace( + "\"regions\":[]", + "\"regions\":[{\"regionTemplateId\":\"" + UUID.randomUUID() + "\"}]")); + var binding = + binding( + f, + TemplateConfigSource.createPayload("Denied", unsupported), + TemplateConfigSource.SCOPE, + "0"); + assertThatThrownBy(() -> apply(f, binding)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("TEMPLATE_CONFIG_WORLD_EXACT_OWNER_READ_UNAVAILABLE"); + assertThat(f.dsl.fetchSingle("SELECT count(*) FROM game_templates").get(0, Long.class)) + .isZero(); + assertThat(new TemplateConfigSourceRepository(f.dsl).readSnapshot(f.target, binding.commitId())) + .isEmpty(); + assertThat( + f.dsl + .fetchSingle( + "SELECT count(*) FROM game_design_template_config_source_qualification") + .get(0, Long.class)) + .isZero(); + } + + @Test + void legacyTenantMatchingRowCannotAcquireCanonicalSourceAssociation() { + var f = fixture(); + long legacy = + f.dsl + .fetchSingle( + "INSERT INTO game_templates (tenant_id, name, config) VALUES (?, 'Unqualified', '{}'::JSONB) RETURNING id", + f.target.gameDesignVersionTenantKey()) + .get(0, Long.class); + var binding = + binding( + f, + TemplateConfigSource.upsertPayload(Long.toString(legacy), config(f, "[]")), + TemplateConfigSource.SCOPE, + "0"); + assertThatThrownBy(() -> apply(f, binding)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("TEMPLATE_CONFIG_TEMPLATE_OWNER_PROVENANCE_UNAVAILABLE"); + assertThatThrownBy( + () -> + f.tx.executeWithoutResult( + ignored -> + f.dsl.execute( + "INSERT INTO game_design_template_config_source_row_insert VALUES (?, pg_current_xact_id()::TEXT)", + legacy))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(new TemplateConfigSourceRepository(f.dsl).readSnapshot(f.target, binding.commitId())) + .isEmpty(); + } + + @Test + void explicitTargetRawInsertAndLegacyReassignmentCannotCommit() { + var f = fixture(); + assertThatThrownBy( + () -> + f.dsl.execute( + "INSERT INTO game_templates (tenant_id, name, config, default_version_id) VALUES (?, 'Raw target', '{}'::JSONB, ?)", + f.target.gameDesignVersionTenantKey(), + f.target.gameDesignVersionRowId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasStackTraceContaining( + "explicit template target requires actual authorized CREATE qualification"); + long legacy = + f.dsl + .fetchSingle( + "INSERT INTO game_templates (tenant_id, name, config) VALUES (?, 'Unrelated legacy', '{}'::JSONB) RETURNING id", + f.target.gameDesignVersionTenantKey()) + .get(0, Long.class); + assertThatThrownBy( + () -> + f.dsl.execute( + "UPDATE game_templates SET default_version_id = ? WHERE id = ?", + f.target.gameDesignVersionRowId(), + legacy)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasStackTraceContaining( + "unqualified template cannot be reassigned into managed source target"); + assertThat( + f.dsl + .fetchSingle("SELECT default_version_id FROM game_templates WHERE id = ?", legacy) + .get(0, Long.class)) + .isNull(); + var selected = binding(f, commandUpsertPayload(), CommandSource.SCOPE, "0"); + apply(f, selected); + assertThat(source(f, selected).entries()).isEmpty(); + assertThatThrownBy( + () -> + f.dsl.execute( + "INSERT INTO game_templates (tenant_id, name, config, default_version_id) VALUES (?, 'After capture', '{}'::JSONB, ?)", + f.target.gameDesignVersionTenantKey(), + f.target.gameDesignVersionRowId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasStackTraceContaining( + "explicit template target requires actual authorized CREATE qualification"); + assertThat(source(f, selected).entries()).isEmpty(); + } + + @Test + void newCaptureCannotIgnorePendingUnqualifiedExplicitTargetRow() { + var f = fixture(); + var selected = binding(f, commandUpsertPayload(), CommandSource.SCOPE, "0"); + assertThatThrownBy( + () -> + f.tx.executeWithoutResult( + ignored -> { + // The deferred insert guard has not fired: new source capture must + // independently deny. + f.dsl.execute( + "INSERT INTO game_templates (tenant_id, name, config, default_version_id) VALUES (?, 'Pending raw target', '{}'::JSONB, ?)", + f.target.gameDesignVersionTenantKey(), + f.target.gameDesignVersionRowId()); + apply(f, selected); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessage("TEMPLATE_CONFIG_EXPLICIT_TARGET_INVENTORY_UNQUALIFIED"); + assertThat( + new TemplateConfigSourceRepository(f.dsl).readSnapshot(f.target, selected.commitId())) + .isEmpty(); + assertThat(f.dsl.fetchSingle("SELECT count(*) FROM game_templates").get(0, Long.class)) + .isZero(); + } + + @Test + void changedGameplayRevisionCannotLeaveStaleTemplateReferencesVisible() { + var f = fixture(); + UUID ruleId = UUID.randomUUID(); + var config = + config( + f, + "[{\"family\":\"ADMISSION_TAGS\",\"key\":\"ordinary\",\"revisionId\":\"" + + ruleId + + "\"}]"); + var initial = + binding( + f, + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + ruleId, + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload( + new GameplayRuleManifest.AdmissionTag("ordinary"))), + new DraftCommitBinding.RevisionPayload( + "1", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSource.createPayload("Starter", config))), + Map.of(GameplayRuleSource.SCOPE, "0", TemplateConfigSource.SCOPE, "0")); + apply(f, initial); + var changed = + binding( + f, + GameplayRuleSource.upsertPayload(new GameplayRuleManifest.AdmissionTag("ordinary")), + GameplayRuleSource.SCOPE, + "1"); + assertThatThrownBy(() -> apply(f, changed)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("TEMPLATE_CONFIG_GAMEPLAY_INPUT_CHANGED"); + assertThat(new TemplateConfigSourceRepository(f.dsl).readSnapshot(f.target, changed.commitId())) + .isEmpty(); + assertThat(source(f, initial).entries()).hasSize(1); + } + + @Test + void selectedPublicationRetainsInheritedTemplateToOriginalWorldSourceAssociation() + throws Exception { + var f = fixture(); + UUID ruleRevision = UUID.randomUUID(); + var rule = + new DraftCommitBinding.RevisionPayload( + "0", + ruleRevision, + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload(new GameplayRuleManifest.AdmissionTag("ordinary"))); + var config = + config( + f, + "[{\"family\":\"ADMISSION_TAGS\",\"key\":\"ordinary\",\"revisionId\":\"" + + ruleRevision + + "\"}]"); + var create = + new DraftCommitBinding.RevisionPayload( + "1", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSource.createPayload("Starter", config)); + var initial = + binding( + f, + List.of(rule, create, policyRevision("2")), + Map.of( + GameplayRuleSource.SCOPE, + "0", + RealmPolicySource.SCOPE, + "0", + TemplateConfigSource.SCOPE, + "0")); + apply(f, initial); + var worldSeed = + IsolatedPublicationOperationFixtures.fresh(f.target, initial.commitId().toString()); + var selectedCommit = worldSeed.account().input().selection().selectedCommit(); + applyIsolatedWorldSuccessor(f, selectedCommit, worldSeed.world()); + assertThat(selectedCommit.commitId()).isNotEqualTo(initial.commitId()); + + // These isolated upstream bytes exercise this owner only; they do not prove authenticated + // Account or World producer authority. + var inputs = + selectedPublicationInputs(f, selectedCommit, "selected inherited template association"); + var reservation = + Objects.requireNonNull( + f.tx.execute( + ignored -> + new SelectedDraftPublicationOwner(f.dsl) + .reserve( + inputs.intent(), + inputs.operation().account(), + inputs.operation().world(), + inputs.operation().inventory(), + inputs.firstRead()))); + var operation = reservation.operation(); + var returnedGameplayCapture = reservation.sourceCapture().gameplay(); + assertThat(returnedGameplayCapture).isPresent(); + var gameplayCapture = returnedGameplayCapture.orElseThrow(); + var selectedGameplay = + new GameplayRuleSourceRepository(f.dsl) + .readSnapshot(f.target, selectedCommit.commitId()) + .orElseThrow(); + assertThat(gameplayCapture.operation().canonicalBytes()) + .containsExactly(operation.canonicalBytes()); + assertThat(gameplayCapture.snapshot().binding()).isEqualTo(selectedCommit); + assertThat(gameplayCapture.snapshot().canonicalBytes()) + .containsExactly(selectedGameplay.canonicalBytes()); + + var sourceCapture = new GameDesignSourceRepository(f.dsl).readCapture(operation).orElseThrow(); + var templateCapture = sourceCapture.templateConfig().orElseThrow(); + assertThat(templateCapture.snapshot().entries()).hasSize(1); + assertThat(templateCapture.snapshot().binding().commitId()) + .isEqualTo(operation.account().input().selection().selectedCommit().commitId()); + assertThat(templateCapture.snapshot().entries().getFirst().sourceBinding().commitId()) + .isEqualTo(initial.commitId()); + + var associations = new SelectedDraftTemplateWorldSourceAssociationRepository(f.dsl); + var retained = associations.readExact(operation, templateCapture); + assertThat(retained).hasSize(1); + assertThat(retained.getFirst().selectedCommitId()) + .isEqualTo(operation.account().input().selection().selectedCommit().commitId()); + assertThat(retained.getFirst().sourceOperationId()).isNotNull(); + assertThat(retained.getFirst().worldOperationId()).isNotNull(); + assertThat(retained.getFirst().worldReadRequestBytes()).isNotEmpty(); + assertThat(retained.getFirst().worldReadResponseBytes()).isNotEmpty(); + assertThat( + f.dsl + .fetchSingle( + "SELECT count(*) FROM game_design_selected_template_world_source_association") + .get(0, Long.class)) + .isEqualTo(1L); + + var selection = + AuthoredDraftPublishSelection.fromStored( + operation.account().input().selection().canonicalJson(), + operation.account().input().selection().digest()); + var originalWorldSourceRead = inputs.firstRead(); + UUID replayReadRequestId = UUID.randomUUID(); + while (replayReadRequestId.equals(originalWorldSourceRead.request().intakeRequestId())) { + replayReadRequestId = UUID.randomUUID(); + } + var replayWorldSourceRead = + new SelectedDraftTemplateWorldSourceAssociation.SourceRead( + new WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest( + 1, + originalWorldSourceRead.request().targetNamespace(), + replayReadRequestId, + originalWorldSourceRead.request().intakeRequestId(), + originalWorldSourceRead.request().canonicalTenantId()), + originalWorldSourceRead.receipt()); + f.tx.executeWithoutResult( + ignored -> + new SelectedDraftPublicationOwner(f.dsl) + .reserve( + selection.intent(), + operation.account(), + operation.world(), + operation.inventory(), + replayWorldSourceRead)); + assertThat(associations.readExact(operation, templateCapture).getFirst().canonicalBytes()) + .containsExactly(retained.getFirst().canonicalBytes()); + var originalReceipt = originalWorldSourceRead.receipt(); + var substitutedReceipt = + new WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt( + originalReceipt.schemaVersion(), + originalReceipt.targetNamespace(), + originalReceipt.intakeRequestId(), + UUID.randomUUID(), + originalReceipt.canonicalTenantId(), + originalReceipt.worldSlug(), + originalReceipt.sourceOperationId(), + originalReceipt.sourceEvidenceDigest(), + originalReceipt.requestDigest(), + originalReceipt.receiptDigest(), + originalReceipt.source()); + UUID substitutedReadRequestId = UUID.randomUUID(); + while (substitutedReadRequestId.equals(originalWorldSourceRead.request().intakeRequestId())) { + substitutedReadRequestId = UUID.randomUUID(); + } + var substitutedWorldSourceRead = + new SelectedDraftTemplateWorldSourceAssociation.SourceRead( + new WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest( + 1, + originalWorldSourceRead.request().targetNamespace(), + substitutedReadRequestId, + originalWorldSourceRead.request().intakeRequestId(), + originalWorldSourceRead.request().canonicalTenantId()), + substitutedReceipt); + assertThatThrownBy( + () -> + f.tx.executeWithoutResult( + ignored -> + new SelectedDraftPublicationOwner(f.dsl) + .reserve( + selection.intent(), + operation.account(), + operation.world(), + operation.inventory(), + substitutedWorldSourceRead))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ASSOCIATION_CONFLICT"); + assertThat(associations.readExact(operation, templateCapture).getFirst().canonicalBytes()) + .containsExactly(retained.getFirst().canonicalBytes()); + assertThatThrownBy( + () -> + f.dsl.execute( + "UPDATE game_design_selected_template_world_source_association SET world_slug = 'substituted'")) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + + @Test + void concurrentExactFirstReservationsKeepTheWinningReadCorrelation() throws Exception { + var f = fixture(); + var template = + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSource.createPayload("Starter", config(f, "[]"))); + var initial = + binding( + f, + List.of(template, policyRevision("1")), + Map.of(RealmPolicySource.SCOPE, "0", TemplateConfigSource.SCOPE, "0")); + apply(f, initial); + var worldSeed = + IsolatedPublicationOperationFixtures.fresh(f.target, initial.commitId().toString()); + var selectedCommit = worldSeed.account().input().selection().selectedCommit(); + applyIsolatedWorldSuccessor(f, selectedCommit, worldSeed.world()); + assertThat(selectedCommit.commitId()).isNotEqualTo(initial.commitId()); + + // The caller names the exact synchronized Draft; concurrent owner calls race only over the + // first durable selection/association transaction. Upstream evidence remains stipulated. + var inputs = + selectedPublicationInputs(f, selectedCommit, "concurrent selected template association"); + var selection = inputs.selection(); + var operation = inputs.operation(); + var firstRead = inputs.firstRead(); + UUID competingReadRequestId = UUID.randomUUID(); + while (competingReadRequestId.equals(firstRead.request().intakeRequestId()) + || competingReadRequestId.equals(firstRead.request().readRequestId())) { + competingReadRequestId = UUID.randomUUID(); + } + var competingRead = + new SelectedDraftTemplateWorldSourceAssociation.SourceRead( + new WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest( + firstRead.request().schemaVersion(), + firstRead.request().targetNamespace(), + competingReadRequestId, + firstRead.request().intakeRequestId(), + firstRead.request().canonicalTenantId()), + firstRead.receipt()); + + var ready = new CountDownLatch(2); + var start = new CountDownLatch(1); + var executor = Executors.newFixedThreadPool(2); + try { + var first = + executor.submit( + () -> concurrentReserve(f, operation, selection, firstRead, ready, start)); + var second = + executor.submit( + () -> concurrentReserve(f, operation, selection, competingRead, ready, start)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + var firstReservation = first.get(30, TimeUnit.SECONDS); + var secondReservation = second.get(30, TimeUnit.SECONDS); + assertThat(firstReservation.operation().canonicalBytes()) + .containsExactly(operation.canonicalBytes()); + assertThat(secondReservation.operation().canonicalBytes()) + .containsExactly(operation.canonicalBytes()); + } finally { + executor.shutdownNow(); + } + + var capture = new GameDesignSourceRepository(f.dsl).readCapture(operation).orElseThrow(); + var retained = + new SelectedDraftTemplateWorldSourceAssociationRepository(f.dsl) + .readExact(operation, capture.templateConfig().orElseThrow()); + assertThat(retained).hasSize(1); + byte[] winnerRequest = retained.getFirst().worldReadRequestBytes(); + assertThat( + Arrays.equals(winnerRequest, firstRead.requestBytes()) + || Arrays.equals(winnerRequest, competingRead.requestBytes())) + .isTrue(); + assertThat(retained.getFirst().worldReadResponseBytes()).isNotEmpty(); + } + + private static SelectedDraftPublicationOwner.Reservation concurrentReserve( + Fixture f, + GameDesignPublicationOperation operation, + AuthoredDraftPublishSelectionBinding selection, + SelectedDraftTemplateWorldSourceAssociation.SourceRead sourceRead, + CountDownLatch ready, + CountDownLatch start) + throws Exception { + ready.countDown(); + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting to start concurrent owner reservation"); + } + return Objects.requireNonNull( + f.tx.execute( + ignored -> + new SelectedDraftPublicationOwner(f.dsl) + .reserve( + AuthoredDraftPublishSelection.fromStored( + selection.canonicalJson(), selection.digest()) + .intent(), + operation.account(), + operation.world(), + operation.inventory(), + sourceRead)), + "concurrent owner reservation returned no result"); + } + + private SelectedPublicationInputs selectedPublicationInputs( + Fixture f, DraftCommitBinding selectedCommit, String notes) throws Exception { + var prepared = + Objects.requireNonNull( + f.tx.execute( + ignored -> { + String versionEpoch = + Objects.requireNonNull( + f.dsl + .fetchSingle( + "SELECT version_state_epoch FROM version WHERE id = ?", + f.target.gameDesignVersionRowId()) + .get(0, Long.class)) + .toString(); + var intent = + new AuthoredDraftPublishSelection.PublishIntent( + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + UUID.randomUUID().toString(), + versionEpoch, + notes, + selectedCommit.requestId(), + selectedCommit.commitId(), + selectedCommit.digest()); + var coordinator = new DraftCommitCoordinatorRepository(f.dsl); + var evidence = + coordinator.requireSynchronizedPublicationEvidence( + f.target, + selectedCommit.requestId(), + selectedCommit.commitId(), + selectedCommit.digest()); + return new PreparedSelection( + intent, AuthoredDraftPublishSelection.capture(intent, f.target, evidence)); + })); + var selection = + AuthoredDraftPublishSelectionBinding.fromStored( + prepared.selection().canonicalJson(), prepared.selection().digest()); + var worldSeed = PublishedWorldSelectorFixtures.evidence(f.target, selectedCommit); + var operation = IsolatedPublicationOperationFixtures.forSelection(selection, worldSeed); + return new SelectedPublicationInputs( + prepared.intent(), + selection, + operation, + syntheticWorldSourceRead(f.target, operation.world())); + } + + /** Structured, isolated source evidence for owner-local association tests only. */ + private static SelectedDraftTemplateWorldSourceAssociation.SourceRead syntheticWorldSourceRead( + DraftCommitBinding.TargetProof target, WorldPublishedStartLocationEvidence world) { + UUID registrationRequestId = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + String namespace = world.request().targetNamespace(); + UUID intakeRequestId = world.request().intakeRequestId(); + UUID tenantId = world.request().canonicalTenantId(); + String tenantSlug = "isolated-tenant"; + String worldSlug = "world"; + String worldDisplayName = "Isolated World"; + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + namespace, registrationRequestId, tenantId, tenantSlug, worldSlug, worldDisplayName); + String sourceEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + namespace, + registrationRequestId, + sourceOperationId, + sourceRequestDigest, + tenantId, + tenantSlug, + worldSlug, + worldDisplayName, + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind()); + var source = + new AuthoredWorldSourceEvidence( + 1, + namespace, + registrationRequestId, + sourceOperationId, + sourceRequestDigest, + tenantId, + tenantSlug, + worldSlug, + worldDisplayName, + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind(), + sourceEvidenceDigest); + var binding = + new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( + 1, + namespace, + intakeRequestId, + tenantId, + worldSlug, + sourceOperationId, + sourceEvidenceDigest); + var receipt = + new WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt( + 1, + namespace, + intakeRequestId, + UUID.randomUUID(), + tenantId, + worldSlug, + sourceOperationId, + sourceEvidenceDigest, + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(binding), + "sha256:" + "a".repeat(64), + source); + return new SelectedDraftTemplateWorldSourceAssociation.SourceRead( + new WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest( + 1, namespace, UUID.randomUUID(), intakeRequestId, tenantId), + receipt); + } + + private record PreparedSelection( + AuthoredDraftPublishSelection.PublishIntent intent, + AuthoredDraftPublishSelection selection) {} + + private record SelectedPublicationInputs( + AuthoredDraftPublishSelection.PublishIntent intent, + AuthoredDraftPublishSelectionBinding selection, + GameDesignPublicationOperation operation, + SelectedDraftTemplateWorldSourceAssociation.SourceRead firstRead) {} + + private TemplateConfigSourceSnapshot source(Fixture f, DraftCommitBinding binding) { + return new GameDesignSourceRepository(f.dsl) + .readSynchronized(f.target, binding.commitId()) + .orElseThrow() + .templateConfig() + .orElseThrow(); + } + + private void apply(Fixture f, DraftCommitBinding binding) { + f.tx.executeWithoutResult( + ignored -> { + var coordinator = new DraftCommitCoordinatorRepository(f.dsl); + var reviewed = new GameDesignReviewedBaseRepository(f.dsl); + var sources = new GameDesignSourceRepository(f.dsl); + sources.claimReviewed( + binding, + reviewed.resolve(f.target, DraftBaseReference.parse(binding.baseCommitId()))); + coordinator.claimApplicationSlot(binding); + coordinator.markOwnerInProgress( + binding, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); + var applied = sources.apply(binding); + coordinator.advanceSourceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof( + binding, List.of(applied.ownerOutcome()))); + sources.captureSynchronized(binding); + coordinator.releaseApplicationSlot(binding); + }); + } + + /** Retains controlled World owner/source inputs without reserving the publication under test. */ + private void applyIsolatedWorldSuccessor( + Fixture f, DraftCommitBinding binding, WorldPublishedStartLocationEvidence worldEvidence) { + f.tx.executeWithoutResult( + ignored -> { + var coordinator = new DraftCommitCoordinatorRepository(f.dsl); + var reviewed = new GameDesignReviewedBaseRepository(f.dsl); + var sources = new GameDesignSourceRepository(f.dsl); + sources.claimReviewed( + binding, + reviewed.resolve(f.target, DraftBaseReference.parse(binding.baseCommitId()))); + coordinator.claimApplicationSlot(binding); + coordinator.markOwnerInProgress(binding, DraftCommitBinding.Owner.WORLD_MANAGEMENT); + var appliedEpochs = + binding.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new DraftCommitCoordinatorRepository.AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(); + var outcome = + new DraftCommitCoordinatorRepository.OwnerOutcome( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + "ISOLATED-world-applied", + worldEvidence.appliedResultBytes(), + appliedEpochs); + coordinator.recordOwnerOutcome(binding, outcome); + coordinator.advanceSourceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof(binding, List.of(outcome))); + sources.captureSynchronized(binding); + coordinator.releaseApplicationSlot(binding); + }); + } + + private static TemplateConfigSourceSnapshot.Application stageInProgressTemplateApplication( + Fixture f, DraftCommitBinding binding) { + var coordinator = new DraftCommitCoordinatorRepository(f.dsl); + coordinator.claim(binding); + coordinator.claimApplicationSlot(binding); + coordinator.markOwnerInProgress(binding, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); + return new TemplateConfigSourceRepository(f.dsl).apply(binding).orElseThrow(); + } + + private static TemplateConfigSource.Config config(Fixture f, String inputs) { + return new TemplateConfigSource.Config( + "{\"schemaVersion\":1,\"baseVersionId\":\"" + + f.target.canonicalVersionId() + + "\",\"world\":{\"regions\":[],\"rooms\":[]},\"entity\":{\"items\":[],\"npcs\":[]},\"gameLogic\":{\"inputs\":" + + inputs + + "},\"automation\":{\"scripts\":[],\"scriptPatch\":{\"presence\":\"ABSENT\"}},\"supportedSettings\":[]}"); + } + + private static DraftCommitBinding.RevisionPayload policyRevision(String revisionOrder) { + return new DraftCommitBinding.RevisionPayload( + revisionOrder, + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{\"revisionKind\":\"REALM_ENTRY_POLICY\"," + + "\"logicalRevisionId\":\"isolated-finalizer-main\"," + + "\"policy\":{\"schemaVersion\":1,\"worldSlug\":\"world\"," + + "\"worldDisplayName\":\"World\",\"realmSlug\":\"main\"," + + "\"realmDisplayName\":\"Main\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\"," + + "\"entryPolicy\":\"PRESEEDED_ONLY\"}}"); + } + + private static String commandUpsertPayload() { + return CommandSource.upsertPayload( + "{\"schemaVersion\":1,\"commandId\":\"ISOLATED-command\"," + + "\"semanticOwner\":\"WORLD\",\"executionDiscipline\":\"DURABLE_GAMEPLAY\"," + + "\"stageRequirement\":\"GAMEPLAY\",\"promptPolicy\":\"NEVER\"," + + "\"actionCategory\":\"GAMEPLAY\",\"historyRecordable\":true," + + "\"aliases\":[\"isolated\"],\"actionTags\":[\"WORLD_BROWSE\"]," + + "\"effects\":[]}"); + } + + private static String automationInventory() { + return "{\"schema\":\"automation-authored-source-inventory/v1\"," + + "\"families\":{\"SCRIPT_DEFINITIONS\":[],\"EVENT_BINDINGS\":[]," + + "\"SCRIPT_PATCH_SOURCES\":[]}}"; + } + + private static String entityInventory() { + return "{\"schema\":\"entity-authored-source-inventory/v1\"," + + "\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":{" + + "\"ACTOR_BODY_LAYOUT_ASSIGNMENTS\":[],\"ARCHETYPE_ASSIGNMENTS\":[]," + + "\"ARCHETYPE_CONSTRAINTS\":[],\"ARCHETYPE_ROOTS\":[]," + + "\"BALANCE_CURVE_ATTACHMENTS\":[],\"BALANCE_CURVE_ROOTS\":[]," + + "\"BODY_LAYOUT_MEMBERSHIPS\":[],\"BODY_LAYOUT_ROOTS\":[]," + + "\"CRAFTING_INGREDIENT_BINDINGS\":[],\"CRAFTING_RECIPE_RESULT_BINDINGS\":[]," + + "\"CRAFTING_RECIPE_ROOTS\":[],\"EQUIPMENT_ATTACHMENT_RULES\":[]," + + "\"EQUIPMENT_CAPABILITIES\":[],\"EQUIPMENT_COMPATIBILITY_RULES\":[]," + + "\"EQUIPMENT_OCCUPANCY_RULES\":[],\"EQUIPMENT_SLOT_GROUPS\":[]," + + "\"EQUIPMENT_SLOT_ROOTS\":[],\"INBOUND_LOOT_BINDINGS\":[]," + + "\"ITEM_TEMPLATE_ROOTS\":[],\"LOOT_ITEM_MAPPINGS\":[]," + + "\"LOOT_TABLE_ROOTS\":[],\"NPC_TEMPLATE_ROOTS\":[]," + + "\"OTHER_ACTOR_TEMPLATE_ROOTS\":[]}}"; + } + + private DraftCommitBinding binding(Fixture f, String payload, String scope, String epoch) { + return binding( + f, + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + payload)), + Map.of(scope, epoch)); + } + + private DraftCommitBinding binding( + Fixture f, List revisions, Map scopes) { + var units = + scopes.entrySet().stream() + .map( + e -> + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + e.getKey(), + f.target.canonicalVersionId().toString(), + e.getKey(), + "effective", + e.getValue())) + .toList(); + return DraftCommitBinding.create( + f.target, UUID.randomUUID(), UUID.randomUUID(), currentBaseReference(f), revisions, units); + } + + private static String currentBaseReference(Fixture f) { + UUID visibleCommit = + f.dsl + .fetchSingle( + "SELECT visible_commit_id FROM game_design_realm_policy_source " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId()) + .get("visible_commit_id", UUID.class); + if (visibleCommit != null) return visibleCommit.toString(); + UUID genesisReceipt = + new GameDesignSourceRepository(f.dsl) + .readGenesis(f.target) + .orElseThrow() + .policy() + .receiptId(); + return "genesis:" + genesisReceipt; + } + + private Fixture fixture() { + return fixture(null); + } + + private Fixture fixture(String migrationTarget) { + String schema = "template_config_" + UUID.randomUUID().toString().replace("-", ""); + var data = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + data.setSchema(schema); + var flyway = + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_game_design_service") + .placeholders(Map.of("serviceSchema", schema)) + .locations( + "filesystem:" + + java.nio.file.Path.of("src/main/resources/db/migration") + .toAbsolutePath() + .normalize()); + if (migrationTarget != null) flyway.target(MigrationVersion.fromVersion(migrationTarget)); + flyway.load().migrate(); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); + var tx = new TransactionTemplate(new DataSourceTransactionManager(data)); + tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var game = new Game(); + game.setTenantId(UUID.randomUUID().toString()); + game.setName("Template source fixture"); + var savedGame = + Objects.requireNonNull(tx.execute(ignored -> new GameRepository(dsl).save(game))); + var version = new Version(); + version.setTenantId(savedGame.getTenantId()); + version.setVersionNumber(1); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(1L); + var saved = + Objects.requireNonNull(tx.execute(ignored -> new VersionRepository(dsl).save(version))); + var target = + new DraftCommitBinding.TargetProof( + saved.getCanonicalTenantId(), + saved.getCanonicalVersionId(), + saved.getId(), + saved.getTenantId(), + saved.getIdentitySourceGameRowId(), + saved.getIdentitySourceGameTenantKey(), + saved.getIdentitySourceProvenanceKind()); + return new Fixture(dsl, tx, target, data, schema); + } + + private static void migrateToLatest(Fixture f) { + Flyway.configure() + .dataSource(f.dataSource()) + .schemas(f.schema()) + .defaultSchema(f.schema()) + .table("flyway_schema_history_game_design_service") + .placeholders(Map.of("serviceSchema", f.schema())) + .locations( + "filesystem:" + + java.nio.file.Path.of("src/main/resources/db/migration") + .toAbsolutePath() + .normalize()) + .load() + .migrate(); + } + + private record Fixture( + DSLContext dsl, + TransactionTemplate tx, + DraftCommitBinding.TargetProof target, + DriverManagerDataSource dataSource, + String schema) {} +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java index 3e59adfca3..5028082e1a 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java @@ -19,6 +19,11 @@ import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; @@ -35,8 +40,9 @@ import org.testcontainers.junit.jupiter.Testcontainers; /** - * V1009 PostgreSQL storage proof definitions. The predecessor selection table and upstream - * authority are explicit fixtures; this is not composed authoring or authenticated intake proof. + * V1009 predecessor storage proof and current selected Gameplay capture/receipt source-join proof. + * The predecessor selection table and upstream authority remain explicit fixtures; the new join + * cases use current owner captures and receipt storage with controlled upstream receipt inputs. */ @Testcontainers(disabledWithoutDocker = true) class SelectedDraftGameLogicReceiptPostgresIntegrationTest { @@ -253,6 +259,174 @@ void ownerTransactionRechecksCompleteSelectionBeforeInsertingDerivedReceipt() { .isZero(); } + @Test + void currentCapturedGameplayAndImmutableReceiptJoinRequiresExactCanonicalBytes() + throws Exception { + assertCurrentCaptureReceiptJoin(false); + assertCurrentCaptureReceiptJoin(true); + } + + private static void assertCurrentCaptureReceiptJoin(boolean changeReceiptSource) + throws Exception { + var fixture = currentCaptureFixture(); + var capture = fixture.sources().readCapture(fixture.operation()).orElseThrow(); + var gameplayCapture = capture.gameplay().orElseThrow(); + var selectedCommit = fixture.operation().account().input().selection().selectedCommit(); + var selectedSnapshot = + new GameplayRuleSourceRepository(fixture.dsl()) + .readSnapshot(fixture.target(), selectedCommit.commitId()) + .orElseThrow(); + assertThat(gameplayCapture.operation().canonicalBytes()) + .containsExactly(fixture.operation().canonicalBytes()); + assertThat(gameplayCapture.snapshot().canonicalBytes()) + .containsExactly(selectedSnapshot.canonicalBytes()); + + String receiptSourceEpoch = + changeReceiptSource + ? new java.math.BigInteger(selectedSnapshot.sourceEpoch()) + .add(java.math.BigInteger.ONE) + .toString() + : selectedSnapshot.sourceEpoch(); + var controlledReceiptSnapshot = + new GameplayRuleSnapshot( + selectedSnapshot.binding(), + receiptSourceEpoch, + selectedSnapshot.inheritedCommitId(), + selectedSnapshot.genesisReceiptId(), + selectedSnapshot.entries()); + var receiptSource = new GameplayRuleSelectedSource(controlledReceiptSnapshot.canonicalJson()); + assertThat(receiptSource.binding()).isEqualTo(selectedCommit); + if (changeReceiptSource) { + assertThat(receiptSource.canonicalBytes()) + .isNotEqualTo(gameplayCapture.snapshot().canonicalBytes()); + } else { + assertThat(receiptSource.canonicalBytes()) + .containsExactly(gameplayCapture.snapshot().canonicalBytes()); + } + + var retained = + retainCurrentFixtureReceipt( + fixture.operation(), fixture.dsl(), fixture.tx(), receiptSource); + var receiptRepository = new SelectedDraftGameLogicReceiptRepository(fixture.dsl()); + var readback = receiptRepository.readForPublication(publicationBinding(retained)).orElseThrow(); + assertThat(readback.receipt().canonicalBytes()) + .containsExactly(retained.receipt().canonicalBytes()); + assertThat(readback.authorization().source().canonicalBytes()) + .containsExactly(receiptSource.canonicalBytes()); + + var operationReadback = + new GameDesignPublicationOperationRepository(fixture.dsl()) + .read(fixture.operation().workflowId()) + .orElseThrow(); + assertThat(operationReadback.outcome()).isEqualTo("PENDING"); + assertThat( + SelectedGameplayRuleSourceJoin.matches( + operationReadback.operation(), gameplayCapture, selectedSnapshot, readback)) + .isEqualTo(!changeReceiptSource); + } + + private static SelectedDraftGameLogicReceipt retainCurrentFixtureReceipt( + GameDesignPublicationOperation operation, + DSLContext dsl, + TransactionTemplate tx, + GameplayRuleSelectedSource source) { + var selection = operation.account().input().selection(); + UUID actor = UUID.randomUUID(); + var authorization = + new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + actor, + source, + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + var terminal = + GameLogicGameplayRuleIntakeTerminal.retained( + new GameLogicGameplayRuleIntakeOperation("controlled-game-logic", authorization), + source.canonicalBytes(), + source.manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); + var candidate = + new SelectedDraftGameLogicReceipt( + AuthoredDraftPublishSelection.fromStored(selection.canonicalJson(), selection.digest()), + authorization, + new AccountGameLogicIntakeSettlementEvidence(terminal)); + var repository = new SelectedDraftGameLogicReceiptRepository(dsl); + tx.executeWithoutResult(ignored -> repository.retain(candidate)); + return candidate; + } + + private static CurrentCaptureFixture currentCaptureFixture() throws Exception { + String schema = "gd_gameplay_join_" + UUID.randomUUID().toString().replace("-", ""); + var dataSource = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations( + "filesystem:" + + java.nio.file.Path.of("src/main/resources/db/migration") + .toAbsolutePath() + .normalize()) + .table("flyway_schema_history_game_design_service") + .load() + .migrate(); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var tx = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + + DraftCommitBinding.TargetProof target = + tx.execute( + ignored -> { + var game = new Game(); + game.setTenantId("ISOLATED-" + UUID.randomUUID().toString().substring(0, 8)); + game.setName("ISOLATED captured Gameplay join"); + game = new GameRepository(dsl).save(game); + var version = new Version(); + version.setTenantId(game.getTenantId()); + version.setVersionNumber(1); + version = new VersionRepository(dsl).save(version); + var proof = + new DraftCommitBinding.TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + new GameDesignSourceRepository(dsl).enrollFreshDraft(proof); + return proof; + }); + var sources = new GameDesignSourceRepository(dsl); + GameDesignPublicationOperation operation = + tx.execute( + ignored -> { + try { + var retained = + IsolatedPublicationOwnerSetup.retainFrozenSourceBacked( + dsl, target, 1L, "controlled exact Gameplay receipt join"); + sources.freeze(retained); + return retained; + } catch (Exception failure) { + throw new IllegalStateException( + "Unable to retain controlled source capture", failure); + } + }); + return new CurrentCaptureFixture(dsl, tx, target, sources, operation); + } + private static Fixture fixture(SelectedDraftGameLogicReceipt value) { String schema = "receipt_" + UUID.randomUUID().toString().replace("-", ""); var data = @@ -442,4 +616,11 @@ private static PublicationDigestRequestBinding publicationBinding( } private record Fixture(DSLContext dsl, TransactionTemplate tx) {} + + private record CurrentCaptureFixture( + DSLContext dsl, + TransactionTemplate tx, + DraftCommitBinding.TargetProof target, + GameDesignSourceRepository sources, + GameDesignPublicationOperation operation) {} } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/TemplateReferencePhasePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/TemplateReferencePhasePostgresIntegrationTest.java new file mode 100644 index 0000000000..84d89f00ce --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/TemplateReferencePhasePostgresIntegrationTest.java @@ -0,0 +1,566 @@ +package integration.net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftBaseReference; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import net.firedevops.firemud.gamedesign.draft.GameDesignReviewedBaseRepository; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import net.firedevops.firemud.gamedesign.publication.TemplateConfigSource; +import net.firedevops.firemud.gamedesign.publication.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.gamedesign.publication.TemplateReferenceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +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.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Focused proof for fresh phase authority, exact current refs, and full-inventory denial. */ +@Testcontainers(disabledWithoutDocker = true) +class TemplateReferencePhasePostgresIntegrationTest { + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void freshOwnerCreationStartsBackfillingAndEmptyInventoryCannotAdvance() { + Fixture fixture = fixture(); + TemplateReferenceRepository references = new TemplateReferenceRepository(fixture.dsl()); + + var phase = references.readPhase(fixture.target().canonicalTenantId()).orElseThrow(); + assertThat(phase.phase()).isEqualTo(TemplateReferenceRepository.Phase.BACKFILLING); + assertThat(phase.phaseEpoch()).isEqualTo(1L); + assertThat(phase.creationOperationId()).isEqualTo(fixture.creation().operationId()); + assertThat(phase.creationRequestId()).isEqualTo(fixture.creation().creationRequestId()); + assertThat(phase.sourceGameRowId()).isEqualTo(fixture.creation().sourceGameRowId()); + assertThat(phase.sourceGameTenantKey()).isEqualTo(fixture.creation().sourceGameTenantKey()); + + assertThatThrownBy( + () -> + fixture + .tx() + .execute( + ignored -> + references.validateAndEnforce(fixture.target().canonicalTenantId()))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("TEMPLATE_REFERENCE_INVENTORY_EMPTY"); + assertThat(references.readPhase(fixture.target().canonicalTenantId()).orElseThrow()) + .isEqualTo(phase); + createTemplate(fixture, "Deleted", true); + String deletedTemplateId = templateId(fixture, "Deleted"); + DraftCommitBinding deleted = + applyTemplateSourceMutation( + fixture, TemplateConfigSource.deletePayload(deletedTemplateId), "1"); + assertThat(sourceSnapshot(fixture, deleted).entries()).isEmpty(); + assertThatThrownBy( + () -> + fixture + .tx() + .execute( + ignored -> + new TemplateReferenceRepository(fixture.dsl()) + .validateAndEnforce(fixture.target().canonicalTenantId()))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("TEMPLATE_REFERENCE_INVENTORY_EMPTY"); + assertThat( + new TemplateReferenceRepository(fixture.dsl()) + .readPhase(fixture.target().canonicalTenantId()) + .orElseThrow() + .phase()) + .isEqualTo(phase.phase()); + } + + @Test + void latestDeleteAfterDecimalEpochBoundaryDoesNotBlockActiveTemplate() { + Fixture fixture = fixture(); + DraftCommitBinding active = createTemplate(fixture, "Active", true); + applyTemplateSourceMutation( + fixture, TemplateConfigSource.createPayload("Deleted", templateConfig(fixture)), "1"); + String deletedTemplateId = templateId(fixture, "Deleted"); + for (int expectedEpoch = 2; expectedEpoch <= 9; expectedEpoch++) { + applyTemplateSourceMutation( + fixture, + TemplateConfigSource.upsertPayload(deletedTemplateId, templateConfig(fixture)), + Integer.toString(expectedEpoch)); + } + DraftCommitBinding deleted = + applyTemplateSourceMutation( + fixture, TemplateConfigSource.deletePayload(deletedTemplateId), "10"); + + var currentSource = sourceSnapshot(fixture, deleted); + assertThat(currentSource.entries()).hasSize(1); + assertThat(currentSource.entries().getFirst().templateId()) + .isEqualTo(templateId(fixture, "Active")); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT count(*) FROM game_templates WHERE tenant_id = ?", + fixture.creation().sourceGameTenantKey()) + .get(0, Long.class)) + .isEqualTo(2L); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT count(*) FROM game_design_template_config_source_qualification " + + "WHERE canonical_tenant_id = ? AND template_id = ?", + fixture.target().canonicalTenantId(), + Long.parseLong(deletedTemplateId)) + .get(0, Long.class)) + .isEqualTo(1L); + + var enforced = + fixture + .tx() + .execute( + ignored -> + new TemplateReferenceRepository(fixture.dsl()) + .validateAndEnforce(fixture.target().canonicalTenantId())); + assertThat(enforced).isNotNull(); + assertThat(enforced.phase()).isEqualTo(TemplateReferenceRepository.Phase.ENFORCED); + assertThat(enforced.inventoryTemplateCount()).isEqualTo(1L); + assertThat(currentSource.entries().getFirst().sourceBinding().commitId()) + .isEqualTo(active.commitId()); + } + + @Test + void upsertCannotResurrectDeletedTemplateAndFailureLeavesCurrentSourceUsable() { + Fixture fixture = fixture(); + DraftCommitBinding active = createTemplate(fixture, "Active", true); + applyTemplateSourceMutation( + fixture, TemplateConfigSource.createPayload("Reactivated", templateConfig(fixture)), "1"); + String reactivatedTemplateId = templateId(fixture, "Reactivated"); + DraftCommitBinding deleted = + applyTemplateSourceMutation( + fixture, TemplateConfigSource.deletePayload(reactivatedTemplateId), "2"); + var currentSource = sourceSnapshot(fixture, deleted); + var phase = + new TemplateReferenceRepository(fixture.dsl()) + .readPhase(fixture.target().canonicalTenantId()) + .orElseThrow(); + assertThat(currentSource.entries()).hasSize(1); + assertThat(currentSource.entries().getFirst().templateId()) + .isEqualTo(templateId(fixture, "Active")); + assertThat(currentSource.entries().getFirst().sourceBinding().commitId()) + .isEqualTo(active.commitId()); + + assertThatThrownBy( + () -> + applyTemplateSourceMutation( + fixture, + TemplateConfigSource.upsertPayload( + reactivatedTemplateId, templateConfig(fixture)), + "3")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Template source identity is not an existing qualified entry"); + assertThat(sourceSnapshot(fixture, deleted)).isEqualTo(currentSource); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT count(*) FROM game_templates WHERE tenant_id = ?", + fixture.creation().sourceGameTenantKey()) + .get(0, Long.class)) + .isEqualTo(2L); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT count(*) FROM game_design_template_config_source_qualification " + + "WHERE canonical_tenant_id = ? AND template_id = ?", + fixture.target().canonicalTenantId(), + Long.parseLong(reactivatedTemplateId)) + .get(0, Long.class)) + .isEqualTo(1L); + assertThat( + new TemplateReferenceRepository(fixture.dsl()) + .readPhase(fixture.target().canonicalTenantId()) + .orElseThrow()) + .isEqualTo(phase); + + String activeTemplateId = templateId(fixture, "Active"); + DraftCommitBinding activeUpsert = + applyTemplateSourceMutation( + fixture, + TemplateConfigSource.upsertPayload(activeTemplateId, templateConfig(fixture)), + "3"); + var currentAfterActiveUpsert = sourceSnapshot(fixture, activeUpsert); + assertThat(currentAfterActiveUpsert.entries()).hasSize(1); + assertThat(currentAfterActiveUpsert.entries().getFirst().templateId()) + .isEqualTo(activeTemplateId); + assertThat(currentAfterActiveUpsert.entries().getFirst().sourceBinding().commitId()) + .isEqualTo(activeUpsert.commitId()); + assertThat(currentAfterActiveUpsert.entries().getFirst().revisionId()) + .isEqualTo(activeUpsert.revisions().getFirst().revisionId()); + assertThat( + currentAfterActiveUpsert.entries().stream() + .map(TemplateConfigSource.Entry::templateId) + .toList()) + .doesNotContain(reactivatedTemplateId); + + var enforced = + fixture + .tx() + .execute( + ignored -> + new TemplateReferenceRepository(fixture.dsl()) + .validateAndEnforce(fixture.target().canonicalTenantId())); + assertThat(enforced).isNotNull(); + assertThat(enforced.phase()).isEqualTo(TemplateReferenceRepository.Phase.ENFORCED); + assertThat(enforced.inventoryTemplateCount()).isEqualTo(1L); + } + + @Test + void qualifiedCurrentSourceCanEnforcePhaseAndRawCreateIsThenDenied() { + Fixture fixture = fixture(); + DraftCommitBinding binding = createTemplate(fixture, "Starter"); + var currentReference = + fixture + .dsl() + .fetchSingle( + "SELECT canonical_version_id, source_commit_id, source_revision_id " + + "FROM game_template_version_ref WHERE canonical_tenant_id = ?", + fixture.target().canonicalTenantId()); + assertThat(currentReference).isNotNull(); + assertThat(currentReference.get("canonical_version_id", UUID.class)) + .isEqualTo(fixture.target().canonicalVersionId()); + assertThat(currentReference.get("source_commit_id", UUID.class)).isEqualTo(binding.commitId()); + assertThat(currentReference.get("source_revision_id", UUID.class)) + .isEqualTo(binding.revisions().getFirst().revisionId()); + + TemplateReferenceRepository references = new TemplateReferenceRepository(fixture.dsl()); + var enforced = + fixture + .tx() + .execute( + ignored -> references.validateAndEnforce(fixture.target().canonicalTenantId())); + assertThat(enforced).isNotNull(); + assertThat(enforced.phase()).isEqualTo(TemplateReferenceRepository.Phase.ENFORCED); + assertThat(enforced.phaseEpoch()).isEqualTo(3L); + assertThat(enforced.inventoryTemplateCount()).isEqualTo(1L); + assertThat(enforced.inventoryDigest()).startsWith("sha256:"); + + assertThatThrownBy( + () -> + fixture + .tx() + .executeWithoutResult( + ignored -> + fixture + .dsl() + .execute( + "INSERT INTO game_templates (tenant_id, name, config) " + + "VALUES (?, 'Raw bypass', '{}'::JSONB)", + fixture.creation().sourceGameTenantKey()))) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining( + "validated template create requires exact active owner source binding"); + assertThat(references.readPhase(fixture.target().canonicalTenantId()).orElseThrow()) + .isEqualTo(enforced); + } + + @Test + void currentSourceSynchronizationStaysBackfillingUntilExplicitFullInventoryValidation() { + Fixture fixture = fixture(); + DraftCommitBinding binding = createTemplate(fixture, "Starter", true); + var references = new TemplateReferenceRepository(fixture.dsl()); + var before = references.readPhase(fixture.target().canonicalTenantId()).orElseThrow(); + assertThat(before.phase()).isEqualTo(TemplateReferenceRepository.Phase.BACKFILLING); + assertThat(before.phaseEpoch()).isEqualTo(1L); + assertThat(before.creationOperationId()).isEqualTo(fixture.creation().operationId()); + assertThat(before.creationRequestId()).isEqualTo(fixture.creation().creationRequestId()); + assertThat(before.sourceGameRowId()).isEqualTo(fixture.creation().sourceGameRowId()); + assertThat(before.sourceGameTenantKey()).isEqualTo(fixture.creation().sourceGameTenantKey()); + + var visibleSources = + new GameDesignSourceRepository(fixture.dsl()) + .readSynchronized(fixture.target(), binding.commitId()) + .orElseThrow(); + assertThat(visibleSources.command().binding()).isEqualTo(binding); + assertThat(visibleSources.policy().binding()).isEqualTo(binding); + var visibleTemplateConfig = visibleSources.templateConfig().orElseThrow(); + assertThat(visibleTemplateConfig.binding()).isEqualTo(binding); + assertThat(visibleTemplateConfig.entries()).hasSize(1); + assertThat(visibleTemplateConfig.entries().getFirst().sourceBinding()).isEqualTo(binding); + assertThat(visibleTemplateConfig.entries().getFirst().revisionId()) + .isEqualTo(binding.revisions().getFirst().revisionId()); + + var currentReference = + fixture + .dsl() + .fetchSingle( + "SELECT template_id, canonical_version_id, source_commit_id, source_revision_id " + + "FROM game_template_version_ref WHERE canonical_tenant_id = ?", + fixture.target().canonicalTenantId()); + assertThat(currentReference).isNotNull(); + assertThat(currentReference.get("canonical_version_id", UUID.class)) + .isEqualTo(fixture.target().canonicalVersionId()); + assertThat(currentReference.get("source_commit_id", UUID.class)).isEqualTo(binding.commitId()); + assertThat(currentReference.get("source_revision_id", UUID.class)) + .isEqualTo(binding.revisions().getFirst().revisionId()); + assertThat( + references + .readExactBaseReference( + fixture.target().canonicalTenantId(), + Objects.requireNonNull(currentReference.get("template_id", Long.class))) + .orElseThrow() + .sourceCommitId()) + .isEqualTo(binding.commitId()); + assertThat(references.readPhase(fixture.target().canonicalTenantId()).orElseThrow()) + .isEqualTo(before); + + var enforced = + fixture + .tx() + .execute( + ignored -> references.validateAndEnforce(fixture.target().canonicalTenantId())); + assertThat(enforced).isNotNull(); + assertThat(enforced.phase()).isEqualTo(TemplateReferenceRepository.Phase.ENFORCED); + assertThat(enforced.phaseEpoch()).isEqualTo(3L); + assertThat(enforced.inventoryTemplateCount()).isEqualTo(1L); + assertThat(enforced.inventoryDigest()).isNotBlank().startsWith("sha256:"); + assertThat(enforced.creationOperationId()).isEqualTo(before.creationOperationId()); + assertThat(enforced.creationRequestId()).isEqualTo(before.creationRequestId()); + assertThat(enforced.sourceGameRowId()).isEqualTo(before.sourceGameRowId()); + assertThat(enforced.sourceGameTenantKey()).isEqualTo(before.sourceGameTenantKey()); + assertThat(enforced.creationEvidenceDigest()).isEqualTo(before.creationEvidenceDigest()); + assertThat(enforced.provenanceKind()).isEqualTo(before.provenanceKind()); + } + + @Test + void unqualifiedPhysicalTemplatePreventsTenantPromotion() { + Fixture fixture = fixture(); + createTemplate(fixture, "Qualified"); + fixture + .tx() + .executeWithoutResult( + ignored -> + fixture + .dsl() + .execute( + "INSERT INTO game_templates (tenant_id, name, config) " + + "VALUES (?, 'Unqualified', '{}'::JSONB)", + fixture.creation().sourceGameTenantKey())); + + assertThatThrownBy( + () -> + fixture + .tx() + .execute( + ignored -> + new TemplateReferenceRepository(fixture.dsl()) + .validateAndEnforce(fixture.target().canonicalTenantId()))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("TEMPLATE_REFERENCE_INVENTORY_UNQUALIFIED"); + assertThat( + new TemplateReferenceRepository(fixture.dsl()) + .readPhase(fixture.target().canonicalTenantId()) + .orElseThrow() + .phase()) + .isEqualTo(TemplateReferenceRepository.Phase.BACKFILLING); + } + + private DraftCommitBinding createTemplate(Fixture fixture, String name) { + return createTemplate(fixture, name, false); + } + + private DraftCommitBinding createTemplate( + Fixture fixture, String name, boolean sourceAwareVisibility) { + GameDesignSourceRepository sources = new GameDesignSourceRepository(fixture.dsl()); + String baseReference = + "genesis:" + sources.readGenesis(fixture.target()).orElseThrow().policy().receiptId(); + return applyTemplateSourceMutation( + fixture, + TemplateConfigSource.createPayload(name, templateConfig(fixture)), + "0", + baseReference, + sourceAwareVisibility); + } + + private DraftCommitBinding applyTemplateSourceMutation( + Fixture fixture, String payload, String expectedEpoch) { + UUID visibleCommitId = + Objects.requireNonNull( + fixture + .dsl() + .fetchSingle( + "SELECT visible_commit_id FROM game_design_realm_policy_source " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()) + .get("visible_commit_id", UUID.class)); + return applyTemplateSourceMutation( + fixture, payload, expectedEpoch, visibleCommitId.toString(), true); + } + + private DraftCommitBinding applyTemplateSourceMutation( + Fixture fixture, + String payload, + String expectedEpoch, + String baseReference, + boolean sourceAwareVisibility) { + UUID revisionId = UUID.randomUUID(); + DraftCommitBinding binding = + DraftCommitBinding.create( + fixture.target(), + UUID.randomUUID(), + UUID.randomUUID(), + baseReference, + List.of( + new DraftCommitBinding.RevisionPayload( + "0", revisionId, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, payload)), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSource.SCOPE, + fixture.target().canonicalVersionId().toString(), + TemplateConfigSource.SCOPE, + TemplateConfigSource.SCOPE_ID, + expectedEpoch))); + var sources = new GameDesignSourceRepository(fixture.dsl()); + fixture + .tx() + .executeWithoutResult( + ignored -> { + var coordinator = new DraftCommitCoordinatorRepository(fixture.dsl()); + var reviewed = new GameDesignReviewedBaseRepository(fixture.dsl()); + sources.claimReviewed( + binding, + reviewed.resolve( + fixture.target(), DraftBaseReference.parse(binding.baseCommitId()))); + coordinator.claimApplicationSlot(binding); + coordinator.markOwnerInProgress( + binding, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); + var applied = sources.apply(binding); + if (sourceAwareVisibility) { + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup + .advanceIsolatedSourceVisibility( + fixture.dsl(), binding, List.of(applied.ownerOutcome())); + } else { + // These primitive-level cases deliberately leave promotion to the explicit + // validator. + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup + .advanceIsolatedVisibility( + fixture.dsl(), binding, List.of(applied.ownerOutcome())); + sources.captureSynchronized(binding); + } + coordinator.releaseApplicationSlot(binding); + }); + return binding; + } + + private TemplateConfigSourceSnapshot sourceSnapshot(Fixture fixture, DraftCommitBinding binding) { + return new GameDesignSourceRepository(fixture.dsl()) + .readSynchronized(fixture.target(), binding.commitId()) + .orElseThrow() + .templateConfig() + .orElseThrow(); + } + + private TemplateConfigSource.Config templateConfig(Fixture fixture) { + return new TemplateConfigSource.Config( + "{\"schemaVersion\":1,\"baseVersionId\":\"" + + fixture.target().canonicalVersionId() + + "\",\"world\":{\"regions\":[],\"rooms\":[]}," + + "\"entity\":{\"items\":[],\"npcs\":[]},\"gameLogic\":{\"inputs\":[]}," + + "\"automation\":{\"scripts\":[],\"scriptPatch\":{\"presence\":\"ABSENT\"}}," + + "\"supportedSettings\":[]}"); + } + + private String templateId(Fixture fixture, String name) { + Long id = + fixture + .dsl() + .fetchSingle( + "SELECT id FROM game_templates WHERE tenant_id = ? AND name = ?", + fixture.creation().sourceGameTenantKey(), + name) + .get("id", Long.class); + return Objects.requireNonNull(id).toString(); + } + + private Fixture fixture() { + String schema = "template_reference_phase_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_game_design_service") + .placeholders(Map.of("serviceSchema", schema)) + .locations( + "filesystem:" + + java.nio.file.Path.of("src/main/resources/db/migration") + .toAbsolutePath() + .normalize()) + .load() + .migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + TransactionTemplate tx = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + + UUID requestId = UUID.randomUUID(); + String tenantKey = UUID.randomUUID().toString(); + FreshTenantCreationEvidence creation = + Objects.requireNonNull( + tx.execute( + ignored -> + new GameTenantCreationRepository(dsl, new GameRepository(dsl)) + .createCandidate( + "template-phase-test", + requestId, + tenantKey, + "Template reference phase fixture", + null))); + Version version = new Version(); + version.setTenantId(tenantKey); + version.setVersionNumber(1); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(1L); + Version savedVersion = + Objects.requireNonNull(tx.execute(ignored -> new VersionRepository(dsl).save(version))); + DraftCommitBinding.TargetProof target = + new DraftCommitBinding.TargetProof( + savedVersion.getCanonicalTenantId(), + savedVersion.getCanonicalVersionId(), + savedVersion.getId(), + savedVersion.getTenantId(), + savedVersion.getIdentitySourceGameRowId(), + savedVersion.getIdentitySourceGameTenantKey(), + savedVersion.getIdentitySourceProvenanceKind()); + return new Fixture(dsl, tx, creation, target); + } + + private record Fixture( + DSLContext dsl, + TransactionTemplate tx, + FreshTenantCreationEvidence creation, + DraftCommitBinding.TargetProof target) {} +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTemplateRepositoryPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTemplateRepositoryPostgresIntegrationTest.java new file mode 100644 index 0000000000..b6f491f875 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTemplateRepositoryPostgresIntegrationTest.java @@ -0,0 +1,120 @@ +package integration.net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import java.nio.file.Path; +import java.sql.Connection; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.GameTemplate; +import net.firedevops.firemud.gamedesign.model.TemplateReferencePhase; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameTemplateRepository; +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; + +/** Owner-local SQL proof; controlled pre-phase rows supply no publication authority. */ +class GameTemplateRepositoryPostgresIntegrationTest { + private static final GameDesignPostgresIntegrationFixture POSTGRES = + new GameDesignPostgresIntegrationFixture(); + + @BeforeAll + static void startPostgres() { + POSTGRES.start(); + } + + @AfterAll + static void stopPostgres() { + POSTGRES.stop(); + } + + @Test + void savesOnlyTheExactTenantRowAndPreservesRowsOnForeignOrMissingIdentity() throws Exception { + String schema = "game_design_template_owner_" + UUID.randomUUID().toString().replace("-", ""); + var source = POSTGRES.dataSource(); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_game_design_service") + .placeholders(Map.of("serviceSchema", schema)) + .locations( + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()) + .load() + .migrate(); + + try (Connection connection = source.getConnection()) { + connection.setSchema(schema); + DSLContext dsl = DSL.using(connection, SQLDialect.POSTGRES); + GameRepository games = new GameRepository(dsl); + for (String tenant : List.of("tenant-a", "tenant-b")) { + Game game = new Game(); + game.setTenantId(tenant); + game.setName(tenant); + games.save(game); + } + // Deliberately exercise retained/pre-phase rows, where SQL's later phase guard is absent. + assertThat(dsl.fetchCount(DSL.table("game_template_reference_phase"))).isZero(); + GameTemplateRepository repository = new GameTemplateRepository(dsl); + GameTemplate first = repository.save(template("tenant-a", "Original A")); + GameTemplate second = repository.save(template("tenant-b", "Original B")); + List before = rows(dsl); + + GameTemplate foreign = template("tenant-b", "Changed foreign row"); + foreign.setId(first.getId()); + Throwable foreignRefusal = catchThrowable(() -> repository.save(foreign)); + + assertThat(rows(dsl)) + .as("foreign save preserves complete rows including xmin") + .isEqualTo(before); + assertThat(foreignRefusal) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("game template not found for tenant"); + assertThat(repository.findByTenantIdAndId("tenant-b", first.getId())).isEmpty(); + + GameTemplate missing = template("tenant-a", "Missing row"); + missing.setId(Long.MAX_VALUE); + Throwable missingRefusal = catchThrowable(() -> repository.save(missing)); + assertThat(rows(dsl)) + .as("missing save preserves complete rows including xmin") + .isEqualTo(before); + assertThat(missingRefusal) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("game template not found for tenant"); + + first.setName("Owned update"); + GameTemplate updated = repository.save(first); + assertThat(updated.getId()).isEqualTo(first.getId()); + assertThat(updated.getTenantId()).isEqualTo("tenant-a"); + assertThat(updated.getName()).isEqualTo("Owned update"); + assertThat(repository.findByTenantIdAndId("tenant-b", second.getId()).orElseThrow()) + .usingRecursiveComparison() + .isEqualTo(second); + } + } + + private static GameTemplate template(String tenant, String name) { + GameTemplate template = new GameTemplate(); + template.setTenantId(tenant); + template.setName(name); + template.setConfig("{}"); + template.setDefaultRuntimeFlagsJson("{}"); + template.setTemplateReferencePhase(TemplateReferencePhase.LEGACY); + return template; + } + + private static List rows(DSLContext dsl) { + return dsl.fetch( + "SELECT row_to_json(t)::TEXT || ':' || xmin::TEXT AS snapshot " + + "FROM game_templates t ORDER BY id") + .getValues("snapshot", String.class); + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java new file mode 100644 index 0000000000..5db106da16 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java @@ -0,0 +1,637 @@ +package integration.net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.SQLDialect; +import org.jooq.Table; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.jooq.impl.DataSourceConnectionProvider; +import org.jooq.impl.DefaultConfiguration; +import org.junit.jupiter.api.Test; +import org.springframework.boot.jooq.autoconfigure.SpringTransactionProvider; +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; + +/** + * Controlled local storage fixtures; these do not exercise an authenticated publication producer. + */ +@Testcontainers(disabledWithoutDocker = true) +class PublishedReleaseCanonicalIdentityIntegrationTest { + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + private static final String OTHER_MANIFEST_HASH = "sha256:" + "b".repeat(64); + private static final String GENERATION_CONFIG_REVISION = "generation-1"; + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final MigrationVersion V35 = MigrationVersion.fromVersion("35"); + private static final Table VERSION = DSL.table(DSL.name("version")); + private static final Table RELEASE_BUNDLE = DSL.table(DSL.name("published_release_bundle")); + private static final Field ID = DSL.field(DSL.name("id"), Long.class); + private static final Field PUBLISHED_RELEASE_BUNDLE_REF = + DSL.field(DSL.name("published_release_bundle_ref"), String.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field CANONICAL_VERSION_ID = + DSL.field(DSL.name("canonical_version_id"), UUID.class); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void normalSavePersistsExactVersionAndVerifiedGameIdentityAndReadsBackWithinTransaction() { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "fresh-release-source"); + Game other = saveGame(fixture, "other-release-source"); + Version version = saveVersion(fixture, owner); + + PublishedReleaseBundle saved = + fixture.releaseBundleRepository().save(bundle(owner.getTenantId(), version.getId())); + assertThat(saved.getCanonicalTenantId()).isEqualTo(owner.getCanonicalTenantId()); + assertThat(saved.getCanonicalVersionId()).isEqualTo(version.getCanonicalVersionId()); + assertThat(saved.getPublishedReleaseBundleRef()).isNotBlank(); + assertThat( + fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId(owner.getTenantId(), version.getId()) + .orElseThrow()) + .usingRecursiveComparison() + .isEqualTo(saved); + + Map bundleTupleBeforeSourceMutation = + releaseBundleTuple(fixture.dsl(), saved.getId()); + String bundleXminBeforeSourceMutation = bundleXmin(fixture.dsl(), saved.getId()); + String versionXminBefore = versionXmin(fixture.dsl(), version.getId()); + String gameXminBefore = gameXmin(fixture.dsl(), owner.getId()); + String otherGameXminBefore = gameXmin(fixture.dsl(), other.getId()); + assertThatThrownBy( + () -> + fixture + .dsl() + .update(VERSION) + .set(CANONICAL_TENANT_ID, other.getCanonicalTenantId()) + .where(ID.eq(version.getId())) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("canonical Version identity and its tenant source are immutable"); + + assertThat(releaseBundleTuple(fixture.dsl(), saved.getId())) + .isEqualTo(bundleTupleBeforeSourceMutation); + assertThat(bundleXmin(fixture.dsl(), saved.getId())).isEqualTo(bundleXminBeforeSourceMutation); + assertThat(bundleCount(fixture.dsl())).isEqualTo(1); + assertThat(versionXmin(fixture.dsl(), version.getId())).isEqualTo(versionXminBefore); + assertThat(gameXmin(fixture.dsl(), owner.getId())).isEqualTo(gameXminBefore); + assertThat(gameXmin(fixture.dsl(), other.getId())).isEqualTo(otherGameXminBefore); + assertThat( + fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId(owner.getTenantId(), version.getId()) + .orElseThrow()) + .usingRecursiveComparison() + .isEqualTo(saved); + } + + @Test + void repositoryNestedTransactionRollsBackWithOuterSpringPublisherTransaction() { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "outer-release-rollback-owner"); + Version version = saveVersion(fixture, owner); + String versionXminBefore = versionXmin(fixture.dsl(), version.getId()); + String gameXminBefore = gameXmin(fixture.dsl(), owner.getId()); + + assertThatThrownBy( + () -> + fixture + .transactionTemplate() + .execute( + status -> { + PublishedReleaseBundle saved = + fixture + .releaseBundleRepository() + .save(bundle(owner.getTenantId(), version.getId())); + assertThat(saved.getCanonicalTenantId()) + .isEqualTo(owner.getCanonicalTenantId()); + assertThat(saved.getCanonicalVersionId()) + .isEqualTo(version.getCanonicalVersionId()); + assertThat(saved.getPublishedReleaseBundleRef()).isNotBlank(); + Version publishingVersion = + fixture + .versionRepository() + .findByTenantIdAndId(owner.getTenantId(), version.getId()) + .orElseThrow(); + publishingVersion.setVersionState(VersionLifecycleState.PUBLISHED); + publishingVersion.setVersionStateEpoch( + publishingVersion.getVersionStateEpoch() + 1L); + fixture.versionRepository().save(publishingVersion); + assertThat(bundleCount(fixture.dsl())).isEqualTo(1); + assertThat( + fixture + .versionRepository() + .findByTenantIdAndId(owner.getTenantId(), version.getId()) + .orElseThrow() + .getVersionState()) + .isEqualTo(VersionLifecycleState.PUBLISHED); + throw new IllegalStateException("simulate failed outer publication"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessage("simulate failed outer publication"); + + assertThat(bundleCount(fixture.dsl())).isZero(); + assertThat( + fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId(owner.getTenantId(), version.getId())) + .isEmpty(); + assertThat(versionXmin(fixture.dsl(), version.getId())).isEqualTo(versionXminBefore); + assertThat(gameXmin(fixture.dsl(), owner.getId())).isEqualTo(gameXminBefore); + Version exactVersionAfterRollback = + fixture + .versionRepository() + .findByTenantIdAndId(owner.getTenantId(), version.getId()) + .orElseThrow(); + assertThat(exactVersionAfterRollback.getCanonicalTenantId()) + .isEqualTo(owner.getCanonicalTenantId()); + assertThat(exactVersionAfterRollback.getCanonicalVersionId()) + .isEqualTo(version.getCanonicalVersionId()); + assertThat(exactVersionAfterRollback.getVersionState()).isEqualTo(VersionLifecycleState.DRAFT); + assertThat(exactVersionAfterRollback.getVersionStateEpoch()) + .isEqualTo(version.getVersionStateEpoch()); + assertThat(exactVersionAfterRollback.getIdentitySourceGameRowId()).isEqualTo(owner.getId()); + assertThat(exactVersionAfterRollback.getIdentitySourceGameTenantKey()) + .isEqualTo(owner.getTenantId()); + } + + @Test + void deniesWrongTenantNilAndSubstitutedCallerOrDatabaseIdentityWithoutGrowingBundles() { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "denied-release-owner"); + Game other = saveGame(fixture, "denied-release-other"); + Version version = saveVersion(fixture, owner); + var ownerBefore = sourceRow(fixture.dsl(), "game", owner.getId()); + var otherBefore = sourceRow(fixture.dsl(), "game", other.getId()); + var versionBefore = sourceRow(fixture.dsl(), "version", version.getId()); + + assertThatThrownBy( + () -> + fixture + .releaseBundleRepository() + .save(bundle(other.getTenantId(), version.getId()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No exact canonical Game Design source association"); + + PublishedReleaseBundle substitutedTenant = bundle(owner.getTenantId(), version.getId()); + substitutedTenant.setCanonicalTenantId(other.getCanonicalTenantId()); + assertThatThrownBy(() -> fixture.releaseBundleRepository().save(substitutedTenant)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Caller-supplied canonical release identity"); + + PublishedReleaseBundle substitutedVersion = bundle(owner.getTenantId(), version.getId()); + substitutedVersion.setCanonicalVersionId(UUID.randomUUID()); + assertThatThrownBy(() -> fixture.releaseBundleRepository().save(substitutedVersion)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Caller-supplied canonical release identity"); + + assertThatThrownBy( + () -> + insertRawBundle( + fixture.dsl(), + owner.getTenantId(), + version.getId(), + NIL_UUID, + version.getCanonicalVersionId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("non-nil canonical identity"); + assertThatThrownBy( + () -> + insertRawBundle( + fixture.dsl(), + owner.getTenantId(), + version.getId(), + other.getCanonicalTenantId(), + version.getCanonicalVersionId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("does not match its exact Version and Game source"); + assertThatThrownBy( + () -> + insertRawBundle( + fixture.dsl(), + other.getTenantId(), + version.getId(), + owner.getCanonicalTenantId(), + version.getCanonicalVersionId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("does not match its exact Version and Game source"); + assertThat(bundleCount(fixture.dsl())).isZero(); + assertThat(sourceRow(fixture.dsl(), "game", owner.getId())).isEqualTo(ownerBefore); + assertThat(sourceRow(fixture.dsl(), "game", other.getId())).isEqualTo(otherBefore); + assertThat(sourceRow(fixture.dsl(), "version", version.getId())).isEqualTo(versionBefore); + } + + @Test + void bundleIdentityIsImmutableRetainedNullCannotBeBackfilledAndMetadataCannotBeDeleted() { + Fixture fixture = fixture(V35); + Game game = saveGame(fixture, "release-retention-owner"); + Long retainedVersionId = insertRetainedVersion(fixture.dsl(), game.getTenantId()); + Long retainedBundleId = + insertRetainedBundle(fixture.dsl(), game.getTenantId(), retainedVersionId); + // Synthetic historical v1 row, seeded before identity enforcement solely for retention proof. + migrate(fixture.dataSource(), fixture.schema(), null); + Version mappedVersion = saveVersion(fixture, game); + PublishedReleaseBundle mapped = + fixture.releaseBundleRepository().save(bundle(game.getTenantId(), mappedVersion.getId())); + Map mappedTupleBefore = releaseBundleTuple(fixture.dsl(), mapped.getId()); + String mappedXminBefore = bundleXmin(fixture.dsl(), mapped.getId()); + Map retainedTupleBefore = releaseBundleTuple(fixture.dsl(), retainedBundleId); + String retainedXminBefore = bundleXmin(fixture.dsl(), retainedBundleId); + + PublishedReleaseBundle exactReadback = + fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId(game.getTenantId(), mappedVersion.getId()) + .orElseThrow(); + assertThat(exactReadback).usingRecursiveComparison().isEqualTo(mapped); + assertThatThrownBy(() -> fixture.releaseBundleRepository().save(exactReadback)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Published release bundle is immutable"); + exactReadback.setManifestHash(OTHER_MANIFEST_HASH); + assertThatThrownBy(() -> fixture.releaseBundleRepository().save(exactReadback)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Published release bundle is immutable"); + + assertThatThrownBy( + () -> + fixture + .dsl() + .update(RELEASE_BUNDLE) + .set(DSL.field(DSL.name("manifest_hash"), String.class), OTHER_MANIFEST_HASH) + .where(ID.eq(mapped.getId())) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("published release bundle attestation is immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE published_release_bundle SET manifest_hash = manifest_hash " + + "WHERE id = ?", + mapped.getId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("published release bundle attestation is immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .update(RELEASE_BUNDLE) + .set(CANONICAL_TENANT_ID, UUID.randomUUID()) + .where(ID.eq(mapped.getId())) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("published release bundle attestation is immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .update(RELEASE_BUNDLE) + .set(CANONICAL_VERSION_ID, UUID.randomUUID()) + .where(ID.eq(mapped.getId())) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("published release bundle attestation is immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .update(RELEASE_BUNDLE) + .set(DSL.field(DSL.name("manifest_hash"), String.class), OTHER_MANIFEST_HASH) + .where(ID.eq(retainedBundleId)) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("published release bundle attestation is immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .update(RELEASE_BUNDLE) + .set(PUBLISHED_RELEASE_BUNDLE_REF, "attempted-retained-release-reference") + .where(ID.eq(retainedBundleId)) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("published release bundle attestation is immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .update(RELEASE_BUNDLE) + .set(CANONICAL_TENANT_ID, game.getCanonicalTenantId()) + .set(CANONICAL_VERSION_ID, mappedVersion.getCanonicalVersionId()) + .where(ID.eq(retainedBundleId)) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("published release bundle attestation is immutable"); + + PublishedReleaseBundle retained = + fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId(game.getTenantId(), retainedVersionId) + .orElseThrow(); + assertThat(retained.getCanonicalTenantId()).isNull(); + assertThat(retained.getCanonicalVersionId()).isNull(); + assertThat(retained.getPublishedReleaseBundleRef()).isNull(); + assertThatThrownBy(() -> fixture.releaseBundleRepository().save(retained)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Published release bundle is immutable"); + retained.setCanonicalTenantId(game.getCanonicalTenantId()); + assertThatThrownBy(() -> fixture.releaseBundleRepository().save(retained)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Published release bundle is immutable"); + + assertThat(releaseBundleTuple(fixture.dsl(), mapped.getId())).isEqualTo(mappedTupleBefore); + assertThat(bundleXmin(fixture.dsl(), mapped.getId())).isEqualTo(mappedXminBefore); + assertThat(releaseBundleTuple(fixture.dsl(), retainedBundleId)).isEqualTo(retainedTupleBefore); + assertThat(bundleXmin(fixture.dsl(), retainedBundleId)).isEqualTo(retainedXminBefore); + assertThat( + fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId(game.getTenantId(), mappedVersion.getId()) + .orElseThrow()) + .usingRecursiveComparison() + .isEqualTo(mapped); + PublishedReleaseBundle retainedAfterAttempts = + fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId(game.getTenantId(), retainedVersionId) + .orElseThrow(); + assertThat(retainedAfterAttempts.getCanonicalTenantId()).isNull(); + assertThat(retainedAfterAttempts.getCanonicalVersionId()).isNull(); + assertThat(retainedAfterAttempts.getPublishedReleaseBundleRef()).isNull(); + assertThat(retainedAfterAttempts.getManifestHash()).isEqualTo(MANIFEST_HASH); + + assertThatThrownBy( + () -> fixture.dsl().deleteFrom(RELEASE_BUNDLE).where(ID.eq(mapped.getId())).execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("published release bundle metadata is retained"); + assertThatThrownBy( + () -> fixture.dsl().execute("TRUNCATE TABLE published_release_bundle CASCADE")) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("metadata cannot be truncated"); + assertThat(bundleCount(fixture.dsl())).isEqualTo(2); + assertThat(releaseBundleTuple(fixture.dsl(), mapped.getId())).isEqualTo(mappedTupleBefore); + assertThat(releaseBundleTuple(fixture.dsl(), retainedBundleId)).isEqualTo(retainedTupleBefore); + } + + @Test + void repositoryNestedTransactionRollsBackWithOuterJooqOwnerTransaction() { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "jooq-release-rollback-owner"); + Version version = saveVersion(fixture, owner); + var gameBefore = sourceRow(fixture.dsl(), "game", owner.getId()); + var versionBefore = sourceRow(fixture.dsl(), "version", version.getId()); + + assertThatThrownBy( + () -> + fixture + .dsl() + .transaction( + configuration -> { + DSLContext ownerSql = DSL.using(configuration); + var repository = new PublishedReleaseBundleRepository(ownerSql); + var saved = repository.save(bundle(owner.getTenantId(), version.getId())); + assertThat(saved.getCanonicalTenantId()) + .isEqualTo(owner.getCanonicalTenantId()); + assertThat(saved.getCanonicalVersionId()) + .isEqualTo(version.getCanonicalVersionId()); + assertThat( + repository.findByTenantIdAndVersionId( + owner.getTenantId(), version.getId())) + .isPresent(); + assertThat(bundleCount(ownerSql)).isEqualTo(1); + throw new IllegalStateException("simulate failed outer jOOQ owner"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("simulate failed outer jOOQ owner"); + + assertThat(bundleCount(fixture.dsl())).isZero(); + assertThat( + fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId(owner.getTenantId(), version.getId())) + .isEmpty(); + assertThat(sourceRow(fixture.dsl(), "game", owner.getId())).isEqualTo(gameBefore); + assertThat(sourceRow(fixture.dsl(), "version", version.getId())).isEqualTo(versionBefore); + } + + private Fixture fixture(MigrationVersion target) { + String schema = "game_design_release_identity_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema, target); + return fixtureFromMigratedSchema(schema, dataSource); + } + + private Fixture fixtureFromMigratedSchema(String schema, DriverManagerDataSource dataSource) { + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + transactionTemplate.setIsolationLevel( + org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED); + DefaultConfiguration jooqConfiguration = new DefaultConfiguration(); + jooqConfiguration.set(SQLDialect.POSTGRES); + jooqConfiguration.set( + new DataSourceConnectionProvider(new TransactionAwareDataSourceProxy(dataSource))); + jooqConfiguration.set(new SpringTransactionProvider(transactionManager)); + DSLContext dsl = DSL.using(jooqConfiguration); + GameRepository gameRepository = new GameRepository(dsl); + VersionRepository versionRepository = new VersionRepository(dsl); + PublishedReleaseBundleRepository releaseBundleRepository = + new PublishedReleaseBundleRepository(dsl); + return new Fixture( + schema, + dataSource, + dsl, + transactionTemplate, + gameRepository, + versionRepository, + releaseBundleRepository); + } + + private DriverManagerDataSource dataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + return dataSource; + } + + private void migrate(DriverManagerDataSource dataSource, String schema, MigrationVersion target) { + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", schema)) + .locations( + "filesystem:" + + java.nio.file.Path.of("src/main/resources/db/migration") + .toAbsolutePath() + .normalize()); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private Game saveGame(Fixture fixture, String tenantKey) { + Game game = new Game(); + game.setTenantId(tenantKey); + game.setName("Published Release Identity Owner"); + game.setDescription("Exact immutable Game source association"); + return fixture.transactionTemplate().execute(status -> fixture.gameRepository().save(game)); + } + + private Version saveVersion(Fixture fixture, Game game) { + Version version = new Version(); + version.setTenantId(game.getTenantId()); + version.setVersionNumber(1); + version.setNotes("fresh release source"); + return fixture + .transactionTemplate() + .execute(status -> fixture.versionRepository().save(version)); + } + + private Long insertRetainedVersion(DSLContext dsl, String tenantId) { + return dsl.resultQuery( + "INSERT INTO version (tenant_id, version_number, version_state, version_state_epoch, " + + "script_patch_version, base_version_id, is_script_only, notes) " + + "VALUES (?, 4, 'FAILED', 3, NULL, NULL, FALSE, 'retained release source') " + + "RETURNING id", + tenantId) + .fetchOne(0, Long.class); + } + + private Long insertRetainedBundle(DSLContext dsl, String tenantId, Long versionId) { + return dsl.resultQuery( + "INSERT INTO published_release_bundle (tenant_id, version_id, version_number, " + + "attestation_schema_version, publish_workflow_id, manifest_hash, " + + "generation_config_revision, required_manifest_asset_keys_json, " + + "participant_digests_json, command_definitions_json, script_only, " + + "script_patch_version) VALUES (?, ?, 4, 'v1', 'retained-workflow', " + + "?, 'retained-config', '[\"asset-a\"]', '[]', '[]', FALSE, NULL) " + + "RETURNING id", + tenantId, + versionId, + MANIFEST_HASH) + .fetchOne(0, Long.class); + } + + private PublishedReleaseBundle bundle(String tenantId, Long versionId) { + PublishedReleaseBundle bundle = new PublishedReleaseBundle(); + bundle.setTenantId(tenantId); + bundle.setVersionId(versionId); + bundle.setVersionNumber(1); + bundle.setAttestationSchemaVersion("v1"); + bundle.setPublishWorkflowId("workflow-" + versionId); + bundle.setManifestHash(MANIFEST_HASH); + bundle.setManifestSchemaVersion(1); + bundle.setArtifactDigestsJson("[]"); + bundle.setGenerationConfigRevision(GENERATION_CONFIG_REVISION); + bundle.setRequiredManifestAssetKeysJson("[]"); + bundle.setParticipantDigestsJson("[]"); + bundle.setCommandDefinitionsJson("[]"); + return bundle; + } + + private void insertRawBundle( + DSLContext dsl, + String tenantId, + Long versionId, + UUID canonicalTenantId, + UUID canonicalVersionId) { + dsl.execute( + "INSERT INTO published_release_bundle (tenant_id, version_id, version_number, " + + "attestation_schema_version, publish_workflow_id, manifest_hash, " + + "generation_config_revision, required_manifest_asset_keys_json, " + + "participant_digests_json, command_definitions_json, manifest_schema_version, " + + "artifact_digests_json, script_only, " + + "canonical_tenant_id, canonical_version_id, published_release_bundle_ref) " + + "VALUES (?, ?, 1, 'v1', 'direct-write-test', ?, 'generation-1', " + + "'[]', '[]', '[]', 1, '[]', FALSE, ?, ?, ?)", + tenantId, + versionId, + MANIFEST_HASH, + canonicalTenantId, + canonicalVersionId, + UUID.randomUUID().toString()); + } + + private long bundleCount(DSLContext dsl) { + return dsl.fetchCount(RELEASE_BUNDLE); + } + + private Map releaseBundleTuple(DSLContext dsl, Long bundleId) { + return sourceRow(dsl, "published_release_bundle", bundleId); + } + + private Map sourceRow(DSLContext dsl, String table, Long rowId) { + return Objects.requireNonNull( + dsl.fetchOne("SELECT *, xmin::text AS xmin FROM " + table + " WHERE id = ?", rowId), + "Required " + table + " row is absent") + .intoMap(); + } + + private String bundleXmin(DSLContext dsl, Long bundleId) { + var row = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT xmin::text AS xmin FROM published_release_bundle WHERE id = ?", bundleId), + "Published release bundle xmin query returned no row"); + return Objects.requireNonNull( + row.get("xmin", String.class), "Published release bundle xmin readback returned null"); + } + + private String versionXmin(DSLContext dsl, Long versionId) { + var row = + Objects.requireNonNull( + dsl.fetchOne("SELECT xmin::text AS xmin FROM version WHERE id = ?", versionId), + "Version xmin query returned no row"); + return Objects.requireNonNull(row.get("xmin", String.class)); + } + + private String gameXmin(DSLContext dsl, Long gameId) { + var row = + Objects.requireNonNull( + dsl.fetchOne("SELECT xmin::text AS xmin FROM game WHERE id = ?", gameId), + "Game xmin query returned no row"); + return Objects.requireNonNull(row.get("xmin", String.class)); + } + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + TransactionTemplate transactionTemplate, + GameRepository gameRepository, + VersionRepository versionRepository, + PublishedReleaseBundleRepository releaseBundleRepository) {} +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionPostgresIntegrationTest.java new file mode 100644 index 0000000000..41944c145e --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionPostgresIntegrationTest.java @@ -0,0 +1,200 @@ +package integration.net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.LocalDateTime; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.repository.StartSessionAuthoredActorCoreProjectionRepository; +import net.firedevops.firemud.gamedesign.repository.StartSessionLaunchDescriptorRepository.Binding; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +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.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** PostgreSQL migration/storage proof; the synthetic row is not authenticated source authority. */ +@Testcontainers(disabledWithoutDocker = true) +class StartSessionAuthoredActorCoreProjectionPostgresIntegrationTest { + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void migratesOwnerKeyReadsSyntheticRetainedStorageAndRejectsMutation() throws Exception { + String schema = "gd_actor_core_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", schema)) + .locations( + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()) + .load() + .migrate(); + + UUID tenantId = UUID.randomUUID(); + UUID bindingId = UUID.randomUUID(); + String requestId = "synthetic-actor-core-owner"; + byte[] sourceBytes = new byte[] {1, 2, 3, 4}; + byte[] projectionBytes = "{\"synthetic\":true}".getBytes(StandardCharsets.UTF_8); + String sourceDigest = sha256(sourceBytes); + String projectionDigest = sha256(projectionBytes); + Binding owner = owner(tenantId, requestId); + + try (Connection connection = dataSource.getConnection()) { + setSearchPath(connection, schema); + connection.setAutoCommit(false); + try (Statement statement = connection.createStatement()) { + // Seed physical retained storage without claiming this synthetic row passed the owner or + // source-authentication triggers; normal application connections never change this role. + statement.execute("SET LOCAL session_replication_role = replica"); + } + try (PreparedStatement statement = + connection.prepareStatement( + "INSERT INTO game_design_start_session_authored_actor_core_projection " + + "(target_namespace, canonical_tenant_id, control_plane_request_id, " + + "launch_descriptor_row_id, policy_order, binding_id, source_binding_bytes, " + + "source_binding_digest, projection_bytes, projection_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")) { + statement.setString(1, owner.targetNamespace()); + statement.setObject(2, tenantId); + statement.setString(3, requestId); + statement.setLong(4, owner.descriptorRowId()); + statement.setInt(5, 0); + statement.setObject(6, bindingId); + statement.setBytes(7, sourceBytes); + statement.setString(8, sourceDigest); + statement.setBytes(9, projectionBytes); + statement.setString(10, projectionDigest); + assertThat(statement.executeUpdate()).isEqualTo(1); + } + + DSLContext dsl = DSL.using(connection, SQLDialect.POSTGRES); + assertThat( + dsl.fetchValue( + "SELECT count(*) FROM pg_constraint " + + "WHERE conrelid = to_regclass(" + + "'game_design_start_session_authored_actor_core_projection') " + + "AND contype = 'f'")) + .isEqualTo(2L); + var retained = new StartSessionAuthoredActorCoreProjectionRepository(dsl).findByOwner(owner); + assertThat(retained).hasSize(1); + assertThat(retained.getFirst().targetNamespace()).isEqualTo(owner.targetNamespace()); + assertThat(retained.getFirst().canonicalTenantId()).isEqualTo(tenantId); + assertThat(retained.getFirst().controlPlaneRequestId()).isEqualTo(requestId); + assertThat(retained.getFirst().descriptorRowId()).isEqualTo(owner.descriptorRowId()); + assertThat(retained.getFirst().bindingId()).isEqualTo(bindingId); + assertThat(retained.getFirst().sourceBindingBytes()).isEqualTo(sourceBytes); + assertThat(retained.getFirst().sourceBindingDigest()).isEqualTo(sourceDigest); + assertThat(retained.getFirst().projectionBytes()).isEqualTo(projectionBytes); + assertThat(retained.getFirst().projectionDigest()).isEqualTo(projectionDigest); + connection.commit(); + } + + assertThatThrownBy( + () -> + mutate( + dataSource, + schema, + "UPDATE game_design_start_session_authored_actor_core_projection SET policy_order = 1")) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("insert-only"); + assertThatThrownBy( + () -> + mutate( + dataSource, + schema, + "DELETE FROM game_design_start_session_authored_actor_core_projection")) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("insert-only"); + assertThatThrownBy( + () -> + mutate( + dataSource, + schema, + "TRUNCATE game_design_start_session_authored_actor_core_projection")) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("retained"); + } + + private static DriverManagerDataSource dataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(POSTGRES.getJdbcUrl()); + dataSource.setUsername(POSTGRES.getUsername()); + dataSource.setPassword(POSTGRES.getPassword()); + return dataSource; + } + + private static Binding owner(UUID tenantId, String requestId) { + return new Binding( + "world-runtime", + tenantId, + requestId, + 987654321L, + 123456789L, + 3L, + new byte[] {1}, + UUID.randomUUID(), + 1L, + 7L, + UUID.randomUUID(), + UUID.randomUUID(), + "synthetic-workflow", + digest('a'), + digest('b'), + UUID.randomUUID(), + digest('c'), + "synthetic-world", + 1L, + "EMPTY_V1", + "synthetic-game-logic-request", + digest('d'), + digest('e'), + digest('f'), + new byte[] {1}, + LocalDateTime.of(2026, 10, 11, 0, 0)); + } + + private static void setSearchPath(Connection connection, String schema) throws SQLException { + try (Statement statement = connection.createStatement()) { + statement.execute("SET search_path TO " + schema); + } + } + + private static void mutate(DriverManagerDataSource dataSource, String schema, String sql) { + try (Connection connection = dataSource.getConnection()) { + setSearchPath(connection, schema); + DSL.using(connection, SQLDialect.POSTGRES).execute(sql); + } catch (SQLException failure) { + throw new IllegalStateException("Could not open PostgreSQL mutation connection", failure); + } + } + + private static String sha256(byte[] bytes) throws java.security.NoSuchAlgorithmException { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(bytes); + return "sha256:" + java.util.HexFormat.of().formatHex(digest); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java index 2649cdb0e7..5667af98f1 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java @@ -208,8 +208,20 @@ void resolvesPersistedSourceAndReplaysOriginalDescriptorAfterDefaultsAndVersionC newDraft.setNotes("new mutable template default"); newDraft.setUpdatedAt(LocalDateTime.now()); newDraft = versionRepository.save(newDraft); - fixture.template().setDefaultVersionId(newDraft.getId()); + fixture.template().setDefaultRuntimeFlagsJson("{\"changed\":true}"); gameTemplateRepository.save(fixture.template()); + fixture.template().setDefaultVersionId(newDraft.getId()); + assertThatThrownBy(() -> gameTemplateRepository.save(fixture.template())) + .isInstanceOf(DataIntegrityViolationException.class) + .hasStackTraceContaining( + "unqualified template cannot be reassigned into managed source target"); + GameTemplate retainedTemplate = + gameTemplateRepository + .findByTenantIdAndId(fixture.privateSourceTenantKey(), fixture.template().getId()) + .orElseThrow(); + assertThat(retainedTemplate.getDefaultVersionId()).isEqualTo(fixture.version().getId()); + assertThat(retainedTemplate.getDefaultRuntimeFlagsJson()).isEqualTo("{\"changed\":true}"); + fixture.template().setDefaultVersionId(fixture.version().getId()); fixture.version().setVersionState(VersionLifecycleState.RETIRED); fixture.version().setVersionStateEpoch(2L); versionRepository.save(fixture.version()); @@ -515,6 +527,241 @@ void rolledBackDescriptorInsertLeavesNoCanonicalOrPrivateRequestClaim() { .isEqualTo(evidence.requestDigest()); } + @Test + void v39MigrationPreservesRetainedPublicationEvidenceAndStoresLongDiagnostics() { + String schema = "game_design_publication_text_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = isolatedDataSource(schema); + migrate(dataSource, schema, MigrationVersion.fromVersion("34.1")); + DSLContext isolatedDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + + String tenantId = privateTenantKey(); + String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 12); + // Synthetic pre-identity rows seed migration preservation only; no source identity is inferred. + long versionId = + requiredId( + isolatedDsl + .resultQuery( + "INSERT INTO version " + + "(tenant_id, version_number, version_state, version_state_epoch) " + + "VALUES (?, 1, 'PUBLISHED', 7) RETURNING id", + tenantId) + .fetchOne(0, Long.class), + "retained Version"); + long templateId = + requiredId( + isolatedDsl + .resultQuery( + "INSERT INTO game_templates (tenant_id, name, config) " + + "VALUES (?, ?, '{}'::jsonb) RETURNING id", + tenantId, + "Retained Publication Template " + suffix) + .fetchOne(0, Long.class), + "retained Game Template"); + String generationRevision = "retained-generation-rév-🧭-" + suffix; + long bundleId = + requiredId( + isolatedDsl + .resultQuery( + "INSERT INTO published_release_bundle " + + "(tenant_id, version_id, version_number, attestation_schema_version, " + + "publish_workflow_id, manifest_hash, required_manifest_asset_keys_json, " + + "participant_digests_json, generation_config_revision) " + + "VALUES (?, ?, 1, 'v1', ?, ?, '[]', '[]', ?) RETURNING id", + tenantId, + versionId, + "v38-retained-bundle-" + suffix, + "sha256:" + "f".repeat(64), + generationRevision) + .fetchOne(0, Long.class), + "retained release bundle"); + long descriptorId = + requiredId( + isolatedDsl + .resultQuery( + "INSERT INTO launch_descriptor " + + "(launch_descriptor_id, tenant_id, game_template_id, " + + "control_plane_request_id, request_hash, version_id, runtime_flags_json, " + + "generation_config_revision, version_state_epoch, release_bundle_id, " + + "published_release_bundle_ref) " + + "VALUES (?, ?, ?, ?, ?, ?, '{}', ?, 7, ?, ?) RETURNING id", + "ld-v38-retained-" + suffix, + tenantId, + templateId, + "v38-retained-request-" + suffix, + "retained-request-hash-" + suffix, + versionId, + generationRevision, + bundleId, + "retained-release-ref-" + suffix) + .fetchOne(0, Long.class), + "retained launch descriptor"); + + migrate(dataSource, schema, MigrationVersion.fromVersion("38")); + String retainedFailure = "retained-failure-雪-" + suffix; + String retainedArtifactError = "retained-artifact-error-🧭-" + suffix; + String attemptWorkflowId = "v38-retained-attempt-" + suffix; + long attemptId = + requiredId( + isolatedDsl + .resultQuery( + "INSERT INTO publish_attempt " + + "(tenant_id, publish_workflow_id, publish_type, status, version_id, " + + "version_number, failure_code, failure_message, completed_at) " + + "VALUES (?, ?, 'FULL_VERSION', 'FAILED', ?, 1, 'PUBLISH_FAILED', ?, " + + "TIMESTAMP '2026-09-30 12:34:56') RETURNING id", + tenantId, + attemptWorkflowId, + versionId, + retainedFailure) + .fetchOne(0, Long.class), + "retained publish attempt"); + long artifactId = + requiredId( + isolatedDsl + .resultQuery( + "INSERT INTO version_asset_artifact " + + "(tenant_id, version_id, artifact_state, state_epoch, " + + "exported_version_number, manifest_hash, last_workflow_id, " + + "last_error_code, last_error_message) " + + "VALUES (?, ?, 'FAILED', 11, 1, ?, ?, 'PUBLISH_FAILED', ?) RETURNING id", + tenantId, + versionId, + "sha256:" + "a".repeat(64), + "v38-retained-artifact-" + suffix, + retainedArtifactError) + .fetchOne(0, Long.class), + "retained version asset artifact"); + + Map> retainedRows = + publicationEvidenceRows( + isolatedDsl, versionId, bundleId, descriptorId, attemptId, artifactId); + var retainedHistory = migrationHistoryRows(isolatedDsl); + migrate(dataSource, schema, MigrationVersion.fromVersion("39")); + assertRetainedMigrationHistory(isolatedDsl, retainedHistory); + Map> v39Rows = + publicationEvidenceRows( + isolatedDsl, versionId, bundleId, descriptorId, attemptId, artifactId); + assertThat(priorPublicationEvidenceColumns(v39Rows, retainedRows)).isEqualTo(retainedRows); + assertThat( + requiredSnapshot(retainedRows, "published_release_bundle") + .get("generation_config_revision")) + .isEqualTo(generationRevision); + assertThat( + requiredSnapshot(retainedRows, "launch_descriptor").get("generation_config_revision")) + .isEqualTo(generationRevision); + assertThat(requiredSnapshot(retainedRows, "publish_attempt").get("failure_message")) + .isEqualTo(retainedFailure); + assertThat(requiredSnapshot(retainedRows, "version_asset_artifact").get("last_error_message")) + .isEqualTo(retainedArtifactError); + + String longFailure = "complete-failure-雪-" + "f".repeat(540); + String longArtifactError = "complete-artifact-error-🧭-" + "e".repeat(540); + isolatedDsl.execute( + "UPDATE publish_attempt SET failure_message = ? WHERE id = ?", longFailure, attemptId); + isolatedDsl.execute( + "UPDATE version_asset_artifact SET last_error_message = ? WHERE id = ?", + longArtifactError, + artifactId); + Map> v39LongDiagnosticsRows = + publicationEvidenceRows( + isolatedDsl, versionId, bundleId, descriptorId, attemptId, artifactId); + assertThat(requiredSnapshot(v39LongDiagnosticsRows, "publish_attempt").get("failure_message")) + .isEqualTo(longFailure); + assertThat( + requiredSnapshot(v39LongDiagnosticsRows, "version_asset_artifact") + .get("last_error_message")) + .isEqualTo(longArtifactError); + assertThat( + requiredRow( + isolatedDsl, + "SELECT failure_message FROM publish_attempt WHERE id = ?", + attemptId, + "long publish-attempt failure readback") + .get("failure_message")) + .isEqualTo(longFailure); + assertThat( + requiredRow( + isolatedDsl, + "SELECT last_error_message FROM version_asset_artifact WHERE id = ?", + artifactId, + "long artifact-error readback") + .get("last_error_message")) + .isEqualTo(longArtifactError); + assertThat( + requiredRow( + isolatedDsl, + "SELECT status, version_number FROM publish_attempt WHERE id = ?", + attemptId, + "publish-attempt state readback")) + .containsEntry("status", "FAILED") + .containsEntry("version_number", 1); + assertThat( + requiredRow( + isolatedDsl, + "SELECT artifact_state, state_epoch FROM version_asset_artifact WHERE id = ?", + artifactId, + "artifact state readback")) + .containsEntry("artifact_state", "FAILED") + .containsEntry("state_epoch", 11L); + + var v39History = migrationHistoryRows(isolatedDsl); + migrate(dataSource, schema, null); + assertRetainedMigrationHistory(isolatedDsl, v39History); + Map> migratedRows = + publicationEvidenceRows( + isolatedDsl, versionId, bundleId, descriptorId, attemptId, artifactId); + assertThat(priorPublicationEvidenceColumns(migratedRows, v39LongDiagnosticsRows)) + .isEqualTo(v39LongDiagnosticsRows); + assertThat(requiredSnapshot(migratedRows, "publish_attempt").get("revision")).isEqualTo(1L); + assertThat( + requiredSnapshot(migratedRows, "published_release_bundle") + .get("world_published_start_location_evidence_json")) + .isNull(); + var publicationOperationCount = + isolatedDsl.fetchOne( + "SELECT count(*) FROM game_design_publication_operation WHERE publish_workflow_id = ?", + attemptWorkflowId); + if (publicationOperationCount == null) { + throw new IllegalStateException("Publication operation count query returned no row"); + } + Long publicationOperationCountValue = publicationOperationCount.get(0, Long.class); + if (publicationOperationCountValue == null) { + throw new IllegalStateException("Publication operation count query returned no count"); + } + assertThat(publicationOperationCountValue).isZero(); + assertThat(requiredSnapshot(migratedRows, "publish_attempt").get("failure_message")) + .isEqualTo(longFailure); + assertThat(requiredSnapshot(migratedRows, "version_asset_artifact").get("last_error_message")) + .isEqualTo(longArtifactError); + + assertThatThrownBy( + () -> + isolatedDsl.execute( + "UPDATE publish_attempt SET failure_message = ? WHERE id = ?", + "forbidden-terminal-rewrite-" + suffix, + attemptId)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasStackTraceContaining("publish attempt is stale or terminal"); + Map> afterRejectedTerminalRewrite = + publicationEvidenceRows( + isolatedDsl, versionId, bundleId, descriptorId, attemptId, artifactId); + assertThat(afterRejectedTerminalRewrite).isEqualTo(migratedRows); + var publicationOperationCountAfterRejectedRewrite = + isolatedDsl.fetchOne( + "SELECT count(*) FROM game_design_publication_operation WHERE publish_workflow_id = ?", + attemptWorkflowId); + if (publicationOperationCountAfterRejectedRewrite == null) { + throw new IllegalStateException("Publication operation count query returned no row"); + } + Long publicationOperationCountAfterRejectedRewriteValue = + publicationOperationCountAfterRejectedRewrite.get(0, Long.class); + if (publicationOperationCountAfterRejectedRewriteValue == null) { + throw new IllegalStateException("Publication operation count query returned no count"); + } + assertThat(publicationOperationCountAfterRejectedRewriteValue).isZero(); + } + @Test void v35AndV36MigrationsPreserveRetainedBundleAndUnboundDescriptorWithoutBackfill() { String schema = "game_design_launch_history_" + UUID.randomUUID().toString().replace("-", ""); @@ -601,7 +848,92 @@ void v35AndV36MigrationsPreserveRetainedBundleAndUnboundDescriptorWithoutBackfil Map retainedBundleSnapshot = retainedReleaseBundleSnapshot(isolatedDsl, bundleId); + long retainedVersionId = requiredId(versionId, "retained Version"); + long retainedDescriptorId = + requiredId((Long) retainedV34Snapshot.get("id"), "retained launch descriptor"); + java.util.function.Supplier>> readRetainedRows = + () -> + Map.of( + "version", + requiredRow( + isolatedDsl, + "SELECT *, xmin::text AS xmin FROM version WHERE id = ?", + retainedVersionId, + "retained Version"), + "published_release_bundle", + requiredRow( + isolatedDsl, + "SELECT *, xmin::text AS xmin FROM published_release_bundle WHERE id = ?", + bundleId, + "retained release bundle"), + "launch_descriptor", + requiredRow( + isolatedDsl, + "SELECT *, xmin::text AS xmin FROM launch_descriptor WHERE id = ?", + retainedDescriptorId, + "retained launch descriptor")); + var priorRows = readRetainedRows.get(); + var priorHistory = migrationHistoryRows(isolatedDsl); + for (String target : java.util.List.of("35", "35.1", "35.2", "36", "38")) { + MigrationVersion targetVersion = MigrationVersion.fromVersion(target); + migrate(dataSource, schema, targetVersion); + var after = readRetainedRows.get(); + assertThat(priorPublicationEvidenceColumns(after, priorRows)) + .as("retained columns and xmin through V%s", target) + .isEqualTo(priorRows); + assertRetainedMigrationHistory(isolatedDsl, priorHistory); + for (String column : + java.util.List.of( + "descriptor_schema_version", + "target_namespace", + "canonical_tenant_id", + "authored_world_source_tenant_slug", + "world_slug", + "authored_world_source_operation_id", + "authored_world_source_game_row_id", + "authored_world_source_game_tenant_key", + "authored_world_source_provenance_kind", + "authored_world_source_evidence_digest", + "request_digest", + "result_digest", + "original_request_json", + "source_evidence_json", + "failure_code", + "failure_message")) { + assertThat(requiredSnapshot(after, "launch_descriptor")).containsEntry(column, null); + } + assertThat(requiredSnapshot(after, "launch_descriptor")) + .containsEntry("outcome_status", "SUCCESS"); + if (targetVersion.compareTo(MigrationVersion.fromVersion("35.1")) >= 0) { + assertThat(requiredSnapshot(after, "version")) + .containsEntry("canonical_version_id", null) + .containsEntry("canonical_tenant_id", null) + .containsEntry("identity_source_game_row_id", null) + .containsEntry("identity_source_game_tenant_key", null) + .containsEntry("identity_source_provenance_kind", null); + } + if (targetVersion.compareTo(MigrationVersion.fromVersion("35.2")) >= 0) { + assertThat(requiredSnapshot(after, "published_release_bundle")) + .containsEntry("canonical_version_id", null) + .containsEntry("canonical_tenant_id", null); + } + if (targetVersion.compareTo(MigrationVersion.fromVersion("36")) >= 0) { + assertThat(requiredSnapshot(after, "published_release_bundle")) + .containsEntry("published_release_bundle_ref", null); + } + if (targetVersion.compareTo(MigrationVersion.fromVersion("38")) >= 0) { + assertThat(requiredSnapshot(after, "published_release_bundle")) + .containsEntry("manifest_schema_version", null) + .containsEntry("artifact_digests_json", null); + } + priorRows = after; + priorHistory = migrationHistoryRows(isolatedDsl); + } migrate(dataSource, schema, null); + var retainedCurrentRows = readRetainedRows.get(); + assertThat(priorPublicationEvidenceColumns(retainedCurrentRows, priorRows)) + .isEqualTo(priorRows); + assertRetainedMigrationHistory(isolatedDsl, priorHistory); LaunchDescriptorRepository launchRepository = new LaunchDescriptorRepository(isolatedDsl); var retainedBundleReference = isolatedDsl.fetchOne( @@ -665,6 +997,7 @@ void v35AndV36MigrationsPreserveRetainedBundleAndUnboundDescriptorWithoutBackfil .isEmpty(); assertRetainedRowUnchanged( before, launchRepository.findByPrivateRequest(privateTenantKey, requestId).orElseThrow()); + assertThat(readRetainedRows.get()).isEqualTo(retainedCurrentRows); assertThatThrownBy( () -> @@ -676,6 +1009,7 @@ void v35AndV36MigrationsPreserveRetainedBundleAndUnboundDescriptorWithoutBackfil .hasStackTraceContaining("launch descriptors are immutable"); assertRetainedRowUnchanged( before, launchRepository.findByPrivateRequest(privateTenantKey, requestId).orElseThrow()); + assertThat(readRetainedRows.get()).isEqualTo(retainedCurrentRows); } private Fixture fixture(String controlPlaneRequestId) { @@ -1083,6 +1417,97 @@ var record = return record.intoMap(); } + private Map> publicationEvidenceRows( + DSLContext isolatedDsl, + long versionId, + long bundleId, + long descriptorId, + long attemptId, + long artifactId) { + return Map.of( + "version", + requiredRow( + isolatedDsl, + "SELECT *, xmin::text AS xmin FROM version WHERE id = ?", + versionId, + "Version"), + "published_release_bundle", + requiredRow( + isolatedDsl, + "SELECT *, xmin::text AS xmin FROM published_release_bundle WHERE id = ?", + bundleId, + "published release bundle"), + "launch_descriptor", + requiredRow( + isolatedDsl, + "SELECT *, xmin::text AS xmin FROM launch_descriptor WHERE id = ?", + descriptorId, + "launch descriptor"), + "publish_attempt", + requiredRow( + isolatedDsl, + "SELECT *, xmin::text AS xmin FROM publish_attempt WHERE id = ?", + attemptId, + "publish attempt"), + "version_asset_artifact", + requiredRow( + isolatedDsl, + "SELECT *, xmin::text AS xmin FROM version_asset_artifact WHERE id = ?", + artifactId, + "version asset artifact")); + } + + // Compare every column that existed before the migration, including xmin. New columns + // remain separate facts and are never interpreted as manufactured historical authority. + private Map> priorPublicationEvidenceColumns( + Map> snapshots, Map> prior) { + Map> projected = new java.util.LinkedHashMap<>(); + prior.forEach( + (table, before) -> { + var after = requiredSnapshot(snapshots, table); + assertThat(after.keySet()).containsAll(before.keySet()); + Map columns = new java.util.LinkedHashMap<>(); + before.keySet().forEach(column -> columns.put(column, after.get(column))); + projected.put(table, columns); + }); + return projected; + } + + private java.util.List> migrationHistoryRows(DSLContext sql) { + return sql.fetch("SELECT * FROM " + FLYWAY_TABLE + " ORDER BY installed_rank").intoMaps(); + } + + private void assertRetainedMigrationHistory( + DSLContext sql, java.util.List> prior) { + var current = migrationHistoryRows(sql); + assertThat(current).containsAll(prior); + } + + private Map requiredRow( + DSLContext isolatedDsl, String query, long rowId, String description) { + var row = isolatedDsl.fetchOne(query, rowId); + if (row == null) { + throw new IllegalStateException(description + " readback is absent"); + } + return row.intoMap(); + } + + private Map requiredSnapshot( + Map> snapshots, String description) { + Map snapshot = snapshots.get(description); + if (snapshot == null) { + throw new IllegalStateException(description + " snapshot is absent"); + } + return snapshot; + } + + private long requiredId(Long id, String description) { + if (id == null) { + throw new IllegalStateException(description + " insert returned no identity"); + } + return id; + } + private String privateTenantKey() { return "src-" + UUID.randomUUID().toString().replace("-", ""); } diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceTest.java new file mode 100644 index 0000000000..0080bc3335 --- /dev/null +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceTest.java @@ -0,0 +1,637 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.gamedesign.AssetSource; +import net.firedevops.firemud.common.gamedesign.BrandingSource; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; +import net.firedevops.firemud.common.gamedesign.TemplateConfigOwnerSourceInventoryDeclaration; +import org.junit.jupiter.api.Test; + +class TemplateConfigSourceTest { + private static final UUID TENANT = UUID.randomUUID(); + private static final UUID VERSION = UUID.randomUUID(); + + @Test + void closedDocumentRequiresEveryExplicitCollectionAndRejectsRecursiveEvidence() { + String valid = config(); + assertThat(new TemplateConfigSource.Config(valid).baseVersionId()).isEqualTo(VERSION); + for (String invalid : + List.of( + valid.replace("\"supportedSettings\":[]", "\"unknown\":[]"), + valid.replace("\"inputs\":[]", "\"inputs\":[],\"receipt\":{}"), + valid.replace("\"inputs\":[]", "\"inputs\":[],\"bindingJson\":\"recursive\""), + valid.replace("\"inputs\":[]", "\"inputs\":[],\"commitDigest\":\"recursive\""), + valid.replace("\"schemaVersion\":1", "\"schemaVersion\":1,\"schemaVersion\":1"), + valid.replace("\"schemaVersion\":1", "\"schemaVersion\":2"), + valid.replace( + "\"supportedSettings\":[]", + "\"supportedSettings\":[{\"defaultRuntimeFlagsJson\":\"{}\"}]"), + valid.replace("\"scriptPatch\":{\"presence\":\"ABSENT\"}", "\"scriptPatch\":null"), + valid + "{}")) + assertThatThrownBy(() -> new TemplateConfigSource.Config(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void canonicalOwnerUuidSyntaxCannotQualifyWorldEntityOrAutomationReferences() { + String ownerId = UUID.randomUUID().toString(); + var world = + new TemplateConfigSource.Config( + config() + .replace( + "\"regions\":[]", "\"regions\":[{\"regionTemplateId\":\"" + ownerId + "\"}]")); + var entity = + new TemplateConfigSource.Config( + config() + .replace("\"items\":[]", "\"items\":[{\"entityTemplateId\":\"" + ownerId + "\"}]")); + var scripts = + new TemplateConfigSource.Config( + config() + .replace( + "\"scripts\":[]", + "\"scripts\":[{\"scriptId\":\"onEnter\",\"eventBindings\":[]}]")); + var patch = + new TemplateConfigSource.Config( + config() + .replace( + "{\"presence\":\"ABSENT\"}", + "{\"presence\":\"PRESENT\",\"scriptPatchVersion\":\" raw-patch-1 \"}")); + assertThatThrownBy(world::requireAvailableOwnerReads) + .hasMessage("TEMPLATE_CONFIG_WORLD_EXACT_OWNER_READ_UNAVAILABLE"); + assertThatThrownBy(entity::requireAvailableOwnerReads) + .hasMessage("TEMPLATE_CONFIG_ENTITY_EXACT_OWNER_READ_UNAVAILABLE"); + assertThatThrownBy(scripts::requireAvailableOwnerReads) + .hasMessage("TEMPLATE_CONFIG_AUTOMATION_EXACT_OWNER_READ_UNAVAILABLE"); + assertThatThrownBy(patch::requireAvailableOwnerReads) + .hasMessage("TEMPLATE_CONFIG_AUTOMATION_EXACT_OWNER_READ_UNAVAILABLE"); + assertThatThrownBy( + () -> + new TemplateConfigSource.Config( + config().replace("\"items\":[]", "\"equipment\":[]"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new TemplateConfigSource.Config( + config() + .replace("\"regions\":[]", "\"regions\":[{\"regionTemplateId\":\"7\"}]"))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void actualGeneratedRowAndOriginalRevisionRemainSeparateFromAuthoredPreimage() { + var create = + binding( + TemplateConfigSource.createPayload( + "Starter", new TemplateConfigSource.Config(config()))); + var revision = create.revisions().getFirst().revisionId(); + assertThat(TemplateConfigSource.mutations(create).getFirst().templateId()).isNull(); + assertThatThrownBy(() -> TemplateConfigSource.replay(List.of(), create, Map.of())) + .isInstanceOf(NullPointerException.class); + var entries = TemplateConfigSource.replay(List.of(), create, Map.of(revision, "7")); + var sibling = binding(CommandSource.deletePayload("absent")); + var inherited = TemplateConfigSource.replay(entries, sibling, Map.of()); + assertThat(inherited.getFirst().sourceBinding()).isSameAs(create); + var snapshot = + new TemplateConfigSourceSnapshot( + sibling, "1", create.commitId(), UUID.randomUUID(), inherited); + assertThat(TemplateConfigSourceSnapshot.fromStored(snapshot.canonicalJson())) + .isEqualTo(snapshot); + assertThatThrownBy( + () -> + TemplateConfigSource.replay( + List.of(), binding(TemplateConfigSource.deletePayload("7")), Map.of())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + TemplateConfigSource.replay( + List.of(), + binding( + TemplateConfigSource.upsertPayload( + "7", new TemplateConfigSource.Config(config()))), + Map.of())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void siblingDispatchDoesNotInventUnknownSourceKindsOrChangeOriginalBinding() { + var binding = + binding( + TemplateConfigSource.createPayload( + "Starter", new TemplateConfigSource.Config(config())), + CommandSource.deletePayload("absent")); + assertThat(TemplateConfigSource.mutations(binding).getFirst().binding()).isSameAs(binding); + assertThat(CommandSource.mutations(binding)).hasSize(1); + assertThat(AssetSource.mutations(binding)).isEmpty(); + assertThat(BrandingSource.mutations(binding)).isEmpty(); + assertThat(GameplayRuleSource.mutations(binding)).isEmpty(); + assertThat(CommandSource.hasRealmPolicyRevision(binding)).isFalse(); + String wrongBase = config().replace(VERSION.toString(), UUID.randomUUID().toString()); + assertThatThrownBy( + () -> + TemplateConfigSource.mutations( + binding( + TemplateConfigSource.createPayload( + "Starter", new TemplateConfigSource.Config(wrongBase))))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void automationInventoryUsesItsExactVersionedOperationAndPreservesLegacySnapshotBytes() { + var inventory = AutomationAuthoredSourceInventoryDeclaration.parse(automationInventory()); + String payload = + TemplateConfigSource.ownerInventoryPayload( + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, inventory); + assertThat(CommandSource.tree(payload).path("schemaVersion").intValue()).isEqualTo(2); + assertThat(CommandSource.tree(payload).path("inventory").isObject()).isTrue(); + assertThat(payload).doesNotContain("inventoryJson"); + var authored = binding(payload); + var mutation = TemplateConfigSource.mutations(authored).getFirst(); + assertThat(mutation.operation()) + .isEqualTo(TemplateConfigSource.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY); + assertThat(mutation.templateId()).isNull(); + assertThat(mutation.templateName()).isNull(); + assertThat(mutation.config()).isNull(); + + var declarations = TemplateConfigSource.replayOwnerInventoryDeclarations(List.of(), authored); + var inherited = + TemplateConfigSource.replayOwnerInventoryDeclarations( + declarations, binding(CommandSource.deletePayload("absent"))); + assertThat(inherited).containsExactly(declarations.getFirst()); + assertThat(inherited.getFirst().sourceBinding()).isSameAs(authored); + + var oldBinding = + binding( + TemplateConfigSource.createPayload( + "Starter", new TemplateConfigSource.Config(config()))); + var oldEntries = + TemplateConfigSource.replay( + List.of(), oldBinding, Map.of(oldBinding.revisions().getFirst().revisionId(), "7")); + var oldSnapshot = + new TemplateConfigSourceSnapshot(oldBinding, "1", null, UUID.randomUUID(), oldEntries); + String legacySnapshotBytes = + CommandSource.canonical( + Map.of( + "schema", + TemplateConfigSourceSnapshot.SCHEMA, + "bindingJson", + oldBinding.canonicalJson(), + "bindingDigest", + oldBinding.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + oldSnapshot.genesisReceiptId().toString(), + "entries", + oldEntries.stream().map(TemplateConfigSource.Entry::object).toList())); + assertThat(oldSnapshot.canonicalJson()).isEqualTo(legacySnapshotBytes); + assertThat(oldSnapshot.canonicalJson()) + .contains("\"schema\":\"game-design-template-config-source-snapshot/v1\"") + .doesNotContain("ownerSourceInventoryDeclarations"); + assertThat(TemplateConfigSourceSnapshot.fromStored(oldSnapshot.canonicalJson())) + .isEqualTo(oldSnapshot); + + var v2Snapshot = + new TemplateConfigSourceSnapshot( + authored, "1", null, UUID.randomUUID(), List.of(), declarations); + assertThat(v2Snapshot.canonicalJson()) + .contains("\"schema\":\"game-design-template-config-source-snapshot/v2\"") + .contains("ownerSourceInventoryDeclarations") + .contains(authored.requestId().toString()) + .contains(authored.commitId().toString()); + assertThat(TemplateConfigSourceSnapshot.fromStored(v2Snapshot.canonicalJson())) + .isEqualTo(v2Snapshot); + } + + @Test + void ownerInventoryOperationRejectsMissingUnknownAndUnsupportedContent() { + var inventory = AutomationAuthoredSourceInventoryDeclaration.parse(automationInventory()); + String valid = + TemplateConfigSource.ownerInventoryPayload( + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, inventory); + String missingInventory = + CommandSource.canonical( + Map.of( + "schemaVersion", + 2, + "revisionKind", + TemplateConfigSource.REVISION_KIND, + "operation", + "DECLARE_OWNER_SOURCE_INVENTORY", + "owner", + "AUTOMATION_SCRIPTING")); + assertThatThrownBy(() -> TemplateConfigSource.mutations(binding(missingInventory))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + TemplateConfigSource.mutations( + binding(valid.replace("AUTOMATION_SCRIPTING", "ENTITY_MANAGEMENT")))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AutomationAuthoredSourceInventoryDeclaration.parse( + automationInventory() + .replace("\"SCRIPT_DEFINITIONS\":[]", "\"SCRIPT_DEFINITIONS\":[{}]"))) + .isInstanceOf(IllegalArgumentException.class); + assertThat( + TemplateConfigSourceSnapshot.fromStored( + new TemplateConfigSourceSnapshot( + binding(CommandSource.deletePayload("absent")), + "0", + null, + UUID.randomUUID(), + List.of()) + .canonicalJson()) + .ownerSourceInventoryDeclarations()) + .isEmpty(); + } + + @Test + void entityInventoryUsesClosedTypedOperationAndRejectsOwnerContentSubstitution() { + var entity = EntityAuthoredSourceInventoryDeclaration.parse(entityInventory()); + String payload = + TemplateConfigSource.ownerInventoryPayload( + DraftCommitBinding.Owner.ENTITY_MANAGEMENT, entity); + assertThat(CommandSource.tree(payload).path("schemaVersion").intValue()).isEqualTo(3); + assertThat(CommandSource.tree(payload).path("inventory").isObject()).isTrue(); + var authored = binding(payload); + var mutation = TemplateConfigSource.mutations(authored).getFirst(); + assertThat(mutation.declaredOwner()).isEqualTo(DraftCommitBinding.Owner.ENTITY_MANAGEMENT); + assertThat(mutation.inventory()).isNull(); + assertThat(mutation.entityInventory()).isEqualTo(entity); + assertThat(mutation.templateId()).isNull(); + assertThat(mutation.config()).isNull(); + + var automation = AutomationAuthoredSourceInventoryDeclaration.parse(automationInventory()); + String autoContentUnderEntity = + typedInventoryPayload(3, "ENTITY_MANAGEMENT", automation.canonicalJson()); + String entityContentUnderAutomation = + typedInventoryPayload(2, "AUTOMATION_SCRIPTING", entity.canonicalJson()); + for (String substituted : List.of(autoContentUnderEntity, entityContentUnderAutomation)) + assertThatThrownBy(() -> TemplateConfigSource.mutations(binding(substituted))) + .isInstanceOf(IllegalArgumentException.class); + String missingEntityInventory = + CommandSource.canonical( + Map.of( + "schemaVersion", + 3, + "revisionKind", + TemplateConfigSource.REVISION_KIND, + "operation", + "DECLARE_OWNER_SOURCE_INVENTORY", + "owner", + "ENTITY_MANAGEMENT")); + assertThatThrownBy(() -> TemplateConfigSource.mutations(binding(missingEntityInventory))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + EntityAuthoredSourceInventoryDeclaration.parse( + entityInventory() + .replace("\"ITEM_TEMPLATE_ROOTS\":[]", "\"ITEM_TEMPLATE_ROOTS\":[{}]"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + EntityAuthoredSourceInventoryDeclaration.parse( + entityInventory().replace("\"families\":{", "\"families\":{\"UNKNOWN\":[],"))) + .isInstanceOf(IllegalArgumentException.class); + + var declarations = TemplateConfigSource.replayOwnerInventoryDeclarations(List.of(), authored); + var bothOwners = + TemplateConfigSource.replayOwnerInventoryDeclarations( + declarations, + binding( + TemplateConfigSource.ownerInventoryPayload( + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, automation))); + assertThat(bothOwners) + .extracting(TemplateConfigOwnerSourceInventoryDeclaration::owner) + .containsExactly( + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, + DraftCommitBinding.Owner.ENTITY_MANAGEMENT); + assertThat(bothOwners.get(1).entityInventory()).isEqualTo(entity); + assertThat(bothOwners.get(1).sourceBinding()).isEqualTo(authored); + var snapshot = + new TemplateConfigSourceSnapshot( + authored, "1", null, UUID.randomUUID(), List.of(), declarations); + assertThat(TemplateConfigSourceSnapshot.fromStored(snapshot.canonicalJson())) + .isEqualTo(snapshot); + assertThat(snapshot.canonicalJson()).contains("ITEM_TEMPLATE_ROOTS"); + } + + @Test + void sharedAndGdPayloadsMatchIndependentExistingEncodings() throws Exception { + var gd = new TemplateConfigSource.Config(config()); + var shared = + new net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues.Config(config()); + String expectedConfig = independentCanonical(CommandSource.tree(config())); + assertThat(gd.canonicalJson()).isEqualTo(expectedConfig); + assertThat(shared.canonicalJson()).isEqualTo(expectedConfig); + for (String operation : List.of("CREATE", "UPSERT", "DELETE")) { + Map expected = new java.util.LinkedHashMap<>(); + expected.put("schemaVersion", 1); + expected.put("revisionKind", "TEMPLATE_CONFIG"); + expected.put("operation", operation); + expected.put( + operation.equals("CREATE") ? "templateName" : "templateId", + operation.equals("CREATE") ? "Starter" : "7"); + if (!operation.equals("DELETE")) expected.put("configJson", expectedConfig); + String expectedPayload = independentCanonical(expected); + String gdPayload = + switch (operation) { + case "CREATE" -> TemplateConfigSource.createPayload("Starter", gd); + case "UPSERT" -> TemplateConfigSource.upsertPayload("7", gd); + default -> TemplateConfigSource.deletePayload("7"); + }; + String sharedPayload = + switch (operation) { + case "CREATE" -> + net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues.createPayload( + "Starter", shared); + case "UPSERT" -> + net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues.upsertPayload( + "7", shared); + default -> + net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues.deletePayload( + "7"); + }; + assertThat(gdPayload).isEqualTo(expectedPayload); + assertThat(sharedPayload).isEqualTo(expectedPayload); + } + var automation = AutomationAuthoredSourceInventoryDeclaration.parse(automationInventory()); + var entity = EntityAuthoredSourceInventoryDeclaration.parse(entityInventory()); + for (var owner : + List.of( + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, + DraftCommitBinding.Owner.ENTITY_MANAGEMENT)) { + boolean isAutomation = owner == DraftCommitBinding.Owner.AUTOMATION_SCRIPTING; + String json = isAutomation ? automation.canonicalJson() : entity.canonicalJson(); + String expected = + independentCanonical( + Map.of( + "schemaVersion", + isAutomation ? 2 : 3, + "revisionKind", + "TEMPLATE_CONFIG", + "operation", + "DECLARE_OWNER_SOURCE_INVENTORY", + "owner", + owner.name(), + "inventory", + CommandSource.tree(json))); + String gdPayload = + isAutomation + ? TemplateConfigSource.ownerInventoryPayload(owner, automation) + : TemplateConfigSource.ownerInventoryPayload(owner, entity); + String sharedPayload = + isAutomation + ? net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues + .ownerInventoryPayload(owner, automation) + : net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues + .ownerInventoryPayload(owner, entity); + assertThat(gdPayload).isEqualTo(expected); + assertThat(sharedPayload).isEqualTo(expected); + } + } + + @Test + void adaptersPreserveIndependentV1V2BytesDigestsAndOriginalInheritedProvenance() + throws Exception { + var config = new TemplateConfigSource.Config(config()); + var automation = AutomationAuthoredSourceInventoryDeclaration.parse(automationInventory()); + var entity = EntityAuthoredSourceInventoryDeclaration.parse(entityInventory()); + var original = + binding( + TemplateConfigSource.createPayload("Starter", config), + TemplateConfigSource.ownerInventoryPayload( + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, automation), + TemplateConfigSource.ownerInventoryPayload( + DraftCommitBinding.Owner.ENTITY_MANAGEMENT, entity)); + var entries = + TemplateConfigSource.replay( + List.of(), original, Map.of(original.revisions().getFirst().revisionId(), "7")); + var declarations = TemplateConfigSource.replayOwnerInventoryDeclarations(List.of(), original); + var selected = binding(CommandSource.deletePayload("unrelated")); + for (boolean v2 : List.of(false, true)) { + var retainedDeclarations = + v2 ? declarations : List.of(); + var snapshot = + new TemplateConfigSourceSnapshot( + selected, "1", original.commitId(), UUID.randomUUID(), entries, retainedDeclarations); + var entry = entries.getFirst(); + Map entryObject = + Map.of( + "templateId", + "7", + "configJson", + config.canonicalJson(), + "sourceBindingJson", + original.canonicalJson(), + "sourceBindingDigest", + original.digest(), + "revisionOrder", + entry.revisionOrder(), + "revisionId", + entry.revisionId().toString(), + "createdName", + "Starter"); + var declarationObjects = new ArrayList>(); + for (var declaration : retainedDeclarations) { + var object = + Map.of( + "owner", + declaration.owner().name(), + "inventoryJson", + declaration.inventoryJson(), + "sourceBindingJson", + original.canonicalJson(), + "sourceBindingDigest", + original.digest(), + "revisionOrder", + declaration.revisionOrder(), + "revisionId", + declaration.revisionId().toString()); + declarationObjects.add(object); + assertThat(declaration.object()).isEqualTo(object); + } + var expected = new java.util.LinkedHashMap(); + expected.put( + "schema", + v2 + ? "game-design-template-config-source-snapshot/v2" + : "game-design-template-config-source-snapshot/v1"); + expected.put("bindingJson", selected.canonicalJson()); + expected.put("bindingDigest", selected.digest()); + expected.put("sourceEpoch", "1"); + expected.put("inheritedCommitId", original.commitId().toString()); + expected.put("genesisReceiptId", snapshot.genesisReceiptId().toString()); + expected.put("entries", List.of(entryObject)); + if (v2) expected.put("ownerSourceInventoryDeclarations", declarationObjects); + String json = independentCanonical(expected); + byte[] bytes = json.getBytes(java.nio.charset.StandardCharsets.UTF_8); + String digest = independentDigest(bytes); + var common = + net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot.fromStored(json); + assertThat(entry.object()).isEqualTo(entryObject); + assertThat(snapshot.canonicalJson()).isEqualTo(json); + assertThat(snapshot.canonicalBytes()).isEqualTo(bytes); + assertThat(snapshot.digest()).isEqualTo(digest); + assertThat(common.canonicalBytes()).isEqualTo(bytes); + assertThat(common.digest()).isEqualTo(digest); + assertThat(TemplateConfigSourceSnapshot.fromStored(json)).isEqualTo(snapshot); + assertThat(TemplateConfigSourceSnapshot.fromShared(common)).isEqualTo(snapshot); + assertThat(common.binding()).isEqualTo(selected); + assertThat(common.entries().getFirst().sourceBinding()).isEqualTo(original); + if (v2) + assertThat(common.ownerSourceInventoryDeclarations()) + .extracting( + net.firedevops.firemud.common.gamedesign + .TemplateConfigOwnerSourceInventoryDeclaration + ::sourceBinding) + .containsExactly(original, original); + } + } + + @Test + void applicationAndCaptureFramesRemainExactIndependentLengthPrefixedBytes() throws Exception { + var authored = + binding( + TemplateConfigSource.createPayload( + "Starter", new TemplateConfigSource.Config(config()))); + var entries = + TemplateConfigSource.replay( + List.of(), authored, Map.of(authored.revisions().getFirst().revisionId(), "7")); + var snapshot = + new TemplateConfigSourceSnapshot(authored, "1", null, UUID.randomUUID(), entries); + byte[] applicationBytes = + independentFrames( + "game-design-template-config-source-application/v1" + .getBytes(java.nio.charset.StandardCharsets.UTF_8), + "0".getBytes(java.nio.charset.StandardCharsets.UTF_8), + snapshot.shared().canonicalBytes()); + assertThat( + new TemplateConfigSourceSnapshot.Application(authored, "0", snapshot).canonicalBytes()) + .isEqualTo(applicationBytes); + + // Stipulated upstream fixture tests encoding only, not owner participation or publication + // proof. + var operation = IsolatedPublicationOperationFixtures.fresh(authored.target()); + var selected = operation.account().input().selection().selectedCommit(); + var inherited = + new TemplateConfigSourceSnapshot( + selected, "1", authored.commitId(), snapshot.genesisReceiptId(), entries); + var capture = new TemplateConfigSourceSnapshot.Capture(operation, inherited); + byte[] captureBytes = + independentFrames( + "game-design-template-config-source-capture/v1" + .getBytes(java.nio.charset.StandardCharsets.UTF_8), + operation.canonicalBytes(), + inherited.shared().canonicalBytes()); + assertThat(capture.canonicalBytes()).isEqualTo(captureBytes); + assertThat(capture.digest()).isEqualTo(independentDigest(captureBytes)); + assertThat(inherited.entries().getFirst().sourceBinding()).isEqualTo(authored); + assertThat(inherited.binding()).isEqualTo(selected); + } + + private static String independentCanonical(Object value) throws Exception { + return new String( + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + new tools.jackson.databind.ObjectMapper().writeValueAsString(value)), + java.nio.charset.StandardCharsets.UTF_8); + } + + private static String independentDigest(byte[] bytes) throws Exception { + return "sha256:" + + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private static byte[] independentFrames(byte[]... fields) throws Exception { + var bytes = new java.io.ByteArrayOutputStream(); + var output = new java.io.DataOutputStream(bytes); + for (byte[] field : fields) { + output.writeInt(field.length); + output.write(field); + } + return bytes.toByteArray(); + } + + private static String config() { + return "{\"schemaVersion\":1,\"baseVersionId\":\"" + + VERSION + + "\",\"world\":{\"regions\":[],\"rooms\":[]},\"entity\":{\"items\":[],\"npcs\":[]},\"gameLogic\":{\"inputs\":[]},\"automation\":{\"scripts\":[],\"scriptPatch\":{\"presence\":\"ABSENT\"}},\"supportedSettings\":[]}"; + } + + private static String automationInventory() { + return "{\"schema\":\"automation-authored-source-inventory/v1\"," + + "\"families\":{\"SCRIPT_DEFINITIONS\":[],\"EVENT_BINDINGS\":[]," + + "\"SCRIPT_PATCH_SOURCES\":[]}}"; + } + + private static String entityInventory() { + return "{\"schema\":\"entity-authored-source-inventory/v1\"," + + "\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":{" + + "\"ACTOR_BODY_LAYOUT_ASSIGNMENTS\":[],\"ARCHETYPE_ASSIGNMENTS\":[]," + + "\"ARCHETYPE_CONSTRAINTS\":[],\"ARCHETYPE_ROOTS\":[]," + + "\"BALANCE_CURVE_ATTACHMENTS\":[],\"BALANCE_CURVE_ROOTS\":[]," + + "\"BODY_LAYOUT_MEMBERSHIPS\":[],\"BODY_LAYOUT_ROOTS\":[]," + + "\"CRAFTING_INGREDIENT_BINDINGS\":[],\"CRAFTING_RECIPE_RESULT_BINDINGS\":[]," + + "\"CRAFTING_RECIPE_ROOTS\":[],\"EQUIPMENT_ATTACHMENT_RULES\":[]," + + "\"EQUIPMENT_CAPABILITIES\":[],\"EQUIPMENT_COMPATIBILITY_RULES\":[]," + + "\"EQUIPMENT_OCCUPANCY_RULES\":[],\"EQUIPMENT_SLOT_GROUPS\":[]," + + "\"EQUIPMENT_SLOT_ROOTS\":[],\"INBOUND_LOOT_BINDINGS\":[]," + + "\"ITEM_TEMPLATE_ROOTS\":[],\"LOOT_ITEM_MAPPINGS\":[]," + + "\"LOOT_TABLE_ROOTS\":[],\"NPC_TEMPLATE_ROOTS\":[]," + + "\"OTHER_ACTOR_TEMPLATE_ROOTS\":[]}}"; + } + + private static String typedInventoryPayload(int schemaVersion, String owner, String inventory) { + return CommandSource.canonical( + Map.of( + "schemaVersion", + schemaVersion, + "revisionKind", + TemplateConfigSource.REVISION_KIND, + "operation", + "DECLARE_OWNER_SOURCE_INVENTORY", + "owner", + owner, + "inventory", + CommandSource.tree(inventory))); + } + + private static DraftCommitBinding binding(String... payloads) { + var revisions = new ArrayList(); + for (int i = 0; i < payloads.length; i++) + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(i), + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + payloads[i])); + return DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + TENANT, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit-0", + revisions, + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSource.SCOPE, + VERSION.toString(), + TemplateConfigSource.SCOPE, + "effective", + "0"))); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionLaunchDescriptorGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionLaunchDescriptorGrpcServiceTest.java new file mode 100644 index 0000000000..2f514b0fe7 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionLaunchDescriptorGrpcServiceTest.java @@ -0,0 +1,380 @@ +package net.firedevops.firemud.gamedesign.draft; + +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.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.InitialConfigured; +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.gamedesign.publication.StartSessionLaunchDescriptorProducer; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveStartSessionLaunchDescriptorResponse; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import tools.jackson.databind.json.JsonMapper; + +/** Callback and codec tests with an injected peer context; not mTLS or persisted-owner proof. */ +class GameDesignStartSessionLaunchDescriptorGrpcServiceTest { + private static final UUID TENANT = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID ATTEMPT = uuid("02222222-2222-4222-8222-222222222222"); + private static final UUID RESERVATION_OWNER = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID ISSUANCE_ID = uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = uuid("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final String NAMESPACE = "world-runtime"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final StartSessionLaunchDescriptorProducer producer = + mock(StartSessionLaunchDescriptorProducer.class); + private final GameDesignStartSessionLaunchDescriptorGrpcService service = + new GameDesignStartSessionLaunchDescriptorGrpcService(producer, NAMESPACE); + + @Test + void authenticatesExactPeerBeforeDecodingOrCallingTheProducer() { + var observer = new Collector(); + service.resolveStartSessionLaunchDescriptor( + ReadStartSessionTemplateAssociationRequest.getDefaultInstance(), observer); + assertThat(observer.error).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + verifyNoInteractions(producer); + } + + @Test + void rejectsWrongWorkloadBeforeDecodingOrCallingTheProducer() { + var observer = + invokeAs( + ReadStartSessionTemplateAssociationRequest.getDefaultInstance(), "account-service"); + assertThat(observer.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(observer.value).isNull(); + verifyNoInteractions(producer); + } + + @Test + void rejectsWrongNamespacePeerBeforeDecodingOrCallingTheProducer() { + var observer = + invokeAsNamespace( + ReadStartSessionTemplateAssociationRequest.getDefaultInstance(), + "another-runtime", + "game-session-service"); + assertThat(observer.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + verifyNoInteractions(producer); + } + + @Test + void rejectsMalformedAndInitialRequestsBeforeCallingTheProducer() { + var malformed = + invokeAs( + ReadStartSessionTemplateAssociationRequest.getDefaultInstance(), + "game-session-service"); + assertThat(malformed.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + + var initial = invokeAs(request(new InitialConfigured()), "game-session-service"); + assertThat(initial.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(producer); + } + + @Test + void rejectsDifferentTargetNamespaceBeforeCallingTheProducer() { + var otherNamespace = + request( + "other-runtime", + new ExactReplay( + uuid("03333333-3333-4333-8333-333333333333"), + uuid("04444444-4444-4444-8444-444444444444"), + "selected-workflow", + digest('a'))); + var observer = invokeAs(otherNamespace, "game-session-service"); + assertThat(observer.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(producer); + } + + @Test + void typedStoredDenialUsesItsExactAssociationBindingAndMessage() { + // This mocked callback exercises status-to-response mapping only; it does not prove storage. + var request = + request( + new ExactReplay( + uuid("03333333-3333-4333-8333-333333333333"), + uuid("04444444-4444-4444-8444-444444444444"), + "selected-workflow", + digest('a'))); + var decoded = + net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec + .fromRequest(request); + var association = mock(StartSessionTemplateAssociationReadEvidence.Result.class); + var denial = mock(StartSessionLaunchDescriptorProducer.StoredBusinessDenial.class); + when(denial.associationRead()).thenReturn(association); + when(denial.failureCode()).thenReturn("INVALID_TEMPLATE_CONFIGURATION"); + when(denial.getMessage()) + .thenReturn("INVALID_TEMPLATE_CONFIGURATION: captured source is unsupported"); + when(producer.resolve(decoded)).thenThrow(denial); + var response = + ResolveStartSessionLaunchDescriptorResponse.newBuilder() + .setSchemaVersion(StartSessionLaunchDescriptorGrpcCodec.RESPONSE_SCHEMA_VERSION) + .build(); + + try (MockedStatic codec = + Mockito.mockStatic(StartSessionLaunchDescriptorGrpcCodec.class)) { + codec + .when(() -> StartSessionLaunchDescriptorGrpcCodec.fromRequest(request)) + .thenReturn(decoded); + codec + .when( + () -> + StartSessionLaunchDescriptorGrpcCodec.toFailureResponse( + decoded, + association, + "INVALID_TEMPLATE_CONFIGURATION", + "INVALID_TEMPLATE_CONFIGURATION: captured source is unsupported")) + .thenReturn(response); + + var observer = invokeAs(request, "game-session-service"); + + assertThat(observer.error).isNull(); + assertThat(observer.value).isEqualTo(response); + assertThat(observer.completed).isTrue(); + verify(producer).resolve(decoded); + codec.verify( + () -> + StartSessionLaunchDescriptorGrpcCodec.toFailureResponse( + decoded, + association, + "INVALID_TEMPLATE_CONFIGURATION", + "INVALID_TEMPLATE_CONFIGURATION: captured source is unsupported")); + } + } + + @Test + void ordinaryFailedPreconditionOwnerFailureRemainsANonOkRpcError() { + var request = + request( + new ExactReplay( + uuid("03333333-3333-4333-8333-333333333333"), + uuid("04444444-4444-4444-8444-444444444444"), + "selected-workflow", + digest('a'))); + var decoded = + net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec + .fromRequest(request); + when(producer.resolve(decoded)) + .thenThrow( + Status.FAILED_PRECONDITION + .withDescription("owner evidence changed") + .asRuntimeException()); + + var observer = invokeAs(request, "game-session-service"); + + assertThat(observer.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + verify(producer).resolve(decoded); + } + + @Test + void ordinaryUnavailableOwnerFailureRemainsANonOkRpcError() { + var request = + request( + new ExactReplay( + uuid("03333333-3333-4333-8333-333333333333"), + uuid("04444444-4444-4444-8444-444444444444"), + "selected-workflow", + digest('a'))); + var decoded = + net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec + .fromRequest(request); + when(producer.resolve(decoded)) + .thenThrow(Status.UNAVAILABLE.withDescription("owner unavailable").asRuntimeException()); + + var observer = invokeAs(request, "game-session-service"); + + assertThat(observer.error).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + verify(producer).resolve(decoded); + } + + private Collector invokeAs(ReadStartSessionTemplateAssociationRequest request, String workload) { + return invokeAsNamespace(request, NAMESPACE, workload); + } + + private Collector invokeAsNamespace( + ReadStartSessionTemplateAssociationRequest request, String namespace, String workload) { + var peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + workload, namespace, workload); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + var observer = new Collector(); + service.resolveStartSessionLaunchDescriptor(request, observer); + return observer; + } finally { + context.detach(previous); + } + } + + private static ReadStartSessionTemplateAssociationRequest request( + StartSessionTemplateAssociationReadEvidence.Selection selection) { + return request(NAMESPACE, selection); + } + + private static ReadStartSessionTemplateAssociationRequest request( + String namespace, StartSessionTemplateAssociationReadEvidence.Selection selection) { + var request = + new StartSessionTemplateAssociationReadEvidence.Request( + 1, + namespace, + uuid("01111111-1111-4111-8111-111111111111"), + postTuple(namespace).canonicalBytes(), + ATTEMPT, + 8L, + selection); + return net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec + .toRequest(request); + } + + private static StartSessionPostAuthorizationExecutionTuple postTuple(String namespace) { + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman( + "start-session-launch-descriptor-test", + ACTOR, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, namespace), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "exact StartSession descriptor selection")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + RESERVATION_OWNER, + 19L, + authorityBundle(pre, namespace), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle( + StartSessionPreAuthorizationReservationTuple tuple, String namespace) { + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", TENANT.toString(), "targetNamespace", namespace), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", TENANT.toString()), + "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.toString(), 3L), + "membershipAuthorityGeneration", Map.of(TENANT.toString(), 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", + Map.of(TENANT.toString(), 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); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class Collector + implements StreamObserver { + private ResolveStartSessionLaunchDescriptorResponse value; + private Status.Code error; + private boolean completed; + + @Override + public void onNext(ResolveStartSessionLaunchDescriptorResponse response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionTemplateAssociationReadGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionTemplateAssociationReadGrpcServiceTest.java new file mode 100644 index 0000000000..1275bb82cd --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionTemplateAssociationReadGrpcServiceTest.java @@ -0,0 +1,147 @@ +package net.firedevops.firemud.gamedesign.draft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.publication.StartSessionTemplateAssociationReadService; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationResponse; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.mockito.Mockito; + +class GameDesignStartSessionTemplateAssociationReadGrpcServiceTest { + private final StartSessionTemplateAssociationReadService owner = + mock(StartSessionTemplateAssociationReadService.class); + private final GameDesignStartSessionTemplateAssociationReadGrpcService service = + new GameDesignStartSessionTemplateAssociationReadGrpcService(owner, "world-runtime"); + + @Test + void authenticatesExactGameSessionPeerBeforeDecodingRequest() { + var observer = new Collector(); + service.readStartSessionTemplateAssociation( + ReadStartSessionTemplateAssociationRequest.getDefaultInstance(), observer); + assertThat(observer.error).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + verifyNoInteractions(owner); + } + + @Test + void rejectsDifferentWorkloadBeforeDecodingRequest() { + var observer = + invokeAs( + ReadStartSessionTemplateAssociationRequest.getDefaultInstance(), "account-service"); + assertThat(observer.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + verifyNoInteractions(owner); + } + + @Test + void exactPeerIsAuthenticatedBeforeMalformedRequestIsRejected() { + var observer = + invokeAs( + ReadStartSessionTemplateAssociationRequest.getDefaultInstance(), + "game-session-service"); + assertThat(observer.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + verifyNoInteractions(owner); + } + + @Test + void completesAfterDeliveringSuccessfulAssociationRead() { + var request = ReadStartSessionTemplateAssociationRequest.getDefaultInstance(); + var decoded = mock(StartSessionTemplateAssociationReadEvidence.Request.class); + var result = mock(StartSessionTemplateAssociationReadEvidence.Result.class); + var response = ReadStartSessionTemplateAssociationResponse.getDefaultInstance(); + Mockito.when(decoded.targetNamespace()).thenReturn("world-runtime"); + + try (MockedStatic codec = + Mockito.mockStatic(StartSessionTemplateAssociationReadGrpcCodec.class)) { + codec + .when(() -> StartSessionTemplateAssociationReadGrpcCodec.fromRequest(request)) + .thenReturn(decoded); + codec + .when(() -> StartSessionTemplateAssociationReadGrpcCodec.toResponse(result)) + .thenReturn(response); + Mockito.when(owner.read(decoded)).thenReturn(result); + + var observer = invokeAs(request, "game-session-service"); + + assertThat(observer.error).isNull(); + assertThat(observer.value).isEqualTo(response); + assertThat(observer.completed).isTrue(); + } + } + + @Test + void mapsResponseEncodingFailureToInternal() { + var request = ReadStartSessionTemplateAssociationRequest.getDefaultInstance(); + var decoded = mock(StartSessionTemplateAssociationReadEvidence.Request.class); + var result = mock(StartSessionTemplateAssociationReadEvidence.Result.class); + Mockito.when(decoded.targetNamespace()).thenReturn("world-runtime"); + + try (MockedStatic codec = + Mockito.mockStatic(StartSessionTemplateAssociationReadGrpcCodec.class)) { + codec + .when(() -> StartSessionTemplateAssociationReadGrpcCodec.fromRequest(request)) + .thenReturn(decoded); + codec + .when(() -> StartSessionTemplateAssociationReadGrpcCodec.toResponse(result)) + .thenThrow(new IllegalArgumentException("invalid retained response")); + Mockito.when(owner.read(decoded)).thenReturn(result); + + var observer = invokeAs(request, "game-session-service"); + + assertThat(observer.error).isEqualTo(Status.Code.INTERNAL); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + } + } + + private Collector invokeAs(ReadStartSessionTemplateAssociationRequest request, String workload) { + var peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/world-runtime/sa/" + workload, "world-runtime", workload); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + var observer = new Collector(); + service.readStartSessionTemplateAssociation(request, observer); + return observer; + } finally { + context.detach(previous); + } + } + + private static final class Collector + implements StreamObserver { + private ReadStartSessionTemplateAssociationResponse value; + private Status.Code error; + private boolean completed; + + @Override + public void onNext(ReadStartSessionTemplateAssociationResponse response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/AuthoredInitialActorCoreReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/AuthoredInitialActorCoreReadServiceTest.java new file mode 100644 index 0000000000..6f3f7146eb --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/AuthoredInitialActorCoreReadServiceTest.java @@ -0,0 +1,90 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.function.Supplier; +import net.firedevops.firemud.common.account.StartSessionRedeemedOperationProjectionClient; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence.ReadRequest; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.springframework.transaction.PlatformTransactionManager; +import tools.jackson.databind.json.JsonMapper; + +class AuthoredInitialActorCoreReadServiceTest { + private final DSLContext dsl = mock(DSLContext.class); + private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + private final StartSessionRedeemedOperationProjectionClient account = + mock(StartSessionRedeemedOperationProjectionClient.class); + private final PublishedReleaseBundleService releases = mock(PublishedReleaseBundleService.class); + private final StartSessionTemplateAssociationReadService associationReader = + new StartSessionTemplateAssociationReadService( + dsl, transactions, "world-runtime", account, releases); + private final AuthoredInitialActorCoreReadService service = + new AuthoredInitialActorCoreReadService( + dsl, "world-runtime", associationReader, JsonMapper.builder().build()); + + @Test + void authenticatesExactCoreReadWorkloadBeforeRequestOrStorageChecks() { + assertThatThrownBy(() -> service.read((ReadRequest) null)) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + + verifyNoInteractions(dsl, transactions, account, releases); + } + + @Test + void rejectsDifferentNamespaceWorkloadBeforeRequestAndOwnerStorage() { + var peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/other-runtime/sa/entity-management-service", + "other-runtime", + "entity-management-service"); + withPeer(peer, () -> service.read((ReadRequest) null)); + verifyNoInteractions(dsl, transactions, account, releases); + } + + @Test + void deniesAuthenticatedEndUserContextAfterAuthenticatingExactWorkload() { + var peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/world-runtime/sa/entity-management-service", + "world-runtime", + "entity-management-service"); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try (MockedStatic sessionContext = mockStatic(SessionContext.class)) { + sessionContext.when(SessionContext::hasAuthenticatedCallerContext).thenReturn(true); + assertThatThrownBy(() -> service.read((ReadRequest) null)) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(dsl, transactions, account, releases); + } finally { + context.detach(previous); + } + } + + private static void withPeer(GrpcPeerIdentity peer, Supplier operation) { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + assertThatThrownBy(operation::get) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + context.detach(previous); + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java index 9295f3f809..e60b0c33c7 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java @@ -20,6 +20,7 @@ import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; import net.firedevops.firemud.gamedesign.publication.RealmPolicySource; +import net.firedevops.firemud.gamedesign.publication.TemplateConfigSource; import org.junit.jupiter.api.Test; class CommandSourceTest { @@ -282,6 +283,30 @@ void gameplayRulePayloadRemainsASeparateTypedSibling() { assertThat(RealmPolicySource.isPolicyRevision(input.revisions().getFirst())).isFalse(); } + @Test + void templateConfigPayloadRemainsASeparateTypedSibling() { + var input = + binding( + UUID.randomUUID(), + List.of( + revision( + "0", + UUID.randomUUID(), + "{\"schemaVersion\":1,\"revisionKind\":\"TEMPLATE_CONFIG\"," + + "\"operation\":\"DELETE\",\"templateId\":\"7\"}")), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSource.SCOPE, + TARGET.canonicalVersionId().toString(), + TemplateConfigSource.SCOPE, + TemplateConfigSource.SCOPE_ID, + "0"))); + + assertThat(CommandSource.mutations(input)).isEmpty(); + assertThat(CommandSource.hasRealmPolicyRevision(input)).isFalse(); + } + private static CommandSource.Definition definition( String commandId, String alias, UUID commitId, UUID revisionId, String revisionOrder) { return new CommandSource.Definition( diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GrpcAuthoredInitialActorCoreReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GrpcAuthoredInitialActorCoreReadServiceTest.java new file mode 100644 index 0000000000..957378e6e2 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GrpcAuthoredInitialActorCoreReadServiceTest.java @@ -0,0 +1,243 @@ +package unit.net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence.ReadRequest; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadGrpcCodec; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +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.gamedesign.publication.AuthoredInitialActorCoreReadService; +import net.firedevops.firemud.gamedesign.publication.GrpcAuthoredInitialActorCoreReadService; +import net.firedevops.firemud.gamedesign.v1.ReadAuthoredInitialActorCoreRequest; +import net.firedevops.firemud.gamedesign.v1.ReadAuthoredInitialActorCoreResponse; +import org.junit.jupiter.api.Test; + +class GrpcAuthoredInitialActorCoreReadServiceTest { + private final AuthoredInitialActorCoreReadService owner = + mock(AuthoredInitialActorCoreReadService.class); + private final GrpcAuthoredInitialActorCoreReadService service = + new GrpcAuthoredInitialActorCoreReadService(owner, "world-runtime"); + + @Test + void rejectsMissingWorkloadIdentityBeforeDecodingOrCallingOwner() { + var observer = new Collector(); + service.readAuthoredInitialActorCore( + ReadAuthoredInitialActorCoreRequest.getDefaultInstance(), observer); + assertThat(observer.error).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + verifyNoInteractions(owner); + } + + @Test + void rejectsOtherWorkloadsBeforeDecodingOrCallingOwner() { + var observer = invokeAs("account-service"); + assertThat(observer.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + verifyNoInteractions(owner); + } + + @Test + void permitsOnlyExactSameNamespaceGameSessionAndEntityIdentities() { + for (String workload : new String[] {"game-session-service", "entity-management-service"}) { + var observer = invokeAs(workload); + assertThat(observer.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + } + verifyNoInteractions(owner); + } + + @Test + void mapsInvalidOwnerResultToSanitizedInternalStatus() throws Exception { + when(owner.read(any(ReadRequest.class))) + .thenThrow(new IllegalArgumentException("private database and identity details")); + + var observer = invokeAs("game-session-service", validRequest()); + + assertThat(observer.error).isEqualTo(Status.Code.INTERNAL); + assertThat(observer.errorDescription) + .isEqualTo("Game Design returned invalid authored-core owner evidence") + .doesNotContain("private database", "identity details"); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + verify(owner, times(1)).read(any(ReadRequest.class)); + } + + private Collector invokeAs(String workload) { + return invokeAs(workload, ReadAuthoredInitialActorCoreRequest.getDefaultInstance()); + } + + private Collector invokeAs(String workload, ReadAuthoredInitialActorCoreRequest request) { + var peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/world-runtime/sa/" + workload, "world-runtime", workload); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + var observer = new Collector(); + service.readAuthoredInitialActorCore(request, observer); + return observer; + } finally { + context.detach(previous); + } + } + + private static ReadAuthoredInitialActorCoreRequest validRequest() throws Exception { + UUID tenant = UUID.fromString("11111111-1111-4111-8111-111111111111"); + UUID actor = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + UUID targetOwner = UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + UUID reservationOwner = UUID.fromString("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + UUID issuanceId = UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + UUID tokenJti = UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"); + UUID version = UUID.fromString("02222222-2222-4222-8222-222222222222"); + UUID commit = UUID.fromString("03333333-3333-4333-8333-333333333333"); + UUID readId = UUID.fromString("01111111-1111-4111-8111-111111111111"); + UUID attempt = UUID.fromString("04444444-4444-4444-8444-444444444444"); + String namespace = "world-runtime"; + String digest = "sha256:" + "a".repeat(64); + String publishWorkflow = "selected-publication-workflow"; + var pre = + StartSessionPreAuthorizationReservationTuple.createHuman( + "actor-core-original-start-session", + actor, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(tenant, namespace), + new StartSessionOperatorAction.Target(19L, targetOwner), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "exact original selected authored actor core")); + byte[] authorityBundle = + Rfc8785CanonicalJson.canonicalizeUtf8( + new tools.jackson.databind.ObjectMapper() + .writeValueAsString( + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", + Map.of("tenantId", tenant.toString(), "targetNamespace", namespace), + "actionFamily", pre.actionFamily(), + "applicableAccountId", actor.toString(), + "applicableTenantId", tenant.toString()), + "accountProjectionEvidence", + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", digest, + "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(tenant.toString(), 3L), + "membershipAuthorityGeneration", Map.of(tenant.toString(), 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", + Map.of(tenant.toString(), 5L), + "issuanceFence", + "23", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + actor.toString(), + "controlUiTokenJti", + tokenJti.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")))); + var post = + StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + reservationOwner, + 19L, + authorityBundle, + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + var associationRequest = + new Request( + 1, + namespace, + readId, + post.canonicalBytes(), + attempt, + 8L, + new ExactReplay(version, commit, publishWorkflow, digest)); + return AuthoredInitialActorCoreReadGrpcCodec.toRequest(new ReadRequest(associationRequest)); + } + + private static final class Collector + implements StreamObserver { + private ReadAuthoredInitialActorCoreResponse value; + private Status.Code error; + private String errorDescription; + private boolean completed; + + @Override + public void onNext(ReadAuthoredInitialActorCoreResponse response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + errorDescription = Status.fromThrowable(failure).getDescription(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceTest.java index 67725f6824..82afc5df86 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceTest.java @@ -27,11 +27,13 @@ void policyClassifierRecognizesKnownSiblingOwnersAndRejectsUnknownKinds() { "2", UUID.randomUUID(), AssetSource.upsertPayload("41", "map", AssetSource.Requiredness.REQUIRED)); - var unknown = policyRevision("3", UUID.randomUUID(), "{\"revisionKind\":\"UNSUPPORTED\"}"); + var template = policyRevision("3", UUID.randomUUID(), TemplateConfigSource.deletePayload("7")); + var unknown = policyRevision("4", UUID.randomUUID(), "{\"revisionKind\":\"UNSUPPORTED\"}"); assertThat(RealmPolicySource.isPolicyRevision(policy)).isTrue(); assertThat(RealmPolicySource.isPolicyRevision(command)).isFalse(); assertThat(RealmPolicySource.isPolicyRevision(asset)).isFalse(); + assertThat(RealmPolicySource.isPolicyRevision(template)).isFalse(); assertThatThrownBy(() -> RealmPolicySource.isPolicyRevision(unknown)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Unsupported Game Design owner revision kind"); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java new file mode 100644 index 0000000000..4a0efa3c9e --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java @@ -0,0 +1,840 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Stream; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreSourceBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; +import net.firedevops.firemud.common.gamedesign.RealmPolicySource; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.InitialConfigured; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Audience; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Disposition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Feedback; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ReplayPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Visibility; +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.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; +import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; +import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; +import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import tools.jackson.databind.json.JsonMapper; + +class StartSessionLaunchDescriptorProducerTest { + private static final UUID TENANT = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID ATTEMPT = uuid("02222222-2222-4222-8222-222222222222"); + private static final UUID RESERVATION_OWNER = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID ISSUANCE_ID = uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = uuid("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final UUID VERSION = uuid("03333333-3333-4333-8333-333333333333"); + private static final UUID COMMIT = uuid("04444444-4444-4444-8444-444444444444"); + private static final String NAMESPACE = "world-runtime"; + private static final long FENCE = 8L; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void requiresExactReplayAndSameNamespacePeerBeforeOwnerWork() { + var associationReader = mock(StartSessionTemplateAssociationReadService.class); + var transactions = mock(PlatformTransactionManager.class); + var producer = + new StartSessionLaunchDescriptorProducer( + mock(DSLContext.class), + transactions, + NAMESPACE, + associationReader, + mock(PublishedReleaseBundleService.class), + JSON); + var initial = request(new InitialConfigured()); + + assertThatThrownBy(() -> withPeer(() -> producer.resolve(initial), "game-session-service")) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(associationReader, transactions); + + assertThatThrownBy(() -> withPeer(() -> producer.resolve(null), "game-session-service")) + .isInstanceOf(NullPointerException.class); + verifyNoInteractions(associationReader, transactions); + + assertThatThrownBy( + () -> + withPeer( + () -> + producer.resolve( + request( + new ExactReplay( + VERSION, COMMIT, "selected-workflow", digest('a')))), + "account-service")) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(associationReader, transactions); + } + + @Test + void delegatesExactReplayToAssociationReaderBeforeOpeningLocalWriteTransaction() { + // This is an explicit upstream boundary double, not Account/mTLS or owner-storage proof. + var associationReader = mock(StartSessionTemplateAssociationReadService.class); + var transactions = mock(PlatformTransactionManager.class); + var producer = + new StartSessionLaunchDescriptorProducer( + mock(DSLContext.class), + transactions, + NAMESPACE, + associationReader, + mock(PublishedReleaseBundleService.class), + JSON); + var request = request(new ExactReplay(VERSION, COMMIT, "selected-workflow", digest('a'))); + when(associationReader.read(request)) + .thenThrow( + Status.UNAVAILABLE + .withDescription("test seam: independent Account projection unavailable") + .asRuntimeException()); + + assertThatThrownBy(() -> withPeer(() -> producer.resolve(request), "game-session-service")) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.UNAVAILABLE); + verifyNoInteractions(transactions); + } + + @Test + void associationAndLaunchCallersShareLosslessPublishedReleaseEncoding() throws Exception { + var dto = completeReleaseDto(); + var producer = producer(); + var associationReader = + new StartSessionTemplateAssociationReadService( + mock(DSLContext.class), + mock(PlatformTransactionManager.class), + NAMESPACE, + (tuple, attempt, fence) -> null, + mock(PublishedReleaseBundleService.class)); + + var launchBundle = producer.toPublishedReleaseBundle(dto); + var associationBundle = associationReader.toPublishedReleaseBundle(dto); + assertThat(launchBundle).isEqualTo(associationBundle); + assertThat(launchBundle.getId()).isEqualTo(dto.id()); + assertThat(launchBundle.getVersionId()).isEqualTo(dto.versionId()); + assertThat(launchBundle.getVersionNumber()).isEqualTo(dto.versionNumber()); + assertThat(launchBundle.getAttestationSchemaVersion()) + .isEqualTo(dto.attestationSchemaVersion()); + assertThat(launchBundle.getPublishWorkflowId()).isEqualTo(dto.publishWorkflowId()); + assertThat(launchBundle.getManifestHash()).isEqualTo(dto.manifestHash()); + assertThat(launchBundle.getRequiredManifestAssetKeysList()) + .containsExactlyElementsOf(dto.requiredManifestAssetKeys()); + assertThat(launchBundle.getIsScriptOnly()).isEqualTo(dto.scriptOnly()); + assertThat(launchBundle.getPublishedAt()).isEqualTo(dto.publishedAt().toString()); + assertThat(launchBundle.getScriptPatchVersion()).isEmpty(); + assertThat(launchBundle.getGenerationConfigRevision()) + .isEqualTo(dto.generationConfigRevision()); + assertThat(launchBundle.getCommandDefinitionsList()) + .containsExactlyElementsOf(dto.commandDefinitions()); + assertThat(launchBundle.getPublishedReleaseBundleRef()) + .isEqualTo(dto.publishedReleaseBundleRef()); + assertThat(launchBundle.getCanonicalTenantId()).isEqualTo(dto.canonicalTenantId().toString()); + assertThat(launchBundle.getCanonicalVersionId()).isEqualTo(dto.canonicalVersionId().toString()); + assertThat(launchBundle.hasManifestSchemaVersion()).isTrue(); + assertThat(launchBundle.getArtifactDigestsList()).hasSize(1); + assertThat(launchBundle.getArtifactDigests(0).getImmutableObjectKey()) + .isEqualTo(dto.artifactDigests().getFirst().immutableObjectKey()); + assertThat(launchBundle.getParticipantDigestsList().get(0).hasAbilitySchemaDigest()).isFalse(); + assertThat(launchBundle.getParticipantDigestsList().get(0).getContentDigest()) + .isEqualTo(dto.participantDigests().getFirst().contentDigest()); + assertThat(launchBundle.getParticipantDigestsList().get(2).hasAbilitySchemaDigest()).isTrue(); + + var launchContent = producer.releaseContent(dto); + var associationContent = associationReader.releaseContent(dto); + assertThat(launchContent.canonicalBytes()).containsExactly(associationContent.canonicalBytes()); + assertThat(launchContent.canonicalBytes()) + .containsExactly(expectedReleaseContent(dto).canonicalBytes()); + assertThat(launchContent.worldStartLocationEvidence()) + .isEqualTo(dto.worldPublishedStartLocationEvidence()); + assertThat(launchContent.artifactDigests()).hasSize(1); + } + + @Test + void sharedReleaseEncodingKeepsCallerSpecificFailureMappings() throws Exception { + var dto = completeReleaseDto(); + var producer = producer(); + var associationReader = + new StartSessionTemplateAssociationReadService( + mock(DSLContext.class), + mock(PlatformTransactionManager.class), + NAMESPACE, + (tuple, attempt, fence) -> null, + mock(PublishedReleaseBundleService.class)); + var failedParticipant = + new PublishParticipantDigestDto( + "WORLD_MANAGEMENT", + dto.participantDigests().getFirst().scopeValue(), + dto.participantDigests().getFirst().appliedCommitId(), + dto.participantDigests().getFirst().contentDigest(), + dto.participantDigests().getFirst().digestSchemaVersion(), + "REJECTED", + "failed"); + var failedDto = + withParticipants( + dto, + Stream.concat(Stream.of(failedParticipant), dto.participantDigests().stream().skip(1)) + .toList()); + + assertThatThrownBy(() -> producer.toPublishedReleaseBundle(failedDto)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> { + var status = ((StatusRuntimeException) failure).getStatus(); + assertThat(status.getCode()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(status.getDescription()) + .isEqualTo("Published release participant did not succeed"); + }); + assertThatThrownBy(() -> associationReader.toPublishedReleaseBundle(failedDto)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("START_SESSION_PUBLISHED_PARTICIPANT_FAILURE"); + + var incomplete = incompleteReleaseDto(); + var legacyBundle = producer.toPublishedReleaseBundle(incomplete); + assertThat(legacyBundle.getScriptPatchVersion()).isEmpty(); + assertThat(legacyBundle.hasManifestSchemaVersion()).isFalse(); + assertThat(legacyBundle.getArtifactDigestsList()).isEmpty(); + assertThatThrownBy(() -> producer.releaseContent(incomplete)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> { + var status = ((StatusRuntimeException) failure).getStatus(); + assertThat(status.getCode()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(status.getDescription()) + .isEqualTo("Immutable release content evidence is incomplete"); + }); + assertThatThrownBy(() -> associationReader.releaseContent(incomplete)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("START_SESSION_IMMUTABLE_RELEASE_ARTIFACT_PROOF_MISSING"); + } + + @Test + void selectedSchema3ActorCoreIsResolvedFromExactOwnerSnapshots() { + var fixture = selectedActorCoreSource(); + var resolved = + StartSessionLaunchDescriptorProducer.resolveSelectedAuthoredInitialActorCoreSources( + uuid("66666666-6666-4666-8666-666666666666"), + digest('a'), + "world", + "selected-workflow", + bytes("selected publication operation"), + bytes("selected publication terminal evidence"), + fixture.binding(), + fixture.policySnapshot(), + fixture.gameplayRules()); + + assertThat(resolved).hasSize(2); + assertThat(resolved.get(0).policySource().policy().realmSlug()).isEqualTo("realm-a"); + assertThat(resolved.get(1).policySource().policy().realmSlug()).isEqualTo("realm-z"); + assertThat(resolved.getFirst().core().displayName()).isEqualTo("Wayfarer"); + assertThat(resolved.getFirst().disposition().dispositionKey()).isEqualTo("newcomer"); + assertThat(resolved.getFirst().safeFeedback().feedbackKey()).isEqualTo("welcome"); + assertThat(resolved.getFirst().selectedCommit()).isEqualTo(fixture.binding()); + assertThat(resolved.getFirst().policySource().commitId()) + .isNotEqualTo(fixture.binding().commitId()); + assertThat(resolved.getFirst().dispositionSource().sourceBinding().commitId()) + .isNotEqualTo(fixture.binding().commitId()); + assertThat(resolved.getFirst().expectedWorldSlug()).isEqualTo("world"); + assertThatThrownBy(resolved::clear).isInstanceOf(UnsupportedOperationException.class); + + assertThat( + StartSessionLaunchDescriptorProducer.resolveSelectedAuthoredInitialActorCoreSources( + uuid("66666666-6666-4666-8666-666666666666"), + digest('a'), + "different-world", + "selected-workflow", + bytes("selected publication operation"), + bytes("selected publication terminal evidence"), + fixture.binding(), + fixture.policySnapshot(), + fixture.gameplayRules())) + .isEmpty(); + + DraftCommitBinding otherCommit = + DraftCommitBinding.create( + fixture.binding().target(), + uuid("99999999-9999-4999-8999-999999999999"), + uuid("88888888-8888-4888-8888-888888888888"), + "base-commit-0", + fixture.binding().revisions(), + fixture.binding().affectedUnits()); + var changedPolicySnapshot = + new net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot( + otherCommit, "1", fixture.policySnapshot().policies()); + + assertThatThrownBy( + () -> + StartSessionLaunchDescriptorProducer.resolveSelectedAuthoredInitialActorCoreSources( + uuid("66666666-6666-4666-8666-666666666666"), + digest('a'), + "world", + "selected-workflow", + bytes("selected publication operation"), + bytes("selected publication terminal evidence"), + fixture.binding(), + changedPolicySnapshot, + fixture.gameplayRules())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("selected authored commit"); + } + + @Test + void resolvedBindingDefensivelyRetainsMinimalActorCoreProjectionAndRejectsChangedProvenance() { + var fixture = selectedActorCoreSource(); + UUID sourceOperation = uuid("66666666-6666-4666-8666-666666666666"); + List sourceBindings = + StartSessionLaunchDescriptorProducer.resolveSelectedAuthoredInitialActorCoreSources( + sourceOperation, + digest('a'), + "world", + "selected-workflow", + bytes("selected publication operation"), + bytes("selected publication terminal evidence"), + fixture.binding(), + fixture.policySnapshot(), + fixture.gameplayRules()); + var mutableBindings = new ArrayList<>(sourceBindings); + var resolved = + resolvedBinding(mutableBindings, sourceOperation, "world", COMMIT, "selected-workflow"); + + mutableBindings.clear(); + assertThat(resolved.actorCoreProjections()).hasSize(2); + assertThat(resolved.actorCoreProjections().get(0).policy().canonicalJson()) + .contains("\"realmSlug\":\"realm-a\""); + assertThat(resolved.actorCoreProjections().get(1).policy().canonicalJson()) + .contains("\"realmSlug\":\"realm-z\""); + assertThat(resolved.actorCoreProjections().getFirst().policy().commitId()) + .isNotEqualTo(resolved.actorCoreProjections().getFirst().selectedCommitId()); + assertThat(resolved.actorCoreProjections().getFirst().disposition().sourceCommitId()) + .isNotEqualTo(resolved.actorCoreProjections().getFirst().selectedCommitId().toString()); + assertThat(resolved.actorCoreProjections().getFirst().bindingDigest()) + .isEqualTo(sourceBindings.getFirst().digest()); + assertThat( + new String( + resolved.actorCoreProjections().getFirst().canonicalBytes(), + StandardCharsets.UTF_8)) + .doesNotContain("selected publication operation") + .doesNotContain("selected publication terminal evidence"); + assertThatThrownBy(resolved.actorCoreProjections()::clear) + .isInstanceOf(UnsupportedOperationException.class); + + assertThatThrownBy( + () -> + resolvedBinding( + sourceBindings, + uuid("77777777-7777-4777-8777-777777777777"), + "world", + COMMIT, + "selected-workflow")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact selected StartSession release"); + assertThatThrownBy( + () -> + resolvedBinding( + sourceBindings, sourceOperation, "other-world", COMMIT, "selected-workflow")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact selected StartSession release"); + assertThatThrownBy( + () -> + resolvedBinding( + sourceBindings, + sourceOperation, + "world", + uuid("88888888-8888-4888-8888-888888888888"), + "selected-workflow")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact selected StartSession release"); + assertThatThrownBy( + () -> + resolvedBinding(sourceBindings, sourceOperation, "world", COMMIT, "other-workflow")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact selected StartSession release"); + } + + private static StartSessionLaunchDescriptorProducer.ResolvedBinding resolvedBinding( + List actorCoreBindings, + UUID associationSourceOperationId, + String descriptorWorldSlug, + UUID associationSelectedCommitId, + String associationWorkflowId) { + var request = request(new ExactReplay(VERSION, COMMIT, "selected-workflow", digest('a'))); + var association = mock(StartSessionTemplateAssociationReadEvidence.Association.class); + when(association.canonicalTenantId()).thenReturn(TENANT); + when(association.templateId()).thenReturn(91L); + when(association.canonicalVersionId()).thenReturn(VERSION); + when(association.selectedCommitId()).thenReturn(associationSelectedCommitId); + when(association.publishWorkflowId()).thenReturn(associationWorkflowId); + when(association.sourceOperationId()).thenReturn(associationSourceOperationId); + when(association.sourceEvidenceDigest()).thenReturn(digest('a')); + when(association.worldSlug()).thenReturn("world"); + + var associationRead = mock(StartSessionTemplateAssociationReadEvidence.Result.class); + when(associationRead.request()).thenReturn(request); + when(associationRead.association()).thenReturn(association); + + var authoredWorld = mock(AuthoredWorldLaunchDescriptorEvidence.class); + when(authoredWorld.worldSlug()).thenReturn(descriptorWorldSlug); + when(authoredWorld.authoredWorldSourceOperationId()) + .thenReturn(uuid("66666666-6666-4666-8666-666666666666")); + when(authoredWorld.authoredWorldSourceEvidenceDigest()).thenReturn(digest('a')); + when(authoredWorld.canonicalTenantId()).thenReturn(TENANT); + when(authoredWorld.versionId()).thenReturn(23L); + when(authoredWorld.gameTemplateId()).thenReturn(91L); + + var descriptor = mock(ResolvedLaunchDescriptorDto.class); + when(descriptor.controlPlaneRequestId()).thenReturn("launch-descriptor-test"); + when(descriptor.canonicalTenantId()).thenReturn(TENANT.toString()); + when(descriptor.gameTemplateId()).thenReturn(91L); + when(descriptor.authoredWorldBinding()).thenReturn(authoredWorld); + // Structural projection fixtures only; Common integrity checks do not authenticate a producer. + List projections = + java.util.stream.IntStream.range(0, actorCoreBindings.size()) + .mapToObj( + index -> + AuthoredInitialActorCoreProjection.fromValidatedBinding( + UUID.nameUUIDFromBytes( + (index + ":" + actorCoreBindings.get(index).digest()) + .getBytes(StandardCharsets.UTF_8)), + actorCoreBindings.get(index))) + .toList(); + return new StartSessionLaunchDescriptorProducer.ResolvedBinding( + request, associationRead, descriptor, projections); + } + + private static SelectedActorCoreFixture selectedActorCoreSource() { + var target = + new TargetProof( + TENANT, VERSION, 23L, "private-owner-key", 42L, "private-owner-key", "NEW_GAME_ROW"); + String policyJson = + "{\"schemaVersion\":3,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\"," + + "\"realmSlug\":\"realm-z\",\"realmDisplayName\":\"Realm Z\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\",\"entryPolicy\":\"PLAYER_CREATED\"," + + "\"creationDescriptor\":{\"schemaVersion\":1,\"descriptorId\":\"11111111-1111-4111-8111-111111111111\"," + + "\"descriptorRevisionId\":\"22222222-2222-4222-8222-222222222222\"," + + "\"inputKind\":\"EMPTY_OBJECT\",\"dependencies\":[]}," + + "\"initialActorCore\":{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}}"; + String earlierPolicyJson = + policyJson + .replace("realm-z", "realm-a") + .replace("Realm Z", "Realm A") + .replace("11111111-1111-4111-8111-111111111111", "12111111-1111-4111-8111-111111111111") + .replace( + "22222222-2222-4222-8222-222222222222", "23222222-2222-4222-8222-222222222222"); + String policyPayload = + RealmPolicySource.canonical( + Map.of( + "revisionKind", + RealmPolicySource.REVISION_KIND, + "logicalRevisionId", + "selected-policy-r3", + "policy", + RealmPolicySource.tree(policyJson))); + var disposition = new Disposition("newcomer", List.of(), "welcome"); + var feedback = + new Feedback( + "welcome", + "actor.created", + Audience.SOURCE_ACTOR, + "actor.created", + "Welcome, traveler.", + List.of(), + Visibility.PUBLIC, + ReplayPolicy.EFFECT_IDEMPOTENT); + List revisions = + List.of( + new RevisionPayload( + "0", + uuid("55555555-5555-4555-8555-555555555555"), + Owner.GAME_DESIGN_CONTROL_PLANE, + policyPayload), + new RevisionPayload( + "1", + uuid("56555555-5555-4555-8555-555555555556"), + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.canonical( + Map.of( + "revisionKind", + RealmPolicySource.REVISION_KIND, + "logicalRevisionId", + "selected-policy-r2", + "policy", + RealmPolicySource.tree(earlierPolicyJson)))), + new RevisionPayload( + "2", + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload(disposition)), + new RevisionPayload( + "3", + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload(feedback))); + List affectedUnits = + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + VERSION.toString(), + RealmPolicySource.SCOPE, + "effective", + "0"), + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.SCOPE, + VERSION.toString(), + GameplayRuleSource.SCOPE, + GameplayRuleSource.SCOPE_ID, + "0")); + DraftCommitBinding originBinding = + DraftCommitBinding.create( + target, + uuid("77777777-7777-4777-8777-777777777777"), + uuid("abababab-abab-4bab-8bab-abababababab"), + "base-commit-0", + revisions, + affectedUnits); + DraftCommitBinding binding = + DraftCommitBinding.create( + target, + uuid("88888888-8888-4888-8888-888888888888"), + COMMIT, + originBinding.commitId().toString(), + List.of( + new RevisionPayload( + "0", + uuid("98989898-9898-4989-8989-989898989898"), + Owner.WORLD_MANAGEMENT, + "{}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, "WORLD_REVISION", "world", "WORLD", "world", "0"))); + var policySources = + List.of( + RealmPolicySource.revision(originBinding, revisions.get(0)), + RealmPolicySource.revision(originBinding, revisions.get(1))); + var policySnapshot = + new net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot( + binding, "1", policySources); + List inheritedRules = + GameplayRuleSource.replay(List.of(), originBinding); + var rulesSnapshot = + new GameplayRuleSnapshot( + binding, + "1", + originBinding.commitId(), + uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + GameplayRuleSource.replay(inheritedRules, binding)); + return new SelectedActorCoreFixture(binding, policySnapshot, rulesSnapshot); + } + + private static PublishedReleaseBundleDto completeReleaseDto() throws Exception { + var target = selectedActorCoreSource().binding().target(); + var worldEvidence = PublishedWorldSelectorFixtures.evidence(target); + String artifactDigest = digest('c'); + return new PublishedReleaseBundleDto( + 17L, + "private-owner-key", + 23L, + 12, + "v2", + worldEvidence.request().publishWorkflowId(), + digest('e'), + List.of("branding/logo"), + PublishedWorldSelectorFixtures.participants( + 1L, worldEvidence, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + List.of("look"), + "generation-config-r1", + false, + null, + java.time.LocalDateTime.parse("2026-10-18T00:00:00"), + target.canonicalTenantId(), + target.canonicalVersionId(), + "release-bundle-ref", + 1, + List.of( + new PublishedArtifactDigest( + "branding/logo", + "IMAGE", + "artifacts/sha256/" + artifactDigest.substring("sha256:".length()), + artifactDigest, + "image/png", + 1)), + worldEvidence); + } + + private static PublishedReleaseBundleDto incompleteReleaseDto() { + return new PublishedReleaseBundleDto( + 17L, + "private-owner-key", + 23L, + 12, + "v1", + "legacy-workflow", + digest('e'), + List.of(), + List.of(), + List.of("look"), + "generation-config-r1", + false, + null, + java.time.LocalDateTime.parse("2026-10-18T00:00:00"), + TENANT, + VERSION, + "release-bundle-ref", + null, + null); + } + + private static PublishedReleaseBundleDto withParticipants( + PublishedReleaseBundleDto dto, List participants) { + return new PublishedReleaseBundleDto( + dto.id(), + dto.tenantId(), + dto.versionId(), + dto.versionNumber(), + dto.attestationSchemaVersion(), + dto.publishWorkflowId(), + dto.manifestHash(), + dto.requiredManifestAssetKeys(), + participants, + dto.commandDefinitions(), + dto.generationConfigRevision(), + dto.scriptOnly(), + dto.scriptPatchVersion(), + dto.publishedAt(), + dto.canonicalTenantId(), + dto.canonicalVersionId(), + dto.publishedReleaseBundleRef(), + dto.manifestSchemaVersion(), + dto.artifactDigests(), + dto.worldPublishedStartLocationEvidence()); + } + + private static GameDesignPublicationTerminalEvidence.ReleaseContent expectedReleaseContent( + PublishedReleaseBundleDto dto) { + var participants = + dto.participantDigests().stream() + .map( + value -> + new GameDesignPublicationTerminalEvidence.Participant( + value.participantKey(), + value.scopeValue(), + value.baseVersionId(), + value.appliedCommitId(), + value.contentDigest(), + value.digestSchemaVersion(), + value.abilitySchemaDigest(), + value.errorCode(), + value.errorMessage())) + .toList(); + var artifacts = + dto.artifactDigests().stream() + .map( + value -> + new AuthoredWorldReleaseAttestationEvidence.Artifact( + value.usageKey(), + value.artifactKind(), + value.immutableObjectKey(), + value.contentDigest(), + value.contentType(), + value.artifactSchemaVersion())) + .toList(); + return new GameDesignPublicationTerminalEvidence.ReleaseContent( + dto.canonicalTenantId(), + dto.canonicalVersionId(), + dto.publishedReleaseBundleRef(), + dto.versionNumber(), + dto.attestationSchemaVersion(), + dto.publishWorkflowId(), + dto.manifestHash(), + dto.manifestSchemaVersion(), + artifacts, + dto.requiredManifestAssetKeys(), + participants, + dto.commandDefinitions(), + dto.generationConfigRevision(), + dto.worldPublishedStartLocationEvidence()); + } + + private static StartSessionLaunchDescriptorProducer producer() { + return new StartSessionLaunchDescriptorProducer( + mock(DSLContext.class), + mock(PlatformTransactionManager.class), + NAMESPACE, + mock(StartSessionTemplateAssociationReadService.class), + mock(PublishedReleaseBundleService.class), + JSON); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private record SelectedActorCoreFixture( + DraftCommitBinding binding, + net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot policySnapshot, + GameplayRuleSnapshot gameplayRules) {} + + private static void withPeer(Runnable action, String workload) { + var peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/" + workload, NAMESPACE, workload); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + action.run(); + } finally { + context.detach(previous); + } + } + + private static StartSessionTemplateAssociationReadEvidence.Request request( + StartSessionTemplateAssociationReadEvidence.Selection selection) { + return new StartSessionTemplateAssociationReadEvidence.Request( + 1, + NAMESPACE, + uuid("01111111-1111-4111-8111-111111111111"), + postTuple("launch-descriptor-test").canonicalBytes(), + ATTEMPT, + FENCE, + selection); + } + + private static StartSessionPostAuthorizationExecutionTuple postTuple(String requestId) { + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman( + requestId, + ACTOR, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, NAMESPACE), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "exact StartSession descriptor selection")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + 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", NAMESPACE), + "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 UUID uuid(String value) { + return UUID.fromString(value); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadServiceTest.java new file mode 100644 index 0000000000..61d379ea32 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadServiceTest.java @@ -0,0 +1,524 @@ +package net.firedevops.firemud.gamedesign.publication; + +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 com.google.protobuf.ByteString; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionResponse; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence.ReadRequest; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +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.gamedesign.dto.PublishedReleaseBundleDto; +import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.dao.TransientDataAccessResourceException; +import org.springframework.transaction.CannotCreateTransactionException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.TransactionSystemException; +import tools.jackson.databind.json.JsonMapper; + +class StartSessionTemplateAssociationReadServiceTest { + 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 ATTEMPT = UUID.fromString("02222222-2222-4222-8222-222222222222"); + 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 long FENCE = 8L; + private static final JsonMapper JSON = JsonMapper.builder().build(); + private final DSLContext dsl = mock(DSLContext.class); + private final PublishedReleaseBundleService releases = mock(PublishedReleaseBundleService.class); + + @Test + void independentlyChecksExactAccountAttemptBeforeOpeningAnyLocalSnapshot() { + var tuple = postTuple("account-before-local-snapshot"); + var request = request(tuple); + var accountCalled = new AtomicBoolean(); + PlatformTransactionManager transactions = + new PlatformTransactionManager() { + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + if (!accountCalled.get()) { + throw new AssertionError("Local snapshot opened before Account projection"); + } + throw new IllegalStateException("test stops at the first local transaction boundary"); + } + + @Override + public void commit(TransactionStatus status) { + throw new AssertionError("No transaction should be committed"); + } + + @Override + public void rollback(TransactionStatus status) { + throw new AssertionError("No transaction should be rolled back"); + } + }; + var service = + new StartSessionTemplateAssociationReadService( + dsl, + transactions, + "world-runtime", + (actualTuple, attempt, fence) -> { + accountCalled.set(true); + if (!tuple.controlPlaneRequestId().equals(actualTuple.controlPlaneRequestId()) + || !ATTEMPT.equals(attempt) + || FENCE != fence) { + throw new AssertionError("Changed exact Account projection selector"); + } + return projection(tuple, ATTEMPT, FENCE); + }, + releases); + + assertThatThrownBy(() -> withPeer(service, request, "game-session-service")) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + verifyNoInteractions(dsl); + verifyNoInteractions(releases); + } + + @Test + void deniesWrongWorkloadBeforeCallingAccountOrOpeningLocalStorage() { + var tuple = postTuple("wrong-peer"); + var service = + new StartSessionTemplateAssociationReadService( + dsl, + unusedTransactionManager(), + "world-runtime", + (ignored, attempt, fence) -> { + throw new AssertionError("Account must not be called for a different workload"); + }, + releases); + assertThatThrownBy(() -> withPeer(service, request(tuple), "account-service")) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(dsl); + verifyNoInteractions(releases); + } + + @Test + void rejectsMismatchedAccountAttemptFenceBeforeLocalRead() { + var tuple = postTuple("changed-account-fence"); + var service = + new StartSessionTemplateAssociationReadService( + dsl, + unusedTransactionManager(), + "world-runtime", + (actual, attempt, fence) -> projection(actual, attempt, fence + 1L), + releases); + assertThatThrownBy(() -> withPeer(service, request(tuple), "game-session-service")) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + verifyNoInteractions(dsl); + verifyNoInteractions(releases); + } + + @Test + void mapsSpringTransientSnapshotFailureThroughAuthoredCoreCallerToUnavailable() { + assertAuthoredCoreStorageFailure( + new TransientDataAccessResourceException("database connection interrupted"), + Status.Code.UNAVAILABLE); + } + + @Test + void mapsSpringResourceFailureThroughAuthoredCoreCallerToUnavailable() { + assertAuthoredCoreStorageFailure( + new DataAccessResourceFailureException("database connection interrupted"), + Status.Code.UNAVAILABLE); + } + + @Test + void mapsSpringIntegrityViolationThroughAuthoredCoreCallerToFailedPrecondition() { + assertAuthoredCoreStorageFailure( + new DataIntegrityViolationException("retained owner evidence conflicts"), + Status.Code.FAILED_PRECONDITION); + } + + @Test + void mapsTransactionCreationFailureToUnavailable() { + var tuple = postTuple("transaction-creation-failure"); + var failure = new CannotCreateTransactionException("database connection unavailable"); + PlatformTransactionManager transactions = + new PlatformTransactionManager() { + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + throw failure; + } + + @Override + public void commit(TransactionStatus status) { + throw new AssertionError("Transaction creation failed before commit"); + } + + @Override + public void rollback(TransactionStatus status) { + throw new AssertionError("Transaction creation failed before rollback"); + } + }; + var service = + new StartSessionTemplateAssociationReadService( + dsl, + transactions, + "world-runtime", + (actual, attempt, fence) -> projection(actual, attempt, fence), + releases); + + assertTransactionFailureMapsToUnavailable(service, request(tuple), failure); + verifyNoInteractions(dsl); + } + + @Test + void mapsTransactionRollbackFailureToUnavailable() { + var tuple = postTuple("transaction-rollback-failure"); + var failure = new TransactionSystemException("read-only transaction rollback failed"); + PlatformTransactionManager transactions = + new PlatformTransactionManager() { + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + return new org.springframework.transaction.support.SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + throw new AssertionError("The absent reference phase fails before commit"); + } + + @Override + public void rollback(TransactionStatus status) { + throw failure; + } + }; + var service = + new StartSessionTemplateAssociationReadService( + dsl, + transactions, + "world-runtime", + (actual, attempt, fence) -> projection(actual, attempt, fence), + releases); + + assertTransactionFailureMapsToUnavailable(service, request(tuple), failure); + } + + @Test + void preservesAssociationCallerConflictForFailedReleaseParticipant() { + var service = + new StartSessionTemplateAssociationReadService( + dsl, + unusedTransactionManager(), + "world-runtime", + (tuple, attempt, fence) -> null, + releases); + var failed = + new PublishedReleaseBundleDto( + 1L, + "tenant", + 2L, + 1, + "v1", + "workflow", + "sha256:" + "a".repeat(64), + List.of(), + List.of( + new net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto( + "GAME_LOGIC", + "full", + "commit", + "sha256:" + "b".repeat(64), + 1, + "REJECTED", + "failed")), + List.of(), + "generation-1", + false, + null, + java.time.LocalDateTime.parse("2026-01-01T00:00:00"), + TENANT, + UUID.fromString("03333333-3333-4333-8333-333333333333"), + "release-ref", + null, + null); + + assertThatThrownBy(() -> service.toPublishedReleaseBundle(failed)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("START_SESSION_PUBLISHED_PARTICIPANT_FAILURE"); + } + + private static void withPeer( + StartSessionTemplateAssociationReadService service, + StartSessionTemplateAssociationReadEvidence.Request request, + String workload) { + withPeer(workload, () -> service.read(request)); + } + + private static void withPeer(String workload, Runnable action) { + var peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/world-runtime/sa/" + workload, "world-runtime", workload); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + action.run(); + } finally { + context.detach(previous); + } + } + + private static void assertTransactionFailureMapsToUnavailable( + StartSessionTemplateAssociationReadService service, + StartSessionTemplateAssociationReadEvidence.Request request, + RuntimeException cause) { + assertThatThrownBy(() -> withPeer(service, request, "game-session-service")) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + thrown -> { + var status = ((StatusRuntimeException) thrown).getStatus(); + assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(status.getDescription()) + .isEqualTo("Game Design association owner storage unavailable"); + assertThat(status.getCause()).isSameAs(cause); + }); + } + + private void assertAuthoredCoreStorageFailure( + RuntimeException storageFailure, Status.Code expectedStatus) { + var tuple = postTuple("authored-core-storage-failure"); + var snapshotOpened = new AtomicBoolean(); + var associationReader = + new StartSessionTemplateAssociationReadService( + dsl, + immediateTransactionManager(snapshotOpened), + "world-runtime", + (actual, attempt, fence) -> projection(actual, attempt, fence), + releases); + var authoredCoreReader = + new AuthoredInitialActorCoreReadService(dsl, "world-runtime", associationReader, JSON); + org.mockito.Mockito.when( + dsl.fetchOne( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(Object[].class))) + .thenAnswer( + ignored -> { + assertThat(snapshotOpened).isTrue(); + throw storageFailure; + }); + + assertThatThrownBy( + () -> + withPeer( + "game-session-service", + () -> authoredCoreReader.read(authoredCoreRequest(tuple)))) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(expectedStatus); + assertThat(snapshotOpened).isTrue(); + org.mockito.Mockito.verify(dsl) + .fetchOne( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(Object[].class)); + } + + private static PlatformTransactionManager immediateTransactionManager( + AtomicBoolean snapshotOpened) { + return new PlatformTransactionManager() { + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + snapshotOpened.set(true); + return new org.springframework.transaction.support.SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) {} + + @Override + public void rollback(TransactionStatus status) {} + }; + } + + private static StartSessionTemplateAssociationReadEvidence.Request request( + StartSessionPostAuthorizationExecutionTuple tuple) { + return new StartSessionTemplateAssociationReadEvidence.Request( + 1, + "world-runtime", + UUID.fromString("01111111-1111-4111-8111-111111111111"), + tuple.canonicalBytes(), + ATTEMPT, + FENCE, + new StartSessionTemplateAssociationReadEvidence.InitialConfigured()); + } + + private static ReadRequest authoredCoreRequest( + StartSessionPostAuthorizationExecutionTuple tuple) { + return new ReadRequest( + new StartSessionTemplateAssociationReadEvidence.Request( + 1, + "world-runtime", + UUID.fromString("01111111-1111-4111-8111-111111111111"), + tuple.canonicalBytes(), + ATTEMPT, + FENCE, + new StartSessionTemplateAssociationReadEvidence.ExactReplay( + UUID.fromString("03333333-3333-4333-8333-333333333333"), + UUID.fromString("04444444-4444-4444-8444-444444444444"), + "selected-workflow", + "sha256:" + "a".repeat(64)))); + } + + private static ReadRedeemedOperationProjectionResponse projection( + StartSessionPostAuthorizationExecutionTuple tuple, UUID attempt, long fence) { + return ReadRedeemedOperationProjectionResponse.newBuilder() + .setControlPlaneRequestId(tuple.controlPlaneRequestId()) + .setCanonicalPreAuthorizationTupleBytes( + ByteString.copyFrom( + tuple + .preAuthorizationTuple() + .canonicalJson() + .getBytes(java.nio.charset.StandardCharsets.UTF_8))) + .setMutationDigest(tuple.preAuthorizationTuple().mutationDigest()) + .setOwnerAttemptId(attempt.toString()) + .setOwnerFence(fence) + .setAuthenticatedRedeemerWorkloadIdentity( + "spiffe://firemud/ns/world-runtime/sa/game-session-service") + .build(); + } + + private static PlatformTransactionManager unusedTransactionManager() { + return new PlatformTransactionManager() { + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + throw new AssertionError("Local storage must not be reached"); + } + + @Override + public void commit(TransactionStatus status) { + throw new AssertionError("No transaction should be committed"); + } + + @Override + public void rollback(TransactionStatus status) { + throw new AssertionError("No transaction should be rolled back"); + } + }; + } + + private static StartSessionPostAuthorizationExecutionTuple postTuple(String requestId) { + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman( + requestId, + 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()), + "exact StartSession account projection")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + 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/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionRepositoryTest.java new file mode 100644 index 0000000000..e352692494 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionRepositoryTest.java @@ -0,0 +1,304 @@ +package net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.time.LocalDateTime; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreSourceBinding; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; +import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; +import net.firedevops.firemud.common.gamedesign.RealmPolicySource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Audience; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Disposition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Feedback; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ReplayPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Visibility; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.gamedesign.repository.StartSessionAuthoredActorCoreProjectionRepository.RetainedProjection; +import net.firedevops.firemud.gamedesign.repository.StartSessionLaunchDescriptorRepository.Binding; +import org.junit.jupiter.api.Test; + +class StartSessionAuthoredActorCoreProjectionRepositoryTest { + private static final String NAMESPACE = "world-runtime"; + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID COMMIT = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID SOURCE_OPERATION = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID BINDING_ID = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID ATTEMPT = uuid("66666666-6666-4666-8666-666666666666"); + private static final String REQUEST_ID = "actor-core-owner-request"; + private static final String WORKFLOW = "published-workflow"; + private static final String SOURCE_DIGEST = digest('a'); + + @Test + void replaysExactFullPrivateProofAndSameProjectionIdentityWithoutReselection() { + AuthoredInitialActorCoreSourceBinding source = sourceBinding("original terminal evidence"); + AuthoredInitialActorCoreProjection projection = + AuthoredInitialActorCoreProjection.fromValidatedBinding(BINDING_ID, source); + RetainedProjection retained = retained(owner(), source, projection, 0); + + var replay = + StartSessionAuthoredActorCoreProjectionRepository.validateReplay( + List.of(retained), List.of(source), owner()); + + assertThat(replay).hasSize(1); + assertThat(replay.getFirst().bindingId()).isEqualTo(BINDING_ID); + assertThat(replay.getFirst().canonicalBytes()).isEqualTo(projection.canonicalBytes()); + assertThat(retained.sourceBindingBytes()).isEqualTo(source.canonicalBytes()); + assertThat(retained.projectionBytes()).isEqualTo(projection.canonicalBytes()); + } + + @Test + void deniesHistoricalMissingProofAndFullPrivateContentConflict() { + AuthoredInitialActorCoreSourceBinding source = sourceBinding("original terminal evidence"); + AuthoredInitialActorCoreProjection projection = + AuthoredInitialActorCoreProjection.fromValidatedBinding(BINDING_ID, source); + + assertThatThrownBy( + () -> + StartSessionAuthoredActorCoreProjectionRepository.validateReplay( + List.of(), List.of(source), owner())) + .isInstanceOf( + StartSessionAuthoredActorCoreProjectionRepository.MissingRetainedProjectionException + .class); + + AuthoredInitialActorCoreSourceBinding changed = + sourceBinding("different but internally well-formed terminal evidence"); + assertThatThrownBy( + () -> + StartSessionAuthoredActorCoreProjectionRepository.validateReplay( + List.of(retained(owner(), source, projection, 0)), List.of(changed), owner())) + .isInstanceOf( + StartSessionAuthoredActorCoreProjectionRepository.RetainedProjectionConflictException + .class) + .hasMessageContaining("private source proof differs"); + } + + @Test + void deniesIncompleteOrReorderedOwnerProofSets() { + AuthoredInitialActorCoreSourceBinding source = sourceBinding("original terminal evidence"); + AuthoredInitialActorCoreProjection projection = + AuthoredInitialActorCoreProjection.fromValidatedBinding(BINDING_ID, source); + RetainedProjection wrongOrder = retained(owner(), source, projection, 1); + + assertThatThrownBy( + () -> + StartSessionAuthoredActorCoreProjectionRepository.validateReplay( + List.of(wrongOrder), List.of(source), owner())) + .isInstanceOf( + StartSessionAuthoredActorCoreProjectionRepository.RetainedProjectionConflictException + .class) + .hasMessageContaining("owner identity or order changed"); + + assertThatThrownBy( + () -> + StartSessionAuthoredActorCoreProjectionRepository.validateReplay( + List.of(retained(owner(), source, projection, 0)), + List.of(source, source), + owner())) + .isInstanceOf( + StartSessionAuthoredActorCoreProjectionRepository.RetainedProjectionConflictException + .class) + .hasMessageContaining("count differs"); + } + + private static RetainedProjection retained( + Binding owner, + AuthoredInitialActorCoreSourceBinding source, + AuthoredInitialActorCoreProjection projection, + int policyOrder) { + return new RetainedProjection( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.controlPlaneRequestId(), + owner.descriptorRowId(), + policyOrder, + projection.bindingId(), + source.canonicalBytes(), + source.digest(), + projection.canonicalBytes(), + projection.digest(), + LocalDateTime.of(2026, 10, 11, 0, 0)); + } + + private static Binding owner() { + return new Binding( + NAMESPACE, + TENANT, + REQUEST_ID, + 81L, + 91L, + 3L, + bytes("original complete Account tuple"), + ATTEMPT, + 2L, + 7L, + VERSION, + COMMIT, + WORKFLOW, + digest('b'), + digest('c'), + SOURCE_OPERATION, + SOURCE_DIGEST, + "world", + 4L, + "EMPTY_V1", + "game-logic-publish-request", + digest('d'), + digest('e'), + digest('f'), + bytes("original association response"), + LocalDateTime.of(2026, 10, 11, 0, 0)); + } + + private static AuthoredInitialActorCoreSourceBinding sourceBinding(String terminalText) { + var target = + new TargetProof( + TENANT, VERSION, 23L, "private-owner-key", 42L, "private-owner-key", "NEW_GAME_ROW"); + String policyJson = + "{\"schemaVersion\":3,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\"," + + "\"realmSlug\":\"realm\",\"realmDisplayName\":\"Realm\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\",\"entryPolicy\":\"PLAYER_CREATED\"," + + "\"creationDescriptor\":{\"schemaVersion\":1,\"descriptorId\":\"77777777-7777-4777-8777-777777777777\"," + + "\"descriptorRevisionId\":\"88888888-8888-4888-8888-888888888888\"," + + "\"inputKind\":\"EMPTY_OBJECT\",\"dependencies\":[]}," + + "\"initialActorCore\":{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}}"; + var policyPayload = + RealmPolicySource.canonical( + Map.of( + "revisionKind", + RealmPolicySource.REVISION_KIND, + "logicalRevisionId", + "policy-logical-r1", + "policy", + RealmPolicySource.tree(policyJson))); + var disposition = new Disposition("newcomer", List.of(), "welcome"); + var feedback = + new Feedback( + "welcome", + "actor.created", + Audience.SOURCE_ACTOR, + "actor.created", + "Welcome, traveler.", + List.of(), + Visibility.PUBLIC, + ReplayPolicy.EFFECT_IDEMPOTENT); + List revisions = + List.of( + new RevisionPayload( + "0", + uuid("99999999-9999-4999-8999-999999999999"), + Owner.GAME_DESIGN_CONTROL_PLANE, + policyPayload), + new RevisionPayload( + "1", + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload(disposition)), + new RevisionPayload( + "2", + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload(feedback))); + DraftCommitBinding commit = + DraftCommitBinding.create( + target, + uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + COMMIT, + "base-0", + revisions, + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + VERSION.toString(), + RealmPolicySource.SCOPE, + "effective", + "0"), + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.SCOPE, + VERSION.toString(), + GameplayRuleSource.SCOPE, + GameplayRuleSource.SCOPE_ID, + "0"))); + RealmPolicySnapshot policySnapshot = + new RealmPolicySnapshot( + commit, "1", List.of(RealmPolicySource.revision(commit, revisions.getFirst()))); + var rules = GameplayRuleSource.replay(List.of(), commit); + GameplayRuleSelectedSource gameplaySnapshot = selectedGameplaySource(commit, rules); + return AuthoredInitialActorCoreSourceBinding.resolveAll( + SOURCE_OPERATION, + SOURCE_DIGEST, + "world", + WORKFLOW, + bytes("original publication request bytes"), + bytes(terminalText), + commit, + policySnapshot, + gameplaySnapshot) + .getFirst(); + } + + private static GameplayRuleSelectedSource selectedGameplaySource( + DraftCommitBinding binding, List entries) { + Map> families = new LinkedHashMap<>(); + for (Family family : Family.values()) { + families.put( + family, + entries.stream() + .filter(entry -> entry.family() == family) + .map(GameplayRuleSource.Entry::definition) + .toList()); + } + GameplayRuleManifest manifest = new GameplayRuleManifest(families); + Map snapshot = new LinkedHashMap<>(); + snapshot.put("schema", "game-design-gameplay-rule-source-snapshot/v1"); + snapshot.put("bindingJson", binding.canonicalJson()); + snapshot.put("bindingDigest", binding.digest()); + snapshot.put("sourceEpoch", "1"); + snapshot.put("inheritedCommitId", ""); + snapshot.put("genesisReceiptId", "dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + snapshot.put("manifestJson", manifest.canonicalJson()); + snapshot.put( + "entries", + entries.stream() + .map( + entry -> + Map.of( + "family", entry.family().name(), + "definitionJson", GameplayRuleManifest.canonical(entry.definition()), + "sourceBindingJson", entry.sourceBinding().canonicalJson(), + "sourceBindingDigest", entry.sourceBinding().digest(), + "revisionOrder", entry.revisionOrder(), + "revisionId", entry.revisionId().toString())) + .toList()); + return new GameplayRuleSelectedSource(CommandSource.canonical(snapshot)); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameTemplateServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameTemplateServiceImplTest.java index 3dc378824f..e6c418c445 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameTemplateServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameTemplateServiceImplTest.java @@ -1,12 +1,15 @@ package net.firedevops.firemud.gamedesign.service.impl; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.util.List; import net.firedevops.firemud.gamedesign.dto.GameTemplateDto; import net.firedevops.firemud.gamedesign.entity.GameTemplate; import net.firedevops.firemud.gamedesign.mapper.GameTemplateMapper; +import net.firedevops.firemud.gamedesign.model.TemplateReferencePhase; import net.firedevops.firemud.gamedesign.repository.GameTemplateRepository; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -15,6 +18,60 @@ import org.springframework.data.domain.PageRequest; class GameTemplateServiceImplTest { + @Test + void createWithoutIdUsesThePersistedIdentityAndPreservesItsTenant() { + GameTemplateRepository repo = Mockito.mock(GameTemplateRepository.class); + GameTemplateMapper mapper = Mockito.mock(GameTemplateMapper.class); + GameTemplateServiceImpl service = new GameTemplateServiceImpl(repo, mapper); + GameTemplateDto request = + new GameTemplateDto(null, "tenant-a", "Fresh", null, "{}", null, null, null, null, null); + GameTemplate mapped = new GameTemplate(); + mapped.setTenantId(request.tenantId()); + mapped.setName(request.name()); + GameTemplate saved = new GameTemplate(); + saved.setId(73L); + saved.setTenantId(request.tenantId()); + GameTemplateDto result = + new GameTemplateDto( + 73L, + "tenant-a", + "Fresh", + null, + "{}", + null, + null, + "{}", + TemplateReferencePhase.ENFORCED, + null); + when(mapper.toEntity(request)).thenReturn(mapped); + when(repo.save(mapped)).thenReturn(saved); + when(mapper.toDto(saved)).thenReturn(result); + + assertEquals(result, service.createTemplate(request)); + Mockito.verify(repo).save(mapped); + } + + @Test + void createRejectsCallerSuppliedIdBeforeMappingOrRepositoryAccess() { + GameTemplateRepository repo = Mockito.mock(GameTemplateRepository.class); + GameTemplateMapper mapper = Mockito.mock(GameTemplateMapper.class); + GameTemplateServiceImpl service = new GameTemplateServiceImpl(repo, mapper); + GameTemplateDto request = + new GameTemplateDto( + 19L, "tenant-b", "Replacement", null, "{}", null, null, null, null, null); + GameTemplate mapped = new GameTemplate(); + mapped.setId(request.id()); + mapped.setTenantId(request.tenantId()); + when(mapper.toEntity(request)).thenReturn(mapped); + when(repo.save(mapped)).thenReturn(mapped); + when(mapper.toDto(mapped)).thenReturn(request); + + assertThatThrownBy(() -> service.createTemplate(request)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("INVALID_ARGUMENT: template id must not be supplied on create"); + verifyNoInteractions(repo, mapper); + } + @Test void listTemplatesReturnsPage() { GameTemplateRepository repo = Mockito.mock(GameTemplateRepository.class); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java index 34efaaa994..d9b9727840 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java @@ -8,6 +8,7 @@ import static org.mockito.ArgumentMatchers.eq; 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.util.List; @@ -25,6 +26,8 @@ import net.firedevops.firemud.gamedesign.repository.VersionRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mapstruct.factory.Mappers; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -69,6 +72,40 @@ void saveRevisionPersistsEntity() { assertEquals(10L, result.id()); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void saveRevisionRejectsGameplayRulesBeforeAnyRepositoryOrWorldCall(boolean withWorldMutation) { + setupGameAndVersion(); + Revision saved = new Revision(); + saved.setId(10L); + saved.setTenantId("1"); + saved.setVersionId(7L); + saved.setRevisionKind("GAMEPLAY_RULE"); + saved.setData("{}"); + when(revisionRepository.save(any(Revision.class))).thenReturn(saved); + RevisionDto dto = + new RevisionDto( + null, + "1", + 7L, + 3L, + "{}", + "GAMEPLAY_RULE", + "rule-revision", + withWorldMutation ? generationSubtreeMutation() : null, + null, + null); + + IllegalArgumentException ex = + assertThrows(IllegalArgumentException.class, () -> service.saveRevision(dto)); + + assertEquals( + "INVALID_ARGUMENT: GAMEPLAY_RULE requires authorized coordinated source authoring", + ex.getMessage()); + verifyNoInteractions( + gameRepository, versionRepository, revisionRepository, worldManagementClient); + } + @Test void saveRevisionRejectsPublishedVersionBeforePersistingOrApplyingMutations() { Game game = new Game(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionRepository.java new file mode 100644 index 0000000000..287ab21208 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionRepository.java @@ -0,0 +1,384 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered, append-only Game Session retention for the exact public Game Design authored-core + * result belonging to one original StartSession launch and owner attempt. + * + *

This repository persists only the already-authenticated public result and its exact owner + * bindings. It does not authenticate Game Design, select a policy, allocate an actor, or grant + * runtime authority. + */ +public final class GameSessionAuthoredActorCoreRetentionRepository { + private static final String TABLE = "gs_original_start_session_authored_actor_core_retention"; + + private final DSLContext dsl; + private final String workloadNamespace; + private final TransactionTemplate readTransaction; + + public GameSessionAuthoredActorCoreRetentionRepository( + DSLContext dsl, PlatformTransactionManager transactionManager, String workloadNamespace) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + Objects.requireNonNull(transactionManager, "transactionManager"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Session workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + readTransaction = new TransactionTemplate(transactionManager); + readTransaction.setReadOnly(true); + readTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + readTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + } + + /** Reads the immutable row by original operation identity in an independent owner snapshot. */ + public Optional readByOriginalOperation( + String targetNamespace, String controlPlaneRequestId) { + requireNoOwnerTransaction(); + requireIdentity(targetNamespace, controlPlaneRequestId); + if (!workloadNamespace.equals(targetNamespace)) { + throw new IllegalArgumentException( + "Authored-core retention read differs from configured Game Session workload namespace"); + } + Optional result = + readTransaction.execute( + status -> { + Record row = select(targetNamespace, controlPlaneRequestId); + return row == null ? Optional.empty() : Optional.of(snapshot(row)); + }); + return Objects.requireNonNull(result, "Authored-core retention read returned no result"); + } + + /** + * Appends or exact-replays one result inside the caller's writable owner transaction. The caller + * must have locked and revalidated the original live attempt in this same transaction. + */ + public StoredSource retainInOwnerTransaction(Candidate candidate) { + requireOwnerTransaction(); + Objects.requireNonNull(candidate, "retention candidate"); + requireIdentity(candidate.targetNamespace(), candidate.controlPlaneRequestId()); + if (!workloadNamespace.equals(candidate.targetNamespace())) { + throw new IllegalArgumentException( + "Authored-core retention namespace differs from configured Game Session owner"); + } + + dsl.execute( + "INSERT INTO " + + TABLE + + " (target_namespace, control_plane_request_id, canonical_tenant_id, " + + "game_instance_uuid, owner_attempt_id, owner_mutation_id, owner_fence, " + + "owner_lease_expires_at, original_post_authorization_tuple, " + + "account_redemption_projection, account_redemption_projection_digest, " + + "canonical_version_id, selected_commit_id, publish_workflow_id, association_digest, " + + "world_source_operation_id, world_source_evidence_digest, world_slug, " + + "launch_descriptor_id, descriptor_request_digest, descriptor_result_digest, " + + "release_attestation_evidence_digest, source_read_request_bytes, " + + "canonical_source_result_bytes, source_result_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (target_namespace, control_plane_request_id) DO NOTHING", + candidate.targetNamespace(), + candidate.controlPlaneRequestId(), + candidate.canonicalTenantId(), + candidate.gameInstanceUuid(), + candidate.ownerAttemptId(), + candidate.ownerMutationId(), + candidate.ownerFence(), + candidate.ownerLeaseExpiresAt(), + candidate.originalPostAuthorizationTuple(), + candidate.accountRedemptionProjection(), + candidate.accountRedemptionProjectionDigest(), + candidate.canonicalVersionId(), + candidate.selectedCommitId(), + candidate.publishWorkflowId(), + candidate.associationDigest(), + candidate.worldSourceOperationId(), + candidate.worldSourceEvidenceDigest(), + candidate.worldSlug(), + candidate.launchDescriptorId(), + candidate.descriptorRequestDigest(), + candidate.descriptorResultDigest(), + candidate.releaseAttestationEvidenceDigest(), + candidate.sourceReadRequestBytes(), + candidate.canonicalSourceResultBytes(), + candidate.sourceResultDigest()); + + Record row = select(candidate.targetNamespace(), candidate.controlPlaneRequestId()); + if (row == null) { + throw new IllegalStateException("Authored-core retention row did not read back"); + } + StoredSource stored = snapshot(row); + requireExactCandidate(candidate, stored.candidate()); + return stored; + } + + private Record select(String targetNamespace, String controlPlaneRequestId) { + return dsl.fetchOne( + "SELECT * FROM " + TABLE + " WHERE target_namespace = ? AND control_plane_request_id = ?", + targetNamespace, + controlPlaneRequestId); + } + + private StoredSource snapshot(Record row) { + Candidate candidate = + new Candidate( + required(row, "target_namespace", String.class), + required(row, "control_plane_request_id", String.class), + required(row, "canonical_tenant_id", UUID.class), + required(row, "game_instance_uuid", UUID.class), + required(row, "owner_attempt_id", UUID.class), + required(row, "owner_mutation_id", UUID.class), + required(row, "owner_fence", Long.class), + required(row, "owner_lease_expires_at", java.time.OffsetDateTime.class).toInstant(), + required(row, "original_post_authorization_tuple", byte[].class), + required(row, "account_redemption_projection", byte[].class), + required(row, "account_redemption_projection_digest", String.class), + required(row, "canonical_version_id", UUID.class), + required(row, "selected_commit_id", UUID.class), + required(row, "publish_workflow_id", String.class), + required(row, "association_digest", String.class), + required(row, "world_source_operation_id", UUID.class), + required(row, "world_source_evidence_digest", String.class), + required(row, "world_slug", String.class), + required(row, "launch_descriptor_id", String.class), + required(row, "descriptor_request_digest", String.class), + required(row, "descriptor_result_digest", String.class), + required(row, "release_attestation_evidence_digest", String.class), + required(row, "source_read_request_bytes", byte[].class), + required(row, "canonical_source_result_bytes", byte[].class), + required(row, "source_result_digest", String.class)); + Instant retainedAt = required(row, "retained_at", java.time.OffsetDateTime.class).toInstant(); + return new StoredSource(candidate, retainedAt); + } + + private static void requireExactCandidate(Candidate expected, Candidate stored) { + if (!expected.targetNamespace().equals(stored.targetNamespace()) + || !expected.controlPlaneRequestId().equals(stored.controlPlaneRequestId()) + || !expected.canonicalTenantId().equals(stored.canonicalTenantId()) + || !expected.gameInstanceUuid().equals(stored.gameInstanceUuid()) + || !expected.ownerAttemptId().equals(stored.ownerAttemptId()) + || !expected.ownerMutationId().equals(stored.ownerMutationId()) + || expected.ownerFence() != stored.ownerFence() + || !expected.ownerLeaseExpiresAt().equals(stored.ownerLeaseExpiresAt()) + || !arraysEqual( + expected.originalPostAuthorizationTuple(), stored.originalPostAuthorizationTuple()) + || !arraysEqual( + expected.accountRedemptionProjection(), stored.accountRedemptionProjection()) + || !expected + .accountRedemptionProjectionDigest() + .equals(stored.accountRedemptionProjectionDigest()) + || !expected.canonicalVersionId().equals(stored.canonicalVersionId()) + || !expected.selectedCommitId().equals(stored.selectedCommitId()) + || !expected.publishWorkflowId().equals(stored.publishWorkflowId()) + || !expected.associationDigest().equals(stored.associationDigest()) + || !expected.worldSourceOperationId().equals(stored.worldSourceOperationId()) + || !expected.worldSourceEvidenceDigest().equals(stored.worldSourceEvidenceDigest()) + || !expected.worldSlug().equals(stored.worldSlug()) + || !expected.launchDescriptorId().equals(stored.launchDescriptorId()) + || !expected.descriptorRequestDigest().equals(stored.descriptorRequestDigest()) + || !expected.descriptorResultDigest().equals(stored.descriptorResultDigest()) + || !expected + .releaseAttestationEvidenceDigest() + .equals(stored.releaseAttestationEvidenceDigest()) + || !arraysEqual(expected.sourceReadRequestBytes(), stored.sourceReadRequestBytes()) + || !arraysEqual(expected.canonicalSourceResultBytes(), stored.canonicalSourceResultBytes()) + || !expected.sourceResultDigest().equals(stored.sourceResultDigest())) { + throw new IllegalStateException( + "Original StartSession authored-core retention conflicts with its first exact result"); + } + } + + private void requireIdentity(String targetNamespace, String controlPlaneRequestId) { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical Game Session namespace required"); + } + if (controlPlaneRequestId == null + || controlPlaneRequestId.isBlank() + || controlPlaneRequestId.length() > 128) { + throw new IllegalArgumentException( + "Canonical original StartSession request identity required"); + } + } + + private static void requireNoOwnerTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Authored-core retention read requires an independent owner snapshot"); + } + } + + private static void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isSynchronizationActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Authored-core retention requires a writable caller-owned owner transaction"); + } + } + + private static T required(Record row, String field, Class type) { + T value = row == null ? null : row.get(field, type); + if (value == null) { + throw new IllegalStateException("Retained authored-core result is missing " + field); + } + return value; + } + + private static boolean arraysEqual(byte[] left, byte[] right) { + return MessageDigest.isEqual(left, right); + } + + /** + * One exact append candidate, including the unchanged canonical result returned by Game Design. + */ + public record Candidate( + String targetNamespace, + String controlPlaneRequestId, + UUID canonicalTenantId, + UUID gameInstanceUuid, + UUID ownerAttemptId, + UUID ownerMutationId, + long ownerFence, + Instant ownerLeaseExpiresAt, + byte[] originalPostAuthorizationTuple, + byte[] accountRedemptionProjection, + String accountRedemptionProjectionDigest, + UUID canonicalVersionId, + UUID selectedCommitId, + String publishWorkflowId, + String associationDigest, + UUID worldSourceOperationId, + String worldSourceEvidenceDigest, + String worldSlug, + String launchDescriptorId, + String descriptorRequestDigest, + String descriptorResultDigest, + String releaseAttestationEvidenceDigest, + byte[] sourceReadRequestBytes, + byte[] canonicalSourceResultBytes, + String sourceResultDigest) { + public Candidate { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + Objects.requireNonNull(controlPlaneRequestId, "controlPlaneRequestId"); + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(gameInstanceUuid, "gameInstanceUuid"); + Objects.requireNonNull(ownerAttemptId, "ownerAttemptId"); + Objects.requireNonNull(ownerMutationId, "ownerMutationId"); + Objects.requireNonNull(ownerLeaseExpiresAt, "ownerLeaseExpiresAt"); + Objects.requireNonNull(canonicalVersionId, "canonicalVersionId"); + Objects.requireNonNull(selectedCommitId, "selectedCommitId"); + Objects.requireNonNull(publishWorkflowId, "publishWorkflowId"); + Objects.requireNonNull(associationDigest, "associationDigest"); + Objects.requireNonNull(worldSourceOperationId, "worldSourceOperationId"); + Objects.requireNonNull(worldSourceEvidenceDigest, "worldSourceEvidenceDigest"); + Objects.requireNonNull(worldSlug, "worldSlug"); + Objects.requireNonNull(launchDescriptorId, "launchDescriptorId"); + Objects.requireNonNull(descriptorRequestDigest, "descriptorRequestDigest"); + Objects.requireNonNull(descriptorResultDigest, "descriptorResultDigest"); + Objects.requireNonNull(releaseAttestationEvidenceDigest, "releaseAttestationEvidenceDigest"); + Objects.requireNonNull( + accountRedemptionProjectionDigest, "accountRedemptionProjectionDigest"); + Objects.requireNonNull(sourceResultDigest, "sourceResultDigest"); + originalPostAuthorizationTuple = + copyBounded(originalPostAuthorizationTuple, 262_144, "original tuple"); + accountRedemptionProjection = + copyBounded(accountRedemptionProjection, 262_144, "Account projection"); + sourceReadRequestBytes = copyBounded(sourceReadRequestBytes, 524_288, "source read request"); + canonicalSourceResultBytes = + copyBounded( + canonicalSourceResultBytes, + AuthoredInitialActorCoreReadEvidence.MAX_RESULT_BYTES, + "canonical source result"); + if (ownerFence <= 0L) { + throw new IllegalArgumentException("ownerFence must be positive"); + } + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(originalPostAuthorizationTuple); + if (!tuple.controlPlaneRequestId().equals(controlPlaneRequestId) + || !tuple + .preAuthorizationTuple() + .action() + .scope() + .targetNamespace() + .equals(targetNamespace) + || !tuple.preAuthorizationTuple().action().scope().tenantId().equals(canonicalTenantId)) { + throw new IllegalArgumentException("Retention identity differs from the original tuple"); + } + if (!sha256Hex(accountRedemptionProjection).equals(accountRedemptionProjectionDigest)) { + throw new IllegalArgumentException("Account projection digest differs from exact bytes"); + } + if (!sha256(canonicalSourceResultBytes).equals(sourceResultDigest)) { + throw new IllegalArgumentException( + "Source result digest differs from exact canonical bytes"); + } + } + + @Override + public byte[] originalPostAuthorizationTuple() { + return originalPostAuthorizationTuple.clone(); + } + + @Override + public byte[] accountRedemptionProjection() { + return accountRedemptionProjection.clone(); + } + + @Override + public byte[] sourceReadRequestBytes() { + return sourceReadRequestBytes.clone(); + } + + @Override + public byte[] canonicalSourceResultBytes() { + return canonicalSourceResultBytes.clone(); + } + } + + /** Immutable independent owner readback. */ + public record StoredSource(Candidate candidate, Instant retainedAt) { + public StoredSource { + Objects.requireNonNull(candidate, "candidate"); + Objects.requireNonNull(retainedAt, "retainedAt"); + } + } + + private static byte[] copyBounded(byte[] value, int maximum, String label) { + Objects.requireNonNull(value, label); + if (value.length == 0 || value.length > maximum) { + throw new IllegalArgumentException("Complete bounded " + label + " bytes required"); + } + return value.clone(); + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static String sha256Hex(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAuthoredActorCoreRetentionService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAuthoredActorCoreRetentionService.java new file mode 100644 index 0000000000..8461a029cb --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAuthoredActorCoreRetentionService.java @@ -0,0 +1,504 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadClient; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; +import net.firedevops.firemud.gamedesign.v1.ParticipantDigest; +import net.firedevops.firemud.gamedesign.v1.PublishedArtifactDigest; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository.OriginalStartSessionAssociation; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredActorCoreRetentionRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredActorCoreRetentionRepository.Candidate; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredActorCoreRetentionRepository.StoredSource; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +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 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; + +/** + * Unregistered composition that retains the exact authenticated Game Design authored-core result + * against its actual Game Session launch and original live owner attempt. + * + *

The result is observation evidence only. An empty projection list remains an exact retained + * source result and does not grant Entity allocation, presence, placement, admission, or activation + * authority. + */ +public final class GameSessionAuthoredActorCoreRetentionService { + private final String workloadNamespace; + private final CanonicalGameInstanceLaunchAssociationRepository launches; + private final GameSessionStartSessionOperatorAttemptRepository attempts; + private final AuthoredInitialActorCoreReadClient gameDesign; + private final GameSessionAuthoredActorCoreRetentionRepository retention; + private final TransactionOperations currentAttemptTransaction; + private final TransactionOperations retentionTransaction; + + public GameSessionAuthoredActorCoreRetentionService( + String workloadNamespace, + CanonicalGameInstanceLaunchAssociationRepository launches, + GameSessionStartSessionOperatorAttemptRepository attempts, + AuthoredInitialActorCoreReadClient gameDesign, + GameSessionAuthoredActorCoreRetentionRepository retention, + PlatformTransactionManager transactionManager) { + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Session workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + this.launches = Objects.requireNonNull(launches, "launches"); + this.attempts = Objects.requireNonNull(attempts, "attempts"); + this.gameDesign = Objects.requireNonNull(gameDesign, "gameDesign"); + this.retention = Objects.requireNonNull(retention, "retention"); + Objects.requireNonNull(transactionManager, "transactionManager"); + currentAttemptTransaction = writableReadCommitted(transactionManager); + retentionTransaction = writableReadCommitted(transactionManager); + } + + /** + * Reads, authenticates, and retains the exact owner-qualified result for one complete historical + * original selection. Exact retries return the first retained bytes, including an empty result, + * without extending the lease or repeating the remote source read. + */ + public StoredSource retain( + HistoricalOriginalStartSessionOwnerEvidence.Result historical, + OriginalStartSessionCurrentAttemptEvidence.Request currentAttemptRequest) { + requireNoAmbientTransaction(); + Objects.requireNonNull(historical, "historical owner evidence"); + Objects.requireNonNull(currentAttemptRequest, "current original-attempt request"); + requireHistoricalAttemptMatch(historical, currentAttemptRequest); + + var historicalRequest = historical.request(); + var associationRequest = historical.descriptorPin().associationRead().request(); + var sourceReadRequest = + new AuthoredInitialActorCoreReadEvidence.ReadRequest(associationRequest); + byte[] sourceReadRequestBytes = + StartSessionTemplateAssociationReadGrpcCodec.toRequest(associationRequest).toByteArray(); + byte[] accountProjection = historical.accountRedemptionProjection(); + String requestId = historical.originalTuple().controlPlaneRequestId(); + + var existing = retention.readByOriginalOperation(workloadNamespace, requestId); + if (existing.isPresent()) { + StoredSource stored = existing.orElseThrow(); + requireStoredRetryMatches( + stored, historical, currentAttemptRequest, sourceReadRequestBytes, accountProjection); + return stored; + } + + OriginalStartSessionAssociation originalLaunch = + launches + .readOriginalStartSessionAssociation(historicalRequest.associationSelector()) + .orElseThrow( + () -> + new IllegalStateException( + "Exact actual Game Session launch association is unavailable")); + requireLaunchMatchesHistorical(originalLaunch, historical, currentAttemptRequest); + CanonicalGameInstanceLaunchAssociation launch = originalLaunch.association(); + + AttemptSnapshot firstAttempt = readCurrentAttempt(currentAttemptRequest); + requireAttemptMatchesHistorical(firstAttempt, historical, currentAttemptRequest); + + requireNoAmbientTransaction(); + AuthoredInitialActorCoreReadEvidence.ReadResult source = gameDesign.read(sourceReadRequest); + requireSourceMatches(launch, historical, sourceReadRequest, source); + Candidate candidate = + candidate(launch, historical, firstAttempt, sourceReadRequestBytes, source); + + StoredSource committed = + retentionTransaction.execute( + status -> { + AttemptSnapshot finalAttempt = + readCurrentAttemptInOwnerTransaction(currentAttemptRequest); + requireSameLiveAttempt(firstAttempt, finalAttempt); + return retention.retainInOwnerTransaction(candidate); + }); + if (committed == null) { + throw new IllegalStateException("Authored-core retention transaction returned no row"); + } + + StoredSource independentReadback = + retention + .readByOriginalOperation(workloadNamespace, requestId) + .orElseThrow( + () -> + new IllegalStateException( + "Committed authored-core source retention is unavailable on independent readback")); + requireSameStoredSource(candidate, committed, independentReadback); + return independentReadback; + } + + private AttemptSnapshot readCurrentAttempt( + OriginalStartSessionCurrentAttemptEvidence.Request request) { + AttemptSnapshot snapshot = + currentAttemptTransaction.execute(status -> readCurrentAttemptInOwnerTransaction(request)); + if (snapshot == null) { + throw new IllegalStateException("Current original-attempt transaction returned no row"); + } + return snapshot; + } + + private AttemptSnapshot readCurrentAttemptInOwnerTransaction( + OriginalStartSessionCurrentAttemptEvidence.Request request) { + AttemptSnapshot snapshot = attempts.readCurrentOriginalAttempt(request); + requireCurrentAttemptSnapshot(request, snapshot); + return snapshot; + } + + private Candidate candidate( + CanonicalGameInstanceLaunchAssociation launch, + HistoricalOriginalStartSessionOwnerEvidence.Result historical, + AttemptSnapshot attempt, + byte[] sourceReadRequestBytes, + AuthoredInitialActorCoreReadEvidence.ReadResult source) { + var association = source.associationRead().association(); + var descriptor = launch.launchBindingEvidence().descriptor(); + var release = launch.launchBindingEvidence().releaseAttestation(); + return new Candidate( + workloadNamespace, + launch.controlPlaneRequestId(), + launch.canonicalTenantId(), + launch.gameInstanceUuid(), + attempt.ownerAttemptId(), + attempt.ownerMutationId(), + attempt.ownerFence(), + attempt.leaseExpiresAt(), + historical.originalTuple().canonicalBytes(), + attempt.accountRedemptionProjection(), + OriginalStartSessionCurrentAttemptEvidence.projectionDigest( + attempt.accountRedemptionProjection()), + association.canonicalVersionId(), + association.selectedCommitId(), + association.publishWorkflowId(), + association.associationDigest(), + association.sourceOperationId(), + association.sourceEvidenceDigest(), + association.worldSlug(), + descriptor.launchDescriptorId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest(), + sourceReadRequestBytes, + source.canonicalBytes(), + source.digest()); + } + + private void requireHistoricalAttemptMatch( + HistoricalOriginalStartSessionOwnerEvidence.Result historical, + OriginalStartSessionCurrentAttemptEvidence.Request request) { + var tuple = historical.originalTuple(); + var action = tuple.preAuthorizationTuple().action(); + if (!workloadNamespace.equals(request.targetNamespace()) + || !workloadNamespace.equals(historical.request().associationSelector().targetNamespace()) + || !action.scope().targetNamespace().equals(workloadNamespace) + || !tuple.controlPlaneRequestId().equals(request.originalTuple().controlPlaneRequestId()) + || !Arrays.equals(tuple.canonicalBytes(), request.canonicalPostAuthorizationTuple()) + || !historical.ownerAttemptId().equals(request.expectedOwnerAttemptId()) + || historical.ownerFence() != request.expectedOwnerFence() + || !tuple + .controlPlaneRequestId() + .equals(historical.request().associationSelector().controlPlaneRequestId()) + || !action + .scope() + .tenantId() + .equals(historical.request().associationSelector().canonicalTenantId()) + || !Arrays.equals( + StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple), + historical.accountRedemptionProjection())) { + throw new StartSessionOperatorAttemptConflictException( + "Historical source selection differs from the exact original attempt or tuple"); + } + } + + private void requireLaunchMatchesHistorical( + OriginalStartSessionAssociation original, + HistoricalOriginalStartSessionOwnerEvidence.Result historical, + OriginalStartSessionCurrentAttemptEvidence.Request request) { + var launch = original.association(); + var retained = historical.launchAssociation(); + if (!Arrays.equals( + original.postAuthorizationExecutionTuple().canonicalBytes(), + historical.originalTuple().canonicalBytes()) + || !Arrays.equals( + original.postAuthorizationExecutionTuple().canonicalBytes(), + request.canonicalPostAuthorizationTuple()) + || !original.ownerAttemptId().equals(historical.ownerAttemptId()) + || !original.ownerAttemptId().equals(request.expectedOwnerAttemptId()) + || original.ownerFence() != historical.ownerFence() + || original.ownerFence() != request.expectedOwnerFence() + || launch.currentGameInstanceStatus() + != CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.STARTING) { + throw new StartSessionOperatorAttemptConflictException( + "Actual original launch differs from the historical tuple or current owner selector"); + } + if (!workloadNamespace.equals(launch.targetNamespace()) + || !launch.targetNamespace().equals(retained.targetNamespace()) + || !launch.canonicalTenantId().equals(retained.canonicalTenantId()) + || !launch.worldSlug().equals(retained.worldSlug()) + || !launch.gameInstanceUuid().equals(retained.gameInstanceUuid()) + || !launch.controlPlaneRequestId().equals(retained.controlPlaneRequestId()) + || !launch + .launchBindingEvidence() + .descriptor() + .launchDescriptorId() + .equals(retained.launchDescriptorId()) + || !launch.playableStateNamespaceId().equals(retained.playableStateNamespaceId()) + || launch.playableStateScope() != retained.playableStateScope() + || launch.publicProduction() != retained.publicProduction() + || launch.capturedStartingRowVersion() != retained.capturedStartingRowVersion() + || !launch.launchBindingEvidence().equals(retained.launchBindingEvidence())) { + throw new StartSessionOperatorAttemptConflictException( + "Actual immutable launch differs from the historical selected descriptor or release"); + } + } + + private void requireAttemptMatchesHistorical( + AttemptSnapshot attempt, + HistoricalOriginalStartSessionOwnerEvidence.Result historical, + OriginalStartSessionCurrentAttemptEvidence.Request request) { + requireCurrentAttemptSnapshot(request, attempt); + if (!historical.ownerAttemptId().equals(attempt.ownerAttemptId()) + || historical.ownerFence() != attempt.ownerFence() + || !Arrays.equals( + historical.accountRedemptionProjection(), attempt.accountRedemptionProjection())) { + throw new StartSessionOperatorAttemptConflictException( + "Current owner attempt differs from the historical Account and selection evidence"); + } + } + + private void requireSourceMatches( + CanonicalGameInstanceLaunchAssociation launch, + HistoricalOriginalStartSessionOwnerEvidence.Result historical, + AuthoredInitialActorCoreReadEvidence.ReadRequest expected, + AuthoredInitialActorCoreReadEvidence.ReadResult source) { + Objects.requireNonNull(source, "authenticated Game Design source result"); + var sourceRequest = expected.associationRequest(); + var selection = source.associationRead().association(); + var expectedSelection = historical.firstSelection().association(); + var descriptor = launch.launchBindingEvidence().descriptor(); + if (!sourceRequest.equals(source.request()) + || !sourceRequest.equals(source.associationRead().request()) + || !selection.equals(expectedSelection) + || !source.descriptor().equals(descriptor) + || !source + .associationRead() + .releaseBundle() + .equals(historical.descriptorPin().associationRead().releaseBundle())) { + throw new StartSessionOperatorAttemptConflictException( + "Authenticated Game Design result differs from the exact original association or launch binding"); + } + requireSelectedReleaseMatches( + selection, + source.associationRead().releaseBundle(), + source.associationRead().worldPublishedStartLocationEvidence(), + descriptor, + launch.launchBindingEvidence().releaseAttestation()); + } + + private static void requireSelectedReleaseMatches( + net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence + .Association + association, + PublishedReleaseBundle bundle, + net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence worldStart, + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldReleaseAttestationEvidence attestation) { + descriptor.requireValid(); + attestation.requireValid(descriptor); + if (!association.canonicalTenantId().equals(attestation.canonicalTenantId()) + || !association.canonicalVersionId().equals(attestation.canonicalVersionId()) + || !association.selectedCommitId().toString().equals(attestation.commitId()) + || !association.publishWorkflowId().equals(attestation.publishWorkflowId()) + || !association.sourceOperationId().equals(attestation.authoredWorldSourceOperationId()) + || !association + .sourceEvidenceDigest() + .equals(attestation.authoredWorldSourceEvidenceDigest()) + || !association.worldSlug().equals(attestation.worldSlug()) + || !Objects.equals(worldStart, attestation.worldStartLocationEvidence()) + || bundle.getId() != descriptor.releaseBundleId() + || bundle.getVersionId() != descriptor.versionId() + || bundle.getIsScriptOnly() + || !bundle.getPublishedReleaseBundleRef().equals(descriptor.publishedReleaseBundleRef()) + || !bundle.getCanonicalTenantId().equals(attestation.canonicalTenantId().toString()) + || !bundle.getCanonicalVersionId().equals(attestation.canonicalVersionId().toString()) + || !bundle.getPublishWorkflowId().equals(attestation.publishWorkflowId()) + || !bundle.getAttestationSchemaVersion().equals("v" + attestation.schemaVersion()) + || !bundle.getManifestHash().equals(attestation.manifestHash()) + || !bundle.hasManifestSchemaVersion() + || bundle.getManifestSchemaVersion() != attestation.manifestSchemaVersion() + || !bundle + .getRequiredManifestAssetKeysList() + .equals(attestation.requiredManifestAssetKeys()) + || !bundle.getGenerationConfigRevision().equals(attestation.generationConfigRevision()) + || !bundle.getCommandDefinitionsList().equals(attestation.commandDefinitions()) + || bundle.getParticipantDigestsCount() != attestation.participantDigests().size() + || bundle.getArtifactDigestsCount() != attestation.artifactDigests().size()) { + throw new StartSessionOperatorAttemptConflictException( + "Selected Game Design release differs from the complete retained launch attestation"); + } + for (int index = 0; index < bundle.getParticipantDigestsCount(); index++) { + ParticipantDigest participant = bundle.getParticipantDigests(index); + AuthoredWorldReleaseAttestationEvidence.Participant expected = + attestation.participantDigests().get(index); + if (!participant.getParticipantKey().equals(expected.participantKey()) + || !participant.getScopeValue().equals(expected.scopeValue()) + || !participant.getAppliedCommitId().equals(expected.appliedCommitId()) + || !participant.getContentDigest().equals(expected.contentDigest()) + || participant.getDigestSchemaVersion() != expected.digestSchemaVersion() + || participant.hasAbilitySchemaDigest() != expected.abilitySchemaDigestPresent() + || (participant.hasAbilitySchemaDigest() + && !participant.getAbilitySchemaDigest().equals(expected.abilitySchemaDigest()))) { + throw new StartSessionOperatorAttemptConflictException( + "Selected release participant evidence differs from the retained launch attestation"); + } + } + for (int index = 0; index < bundle.getArtifactDigestsCount(); index++) { + PublishedArtifactDigest artifact = bundle.getArtifactDigests(index); + AuthoredWorldReleaseAttestationEvidence.Artifact expected = + attestation.artifactDigests().get(index); + if (!artifact.getUsageKey().equals(expected.usageKey()) + || !artifact.getArtifactKind().equals(expected.artifactKind()) + || !artifact.getImmutableObjectKey().equals(expected.immutableObjectKey()) + || !artifact.getContentDigest().equals(expected.contentDigest()) + || !artifact.getContentType().equals(expected.contentType()) + || artifact.getArtifactSchemaVersion() != expected.artifactSchemaVersion()) { + throw new StartSessionOperatorAttemptConflictException( + "Selected release artifacts differ from the retained launch attestation"); + } + } + } + + private static void requireCurrentAttemptSnapshot( + OriginalStartSessionCurrentAttemptEvidence.Request request, AttemptSnapshot snapshot) { + Objects.requireNonNull(snapshot, "current original-attempt 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 + || !Arrays.equals( + StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple), + snapshot.accountRedemptionProjection())) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Exact live pending original StartSession attempt and Account projection are required"); + } + } + + private static void requireSameLiveAttempt(AttemptSnapshot before, AttemptSnapshot after) { + if (!before.targetNamespace().equals(after.targetNamespace()) + || !before.controlPlaneRequestId().equals(after.controlPlaneRequestId()) + || !before.canonicalTenantId().equals(after.canonicalTenantId()) + || !before.ownerAttemptId().equals(after.ownerAttemptId()) + || !before.ownerMutationId().equals(after.ownerMutationId()) + || before.ownerFence() != after.ownerFence() + || !before.phaseState().equals(after.phaseState()) + || !before.leaseExpiresAt().equals(after.leaseExpiresAt()) + || !Arrays.equals( + before.postAuthorizationExecutionTuple(), after.postAuthorizationExecutionTuple()) + || !Arrays.equals( + before.accountRedemptionProjection(), after.accountRedemptionProjection())) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Original StartSession attempt changed during authenticated Game Design read"); + } + } + + private static void requireStoredRetryMatches( + StoredSource stored, + HistoricalOriginalStartSessionOwnerEvidence.Result historical, + OriginalStartSessionCurrentAttemptEvidence.Request request, + byte[] sourceReadRequestBytes, + byte[] accountProjection) { + Candidate candidate = stored.candidate(); + var association = historical.firstSelection().association(); + var descriptor = historical.launchAssociation().launchBindingEvidence().descriptor(); + var release = historical.launchAssociation().launchBindingEvidence().releaseAttestation(); + if (!candidate.targetNamespace().equals(request.targetNamespace()) + || !candidate + .controlPlaneRequestId() + .equals(request.originalTuple().controlPlaneRequestId()) + || !candidate + .canonicalTenantId() + .equals(request.originalTuple().preAuthorizationTuple().action().scope().tenantId()) + || !candidate.gameInstanceUuid().equals(historical.launchAssociation().gameInstanceUuid()) + || !candidate.ownerAttemptId().equals(request.expectedOwnerAttemptId()) + || !candidate.ownerMutationId().equals(request.expectedOwnerMutationId()) + || candidate.ownerFence() != request.expectedOwnerFence() + || !Arrays.equals( + candidate.originalPostAuthorizationTuple(), request.canonicalPostAuthorizationTuple()) + || !Arrays.equals(candidate.accountRedemptionProjection(), accountProjection) + || !Arrays.equals(candidate.sourceReadRequestBytes(), sourceReadRequestBytes) + || !candidate.canonicalVersionId().equals(association.canonicalVersionId()) + || !candidate.selectedCommitId().equals(association.selectedCommitId()) + || !candidate.publishWorkflowId().equals(association.publishWorkflowId()) + || !candidate.associationDigest().equals(association.associationDigest()) + || !candidate.worldSourceOperationId().equals(association.sourceOperationId()) + || !candidate.worldSourceEvidenceDigest().equals(association.sourceEvidenceDigest()) + || !candidate.worldSlug().equals(association.worldSlug()) + || !candidate.launchDescriptorId().equals(descriptor.launchDescriptorId()) + || !candidate.descriptorRequestDigest().equals(descriptor.requestDigest()) + || !candidate.descriptorResultDigest().equals(descriptor.resultDigest()) + || !candidate.releaseAttestationEvidenceDigest().equals(release.evidenceDigest())) { + throw new StartSessionOperatorAttemptConflictException( + "Original StartSession authored-core retry differs from the first retained request"); + } + } + + private static void requireSameStoredSource( + Candidate candidate, StoredSource committed, StoredSource readback) { + if (!committed.retainedAt().equals(readback.retainedAt()) + || !committed + .candidate() + .sourceResultDigest() + .equals(readback.candidate().sourceResultDigest()) + || !committed.candidate().sourceResultDigest().equals(candidate.sourceResultDigest()) + || !MessageDigest.isEqual( + committed.candidate().canonicalSourceResultBytes(), + readback.candidate().canonicalSourceResultBytes()) + || !MessageDigest.isEqual( + candidate.canonicalSourceResultBytes(), + readback.candidate().canonicalSourceResultBytes())) { + throw new IllegalStateException( + "Committed authored-core source failed exact independent readback"); + } + } + + private static TransactionOperations writableReadCommitted( + PlatformTransactionManager transactionManager) { + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setReadOnly(false); + return transaction; + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Authenticated Game Design authored-core read must remain outside Game Session SQL"); + } + } +} diff --git a/services/game-session-service/src/main/resources/db/migration/V1013__retained_original_start_session_authored_core.sql b/services/game-session-service/src/main/resources/db/migration/V1013__retained_original_start_session_authored_core.sql new file mode 100644 index 0000000000..a31149137e --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1013__retained_original_start_session_authored_core.sql @@ -0,0 +1,181 @@ +-- Retain Game Design's exact public authored-core result against its original launch and +-- attempt. The row is source evidence only; it does not authorize allocation or runtime use. +CREATE TABLE gs_original_start_session_authored_actor_core_retention ( + target_namespace VARCHAR(63) NOT NULL, + control_plane_request_id VARCHAR(128) NOT NULL, + canonical_tenant_id UUID NOT NULL, + game_instance_uuid UUID NOT NULL, + owner_attempt_id UUID NOT NULL, + owner_mutation_id UUID NOT NULL, + owner_fence BIGINT NOT NULL, + owner_lease_expires_at TIMESTAMPTZ NOT NULL, + original_post_authorization_tuple BYTEA NOT NULL, + account_redemption_projection BYTEA NOT NULL, + account_redemption_projection_digest VARCHAR(64) NOT NULL, + canonical_version_id UUID NOT NULL, + selected_commit_id UUID NOT NULL, + publish_workflow_id VARCHAR(256) NOT NULL, + association_digest VARCHAR(71) NOT NULL, + world_source_operation_id UUID NOT NULL, + world_source_evidence_digest VARCHAR(71) NOT NULL, + world_slug VARCHAR(120) NOT NULL, + launch_descriptor_id VARCHAR(128) NOT NULL, + descriptor_request_digest VARCHAR(71) NOT NULL, + descriptor_result_digest VARCHAR(71) NOT NULL, + release_attestation_evidence_digest VARCHAR(71) NOT NULL, + source_read_request_bytes BYTEA NOT NULL, + canonical_source_result_bytes BYTEA NOT NULL, + source_result_digest VARCHAR(71) NOT NULL, + retained_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT pk_gs_original_start_session_actor_core_retention + PRIMARY KEY (target_namespace, control_plane_request_id), + CONSTRAINT uq_gs_original_start_session_actor_core_instance + UNIQUE (target_namespace, game_instance_uuid), + CONSTRAINT uq_gs_original_start_session_actor_core_attempt + UNIQUE (owner_attempt_id), + CONSTRAINT fk_gs_original_start_session_actor_core_launch + FOREIGN KEY (target_namespace, control_plane_request_id) + REFERENCES game_session_canonical_instance_launch + (target_namespace, control_plane_request_id) ON DELETE RESTRICT, + CONSTRAINT ck_gs_original_start_session_actor_core_identity CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND control_plane_request_id !~ '^[[:space:]]*$' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND game_instance_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND owner_attempt_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND owner_mutation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND owner_fence > 0 + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND selected_commit_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND publish_workflow_id !~ '^[[:space:]]*$' + AND world_source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + AND launch_descriptor_id !~ '^[[:space:]]*$'), + CONSTRAINT ck_gs_original_start_session_actor_core_content CHECK ( + octet_length(original_post_authorization_tuple) BETWEEN 1 AND 262144 + AND octet_length(account_redemption_projection) BETWEEN 1 AND 262144 + AND account_redemption_projection_digest ~ '^[0-9a-f]{64}$' + AND account_redemption_projection_digest = encode(sha256(account_redemption_projection), 'hex') + AND association_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_source_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND descriptor_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND descriptor_result_digest ~ '^sha256:[0-9a-f]{64}$' + AND release_attestation_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(source_read_request_bytes) BETWEEN 1 AND 524288 + AND octet_length(canonical_source_result_bytes) BETWEEN 1 AND 8388608 + AND source_result_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_result_digest = 'sha256:' || encode(sha256(canonical_source_result_bytes), 'hex')) +); + +-- V35's original-attempt table is intentionally hidden from jOOQ's DDL simulator. Keep the +-- durable relational binding in PostgreSQL while excluding only this cross-relation constraint. +-- [jooq ignore start] +ALTER TABLE gs_original_start_session_authored_actor_core_retention + ADD CONSTRAINT fk_gs_original_start_session_actor_core_attempt + FOREIGN KEY (target_namespace, control_plane_request_id) + REFERENCES game_session_start_session_operator_attempt + (target_namespace, control_plane_request_id) ON DELETE RESTRICT; +-- [jooq ignore stop] + +-- New rows must join the exact complete launch and still-live original pending attempt. The +-- authenticated source result is independently validated in Game Session before it reaches SQL. +-- [jooq ignore start] +CREATE FUNCTION guard_gs_original_start_session_actor_core_retention() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE launch game_session_canonical_instance_launch%ROWTYPE; + attempt game_session_start_session_operator_attempt%ROWTYPE; + source_result JSONB; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Game Session authored-core source retention is immutable and append-only' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT * INTO STRICT launch + FROM game_session_canonical_instance_launch + WHERE target_namespace = NEW.target_namespace + AND control_plane_request_id = NEW.control_plane_request_id; + SELECT * INTO STRICT attempt + FROM game_session_start_session_operator_attempt + WHERE target_namespace = NEW.target_namespace + AND control_plane_request_id = NEW.control_plane_request_id; + + source_result := convert_from(NEW.canonical_source_result_bytes, 'UTF8')::JSONB; + IF launch.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR launch.game_instance_uuid IS DISTINCT FROM NEW.game_instance_uuid + OR launch.original_start_session_tuple IS DISTINCT FROM + NEW.original_post_authorization_tuple + OR launch.launch_descriptor_id IS DISTINCT FROM NEW.launch_descriptor_id + OR launch.world_slug IS DISTINCT FROM NEW.world_slug + OR launch.complete_launch_binding_evidence -> 'descriptor' ->> 'requestDigest' + IS DISTINCT FROM NEW.descriptor_request_digest + OR launch.complete_launch_binding_evidence -> 'descriptor' ->> 'resultDigest' + IS DISTINCT FROM NEW.descriptor_result_digest + OR launch.complete_launch_binding_evidence -> 'descriptor' ->> 'authoredWorldSourceOperationId' + IS DISTINCT FROM NEW.world_source_operation_id::TEXT + OR launch.complete_launch_binding_evidence -> 'descriptor' ->> 'authoredWorldSourceEvidenceDigest' + IS DISTINCT FROM NEW.world_source_evidence_digest + OR launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'evidenceDigest' + IS DISTINCT FROM NEW.release_attestation_evidence_digest + OR launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'canonicalVersionId' + IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'commitId' + IS DISTINCT FROM NEW.selected_commit_id::TEXT + OR launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'publishWorkflowId' + IS DISTINCT FROM NEW.publish_workflow_id + OR launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'authoredWorldSourceOperationId' + IS DISTINCT FROM NEW.world_source_operation_id::TEXT + OR launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'authoredWorldSourceEvidenceDigest' + IS DISTINCT FROM NEW.world_source_evidence_digest + OR launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'worldSlug' + IS DISTINCT FROM NEW.world_slug + OR attempt.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR attempt.owner_attempt_id IS DISTINCT FROM NEW.owner_attempt_id + OR attempt.owner_mutation_id IS DISTINCT FROM NEW.owner_mutation_id + OR attempt.owner_fence IS DISTINCT FROM NEW.owner_fence + OR attempt.post_authorization_execution_tuple IS DISTINCT FROM + NEW.original_post_authorization_tuple + OR attempt.account_redemption_projection IS DISTINCT FROM + NEW.account_redemption_projection + OR attempt.phase_state IS DISTINCT FROM 'OWNER_EXECUTION_PENDING' + OR attempt.lease_expires_at IS DISTINCT FROM NEW.owner_lease_expires_at + OR attempt.lease_expires_at <= clock_timestamp() + OR jsonb_typeof(source_result) IS DISTINCT FROM 'object' + OR source_result ->> 'schema' IS DISTINCT FROM + 'game-design-authored-initial-actor-core-read/v1' + OR (SELECT count(*) FROM jsonb_object_keys(source_result)) <> 5 + OR jsonb_typeof(source_result -> 'request') IS DISTINCT FROM 'string' + OR decode(source_result ->> 'request', 'base64') IS DISTINCT FROM + NEW.source_read_request_bytes + OR jsonb_typeof(source_result -> 'associationRead') IS DISTINCT FROM 'string' + OR jsonb_typeof(source_result -> 'launchDescriptor') IS DISTINCT FROM 'string' + OR jsonb_typeof(source_result -> 'projections') IS DISTINCT FROM 'array' THEN + RAISE EXCEPTION 'Authored-core retention differs from the exact live launch, attempt, or closed result' + USING ERRCODE = '23514', + CONSTRAINT = 'ck_gs_original_start_session_actor_core_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_original_start_session_actor_core_retention_guard + BEFORE INSERT OR UPDATE OR DELETE + ON gs_original_start_session_authored_actor_core_retention + FOR EACH ROW EXECUTE FUNCTION guard_gs_original_start_session_actor_core_retention(); + +CREATE FUNCTION reject_gs_original_start_session_actor_core_retention_truncate() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Game Session authored-core source retention cannot be truncated' + USING ERRCODE = 'check_violation'; +END; +$$; + +CREATE TRIGGER gs_original_start_session_actor_core_retention_no_truncate + BEFORE TRUNCATE ON gs_original_start_session_authored_actor_core_retention + FOR EACH STATEMENT EXECUTE FUNCTION reject_gs_original_start_session_actor_core_retention_truncate(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java index d7f9453d34..a54e968317 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java @@ -1,9 +1,12 @@ package net.firedevops.firemud.gamesession; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; import java.net.URI; +import java.sql.SQLException; import java.time.Duration; +import java.util.EnumMap; import java.util.List; import java.util.Map; import net.firedevops.firemud.gamesession.test.ChatTestFixtures; @@ -39,6 +42,23 @@ class CommunicationWebSocketCrossServiceTest { private static final long DEMO_WORLD_INSTANCE_ID = 1L; private static final String READY_LOOK_TEXT = "Candle-lit Antechamber"; + private enum BaselineTruncateGuard { + CANONICAL_LAUNCH( + "game_session_canonical_instance_launch", + "game_session_canonical_instance_launch_no_truncate"), + AUTHORED_ACTOR_CORE( + "gs_original_start_session_authored_actor_core_retention", + "gs_original_start_session_actor_core_retention_no_truncate"); + + private final String tableName; + private final String triggerName; + + BaselineTruncateGuard(String tableName, String triggerName) { + this.tableName = tableName; + this.triggerName = triggerName; + } + } + @Container static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>(TestContainerImages.postgres()) @@ -265,28 +285,35 @@ void freshGameplayBaselineReappliesConfiguredFriendPresenceBaseline() throws Exc } @Test - void freshGameplayBaselineRestoresAlwaysEnabledLaunchTruncateGuard() throws Exception { + void freshGameplayBaselineRestoresAlwaysEnabledLaunchAndActorCoreTruncateGuards() + throws Exception { ensureTestServicesStarted(); prepareGameInstance(); JdbcTemplate jdbc = STACK.jdbc(); - String originalState = launchGuardState(jdbc); - assertThat(originalState).isIn("O", "A"); + Map originalStates = new EnumMap<>(BaselineTruncateGuard.class); + for (BaselineTruncateGuard guard : BaselineTruncateGuard.values()) { + String originalState = truncateGuardState(jdbc, guard); + assertThat(originalState).isIn("O", "A"); + originalStates.put(guard, originalState); + } try { - jdbc.execute( - "ALTER TABLE game_session_canonical_instance_launch ENABLE ALWAYS TRIGGER " - + "game_session_canonical_instance_launch_no_truncate"); - assertThat(launchGuardState(jdbc)).isEqualTo("A"); + for (BaselineTruncateGuard guard : BaselineTruncateGuard.values()) { + setTruncateGuardState(jdbc, guard, "A"); + assertThat(truncateGuardState(jdbc, guard)).isEqualTo("A"); + } prepareGameInstance(); - assertThat(launchGuardState(jdbc)).isEqualTo("A"); + for (BaselineTruncateGuard guard : BaselineTruncateGuard.values()) { + assertThat(truncateGuardState(jdbc, guard)).isEqualTo("A"); + } + assertOrdinaryTruncateIsRejected(jdbc, BaselineTruncateGuard.AUTHORED_ACTOR_CORE); } finally { - String enableMode = "A".equals(originalState) ? "ENABLE ALWAYS" : "ENABLE"; - jdbc.execute( - "ALTER TABLE game_session_canonical_instance_launch " - + enableMode - + " TRIGGER game_session_canonical_instance_launch_no_truncate"); + originalStates.forEach((guard, state) -> setTruncateGuardState(jdbc, guard, state)); + } + for (BaselineTruncateGuard guard : BaselineTruncateGuard.values()) { + assertThat(truncateGuardState(jdbc, guard)).isEqualTo(originalStates.get(guard)); } } @@ -642,12 +669,52 @@ private long prepareGameInstance() { Long.parseLong(ChatTestFixtures.PLAYER_NYX)); } - private static String launchGuardState(JdbcTemplate jdbc) { - return jdbc.queryForObject( - "SELECT tgenabled::text FROM pg_trigger WHERE tgrelid = " - + "'game_session_canonical_instance_launch'::regclass AND tgname = " - + "'game_session_canonical_instance_launch_no_truncate' AND NOT tgisinternal", - String.class); + private static String truncateGuardState(JdbcTemplate jdbc, BaselineTruncateGuard guard) { + List states = + jdbc.query( + """ + SELECT tgenabled::text + FROM pg_trigger + WHERE tgrelid = CAST(? AS regclass) + AND tgname = CAST(? AS name) + AND NOT tgisinternal + """, + (row, rowNumber) -> row.getString(1), + guard.tableName, + guard.triggerName); + assertThat(states).hasSize(1); + return states.getFirst(); + } + + private static void setTruncateGuardState( + JdbcTemplate jdbc, BaselineTruncateGuard guard, String state) { + String enableMode = + switch (state) { + case "O" -> "ENABLE"; + case "A" -> "ENABLE ALWAYS"; + default -> throw new IllegalArgumentException("Unsupported enabled trigger state"); + }; + jdbc.execute( + "ALTER TABLE " + guard.tableName + " " + enableMode + " TRIGGER " + guard.triggerName); + } + + private static void assertOrdinaryTruncateIsRejected( + JdbcTemplate jdbc, BaselineTruncateGuard guard) { + Throwable failure = catchThrowable(() -> jdbc.execute("TRUNCATE TABLE " + guard.tableName)); + assertThat(failure).isNotNull(); + SQLException sqlException = mostSpecificSqlException(failure); + assertThat((Throwable) sqlException).isNotNull(); + assertThat(sqlException.getSQLState()).isEqualTo("23514"); + } + + private static SQLException mostSpecificSqlException(Throwable failure) { + SQLException result = null; + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sqlException) { + result = sqlException; + } + } + return result; } private void seedLiveTargetSession() { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java index 83688f80f3..d624f10ccd 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java @@ -637,6 +637,7 @@ void pre1006CommittedAndAbortedRowsSurviveForwardProtectionMigration() throws Ex String v1011Guard = launchGuardProjection(predecessor, true); migration(predecessor, null).migrate(); migration(predecessor, null).validate(); + assertV1013RetentionLaunchForeignKey(predecessor); assertThat( predecessor .dsl @@ -1473,16 +1474,85 @@ private static String launchGuardProjection(Fixture fixture, boolean corrected) return guards.get(0).formatJSON(); } + private static void assertV1013RetentionLaunchForeignKey(Fixture fixture) { + var foreignKey = + fixture.dsl.fetchSingle( + "SELECT fk.conname::TEXT, child_namespace.nspname::TEXT AS child_schema, " + + "child.relname::TEXT AS child_table, parent_namespace.nspname::TEXT AS parent_schema, " + + "parent.relname::TEXT AS parent_table, pg_get_constraintdef(fk.oid) AS definition, " + + "fk.convalidated, fk.condeferrable FROM pg_constraint fk " + + "JOIN pg_class child ON child.oid = fk.conrelid " + + "JOIN pg_namespace child_namespace ON child_namespace.oid = child.relnamespace " + + "JOIN pg_class parent ON parent.oid = fk.confrelid " + + "JOIN pg_namespace parent_namespace ON parent_namespace.oid = parent.relnamespace " + + "WHERE fk.conname = 'fk_gs_original_start_session_actor_core_launch' " + + "AND child.relname = 'gs_original_start_session_authored_actor_core_retention' " + + "AND child_namespace.nspname = current_schema() " + + "AND parent.relname = 'game_session_canonical_instance_launch' " + + "AND parent_namespace.nspname = current_schema()"); + assertThat(foreignKey.get("child_schema", String.class)) + .isEqualTo(foreignKey.get("parent_schema", String.class)); + assertThat(foreignKey.get("child_table", String.class)) + .isEqualTo("gs_original_start_session_authored_actor_core_retention"); + assertThat(foreignKey.get("parent_table", String.class)) + .isEqualTo("game_session_canonical_instance_launch"); + assertThat(foreignKey.get("definition", String.class)) + .contains( + "FOREIGN KEY (target_namespace, control_plane_request_id)", + "REFERENCES game_session_canonical_instance_launch(target_namespace, control_plane_request_id)", + "ON DELETE RESTRICT"); + assertThat(foreignKey.get("convalidated", Boolean.class)).isTrue(); + assertThat(foreignKey.get("condeferrable", Boolean.class)).isFalse(); + + var launchTriggers = + fixture.dsl.fetch( + "SELECT launch_trigger.tgtype, launch_trigger.tgenabled::TEXT, " + + "launch_trigger.tgisinternal FROM pg_trigger launch_trigger " + + "JOIN pg_constraint fk ON fk.oid = launch_trigger.tgconstraint " + + "JOIN pg_class child ON child.oid = fk.conrelid " + + "JOIN pg_namespace child_namespace ON child_namespace.oid = child.relnamespace " + + "JOIN pg_class parent ON parent.oid = fk.confrelid " + + "JOIN pg_namespace parent_namespace ON parent_namespace.oid = parent.relnamespace " + + "WHERE fk.conname = 'fk_gs_original_start_session_actor_core_launch' " + + "AND child.relname = 'gs_original_start_session_authored_actor_core_retention' " + + "AND child_namespace.nspname = current_schema() " + + "AND parent.relname = 'game_session_canonical_instance_launch' " + + "AND parent_namespace.nspname = current_schema() " + + "AND launch_trigger.tgrelid = parent.oid ORDER BY launch_trigger.tgtype"); + assertThat(launchTriggers).hasSize(2); + assertThat(launchTriggers) + .extracting(row -> row.get("tgtype", Integer.class)) + .containsExactly(9, 17); + assertThat(launchTriggers) + .allSatisfy( + trigger -> { + assertThat(trigger.get("tgenabled", String.class)).isEqualTo("O"); + assertThat(trigger.get("tgisinternal", Boolean.class)).isTrue(); + }); + } + private static String otherGuardProjection(Fixture fixture) { return fixture .dsl .fetchSingle( "SELECT jsonb_agg(to_jsonb(guard) ORDER BY guard.oid)::TEXT FROM (" - + "SELECT oid, tgrelid, tgname, tgfoid, tgtype, tgenabled FROM pg_trigger " - + "WHERE tgrelid IN ('game_session_canonical_instance_launch'::regclass, " + + "SELECT trigger.oid, trigger.tgrelid, trigger.tgname, trigger.tgfoid, " + + "trigger.tgtype, trigger.tgenabled FROM pg_trigger trigger " + + "WHERE trigger.tgrelid IN ('game_session_canonical_instance_launch'::regclass, " + "'game_session_canonical_initial_admission_attempt'::regclass, " + "'game_session_canonical_initial_admission_intent'::regclass) " - + "AND tgfoid <> 'require_complete_canonical_launch_catalog_identity()'::regprocedure) guard") + + "AND trigger.tgfoid <> 'require_complete_canonical_launch_catalog_identity()'::regprocedure " + + "AND NOT EXISTS (SELECT 1 FROM pg_constraint fk " + + "JOIN pg_class retention_child ON retention_child.oid = fk.conrelid " + + "JOIN pg_namespace retention_namespace ON retention_namespace.oid = retention_child.relnamespace " + + "JOIN pg_class launch_parent ON launch_parent.oid = fk.confrelid " + + "JOIN pg_namespace launch_namespace ON launch_namespace.oid = launch_parent.relnamespace " + + "WHERE fk.oid = trigger.tgconstraint " + + "AND fk.conname = 'fk_gs_original_start_session_actor_core_launch' " + + "AND retention_child.relname = 'gs_original_start_session_authored_actor_core_retention' " + + "AND retention_namespace.nspname = current_schema() " + + "AND launch_parent.relname = 'game_session_canonical_instance_launch' " + + "AND launch_namespace.nspname = current_schema())) guard") .get(0, String.class); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest.java new file mode 100644 index 0000000000..327a4fbdce --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest.java @@ -0,0 +1,1131 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import integration.net.firedevops.firemud.gamesession.repository.CanonicalHumanPublicationOwnerTestFixtures; +import java.io.IOException; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.time.Duration; +import java.time.Instant; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.saga.persistence.SagaInstance; +import net.firedevops.firemud.common.saga.persistence.SagaInstanceRepository; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository.OriginalStartSessionAssociation; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredActorCoreRetentionRepository.Candidate; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredActorCoreRetentionRepository.StoredSource; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalStartingInstanceRepository.StartingInstance; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot; +import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +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; +import tools.jackson.databind.json.JsonMapper; + +/** + * PostgreSQL proof of append-only exact authored-core retention, including a valid empty result. + * Synthetic result bytes prove storage binding only, not authenticated Game Design transport. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest { + private static final String NAMESPACE = "test"; + private static final String[] MIGRATION_LOCATIONS = { + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(), + "filesystem:" + + Path.of("../common-saga/src/main/resources/db/migration/saga") + .toAbsolutePath() + .normalize() + }; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void v1013UpgradePreservesCombinedHistoryAndExistingOwnerRows() throws Exception { + try (Fixture fixture = newFixture("1012")) { + LaunchInputs launch = fixture.createLaunch(); + String operationId = launch.tuple().controlPlaneRequestId(); + + SagaInstance saga = new SagaInstance(); + saga.setSagaName("gs-v1013-retention-proof"); + saga.setState("RUNNING"); + saga.setCreatedAt(Instant.parse("2026-10-15T00:00:00Z")); + saga.setUpdatedAt(Instant.parse("2026-10-15T00:00:01Z")); + SagaInstance retainedSaga = + new SagaInstanceRepository(fixture.dsl(), fixture.schema()).save(saga); + + List> historyBefore = appliedMigrationHistory(fixture); + assertThat(historyBefore) + .allSatisfy(row -> assertThat(row.get("success")).isEqualTo(Boolean.TRUE)); + List versionsBefore = + historyBefore.stream().map(row -> Objects.toString(row.get("version"))).toList(); + assertThat(versionsBefore).contains("1000", "1001", "1002", "1012"); + assertThat(versionsBefore).doesNotContain("1013"); + assertThat(versionsBefore.get(versionsBefore.size() - 1)).isEqualTo("1012"); + + RowSnapshot launchBefore = + retainedRowSnapshot( + fixture, + "game_session_canonical_instance_launch", + "target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + operationId); + RowSnapshot attemptBefore = + retainedRowSnapshot( + fixture, + "game_session_start_session_operator_attempt", + "target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + operationId); + RowSnapshot sagaBefore = + retainedRowSnapshot(fixture, "saga_instance", "id = ?", retainedSaga.getId()); + + migrationFlyway(fixture.dataSource(), fixture.schema(), null).migrate(); + + List> historyAfter = appliedMigrationHistory(fixture); + assertThat(historyAfter).hasSize(historyBefore.size() + 1); + assertThat(historyAfter.subList(0, historyBefore.size())) + .containsExactlyElementsOf(historyBefore); + Map v1013 = historyAfter.get(historyAfter.size() - 1); + assertThat(v1013.get("version")).isEqualTo("1013"); + assertThat(v1013.get("script")) + .isEqualTo("V1013__retained_original_start_session_authored_core.sql"); + assertThat(v1013.get("success")).isEqualTo(Boolean.TRUE); + assertThat(v1013.get("installed_rank")) + .isEqualTo( + ((Number) historyBefore.get(historyBefore.size() - 1).get("installed_rank")) + .intValue() + + 1); + + assertRowUnchanged( + launchBefore, + retainedRowSnapshot( + fixture, + "game_session_canonical_instance_launch", + "target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + operationId)); + assertRowUnchanged( + attemptBefore, + retainedRowSnapshot( + fixture, + "game_session_start_session_operator_attempt", + "target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + operationId)); + assertRowUnchanged( + sagaBefore, + retainedRowSnapshot(fixture, "saga_instance", "id = ?", retainedSaga.getId())); + var remainingRetentionRows = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT count(*) FROM gs_original_start_session_authored_actor_core_retention"), + "new V1013 table count query returned no row"); + Long remainingRetentionCount = remainingRetentionRows.get(0, Long.class); + assertThat(remainingRetentionCount).isZero(); + } + } + + @Test + void retainsExactEmptyOwnerResultAndRejectsConflictOrMutation() throws Exception { + try (Fixture fixture = newFixture()) { + LaunchInputs launch = fixture.createLaunch(); + var attempt = launch.attempt(); + var selector = exactReplayRequest(launch, launch.claim()); + byte[] requestBytes = + StartSessionTemplateAssociationReadGrpcCodec.toRequest(selector).toByteArray(); + byte[] sourceBytes = canonicalEmptyResult(requestBytes); + Candidate candidate = candidate(launch, attempt, requestBytes, sourceBytes); + + StoredSource first = + Objects.requireNonNull( + fixture + .transactions() + .execute( + status -> fixture.retentionRepository().retainInOwnerTransaction(candidate))); + StoredSource independent = + fixture + .retentionRepository() + .readByOriginalOperation(NAMESPACE, launch.tuple().controlPlaneRequestId()) + .orElseThrow(); + + assertThat(first.candidate().canonicalSourceResultBytes()).containsExactly(sourceBytes); + assertThat(independent.candidate().canonicalSourceResultBytes()).containsExactly(sourceBytes); + assertThat(independent.candidate().sourceResultDigest()) + .isEqualTo(candidate.sourceResultDigest()); + assertThat(independent.retainedAt()).isEqualTo(first.retainedAt()); + assertThat(new String(sourceBytes, java.nio.charset.StandardCharsets.UTF_8)) + .contains("\"projections\":[]"); + + byte[] conflictingBytes = canonicalEmptyResult(requestBytes, "different exact result"); + Candidate conflict = candidate(launch, attempt, requestBytes, conflictingBytes); + assertThatThrownBy( + () -> + fixture + .transactions() + .execute( + status -> + fixture.retentionRepository().retainInOwnerTransaction(conflict))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts with its first exact result"); + assertThat( + fixture + .retentionRepository() + .readByOriginalOperation(NAMESPACE, launch.tuple().controlPlaneRequestId()) + .orElseThrow() + .candidate() + .canonicalSourceResultBytes()) + .containsExactly(sourceBytes); + + String where = + " WHERE target_namespace = '" + + NAMESPACE + + "' AND control_plane_request_id = '" + + launch.tuple().controlPlaneRequestId() + + "'"; + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE gs_original_start_session_authored_actor_core_retention" + + " SET source_result_digest = 'sha256:' || repeat('0', 64)" + + where)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining( + "Game Session authored-core source retention is immutable and append-only"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "DELETE FROM gs_original_start_session_authored_actor_core_retention" + + where)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining( + "Game Session authored-core source retention is immutable and append-only"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute("TRUNCATE gs_original_start_session_authored_actor_core_retention")) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("Game Session authored-core source retention cannot be truncated"); + } + } + + @Test + void originalAssociationReadRequiresExactLiveOwnerAndActualPinsAreAppendOnly() throws Exception { + try (Fixture fixture = newFixture()) { + LaunchInputs launch = fixture.createLaunch(); + AttemptSnapshot attempt = launch.attempt(); + var tuple = launch.tuple(); + String operationId = tuple.controlPlaneRequestId(); + var owner = attempt; + LaunchPinBytes pinBytes = retainedLaunchPinBytes(fixture, launch); + assertThat(pinBytes.selectionRequest()).isNotEmpty(); + assertThat(pinBytes.selectionResponse()).isNotEmpty(); + assertThat(pinBytes.descriptorRequest()).isNotEmpty(); + assertThat(pinBytes.descriptorResponse()).isNotEmpty(); + + RowSnapshot selectionBefore = + retainedRowSnapshot( + fixture, + "game_session_start_session_template_association_pin", + "target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + operationId); + RowSnapshot descriptorBefore = + retainedRowSnapshot( + fixture, + "game_session_start_session_launch_descriptor_pin", + "target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + operationId); + RowSnapshot attemptBefore = + retainedRowSnapshot( + fixture, + "game_session_start_session_operator_attempt", + "target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + operationId); + RowSnapshot launchBefore = + retainedRowSnapshot( + fixture, + "game_session_canonical_instance_launch", + "target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + operationId); + + var associationReadRepository = + new CanonicalGameInstanceLaunchAssociationRepository(fixture.dsl(), NAMESPACE); + var exactSelector = originalSelector(launch.association(), tuple, launch.claim()); + OriginalStartSessionAssociation exactRead = + associationReadRepository + .readOriginalStartSessionAssociation(exactSelector) + .orElseThrow(); + assertThat(exactRead.association()).isEqualTo(launch.association()); + assertThat(exactRead.postAuthorizationExecutionTuple().canonicalBytes()) + .containsExactly(tuple.canonicalBytes()); + assertThat(exactRead.ownerAttemptId()).isEqualTo(owner.ownerAttemptId()); + assertThat(exactRead.ownerFence()).isEqualTo(owner.ownerFence()); + + var attemptRepository = + new GameSessionStartSessionOperatorAttemptRepository( + fixture.dsl(), Duration.ofMinutes(5)); + assertThatThrownBy( + () -> + attemptRepository.readHistoricalOwnerAttempt( + tuple, UUID.randomUUID(), owner.ownerFence())) + .isInstanceOf( + GameSessionStartSessionOperatorAttemptRepository + .StaleStartSessionOperatorAttemptClaimException.class) + .hasMessage("Historical owner read does not match the original owner attempt and fence"); + assertThatThrownBy( + () -> + attemptRepository.readHistoricalOwnerAttempt( + tuple, owner.ownerAttemptId(), owner.ownerFence() + 1)) + .isInstanceOf( + GameSessionStartSessionOperatorAttemptRepository + .StaleStartSessionOperatorAttemptClaimException.class) + .hasMessage("Historical owner read does not match the original owner attempt and fence"); + + UUID wrongTenantId = UUID.randomUUID(); + assertThatThrownBy( + () -> + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.randomUUID(), + exactSelector.targetNamespace(), + wrongTenantId, + exactSelector.worldSlug(), + exactSelector.gameInstanceUuid(), + exactSelector.controlPlaneRequestId(), + exactSelector.launchDescriptorId(), + exactSelector.expectedDescriptorRequestDigest(), + exactSelector.expectedDescriptorResultDigest(), + exactSelector.expectedReleaseAttestationEvidenceDigest(), + exactSelector.originalOperation())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Original operation differs from the exact independent launch selector"); + + var wrongTenantSelector = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.randomUUID(), + exactSelector.targetNamespace(), + wrongTenantId, + exactSelector.worldSlug(), + exactSelector.gameInstanceUuid(), + exactSelector.controlPlaneRequestId(), + exactSelector.launchDescriptorId(), + exactSelector.expectedDescriptorRequestDigest(), + exactSelector.expectedDescriptorResultDigest(), + exactSelector.expectedReleaseAttestationEvidenceDigest()); + assertThat(associationReadRepository.readOriginalStartSessionAssociation(wrongTenantSelector)) + .isEmpty(); + + var wrongOwnerSelector = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.randomUUID(), + exactSelector.targetNamespace(), + exactSelector.canonicalTenantId(), + exactSelector.worldSlug(), + exactSelector.gameInstanceUuid(), + exactSelector.controlPlaneRequestId(), + exactSelector.launchDescriptorId(), + exactSelector.expectedDescriptorRequestDigest(), + exactSelector.expectedDescriptorResultDigest(), + exactSelector.expectedReleaseAttestationEvidenceDigest(), + new CanonicalGameInstanceLaunchAssociationReadEvidence.OriginalOperation( + tuple.canonicalBytes(), + owner.ownerMutationId(), + UUID.randomUUID(), + owner.ownerFence())); + assertThat(associationReadRepository.readOriginalStartSessionAssociation(wrongOwnerSelector)) + .isEmpty(); + + var wrongFenceSelector = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.randomUUID(), + exactSelector.targetNamespace(), + exactSelector.canonicalTenantId(), + exactSelector.worldSlug(), + exactSelector.gameInstanceUuid(), + exactSelector.controlPlaneRequestId(), + exactSelector.launchDescriptorId(), + exactSelector.expectedDescriptorRequestDigest(), + exactSelector.expectedDescriptorResultDigest(), + exactSelector.expectedReleaseAttestationEvidenceDigest(), + new CanonicalGameInstanceLaunchAssociationReadEvidence.OriginalOperation( + tuple.canonicalBytes(), + owner.ownerMutationId(), + owner.ownerAttemptId(), + owner.ownerFence() + 1)); + assertThat(associationReadRepository.readOriginalStartSessionAssociation(wrongFenceSelector)) + .isEmpty(); + + var wrongMutationSelector = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.randomUUID(), + exactSelector.targetNamespace(), + exactSelector.canonicalTenantId(), + exactSelector.worldSlug(), + exactSelector.gameInstanceUuid(), + exactSelector.controlPlaneRequestId(), + exactSelector.launchDescriptorId(), + exactSelector.expectedDescriptorRequestDigest(), + exactSelector.expectedDescriptorResultDigest(), + exactSelector.expectedReleaseAttestationEvidenceDigest(), + new CanonicalGameInstanceLaunchAssociationReadEvidence.OriginalOperation( + tuple.canonicalBytes(), + UUID.randomUUID(), + owner.ownerAttemptId(), + owner.ownerFence())); + assertThat( + associationReadRepository.readOriginalStartSessionAssociation(wrongMutationSelector)) + .isEmpty(); + + var wrongWorldSelector = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.randomUUID(), + exactSelector.targetNamespace(), + exactSelector.canonicalTenantId(), + "other-world", + exactSelector.gameInstanceUuid(), + exactSelector.controlPlaneRequestId(), + exactSelector.launchDescriptorId(), + exactSelector.expectedDescriptorRequestDigest(), + exactSelector.expectedDescriptorResultDigest(), + exactSelector.expectedReleaseAttestationEvidenceDigest(), + exactSelector.originalOperation()); + assertThatThrownBy( + () -> + associationReadRepository.readOriginalStartSessionAssociation(wrongWorldSelector)) + .isInstanceOf( + CanonicalGameInstanceLaunchAssociationRepository + .LaunchAssociationOwnerReadMismatchException.class) + .hasMessage( + "Canonical launch association differs from its exact original StartSession selector"); + + String where = + " WHERE target_namespace = '" + + NAMESPACE + + "' AND control_plane_request_id = '" + + operationId + + "'"; + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE game_session_start_session_template_association_pin" + + " SET association_response_digest = 'sha256:' || repeat('0', 64)" + + where)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasStackTraceContaining("StartSession template association pins are immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE game_session_start_session_launch_descriptor_pin" + + " SET descriptor_response_digest = 'sha256:' || repeat('0', 64)" + + where)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasStackTraceContaining("StartSession launch descriptor pins are immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "DELETE FROM game_session_start_session_launch_descriptor_pin" + where)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasStackTraceContaining("StartSession launch descriptor pins are immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "DELETE FROM game_session_start_session_template_association_pin" + + where)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasStackTraceContaining("StartSession template association pins are immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute("TRUNCATE game_session_start_session_launch_descriptor_pin")) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasStackTraceContaining("StartSession launch descriptor pins are immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute("TRUNCATE game_session_start_session_template_association_pin")) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasStackTraceContaining("cannot truncate a table referenced in a foreign key constraint") + .hasStackTraceContaining("game_session_start_session_launch_descriptor_pin") + .hasStackTraceContaining("game_session_start_session_template_association_pin"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "TRUNCATE game_session_start_session_template_association_pin CASCADE")) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasStackTraceContaining("pins are immutable"); + + LaunchPinBytes pinBytesAfter = retainedLaunchPinBytes(fixture, launch); + assertThat(pinBytesAfter.selectionRequest()).containsExactly(pinBytes.selectionRequest()); + assertThat(pinBytesAfter.selectionResponse()).containsExactly(pinBytes.selectionResponse()); + assertThat(pinBytesAfter.descriptorRequest()).containsExactly(pinBytes.descriptorRequest()); + assertThat(pinBytesAfter.descriptorResponse()).containsExactly(pinBytes.descriptorResponse()); + assertRowUnchanged( + selectionBefore, + retainedRowSnapshot( + fixture, + "game_session_start_session_template_association_pin", + "target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + operationId)); + assertRowUnchanged( + descriptorBefore, + retainedRowSnapshot( + fixture, + "game_session_start_session_launch_descriptor_pin", + "target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + operationId)); + assertRowUnchanged( + attemptBefore, + retainedRowSnapshot( + fixture, + "game_session_start_session_operator_attempt", + "target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + operationId)); + assertRowUnchanged( + launchBefore, + retainedRowSnapshot( + fixture, + "game_session_canonical_instance_launch", + "target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + operationId)); + } + + try (Fixture fixture = newFixture()) { + LaunchInputs launch = fixture.createLaunch(Duration.ofSeconds(15)); + String operationId = launch.tuple().controlPlaneRequestId(); + LaunchPinBytes pinBytes = retainedLaunchPinBytes(fixture, launch); + RowSnapshot selectionBefore = + retainedRowSnapshot( + fixture, + "game_session_start_session_template_association_pin", + "target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + operationId); + RowSnapshot descriptorBefore = + retainedRowSnapshot( + fixture, + "game_session_start_session_launch_descriptor_pin", + "target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + operationId); + var leaseExpiry = + fixture + .dsl() + .fetchOne( + "SELECT lease_expires_at <= clock_timestamp() AS expired " + + "FROM game_session_start_session_operator_attempt " + + "WHERE target_namespace = ? AND control_plane_request_id = ? " + + "AND owner_attempt_id = ? AND owner_mutation_id = ? AND owner_fence = ?", + NAMESPACE, + operationId, + launch.attempt().ownerAttemptId(), + launch.attempt().ownerMutationId(), + launch.attempt().ownerFence()); + assertThat(leaseExpiry) + .as("exact original owner attempt remains present before the expiry wait") + .isNotNull(); + Boolean expired = + Objects.requireNonNull( + leaseExpiry.get("expired", Boolean.class), + "exact original owner attempt expiry state is required"); + assertThat(expired) + .as("original owner claim must remain live before waiting for its immutable deadline") + .isFalse(); + + long expiryWaitDeadline = System.nanoTime() + Duration.ofSeconds(20).toNanos(); + while (!expired && System.nanoTime() < expiryWaitDeadline) { + Thread.sleep(Duration.ofMillis(100).toMillis()); + leaseExpiry = + fixture + .dsl() + .fetchOne( + "SELECT lease_expires_at <= clock_timestamp() AS expired " + + "FROM game_session_start_session_operator_attempt " + + "WHERE target_namespace = ? AND control_plane_request_id = ? " + + "AND owner_attempt_id = ? AND owner_mutation_id = ? AND owner_fence = ?", + NAMESPACE, + operationId, + launch.attempt().ownerAttemptId(), + launch.attempt().ownerMutationId(), + launch.attempt().ownerFence()); + assertThat(leaseExpiry) + .as("exact original owner attempt remains present while polling its expiry") + .isNotNull(); + expired = + Objects.requireNonNull( + leaseExpiry.get("expired", Boolean.class), + "exact original owner attempt expiry state is required"); + } + assertThat(expired) + .as("original owner claim reaches its immutable database-clock deadline") + .isTrue(); + + var associationReadRepository = + new CanonicalGameInstanceLaunchAssociationRepository(fixture.dsl(), NAMESPACE); + assertThat( + associationReadRepository.readOriginalStartSessionAssociation( + originalSelector(launch.association(), launch.tuple(), launch.claim()))) + .isEmpty(); + LaunchPinBytes pinBytesAfter = retainedLaunchPinBytes(fixture, launch); + assertThat(pinBytesAfter.selectionRequest()).containsExactly(pinBytes.selectionRequest()); + assertThat(pinBytesAfter.selectionResponse()).containsExactly(pinBytes.selectionResponse()); + assertThat(pinBytesAfter.descriptorRequest()).containsExactly(pinBytes.descriptorRequest()); + assertThat(pinBytesAfter.descriptorResponse()).containsExactly(pinBytes.descriptorResponse()); + assertRowUnchanged( + selectionBefore, + retainedRowSnapshot( + fixture, + "game_session_start_session_template_association_pin", + "target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + operationId)); + assertRowUnchanged( + descriptorBefore, + retainedRowSnapshot( + fixture, + "game_session_start_session_launch_descriptor_pin", + "target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + operationId)); + } + } + + private static CanonicalGameInstanceLaunchAssociationReadEvidence.Request historicalSelector( + LaunchInputs launch) { + var tuple = launch.tuple(); + var descriptor = launch.binding().descriptor(); + var release = launch.binding().releaseAttestation(); + var association = launch.association(); + return new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.randomUUID(), + association.targetNamespace(), + association.canonicalTenantId(), + association.worldSlug(), + association.gameInstanceUuid(), + tuple.controlPlaneRequestId(), + descriptor.launchDescriptorId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + } + + private static LaunchPinBytes retainedLaunchPinBytes(Fixture fixture, LaunchInputs launch) { + String namespace = launch.association().targetNamespace(); + String requestId = launch.tuple().controlPlaneRequestId(); + var selection = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT association_request_wire, association_response_wire FROM " + + "game_session_start_session_template_association_pin " + + "WHERE target_namespace = ? AND control_plane_request_id = ?", + namespace, + requestId), + "retained canonical initial selection pin is required"); + var descriptor = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT descriptor_request_wire, descriptor_response_wire FROM " + + "game_session_start_session_launch_descriptor_pin " + + "WHERE target_namespace = ? AND control_plane_request_id = ?", + namespace, + requestId), + "retained canonical launch descriptor pin is required"); + return new LaunchPinBytes( + Objects.requireNonNull( + selection.get("association_request_wire", byte[].class), + "canonical selection request bytes are required"), + Objects.requireNonNull( + selection.get("association_response_wire", byte[].class), + "canonical selection response bytes are required"), + Objects.requireNonNull( + descriptor.get("descriptor_request_wire", byte[].class), + "canonical descriptor request bytes are required"), + Objects.requireNonNull( + descriptor.get("descriptor_response_wire", byte[].class), + "canonical descriptor response bytes are required")); + } + + private static Candidate candidate( + LaunchInputs launch, AttemptSnapshot attempt, byte[] requestBytes, byte[] sourceBytes) { + var tuple = launch.tuple(); + var binding = launch.binding(); + var release = binding.releaseAttestation(); + byte[] projection = attempt.accountRedemptionProjection(); + return new Candidate( + NAMESPACE, + tuple.controlPlaneRequestId(), + launch.association().canonicalTenantId(), + launch.association().gameInstanceUuid(), + attempt.ownerAttemptId(), + attempt.ownerMutationId(), + attempt.ownerFence(), + attempt.leaseExpiresAt(), + tuple.canonicalBytes(), + projection, + OriginalStartSessionCurrentAttemptEvidence.projectionDigest(projection), + release.canonicalVersionId(), + UUID.fromString(release.commitId()), + release.publishWorkflowId(), + associationDigest(), + release.authoredWorldSourceOperationId(), + release.authoredWorldSourceEvidenceDigest(), + release.worldSlug(), + binding.descriptor().launchDescriptorId(), + binding.descriptor().requestDigest(), + binding.descriptor().resultDigest(), + release.evidenceDigest(), + requestBytes, + sourceBytes, + sha256(sourceBytes)); + } + + private static StartSessionTemplateAssociationReadEvidence.Request exactReplayRequest( + LaunchInputs launch, AttemptClaim claim) { + var tuple = launch.tuple(); + var release = launch.binding().releaseAttestation(); + return new StartSessionTemplateAssociationReadEvidence.Request( + StartSessionTemplateAssociationReadEvidence.SCHEMA_VERSION, + NAMESPACE, + UUID.randomUUID(), + tuple.canonicalBytes(), + claim.ownerAttemptId(), + claim.ownerFence(), + new StartSessionTemplateAssociationReadEvidence.ExactReplay( + release.canonicalVersionId(), + UUID.fromString(release.commitId()), + release.publishWorkflowId(), + associationDigest())); + } + + private static byte[] canonicalEmptyResult(byte[] requestBytes) { + return canonicalEmptyResult(requestBytes, ""); + } + + private static byte[] canonicalEmptyResult(byte[] requestBytes, String associationRead) { + Map result = + Map.of( + "schema", "game-design-authored-initial-actor-core-read/v1", + "request", Base64.getEncoder().encodeToString(requestBytes), + "associationRead", Base64.getEncoder().encodeToString(associationRead.getBytes()), + "launchDescriptor", Base64.getEncoder().encodeToString("descriptor".getBytes()), + "projections", List.of()); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(result)); + } catch (IOException invalid) { + throw new IllegalStateException("Cannot serialize empty source fixture", invalid); + } + } + + private static String associationDigest() { + return "sha256:" + "b".repeat(64); + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static List> appliedMigrationHistory(Fixture fixture) { + return fixture + .dsl() + .fetch( + "SELECT installed_rank, version, description, type, script, checksum, installed_by," + + " installed_on, execution_time, success FROM " + + fixture.schema() + + ".flyway_schema_history WHERE version IS NOT NULL ORDER BY installed_rank") + .stream() + .map(record -> record.intoMap()) + .toList(); + } + + private static RowSnapshot retainedRowSnapshot( + Fixture fixture, String table, String predicate, Object... bindings) { + var row = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT convert_to(row_to_json(retained_row)::TEXT, 'UTF8') AS row_bytes," + + " retained_row.xmin::TEXT AS row_xmin FROM " + + fixture.schema() + + "." + + table + + " AS retained_row WHERE " + + predicate, + bindings), + "retained row snapshot returned no row for " + table); + return new RowSnapshot(row.get("row_bytes", byte[].class), row.get("row_xmin", String.class)); + } + + private static void assertRowUnchanged(RowSnapshot before, RowSnapshot after) { + assertThat(after.bytes()).containsExactly(before.bytes()); + assertThat(after.xmin()).isEqualTo(before.xmin()); + } + + private static Flyway migrationFlyway( + DriverManagerDataSource dataSource, String schema, String targetVersion) { + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATIONS) + .placeholders(Map.of("serviceSchema", schema)); + if (targetVersion != null) { + configuration.target(MigrationVersion.fromVersion(targetVersion)); + } + return configuration.load(); + } + + private static Fixture newFixture() { + return newFixture(null); + } + + private static Fixture newFixture(String targetVersion) { + String schema = "gs_authored_core_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(postgres.getDriverClassName()); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + migrationFlyway(dataSource, schema, targetVersion).migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new Fixture(schema, dataSource, dsl, new DataSourceTransactionManager(dataSource)); + } + + private record RowSnapshot(byte[] bytes, String xmin) {} + + private record LaunchPinBytes( + byte[] selectionRequest, + byte[] selectionResponse, + byte[] descriptorRequest, + byte[] descriptorResponse) {} + + private static AuthoredWorldSourceEvidence sourceEvidence() { + UUID tenantId = UUID.randomUUID(); + UUID registrationRequestId = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + String tenantSlug = "authored-core-" + UUID.randomUUID().toString().substring(0, 8); + String worldSlug = "retained-core-" + UUID.randomUUID().toString().substring(0, 8); + String displayName = "Retained authored core owner"; + long sourceGameRowId = 91L; + String sourceGameTenantKey = + "retained-core-key-" + UUID.randomUUID().toString().substring(0, 8); + String provenanceKind = "NEW_GAME_ROW"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequestId, tenantId, tenantSlug, worldSlug, displayName); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind)); + } + + private static AuthoredWorldLaunchDescriptorEvidence unpinnedDescriptor( + StartSessionPostAuthorizationExecutionTuple tuple, AuthoredWorldSourceEvidence source) { + var action = tuple.preAuthorizationTuple().action(); + var request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + action.scope().targetNamespace(), + tuple.controlPlaneRequestId(), + action.scope().tenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + action.target().gameTemplateId(), + false, + null, + false, + null, + false, + null, + true, + "{}"); + return AuthoredWorldLaunchDescriptorEvidence.create( + request, + "unowned-start-session-descriptor", + 19L, + false, + null, + "{}", + "generation-1", + 5L, + 91L, + "immutable-release-ref", + false, + null); + } + + private static CanonicalGameInstanceLaunchAssociationReadEvidence.Request originalSelector( + CanonicalGameInstanceLaunchAssociation association, + StartSessionPostAuthorizationExecutionTuple tuple, + AttemptClaim claim) { + var descriptor = association.launchBindingEvidence().descriptor(); + return new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.randomUUID(), + association.targetNamespace(), + association.canonicalTenantId(), + association.worldSlug(), + association.gameInstanceUuid(), + association.controlPlaneRequestId(), + association.launchDescriptorId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + association.launchBindingEvidence().releaseAttestation().evidenceDigest(), + new CanonicalGameInstanceLaunchAssociationReadEvidence.OriginalOperation( + tuple.canonicalBytes(), + claim.ownerMutationId(), + claim.ownerAttemptId(), + claim.ownerFence())); + } + + private record LaunchInputs( + StartSessionPostAuthorizationExecutionTuple tuple, + CompleteLaunchBindingEvidence binding, + AttemptClaim claim, + AttemptSnapshot attempt, + OriginalStartSessionAssociation originalAssociation) { + CanonicalGameInstanceLaunchAssociation association() { + return originalAssociation.association(); + } + } + + private record FreshAssociationInputs( + GameSessionAuthoredWorldSourceRepository.IntakeReceipt sourceReceipt, + FreshGameSessionTenantAssociation tenantAssociation) {} + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + DataSourceTransactionManager transactionManager) + implements AutoCloseable { + TransactionTemplate transactions() { + return new TransactionTemplate(transactionManager); + } + + GameSessionAuthoredActorCoreRetentionRepository retentionRepository() { + return new GameSessionAuthoredActorCoreRetentionRepository( + dsl, transactionManager, NAMESPACE); + } + + LaunchInputs createLaunch() { + return createLaunch(Duration.ofMinutes(5)); + } + + LaunchInputs createLaunch(Duration leaseDuration) { + AuthoredWorldSourceEvidence source = sourceEvidence(); + FreshAssociationInputs fresh = createFreshAssociation(source); + UUID canonicalVersionId = UUID.randomUUID(); + var createCatalog = + new CreateCanonicalRealmCatalogRequest( + UUID.randomUUID(), + NAMESPACE, + source.canonicalTenantId(), + fresh.sourceReceipt().operationId(), + source.worldSlug(), + source.worldDisplayName(), + true, + true, + "SHARED", + "PRESEEDED_ONLY", + null, + null); + RealmPolicyPublishedEvidence.PublishedSet publishedSet = + CanonicalHumanPublicationOwnerTestFixtures.publishedSet( + createCatalog, + source, + canonicalVersionId, + 19L, + "retained-core-publication-" + UUID.randomUUID(), + "immutable-release-ref", + "generation-1", + 5L); + var catalogRepository = new GameSessionCanonicalRealmCatalogRepository(dsl); + var preparedCatalog = + catalogRepository.prepareInitialPublicProduction(createCatalog, publishedSet); + transactions() + .executeWithoutResult( + status -> catalogRepository.createInitialPublicProduction(preparedCatalog)); + + var tuple = + CanonicalHumanPublicationOwnerTestFixtures.tuple( + NAMESPACE, + source.canonicalTenantId(), + UUID.randomUUID(), + 91L, + "retained-authored-core-" + UUID.randomUUID()); + CompleteLaunchBindingEvidence binding = + CanonicalHumanPublicationOwnerTestFixtures.completeBinding( + unpinnedDescriptor(tuple, source), publishedSet); + AttemptClaim claim = + CanonicalHumanPublicationOwnerTestFixtures.pinLaunch( + dsl, transactions(), tuple, source, publishedSet, binding, leaseDuration); + var startingRepository = new GameSessionCanonicalStartingInstanceRepository(dsl, NAMESPACE); + StartingInstance starting = + Objects.requireNonNull( + transactions() + .execute( + status -> + startingRepository.createStarting( + fresh.tenantAssociation(), + binding, + tuple.preAuthorizationTuple().action().target().ownerAccountId(), + tuple.controlPlaneRequestId(), + tuple.mutationDigest(), + tuple)), + "created original Human StartSession instance"); + var attempts = new GameSessionStartSessionOperatorAttemptRepository(dsl, leaseDuration); + AttemptSnapshot attempt = + Objects.requireNonNull( + transactions().execute(status -> attempts.validateCurrentClaim(claim)), + "validated original pending StartSession attempt"); + var associationReadRepository = + new CanonicalGameInstanceLaunchAssociationRepository(dsl, NAMESPACE); + OriginalStartSessionAssociation original = + associationReadRepository + .readOriginalStartSessionAssociation( + originalSelector(starting.launchAssociation(), tuple, claim)) + .orElseThrow( + () -> + new IllegalStateException( + "Canonical Human launch association must read back with its original owner")); + assertThat(original.association()).isEqualTo(starting.launchAssociation()); + assertThat(original.postAuthorizationExecutionTuple().canonicalBytes()) + .containsExactly(tuple.canonicalBytes()); + assertThat(original.ownerAttemptId()).isEqualTo(claim.ownerAttemptId()); + assertThat(original.ownerFence()).isEqualTo(claim.ownerFence()); + assertThat(original.association().currentGameInstanceStatus()) + .isEqualTo(CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.STARTING); + assertThat(attempt.phaseState()) + .isEqualTo(OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE); + assertThat(attempt.accountRedemptionProjection()) + .containsExactly( + net.firedevops.firemud.common.account.startsession + .StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple)); + assertThat(original.canonicalRealmId()).isNotNull(); + assertThat(original.catalogRevision()).isPositive(); + return new LaunchInputs(tuple, binding, claim, attempt, original); + } + + private FreshAssociationInputs createFreshAssociation(AuthoredWorldSourceEvidence source) { + var sourceRepository = new GameSessionAuthoredWorldSourceRepository(dsl); + var sourceReceipt = + Objects.requireNonNull( + transactions() + .execute(status -> sourceRepository.register(UUID.randomUUID(), source)), + "registered controlled upstream source receipt"); + var tenantRepository = new GameSessionFreshTenantAssociationRepository(dsl); + FreshGameSessionTenantAssociation tenantAssociation = + Objects.requireNonNull( + transactions() + .execute( + status -> + tenantRepository.associateFresh( + UUID.randomUUID(), + NAMESPACE, + sourceReceipt, + CanonicalHumanPublicationOwnerTestFixtures.creationEvidence(source))), + "created canonical fresh tenant association"); + return new FreshAssociationInputs(sourceReceipt, tenantAssociation); + } + + @Override + public void close() throws Exception { + try (var connection = dataSource.getConnection(); + var statement = connection.createStatement()) { + statement.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionServiceTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionServiceTest.java new file mode 100644 index 0000000000..4e98f89a0c --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionServiceTest.java @@ -0,0 +1,667 @@ +package 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.ArgumentMatchers.any; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.security.MessageDigest; +import java.time.Instant; +import java.util.Base64; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadClient; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.ParticipantDigest; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository.OriginalStartSessionAssociation; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredActorCoreRetentionRepository.Candidate; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredActorCoreRetentionRepository.StoredSource; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.StaleStartSessionOperatorAttemptClaimException; +import net.firedevops.firemud.gamesession.service.impl.GameSessionAuthoredActorCoreRetentionService; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** + * Service-ordering proof with controlled launch/Account values and mocked canonical Human owner + * repositories and clients. It does not prove actual owner production, authenticated Game Design + * transport or mTLS behavior. + */ +class GameSessionAuthoredActorCoreRetentionServiceTest { + private static final String NAMESPACE = "test"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void exactRetainedRetryReturnsFirstEmptyBytesWithoutRemoteReadOrLeaseRenewal() throws Exception { + TestInputs inputs = inputs(); + byte[] firstBytes = emptyCanonicalSourceBytes(sourceRequestBytes(inputs)); + Candidate first = candidate(inputs, firstBytes); + StoredSource stored = new StoredSource(first, Instant.parse("2026-01-02T03:04:05Z")); + when(inputs + .retention() + .readByOriginalOperation(NAMESPACE, inputs.tuple().controlPlaneRequestId())) + .thenReturn(Optional.of(stored)); + + StoredSource result = + inputs.service().retain(inputs.historical(), inputs.currentAttemptRequest()); + + assertThat(result).isSameAs(stored); + assertThat(result.candidate().canonicalSourceResultBytes()).containsExactly(firstBytes); + assertThat(new String(firstBytes, java.nio.charset.StandardCharsets.UTF_8)) + .contains("\"projections\":[]"); + verify(inputs.retention()) + .readByOriginalOperation(NAMESPACE, inputs.tuple().controlPlaneRequestId()); + verifyNoInteractions( + inputs.launches(), inputs.attempts(), inputs.gameDesign(), inputs.transactionManager()); + } + + @Test + void changedHistoricalGameInstanceRejectsRetainedRetryBeforeOwnerOrRemoteReads() + throws Exception { + TestInputs inputs = inputs(); + Candidate first = candidate(inputs, emptyCanonicalSourceBytes(sourceRequestBytes(inputs))); + StoredSource stored = new StoredSource(first, Instant.parse("2026-01-02T03:04:05Z")); + when(inputs + .retention() + .readByOriginalOperation(NAMESPACE, inputs.tuple().controlPlaneRequestId())) + .thenReturn(Optional.of(stored)); + var originalLaunch = inputs.historical().launchAssociation(); + when(inputs.historical().launchAssociation()) + .thenReturn( + new HistoricalOriginalStartSessionOwnerEvidence.LaunchAssociation( + originalLaunch.targetNamespace(), + originalLaunch.canonicalTenantId(), + originalLaunch.worldSlug(), + UUID.randomUUID(), + originalLaunch.controlPlaneRequestId(), + originalLaunch.launchDescriptorId(), + originalLaunch.playableStateNamespaceId(), + originalLaunch.playableStateScope(), + originalLaunch.publicProduction(), + originalLaunch.capturedStartingRowVersion(), + originalLaunch.launchBindingEvidence())); + + assertThatThrownBy( + () -> inputs.service().retain(inputs.historical(), inputs.currentAttemptRequest())) + .isInstanceOf( + net.firedevops.firemud.gamesession.repository + .GameSessionStartSessionOperatorAttemptRepository + .StartSessionOperatorAttemptConflictException.class) + .hasMessageContaining("differs from the first retained request"); + + verify(inputs.retention()) + .readByOriginalOperation(NAMESPACE, inputs.tuple().controlPlaneRequestId()); + verify(inputs.retention(), never()).retainInOwnerTransaction(any(Candidate.class)); + verifyNoInteractions( + inputs.launches(), inputs.attempts(), inputs.gameDesign(), inputs.transactionManager()); + } + + @Test + void changedCurrentAttemptAfterSourceReadDeniesBeforeRetentionInsert() throws Exception { + TestInputs inputs = inputs(); + when(inputs + .retention() + .readByOriginalOperation(NAMESPACE, inputs.tuple().controlPlaneRequestId())) + .thenReturn(Optional.empty()); + when(inputs + .launches() + .readOriginalStartSessionAssociation( + inputs.historical().request().associationSelector())) + .thenReturn(Optional.of(inputs.launch())); + AttemptSnapshot original = snapshot(inputs, inputs.ownerMutationId()); + AttemptSnapshot changed = snapshot(inputs, UUID.randomUUID()); + when(inputs.attempts().readCurrentOriginalAttempt(inputs.currentAttemptRequest())) + .thenReturn(original, changed); + stubAuthenticatedSourceResult(inputs, inputs.binding().descriptor()); + + assertThatThrownBy( + () -> inputs.service().retain(inputs.historical(), inputs.currentAttemptRequest())) + .isInstanceOf(StaleStartSessionOperatorAttemptClaimException.class) + .hasMessageContaining("Exact live pending original StartSession attempt"); + + verify(inputs.gameDesign()).read(any(AuthoredInitialActorCoreReadEvidence.ReadRequest.class)); + verify(inputs.attempts(), times(2)).readCurrentOriginalAttempt(inputs.currentAttemptRequest()); + verify(inputs.retention(), never()).retainInOwnerTransaction(any(Candidate.class)); + } + + @Test + void sourceDescriptorThatDiffersFromActualLaunchDeniesBeforeRetentionInsert() throws Exception { + TestInputs inputs = inputs(); + when(inputs + .retention() + .readByOriginalOperation(NAMESPACE, inputs.tuple().controlPlaneRequestId())) + .thenReturn(Optional.empty()); + when(inputs + .launches() + .readOriginalStartSessionAssociation( + inputs.historical().request().associationSelector())) + .thenReturn(Optional.of(inputs.launch())); + AttemptSnapshot original = snapshot(inputs, inputs.ownerMutationId()); + when(inputs.attempts().readCurrentOriginalAttempt(inputs.currentAttemptRequest())) + .thenReturn(original); + AuthoredWorldLaunchDescriptorEvidence mismatchedDescriptor = + mock(AuthoredWorldLaunchDescriptorEvidence.class); + stubAuthenticatedSourceResult(inputs, mismatchedDescriptor); + + assertThatThrownBy( + () -> inputs.service().retain(inputs.historical(), inputs.currentAttemptRequest())) + .isInstanceOf( + net.firedevops.firemud.gamesession.repository + .GameSessionStartSessionOperatorAttemptRepository + .StartSessionOperatorAttemptConflictException.class) + .hasMessageContaining("exact original association or launch binding"); + + verify(inputs.gameDesign()).read(any(AuthoredInitialActorCoreReadEvidence.ReadRequest.class)); + verify(inputs.attempts()).readCurrentOriginalAttempt(inputs.currentAttemptRequest()); + verify(inputs.retention(), never()).retainInOwnerTransaction(any(Candidate.class)); + } + + @Test + void substitutedCanonicalOriginalTupleAttemptFenceOrAssociationDeniesBeforeFreshReads() + throws Exception { + for (int substitution = 0; substitution < 4; substitution++) { + TestInputs inputs = inputs(); + when(inputs + .retention() + .readByOriginalOperation(NAMESPACE, inputs.tuple().controlPlaneRequestId())) + .thenReturn(Optional.empty()); + var original = inputs.launch(); + var tuple = inputs.tuple(); + if (substitution == 0) { + // Structurally valid controlled tuple with a substituted original reservation identity. + tuple = + net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple + .createHuman( + tuple.preAuthorizationTuple(), + tuple.authenticatedWorkloadIdentity(), + tuple.authorizationReferenceFingerprint(), + UUID.randomUUID(), + tuple.reservationClaimFence(), + tuple.authorityEvidenceBundleBytes(), + tuple.bundleReference()); + } + var association = original.association(); + if (substitution == 3) { + association = + new CanonicalGameInstanceLaunchAssociation( + association.targetNamespace(), + association.gameSessionTenantId(), + association.tenantAssociationOperationId(), + association.canonicalTenantId(), + UUID.randomUUID(), + association.worldSlug(), + association.playableStateNamespaceId(), + association.playableStateScope(), + association.publicProduction(), + association.controlPlaneRequestId(), + association.launchDescriptorId(), + association.capturedStartingRowVersion(), + association.launchBindingEvidence(), + association.currentGameInstanceStatus(), + association.currentRowVersion()); + } + var changed = + new OriginalStartSessionAssociation( + association, + tuple, + substitution == 1 ? UUID.randomUUID() : original.ownerAttemptId(), + substitution == 2 ? original.ownerFence() + 1L : original.ownerFence(), + original.canonicalRealmId(), + original.catalogRevision()); + when(inputs + .launches() + .readOriginalStartSessionAssociation( + inputs.historical().request().associationSelector())) + .thenReturn(Optional.of(changed)); + assertThatThrownBy( + () -> inputs.service().retain(inputs.historical(), inputs.currentAttemptRequest())) + .isInstanceOf( + net.firedevops.firemud.gamesession.repository + .GameSessionStartSessionOperatorAttemptRepository + .StartSessionOperatorAttemptConflictException.class); + verify(inputs.launches()) + .readOriginalStartSessionAssociation(inputs.historical().request().associationSelector()); + verifyNoInteractions(inputs.attempts(), inputs.gameDesign(), inputs.transactionManager()); + verify(inputs.retention(), never()).retainInOwnerTransaction(any(Candidate.class)); + } + } + + private static TestInputs inputs() throws Exception { + UUID tenantId = UUID.randomUUID(); + String tenantSlug = "retention-fixture-tenant"; + String worldSlug = "retention-fixture-world"; + String displayName = "Retention Fixture"; + UUID sourceOperationId = UUID.randomUUID(); + UUID registrationRequestId = UUID.randomUUID(); + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequestId, tenantId, tenantSlug, worldSlug, displayName); + AuthoredWorldSourceEvidence sourceEvidence = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + sourceOperationId, + sourceRequestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + 91L, + "retention-fixture-key", + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + sourceOperationId, + sourceRequestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + 91L, + "retention-fixture-key", + "NEW_GAME_ROW")); + + var tuple = + integration.net.firedevops.firemud.gamesession.repository + .CanonicalHumanPublicationOwnerTestFixtures.tuple( + NAMESPACE, + tenantId, + UUID.randomUUID(), + 91L, + "retained-authored-core-" + UUID.randomUUID()); + var createCatalog = + new CreateCanonicalRealmCatalogRequest( + UUID.randomUUID(), + NAMESPACE, + tenantId, + sourceOperationId, + worldSlug, + displayName, + true, + true, + "SHARED", + "PRESEEDED_ONLY", + null, + null); + RealmPolicyPublishedEvidence.PublishedSet publishedSet = + integration.net.firedevops.firemud.gamesession.repository + .CanonicalHumanPublicationOwnerTestFixtures.publishedSet( + createCatalog, + sourceEvidence, + UUID.randomUUID(), + 19L, + "retention-fixture-publication-" + UUID.randomUUID(), + "immutable-release-ref", + "generation-1", + 5L); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + tuple.controlPlaneRequestId(), + tenantId, + worldSlug, + sourceOperationId, + sourceEvidence.evidenceDigest(), + 91L, + false, + null, + false, + null, + false, + null, + true, + "{}"); + var unpinnedDescriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "unowned-start-session-descriptor", + 19L, + false, + null, + "{}", + "generation-1", + publishedSet.publicationVersionStateEpoch(), + 91L, + "immutable-release-ref", + false, + null); + CompleteLaunchBindingEvidence binding = + integration.net.firedevops.firemud.gamesession.repository + .CanonicalHumanPublicationOwnerTestFixtures.completeBinding( + unpinnedDescriptor, publishedSet); + var descriptor = binding.descriptor(); + var release = binding.releaseAttestation(); + UUID ownerAttemptId = UUID.randomUUID(); + UUID ownerMutationId = UUID.randomUUID(); + long ownerFence = 7L; + UUID gameInstanceUuid = UUID.randomUUID(); + UUID playableNamespaceId = UUID.randomUUID(); + String associationDigest = "sha256:" + "b".repeat(64); + + var selector = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.randomUUID(), + NAMESPACE, + tenantId, + worldSlug, + gameInstanceUuid, + tuple.controlPlaneRequestId(), + descriptor.launchDescriptorId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + var exactRequest = + new StartSessionTemplateAssociationReadEvidence.Request( + StartSessionTemplateAssociationReadEvidence.SCHEMA_VERSION, + NAMESPACE, + UUID.randomUUID(), + tuple.canonicalBytes(), + ownerAttemptId, + ownerFence, + new StartSessionTemplateAssociationReadEvidence.ExactReplay( + release.canonicalVersionId(), + UUID.fromString(release.commitId()), + release.publishWorkflowId(), + associationDigest)); + var historicalRequest = + new HistoricalOriginalStartSessionOwnerEvidence.Request( + selector, ownerAttemptId, ownerFence); + byte[] accountProjection = StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple); + + var selection = mock(StartSessionTemplateAssociationReadEvidence.Association.class); + when(selection.canonicalTenantId()).thenReturn(tenantId); + when(selection.canonicalVersionId()).thenReturn(release.canonicalVersionId()); + when(selection.selectedCommitId()).thenReturn(UUID.fromString(release.commitId())); + when(selection.publishWorkflowId()).thenReturn(release.publishWorkflowId()); + when(selection.associationDigest()).thenReturn(associationDigest); + when(selection.sourceOperationId()).thenReturn(sourceOperationId); + when(selection.sourceEvidenceDigest()).thenReturn(sourceEvidence.evidenceDigest()); + when(selection.worldSlug()).thenReturn(worldSlug); + var firstSelection = mock(StartSessionTemplateAssociationReadEvidence.Result.class); + when(firstSelection.association()).thenReturn(selection); + + PublishedReleaseBundle bundle = releaseBundle(binding); + var pinnedAssociationRead = mock(StartSessionTemplateAssociationReadEvidence.Result.class); + when(pinnedAssociationRead.request()).thenReturn(exactRequest); + when(pinnedAssociationRead.releaseBundle()).thenReturn(bundle); + var descriptorPin = + new StartSessionLaunchDescriptorGrpcCodec.Resolved( + pinnedAssociationRead, + new StartSessionLaunchDescriptorGrpcCodec.DescriptorOutcome(descriptor)); + var launchAssociation = + new HistoricalOriginalStartSessionOwnerEvidence.LaunchAssociation( + NAMESPACE, + tenantId, + worldSlug, + gameInstanceUuid, + tuple.controlPlaneRequestId(), + descriptor.launchDescriptorId(), + playableNamespaceId, + RealmEntryPolicy.StateScope.SHARED, + true, + 0L, + binding); + var historical = mock(HistoricalOriginalStartSessionOwnerEvidence.Result.class); + when(historical.request()).thenReturn(historicalRequest); + when(historical.originalTuple()).thenReturn(tuple); + when(historical.ownerAttemptId()).thenReturn(ownerAttemptId); + when(historical.ownerFence()).thenReturn(ownerFence); + when(historical.accountRedemptionProjection()).thenReturn(accountProjection); + when(historical.firstSelection()).thenReturn(firstSelection); + when(historical.descriptorPin()).thenReturn(descriptorPin); + when(historical.launchAssociation()).thenReturn(launchAssociation); + + // Controlled canonical Human owner readback; repository and transport ordering remain mocked. + var association = + new CanonicalGameInstanceLaunchAssociation( + NAMESPACE, + 1L, + UUID.randomUUID(), + tenantId, + gameInstanceUuid, + worldSlug, + playableNamespaceId, + RealmEntryPolicy.StateScope.SHARED, + true, + tuple.controlPlaneRequestId(), + descriptor.launchDescriptorId(), + 0L, + binding, + CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.STARTING, + 0L); + var launch = + new OriginalStartSessionAssociation( + association, tuple, ownerAttemptId, ownerFence, UUID.randomUUID(), 1L); + + UUID readId = UUID.randomUUID(); + var currentAttemptRequest = + new OriginalStartSessionCurrentAttemptEvidence.Request( + readId, NAMESPACE, tuple.canonicalBytes(), ownerAttemptId, ownerMutationId, ownerFence); + AttemptSnapshot attempt = mock(AttemptSnapshot.class); + Instant leaseExpiresAt = Instant.now().plusSeconds(300); + when(attempt.targetNamespace()).thenReturn(NAMESPACE); + when(attempt.controlPlaneRequestId()).thenReturn(tuple.controlPlaneRequestId()); + when(attempt.canonicalTenantId()).thenReturn(tenantId); + when(attempt.ownerAttemptId()).thenReturn(ownerAttemptId); + when(attempt.ownerMutationId()).thenReturn(ownerMutationId); + when(attempt.ownerFence()).thenReturn(ownerFence); + when(attempt.phaseState()).thenReturn(OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE); + when(attempt.postAuthorizationExecutionTuple()).thenReturn(tuple.canonicalBytes()); + when(attempt.accountRedemptionProjection()).thenReturn(accountProjection); + when(attempt.leaseExpiresAt()).thenReturn(leaseExpiresAt); + + var launches = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + var attempts = mock(GameSessionStartSessionOperatorAttemptRepository.class); + var gameDesign = mock(AuthoredInitialActorCoreReadClient.class); + var retention = mock(GameSessionAuthoredActorCoreRetentionRepository.class); + var transactionManager = mock(PlatformTransactionManager.class); + TransactionStatus status = mock(TransactionStatus.class); + when(transactionManager.getTransaction(any(TransactionDefinition.class))).thenReturn(status); + doNothing().when(transactionManager).commit(status); + doNothing().when(transactionManager).rollback(status); + var service = + new GameSessionAuthoredActorCoreRetentionService( + NAMESPACE, launches, attempts, gameDesign, retention, transactionManager); + return new TestInputs( + tuple, + binding, + ownerAttemptId, + ownerMutationId, + ownerFence, + gameInstanceUuid, + exactRequest, + currentAttemptRequest, + historical, + launch, + attempt, + launches, + attempts, + gameDesign, + retention, + transactionManager, + service); + } + + private static void stubAuthenticatedSourceResult( + TestInputs inputs, AuthoredWorldLaunchDescriptorEvidence sourceDescriptor) throws Exception { + PublishedReleaseBundle bundle = releaseBundle(inputs.binding()); + var retainedAssociation = inputs.historical().firstSelection().association(); + var associationRead = mock(StartSessionTemplateAssociationReadEvidence.Result.class); + when(associationRead.request()).thenReturn(inputs.associationRequest()); + when(associationRead.association()).thenReturn(retainedAssociation); + when(associationRead.releaseBundle()).thenReturn(bundle); + when(associationRead.worldPublishedStartLocationEvidence()).thenReturn(null); + var source = mock(AuthoredInitialActorCoreReadEvidence.ReadResult.class); + byte[] bytes = emptyCanonicalSourceBytes(sourceRequestBytes(inputs)); + when(source.request()).thenReturn(inputs.associationRequest()); + when(source.associationRead()).thenReturn(associationRead); + when(source.descriptor()).thenReturn(sourceDescriptor); + when(source.canonicalBytes()).thenReturn(bytes); + when(source.digest()).thenReturn(sha256(bytes)); + when(inputs.gameDesign().read(any(AuthoredInitialActorCoreReadEvidence.ReadRequest.class))) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return source; + }); + } + + private static AttemptSnapshot snapshot(TestInputs inputs, UUID mutationId) { + AttemptSnapshot snapshot = mock(AttemptSnapshot.class); + when(snapshot.targetNamespace()).thenReturn(NAMESPACE); + when(snapshot.controlPlaneRequestId()).thenReturn(inputs.tuple().controlPlaneRequestId()); + when(snapshot.canonicalTenantId()) + .thenReturn(inputs.tuple().preAuthorizationTuple().action().scope().tenantId()); + when(snapshot.ownerAttemptId()).thenReturn(inputs.ownerAttemptId()); + when(snapshot.ownerMutationId()).thenReturn(mutationId); + when(snapshot.ownerFence()).thenReturn(inputs.ownerFence()); + when(snapshot.phaseState()) + .thenReturn(OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE); + when(snapshot.postAuthorizationExecutionTuple()).thenReturn(inputs.tuple().canonicalBytes()); + when(snapshot.accountRedemptionProjection()) + .thenReturn(StartSessionAccountRedemptionProjection.fromOriginalTuple(inputs.tuple())); + when(snapshot.leaseExpiresAt()).thenReturn(Instant.now().plusSeconds(300)); + return snapshot; + } + + private static Candidate candidate(TestInputs inputs, byte[] bytes) throws Exception { + var release = inputs.binding().releaseAttestation(); + var descriptor = inputs.binding().descriptor(); + byte[] projection = StartSessionAccountRedemptionProjection.fromOriginalTuple(inputs.tuple()); + byte[] requestBytes = + StartSessionTemplateAssociationReadGrpcCodec.toRequest(inputs.associationRequest()) + .toByteArray(); + return new Candidate( + NAMESPACE, + inputs.tuple().controlPlaneRequestId(), + inputs.tuple().preAuthorizationTuple().action().scope().tenantId(), + inputs.gameInstanceUuid(), + inputs.ownerAttemptId(), + inputs.ownerMutationId(), + inputs.ownerFence(), + Instant.parse("2026-01-01T00:00:00Z"), + inputs.tuple().canonicalBytes(), + projection, + OriginalStartSessionCurrentAttemptEvidence.projectionDigest(projection), + release.canonicalVersionId(), + UUID.fromString(release.commitId()), + release.publishWorkflowId(), + inputs.historical().firstSelection().association().associationDigest(), + release.authoredWorldSourceOperationId(), + release.authoredWorldSourceEvidenceDigest(), + release.worldSlug(), + descriptor.launchDescriptorId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest(), + requestBytes, + bytes, + sha256(bytes)); + } + + private static PublishedReleaseBundle releaseBundle(CompleteLaunchBindingEvidence binding) { + var descriptor = binding.descriptor(); + var release = binding.releaseAttestation(); + var builder = + PublishedReleaseBundle.newBuilder() + .setId(descriptor.releaseBundleId()) + .setVersionId(descriptor.versionId()) + .setIsScriptOnly(false) + .setPublishedReleaseBundleRef(descriptor.publishedReleaseBundleRef()) + .setCanonicalTenantId(release.canonicalTenantId().toString()) + .setCanonicalVersionId(release.canonicalVersionId().toString()) + .setPublishWorkflowId(release.publishWorkflowId()) + .setAttestationSchemaVersion("v" + release.schemaVersion()) + .setManifestHash(release.manifestHash()) + .setManifestSchemaVersion(release.manifestSchemaVersion()) + .setGenerationConfigRevision(release.generationConfigRevision()) + .addAllRequiredManifestAssetKeys(release.requiredManifestAssetKeys()) + .addAllCommandDefinitions(release.commandDefinitions()); + for (AuthoredWorldReleaseAttestationEvidence.Participant expected : + release.participantDigests()) { + var participant = + ParticipantDigest.newBuilder() + .setParticipantKey(expected.participantKey()) + .setScopeValue(expected.scopeValue()) + .setAppliedCommitId(expected.appliedCommitId()) + .setContentDigest(expected.contentDigest()) + .setDigestSchemaVersion(expected.digestSchemaVersion()); + if (expected.abilitySchemaDigestPresent()) { + participant.setAbilitySchemaDigest(expected.abilitySchemaDigest()); + } + builder.addParticipantDigests(participant); + } + return builder.build(); + } + + private static byte[] sourceRequestBytes(TestInputs inputs) { + return StartSessionTemplateAssociationReadGrpcCodec.toRequest(inputs.associationRequest()) + .toByteArray(); + } + + private static byte[] emptyCanonicalSourceBytes(byte[] requestBytes) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString( + java.util.Map.of( + "schema", "game-design-authored-initial-actor-core-read/v1", + "request", Base64.getEncoder().encodeToString(requestBytes), + "associationRead", "fixture-association", + "launchDescriptor", "fixture-descriptor", + "projections", List.of()))); + } + + private static String sha256(byte[] bytes) throws Exception { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private record TestInputs( + net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple tuple, + CompleteLaunchBindingEvidence binding, + UUID ownerAttemptId, + UUID ownerMutationId, + long ownerFence, + UUID gameInstanceUuid, + StartSessionTemplateAssociationReadEvidence.Request associationRequest, + OriginalStartSessionCurrentAttemptEvidence.Request currentAttemptRequest, + HistoricalOriginalStartSessionOwnerEvidence.Result historical, + OriginalStartSessionAssociation launch, + AttemptSnapshot attempt, + CanonicalGameInstanceLaunchAssociationRepository launches, + GameSessionStartSessionOperatorAttemptRepository attempts, + AuthoredInitialActorCoreReadClient gameDesign, + GameSessionAuthoredActorCoreRetentionRepository retention, + PlatformTransactionManager transactionManager, + GameSessionAuthoredActorCoreRetentionService service) {} +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionRepositoryTest.java new file mode 100644 index 0000000000..bed811662f --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionRepositoryTest.java @@ -0,0 +1,83 @@ +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 java.util.UUID; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameSessionAuthoredActorCoreRetentionRepositoryTest { + private static final String NAMESPACE = "test"; + + @AfterEach + void clearAmbientTransactionState() { + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void rejectsInvalidWorkloadNamespaceBeforeStorage() { + DSLContext dsl = mock(DSLContext.class); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + + assertThatThrownBy( + () -> + new GameSessionAuthoredActorCoreRetentionRepository( + dsl, transactionManager, "Not a DNS label")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload namespace"); + + verifyNoInteractions(dsl, transactionManager); + } + + @Test + void independentReadRejectsAmbientOwnerTransactionBeforeInspectingIdentityOrStorage() { + DSLContext dsl = mock(DSLContext.class); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + var repository = + new GameSessionAuthoredActorCoreRetentionRepository(dsl, transactionManager, NAMESPACE); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> repository.readByOriginalOperation(null, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("independent owner snapshot"); + + verifyNoInteractions(dsl, transactionManager); + } + + @Test + void appendRequiresCallerOwnedWritableTransactionBeforeInspectingCandidate() { + DSLContext dsl = mock(DSLContext.class); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + var repository = + new GameSessionAuthoredActorCoreRetentionRepository(dsl, transactionManager, NAMESPACE); + + assertThatThrownBy(() -> repository.retainInOwnerTransaction(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable caller-owned owner transaction"); + + verifyNoInteractions(dsl, transactionManager); + } + + @Test + void invalidReadIdentityIsRejectedBeforeOpeningSnapshot() { + DSLContext dsl = mock(DSLContext.class); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + var repository = + new GameSessionAuthoredActorCoreRetentionRepository(dsl, transactionManager, NAMESPACE); + + assertThatThrownBy( + () -> repository.readByOriginalOperation("other", UUID.randomUUID().toString())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured Game Session workload namespace"); + + verifyNoInteractions(dsl, transactionManager); + } +} diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java index 599c50c2f8..0906be4996 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java @@ -212,27 +212,27 @@ public long freshGameplayBaseline( } jdbc.execute("TRUNCATE TABLE runtime_region_status RESTART IDENTITY"); // This is a disposable Testcontainers baseline reset, not runtime/bootstrap behavior. Keep - // the FK descendants explicit and temporarily suspend only the launch-evidence TRUNCATE guard - // inside the same transaction; the production migration and all application SQL retain it. + // the FK descendants explicit and temporarily suspend only the launch-evidence and retained + // actor-core TRUNCATE guards inside the same transaction; production SQL retains both. TransactionTemplate baselineReset = new TransactionTemplate(gameSession.bean(PlatformTransactionManager.class)); - String originalLaunchGuardState = + BaselineTruncateGuardStates originalGuardStates = baselineReset.execute( status -> { - String originalState = canonicalLaunchTruncateGuardState(jdbc); - if (!"O".equals(originalState) && !"A".equals(originalState)) { - throw new IllegalStateException( - "Expected exactly one canonical launch TRUNCATE guard enabled during" - + " disposable gameplay fixture reset; observed " - + originalState); - } - jdbc.execute( - "ALTER TABLE game_session_canonical_instance_launch " - + "DISABLE TRIGGER game_session_canonical_instance_launch_no_truncate"); - requireCanonicalLaunchTruncateGuardState(jdbc, "D"); + BaselineTruncateGuardStates originalStates = + new BaselineTruncateGuardStates( + requireOriginalTruncateGuardState( + jdbc, BaselineTruncateGuard.CANONICAL_LAUNCH), + requireOriginalTruncateGuardState( + jdbc, BaselineTruncateGuard.AUTHORED_ACTOR_CORE)); + disableTruncateGuard(jdbc, BaselineTruncateGuard.CANONICAL_LAUNCH); + requireTruncateGuardState(jdbc, BaselineTruncateGuard.CANONICAL_LAUNCH, "D"); + disableTruncateGuard(jdbc, BaselineTruncateGuard.AUTHORED_ACTOR_CORE); + requireTruncateGuardState(jdbc, BaselineTruncateGuard.AUTHORED_ACTOR_CORE, "D"); jdbc.execute( """ TRUNCATE TABLE + gs_original_start_session_authored_actor_core_retention, game_session_canonical_closed_admission_pointer_request, gameplay_initial_admission_bind_attempt, game_session_canonical_initial_admission_intent, @@ -247,11 +247,24 @@ public long freshGameplayBaseline( // preserving // the real guard failure instead of masking it with a re-enable attempt on an aborted // transaction. - restoreCanonicalLaunchTruncateGuard(jdbc, originalState); - requireCanonicalLaunchTruncateGuardState(jdbc, originalState); - return originalState; + restoreTruncateGuard( + jdbc, BaselineTruncateGuard.CANONICAL_LAUNCH, originalStates.canonicalLaunch()); + requireTruncateGuardState( + jdbc, BaselineTruncateGuard.CANONICAL_LAUNCH, originalStates.canonicalLaunch()); + restoreTruncateGuard( + jdbc, + BaselineTruncateGuard.AUTHORED_ACTOR_CORE, + originalStates.authoredActorCore()); + requireTruncateGuardState( + jdbc, + BaselineTruncateGuard.AUTHORED_ACTOR_CORE, + originalStates.authoredActorCore()); + return originalStates; }); - requireCanonicalLaunchTruncateGuardState(jdbc, originalLaunchGuardState); + requireTruncateGuardState( + jdbc, BaselineTruncateGuard.CANONICAL_LAUNCH, originalGuardStates.canonicalLaunch()); + requireTruncateGuardState( + jdbc, BaselineTruncateGuard.AUTHORED_ACTOR_CORE, originalGuardStates.authoredActorCore()); if (characterIds.length > 0) { clearScreenBuffers(tenantId, gameplayInstanceId, characterIds); } @@ -265,54 +278,102 @@ public long freshGameplayBaseline( return gameInstanceId; } - private static String canonicalLaunchTruncateGuardState(JdbcTemplate jdbc) { + private enum BaselineTruncateGuard { + CANONICAL_LAUNCH( + "canonical launch", + "game_session_canonical_instance_launch", + "game_session_canonical_instance_launch_no_truncate"), + AUTHORED_ACTOR_CORE( + "authored actor-core retention", + "gs_original_start_session_authored_actor_core_retention", + "gs_original_start_session_actor_core_retention_no_truncate"); + + private final String description; + private final String tableName; + private final String triggerName; + + BaselineTruncateGuard(String description, String tableName, String triggerName) { + this.description = description; + this.tableName = tableName; + this.triggerName = triggerName; + } + } + + private record BaselineTruncateGuardStates(String canonicalLaunch, String authoredActorCore) {} + + private static String requireOriginalTruncateGuardState( + JdbcTemplate jdbc, BaselineTruncateGuard guard) { + String state = truncateGuardState(jdbc, guard); + if (!"O".equals(state) && !"A".equals(state)) { + throw new IllegalStateException( + "Expected exactly one " + + guard.description + + " TRUNCATE guard enabled during disposable gameplay fixture reset; observed " + + state); + } + return state; + } + + private static String truncateGuardState(JdbcTemplate jdbc, BaselineTruncateGuard guard) { List states = jdbc.query( """ SELECT tgenabled::text FROM pg_trigger - WHERE tgrelid = 'game_session_canonical_instance_launch'::regclass - AND tgname = 'game_session_canonical_instance_launch_no_truncate' + WHERE tgrelid = CAST(? AS regclass) + AND tgname = CAST(? AS name) AND NOT tgisinternal """, - (row, rowNumber) -> row.getString(1)); + (row, rowNumber) -> row.getString(1), + guard.tableName, + guard.triggerName); if (states.size() != 1 || (!"O".equals(states.getFirst()) && !"A".equals(states.getFirst()) && !"D".equals(states.getFirst()))) { throw new IllegalStateException( - "Expected exactly one canonical launch TRUNCATE guard in O, A, or D state during" - + " disposable gameplay fixture reset; observed " + "Expected exactly one " + + guard.description + + " TRUNCATE guard in O, A, or D state during disposable " + + "gameplay fixture reset; observed " + states); } return states.getFirst(); } - private static void requireCanonicalLaunchTruncateGuardState( - JdbcTemplate jdbc, String expectedState) { - String observedState = canonicalLaunchTruncateGuardState(jdbc); + private static void requireTruncateGuardState( + JdbcTemplate jdbc, BaselineTruncateGuard guard, String expectedState) { + String observedState = truncateGuardState(jdbc, guard); if (!expectedState.equals(observedState)) { throw new IllegalStateException( - "Expected canonical launch TRUNCATE guard state " + "Expected " + + guard.description + + " TRUNCATE guard state " + expectedState + " during disposable gameplay fixture reset; observed " + observedState); } } - private static void restoreCanonicalLaunchTruncateGuard(JdbcTemplate jdbc, String state) { + private static void disableTruncateGuard(JdbcTemplate jdbc, BaselineTruncateGuard guard) { + jdbc.execute("ALTER TABLE " + guard.tableName + " DISABLE TRIGGER " + guard.triggerName); + } + + private static void restoreTruncateGuard( + JdbcTemplate jdbc, BaselineTruncateGuard guard, String state) { String enableMode = switch (state) { case "O" -> "ENABLE"; case "A" -> "ENABLE ALWAYS"; default -> throw new IllegalStateException( - "Cannot restore unsupported canonical launch TRUNCATE guard state " + state); + "Cannot restore unsupported " + + guard.description + + " TRUNCATE guard state " + + state); }; jdbc.execute( - "ALTER TABLE game_session_canonical_instance_launch " - + enableMode - + " TRIGGER game_session_canonical_instance_launch_no_truncate"); + "ALTER TABLE " + guard.tableName + " " + enableMode + " TRIGGER " + guard.triggerName); } private void clearDefaultDemoAdmissionBinding(JdbcTemplate jdbc, long tenantId) { diff --git a/services/world-management-service/build.gradle.kts b/services/world-management-service/build.gradle.kts index a1eabcc8b1..b160ad6920 100644 --- a/services/world-management-service/build.gradle.kts +++ b/services/world-management-service/build.gradle.kts @@ -44,3 +44,20 @@ val worldClassesProof by configurations.creating { extendsFrom(configurations.implementation.get()) outgoing.artifact(worldClassesProofJar) } + +// Only the selected-publication fixture classes cross the proof boundary; service resources stay local. +val worldSelectedPublicationProofJar by tasks.registering(Jar::class) { + archiveClassifier.set("selected-publication-proof") + dependsOn(tasks.named("integrationTestClasses")) + from(sourceSets["integrationTest"].output.classesDirs) { + include("net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.class") + include("net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture\$*.class") + } +} + +val worldSelectedPublicationProof by configurations.creating { + isCanBeConsumed = true + isCanBeResolved = false + extendsFrom(configurations.implementation.get()) + outgoing.artifact(worldSelectedPublicationProofJar) +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java index b240317958..60045c83fc 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java @@ -476,7 +476,9 @@ private static int expectedFrozenGraphSchemaVersion( int expectedWorldDigestSchema = switch (release.schemaVersion()) { case AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION -> 3; - case AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION -> 4; + case AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION, + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION -> + 4; default -> throw invalid("Retained release has no supported selected World graph profile"); }; diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadGrpcService.java new file mode 100644 index 0000000000..f6d37dbd49 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadGrpcService.java @@ -0,0 +1,61 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Map; +import java.util.Objects; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsGrpcCodec; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedSpawnRequirementsRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedSpawnRequirementsResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedSpawnRequirementsReadServiceGrpc; + +/** Standalone transport adapter; intentionally not registered in production composition. */ +final class WorldPublishedSpawnRequirementsReadGrpcService + extends WorldPublishedSpawnRequirementsReadServiceGrpc + .WorldPublishedSpawnRequirementsReadServiceImplBase { + private static final Map DESCRIPTIONS = + Map.of( + Status.Code.PERMISSION_DENIED, + "Published World source read is not authorized", + Status.Code.INVALID_ARGUMENT, + "Published World source selector is invalid", + Status.Code.NOT_FOUND, + "No exact published World source matches the selector", + Status.Code.FAILED_PRECONDITION, + "Published World source evidence is incomplete or inconsistent", + Status.Code.UNAVAILABLE, + "Published World source is temporarily unavailable", + Status.Code.INTERNAL, + "Published World source read failed"); + + private final WorldPublishedSpawnRequirementsReadOwner owner; + + WorldPublishedSpawnRequirementsReadGrpcService(WorldPublishedSpawnRequirementsReadOwner owner) { + this.owner = Objects.requireNonNull(owner, "owner"); + } + + @Override + public void readWorldPublishedSpawnRequirements( + ReadWorldPublishedSpawnRequirementsRequest request, + StreamObserver responseObserver) { + final ReadWorldPublishedSpawnRequirementsResponse response; + try { + var evidence = owner.read(request); + response = WorldPublishedSpawnRequirementsGrpcCodec.toResponse(evidence.request(), evidence); + } catch (WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException rejected) { + responseObserver.onError(status(rejected.code())); + return; + } catch (RuntimeException failure) { + responseObserver.onError(status(Status.Code.INTERNAL)); + return; + } + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + private static io.grpc.StatusRuntimeException status(Status.Code code) { + return Status.fromCode(code) + .withDescription(DESCRIPTIONS.getOrDefault(code, "Published World source read failed")) + .asRuntimeException(); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwner.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwner.java new file mode 100644 index 0000000000..28adf84086 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwner.java @@ -0,0 +1,492 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence.EntityTemplateReference; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence.FamilyCount; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence.GenerationRequirement; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence.Request; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence.SpawnRequirement; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsGrpcCodec; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Family; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Row; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.FreshGraphDeclaration; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.Node; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedSpawnRequirementsRequest; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import org.springframework.dao.DataAccessException; +import org.springframework.dao.RecoverableDataAccessException; +import org.springframework.dao.TransientDataAccessException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Standalone authenticated read owner for immutable published World spawn requirements. */ +final class WorldPublishedSpawnRequirementsReadOwner { + private final String workloadNamespace; + private final AuthoredWorldLaunchDescriptorClient gameDesignClient; + private final WorldPublishedStartLocationRepository publishedSources; + private final PlatformTransactionManager transactionManager; + + WorldPublishedSpawnRequirementsReadOwner( + String workloadNamespace, + AuthoredWorldLaunchDescriptorClient gameDesignClient, + WorldPublishedStartLocationRepository publishedSources, + PlatformTransactionManager transactionManager) { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.workloadNamespace = workloadNamespace; + this.gameDesignClient = Objects.requireNonNull(gameDesignClient, "gameDesignClient"); + this.publishedSources = Objects.requireNonNull(publishedSources, "publishedSources"); + this.transactionManager = Objects.requireNonNull(transactionManager, "transactionManager"); + } + + WorldPublishedSpawnRequirementsEvidence read( + ReadWorldPublishedSpawnRequirementsRequest wireRequest) { + requireAuthenticatedEntityPeer(); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw rejected( + Status.Code.FAILED_PRECONDITION, + "Published spawn-requirement read requires no ambient World transaction"); + } + + final Request request; + try { + request = WorldPublishedSpawnRequirementsGrpcCodec.fromRequest(wireRequest); + } catch (IllegalArgumentException invalid) { + throw rejected(Status.Code.INVALID_ARGUMENT, "Published spawn selector is invalid"); + } + if (!workloadNamespace.equals(request.targetNamespace())) { + throw rejected(Status.Code.PERMISSION_DENIED, "Published spawn namespace is not authorized"); + } + + CompleteLaunchBindingEvidence launchBinding = readLaunchBinding(request); + AuthoredWorldReleaseAttestationEvidence release = launchBinding.releaseAttestation(); + if (!workloadNamespace.equals(launchBinding.descriptor().targetNamespace()) + || !workloadNamespace.equals(release.targetNamespace()) + || !request.expectedReleaseAttestationDigest().equals(release.evidenceDigest()) + || !AuthoredWorldReleaseAttestationEvidence.requiresWorldStartLocationEvidence( + release.schemaVersion()) + || release.worldStartLocationEvidence() == null) { + throw rejected( + Status.Code.FAILED_PRECONDITION, + "Authenticated Game Design release differs from the exact published selector"); + } + + CaptureRequest captureRequest = captureRequest(release.worldStartLocationEvidence()); + Optional stored = readInOwnedSnapshot(captureRequest); + if (stored.isEmpty()) { + throw rejected(Status.Code.NOT_FOUND, "No exact frozen World source matches the release"); + } + + WorldPublishedStartLocationSource source = stored.orElseThrow(); + try { + if (!WorldCanonicalFrozenTopology.STATUS.equals(source.frozenTopology().status())) { + throw new IllegalArgumentException("Frozen World source is not a retained capture"); + } + requireExactReleaseGraph(release, source.frozenTopology()); + WorldPublishedStartLocationEvidence actualSelector = + actualSelectorEvidence(source, release.worldStartLocationEvidence().request()); + if (!actualSelector.equals(release.worldStartLocationEvidence())) { + throw new IllegalArgumentException( + "Frozen selector, Account binding, or APPLIED result differs from Game Design release"); + } + var projection = + projectRequirements( + source.frozenTopology().request().plan().graph(), source.frozenTopology().graph()); + return new WorldPublishedSpawnRequirementsEvidence( + request, + launchBinding, + source.frozenTopology().captureId(), + WorldDraftGraphAppliedResult.digest(source.frozenTopology().graphBytes()), + projection.familyCounts(), + projection.spawnRequirements(), + projection.generationRequirements()); + } catch (RuntimeException invalid) { + throw rejected( + Status.Code.FAILED_PRECONDITION, + "Frozen World source differs from authenticated release evidence"); + } + } + + private CompleteLaunchBindingEvidence readLaunchBinding(Request request) { + try { + return gameDesignClient.getComplete(request.launchBindingRequest()); + } catch (StatusRuntimeException foreignFailure) { + Status.Code code = foreignFailure.getStatus().getCode(); + Status.Code localCode = + switch (code) { + case UNAVAILABLE, DEADLINE_EXCEEDED, CANCELLED, RESOURCE_EXHAUSTED, INTERNAL, UNKNOWN -> + code; + default -> Status.Code.FAILED_PRECONDITION; + }; + throw rejected(localCode, "Authenticated Game Design release read could not complete"); + } catch (IllegalArgumentException | IllegalStateException invalidCarrier) { + throw rejected(Status.Code.INTERNAL, "Authenticated Game Design release evidence is invalid"); + } catch (RuntimeException failure) { + throw rejected(Status.Code.INTERNAL, "Authenticated Game Design release read failed"); + } + } + + private Optional readInOwnedSnapshot( + CaptureRequest captureRequest) { + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + transaction.setReadOnly(true); + try { + return Objects.requireNonNull( + transaction.execute(status -> publishedSources.readInOwnedSnapshot(captureRequest)), + "World published source transaction result"); + } catch (WorldDesignPublicationFenceRepository.ConflictException conflict) { + throw rejected( + Status.Code.FAILED_PRECONDITION, + "Frozen World source conflicts with the exact publication selection"); + } catch (TransientDataAccessException | RecoverableDataAccessException unavailable) { + throw rejected(Status.Code.UNAVAILABLE, "World published source is temporarily unavailable"); + } catch (DataAccessException failure) { + throw rejected(Status.Code.INTERNAL, "World published source read failed"); + } catch (RuntimeException failure) { + throw rejected(Status.Code.INTERNAL, "World published source read failed"); + } + } + + static RequirementProjection projectRequirements( + WorldDraftTopologyInputGraph authoredGraph, WorldCanonicalAuthoredGraph frozenGraph) { + FreshGraphDeclaration declaration = + authoredGraph + .freshGraphDeclaration() + .orElseThrow( + () -> + new IllegalArgumentException( + "Published World source lacks its original complete family declaration")); + if (!authoredGraph.tenantId().equals(frozenGraph.tenantId()) + || !authoredGraph.versionId().equals(frozenGraph.versionId()) + || authoredGraph.nodes().size() != frozenGraph.rows().size()) { + throw new IllegalArgumentException("Frozen World graph differs from its original source"); + } + + Map rowsByRevision = new HashMap<>(); + for (Row row : frozenGraph.rows()) { + if (rowsByRevision.putIfAbsent(row.authored().revisionId(), row) != null) { + throw new IllegalArgumentException("Frozen World source repeats a revision"); + } + } + + List spawns = new ArrayList<>(); + List generations = new ArrayList<>(); + for (Node node : authoredGraph.nodes()) { + Row row = rowsByRevision.remove(node.revisionId()); + if (row == null + || !row.authored().equals(node) + || !row.template().templateId().equals(node.templateId()) + || familyType(row.template().family()) != node.mutation().getAggregateType()) { + throw new IllegalArgumentException( + "Frozen World row differs from its exact original revision"); + } + var content = row.content(); + if (node.mutation().getAggregateType() + == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING) { + if (!content.hasWorldEntitySpawnBinding() || row.entityReference() == null) { + throw new IllegalArgumentException( + "Spawn projection differs from its original canonical Entity reference"); + } + var binding = content.getWorldEntitySpawnBinding(); + var entity = row.entityReference(); + if (entity.kind() != binding.getEntityTemplateType() + || !entity.templateId().toString().equals(binding.getEntityTemplateId()) + || !entity.tenantId().equals(frozenGraph.tenantId()) + || !entity.versionId().equals(frozenGraph.versionId())) { + throw new IllegalArgumentException( + "Spawn projection differs from its exact canonical Entity reference"); + } + spawns.add( + new SpawnRequirement( + node.revisionOrder(), + node.revisionId(), + node.templateId(), + new RoomTemplateRef( + frozenGraph.tenantId(), + frozenGraph.versionId(), + UUID.fromString(binding.getRoomId())), + new EntityTemplateReference( + entity.kind(), entity.tenantId(), entity.versionId(), entity.templateId()), + binding.getSpawnCount(), + binding.getRespawnDelaySeconds())); + } else if (node.mutation().getAggregateType() + == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE) { + if (!content.hasGenerationRule()) { + throw new IllegalArgumentException( + "Generation projection differs from its original revision"); + } + WorldDesignAggregateType scopeFamily = + switch (node.mutation().getScopeType()) { + case WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE -> + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION; + case WORLD_DESIGN_SCOPE_TYPE_ZONE_SUBTREE -> + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE; + default -> + throw new IllegalArgumentException( + "Generation scope is not an authored REGION or ZONE"); + }; + generations.add( + new GenerationRequirement( + node.revisionOrder(), + node.revisionId(), + node.templateId(), + scopeFamily, + node.scopeId(), + content.getGenerationRule().getName(), + content.getGenerationRule().getValue())); + } + } + if (!rowsByRevision.isEmpty()) { + throw new IllegalArgumentException("Frozen source omits original revision rows"); + } + + List familyCounts = + declaration.familyCounts().stream() + .map(count -> new FamilyCount(count.family(), count.count())) + .toList(); + for (FamilyCount count : familyCounts) { + if (frozenGraph.family(graphFamily(count.family())).size() != count.count()) { + throw new IllegalArgumentException( + "Frozen World family count differs from its complete original declaration"); + } + } + return new RequirementProjection(familyCounts, spawns, generations); + } + + private static Family graphFamily(WorldDesignAggregateType family) { + return switch (family) { + case WORLD_DESIGN_AGGREGATE_TYPE_REGION -> Family.REGION; + case WORLD_DESIGN_AGGREGATE_TYPE_ZONE -> Family.ZONE; + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM -> Family.ROOM; + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT -> Family.ROOM_EXIT; + case WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE -> Family.GENERATION_RULE; + case WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING -> + Family.WORLD_ENTITY_SPAWN_BINDING; + default -> throw new IllegalArgumentException("Unsupported World graph family"); + }; + } + + private static WorldDesignAggregateType familyType(Family family) { + return switch (family) { + case REGION -> WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION; + case ZONE -> WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE; + case ROOM -> WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM; + case ROOM_EXIT -> WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT; + case GENERATION_RULE -> WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE; + case WORLD_ENTITY_SPAWN_BINDING -> + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING; + }; + } + + private static void requireExactReleaseGraph( + AuthoredWorldReleaseAttestationEvidence release, + WorldCanonicalFrozenTopology frozenTopology) { + var source = frozenTopology.request(); + var plan = source.plan(); + var binding = plan.binding(); + var owner = plan.ownerBinding(); + var freeze = source.freeze(); + var worldParticipants = + release.participantDigests().stream() + .filter(participant -> "WORLD_MANAGEMENT".equals(participant.participantKey())) + .toList(); + if (!release.targetNamespace().equals(owner.targetNamespace()) + || !release.targetNamespace().equals(freeze.targetNamespace()) + || !release.canonicalTenantId().equals(binding.target().canonicalTenantId()) + || !release.canonicalTenantId().equals(plan.graph().tenantId()) + || !release.canonicalTenantId().equals(freeze.canonicalTenantId()) + || !release.canonicalVersionId().equals(binding.target().canonicalVersionId()) + || !release.canonicalVersionId().equals(plan.graph().versionId()) + || !release.canonicalVersionId().equals(freeze.canonicalVersionId()) + || !release.commitId().equals(binding.commitId().toString()) + || !release.commitId().equals(freeze.appliedCommitId()) + || !release.publishWorkflowId().equals(freeze.publishWorkflowId()) + || worldParticipants.size() != 1) { + throw new IllegalArgumentException( + "Release differs from the exact selected frozen World graph"); + } + var world = worldParticipants.getFirst(); + if (!world.scopeValue().equals(Long.toString(owner.gameDesignVersionId())) + || world.baseVersionIdPresent() + || world.baseVersionId() != null + || !world.appliedCommitId().equals(freeze.appliedCommitId()) + || !world.contentDigest().equals(freeze.contentDigest()) + || world.digestSchemaVersion() + != AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + "WORLD_MANAGEMENT", release.schemaVersion()) + || world.digestSchemaVersion() != freeze.digestSchemaVersion()) { + throw new IllegalArgumentException( + "Release World participant differs from its exact frozen checkpoint"); + } + if (!AuthoredWorldReleaseAttestationEvidence.requiresWorldStartLocationEvidence( + release.schemaVersion()) + || release.worldStartLocationEvidence() == null) { + throw new IllegalArgumentException( + "Published spawn requirements require selected release World selector evidence"); + } + + var selector = release.worldStartLocationEvidence(); + var expected = + new WorldPublishedStartLocationEvidence.Request( + freeze.targetNamespace(), + freeze.canonicalTenantId(), + freeze.canonicalVersionId(), + freeze.intakeRequestId(), + freeze.publicationFence(), + freeze.publicationRequestId(), + freeze.requestDigest(), + freeze.versionStateEpoch(), + freeze.publishWorkflowId(), + freeze.appliedCommitId(), + freeze.contentDigest(), + freeze.digestSchemaVersion(), + freeze.suppliedOwnedAffectedTuples().stream() + .map( + tuple -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + tuple.owner(), + tuple.aggregateType(), + tuple.aggregateId(), + tuple.scopeType(), + tuple.scopeId(), + tuple.expectedEpoch())) + .toList()); + var receipt = WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()); + FreshGraphDeclaration declaration = + plan.graph() + .freshGraphDeclaration() + .orElseThrow( + () -> + new IllegalArgumentException( + "Selected World graph has no original fresh declaration")); + if (!selector.request().equals(expected) + || !declaration.startLocation().equals(receipt.startLocation()) + || !receipt.bindingDigest().equals(binding.digest()) + || frozenTopology.graph().family(Family.ROOM).stream() + .filter( + room -> + room.template() + .templateId() + .equals(receipt.startLocation().roomTemplateId())) + .count() + != 1) { + throw new IllegalArgumentException( + "Release selector differs from the exact frozen request, declaration or ROOM"); + } + } + + private static CaptureRequest captureRequest(WorldPublishedStartLocationEvidence selector) { + var request = selector.request(); + return new CaptureRequest( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + request.intakeRequestId(), + request.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId(), + request.appliedCommitId(), + request.contentDigest(), + request.digestSchemaVersion(), + request.worldAffectedTuples().stream() + .map( + tuple -> + new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( + tuple.owner(), + tuple.aggregateType(), + tuple.aggregateId(), + tuple.scopeType(), + tuple.scopeId(), + tuple.expectedEpoch())) + .toList()); + } + + private static WorldPublishedStartLocationEvidence actualSelectorEvidence( + WorldPublishedStartLocationSource source, + WorldPublishedStartLocationEvidence.Request selectorRequest) { + var receipt = source.selectorReceipt(); + var receiptEvidence = + new net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence( + receipt.targetNamespace(), + receipt.operationId(), + receipt.requestId(), + receipt.commitId(), + receipt.authorizationFenceId(), + receipt.accountBindingDigest(), + receipt.bindingDigest(), + receipt.startLocation(), + receipt.graphDigest(), + receipt.receiptDigest()); + return new WorldPublishedStartLocationEvidence( + selectorRequest, + receiptEvidence.canonicalBytes(), + source.appliedResult().application().operation().accountBindingBytes(), + source.appliedResult().canonicalBytes()); + } + + private void requireAuthenticatedEntityPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || !peer.isService("entity-management-service") + || !peer.isInNamespace(workloadNamespace) + || SessionContext.hasAuthenticatedCallerContext()) { + throw rejected( + Status.Code.PERMISSION_DENIED, + "Only the verified same-namespace Entity workload without end-user context is allowed"); + } + } + + private static ReadRejectedException rejected(Status.Code code, String message) { + return new ReadRejectedException(code, message); + } + + static final class ReadRejectedException extends IllegalStateException { + private final Status.Code code; + + ReadRejectedException(Status.Code code, String message) { + super(message); + this.code = code; + } + + Status.Code code() { + return code; + } + } + + record RequirementProjection( + List familyCounts, + List spawnRequirements, + List generationRequirements) { + RequirementProjection { + familyCounts = List.copyOf(familyCounts); + spawnRequirements = List.copyOf(spawnRequirements); + generationRequirements = List.copyOf(generationRequirements); + } + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java new file mode 100644 index 0000000000..cbc19aa846 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java @@ -0,0 +1,572 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Function; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.worldmanagement.repository.GenerationRuleRepository; +import net.firedevops.firemud.worldmanagement.repository.RegionRepository; +import net.firedevops.firemud.worldmanagement.repository.RoomExitRepository; +import net.firedevops.firemud.worldmanagement.repository.RoomRepository; +import net.firedevops.firemud.worldmanagement.repository.WorldEntitySpawnBindingRepository; +import net.firedevops.firemud.worldmanagement.repository.ZoneRepository; +import net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService; +import net.firedevops.firemud.worldmanagement.service.impl.WorldDraftDesignDigestServiceImpl; +import org.jooq.DSLContext; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.databind.ObjectMapper; + +/** + * Package-local access to the actual World selected-freeze owner path for the GDS schema-4 proof. + * + *

Inputs from the original Account authorization and authored-world producer are controlled test + * evidence. This fixture does not establish production authority. Every World source, Version, + * graph application, first-freeze checkpoint, inventory, frozen-graph capture, and committed + * readback below goes through the current World SQL owners with their guards enabled. + */ +public final class WorldSelectedFullPublicationEvidenceFixture { + private static final ObjectMapper JSON = new ObjectMapper(); + + private WorldSelectedFullPublicationEvidenceFixture() {} + + /** Exact retained World evidence consumed by the actual GDS selected-publication owner. */ + public record Result( + AuthoredDraftPublishSelectionBinding selection, + AccountPublicationAuthorizationBinding accountBinding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence, + WorldSelectedPublicationArtifactInventoryEvidence inventoryEvidence, + WorldPublishedStartLocationEvidence startLocationEvidence, + ByIdReadRequest sourceReadRequest, + PublicReceipt sourceReadReceipt, + WorldDraftDesignDigestService.WorldDraftDesignDigest selectedWorldDigest, + byte[] appliedResultBytes, + byte[] graphBytes) { + public Result { + Objects.requireNonNull(selection, "selection"); + Objects.requireNonNull(accountBinding, "accountBinding"); + Objects.requireNonNull(freezeEvidence, "freezeEvidence"); + Objects.requireNonNull(inventoryEvidence, "inventoryEvidence"); + Objects.requireNonNull(startLocationEvidence, "startLocationEvidence"); + Objects.requireNonNull(sourceReadRequest, "sourceReadRequest"); + Objects.requireNonNull(sourceReadReceipt, "sourceReadReceipt"); + Objects.requireNonNull(selectedWorldDigest, "selectedWorldDigest"); + appliedResultBytes = Objects.requireNonNull(appliedResultBytes, "appliedResultBytes").clone(); + graphBytes = Objects.requireNonNull(graphBytes, "graphBytes").clone(); + } + + @Override + public byte[] appliedResultBytes() { + return appliedResultBytes.clone(); + } + + @Override + public byte[] graphBytes() { + return graphBytes.clone(); + } + } + + /** Actual World source/version and APPLIED graph owner rows for one exact full Draft binding. */ + public record AppliedGraph( + AuthoredWorldSourceEvidence controlledWorldSource, + WorldAuthoredSourceIntakeReceipt sourceIntake, + WorldAuthoredVersionIdentityReceipt versionIdentity, + WorldDraftTopologyCommitPlan plan, + WorldDraftGraphApplication application, + WorldDraftGraphAppliedResult applied) { + public AppliedGraph { + Objects.requireNonNull(controlledWorldSource, "controlledWorldSource"); + Objects.requireNonNull(sourceIntake, "sourceIntake"); + Objects.requireNonNull(versionIdentity, "versionIdentity"); + Objects.requireNonNull(plan, "plan"); + Objects.requireNonNull(application, "application"); + Objects.requireNonNull(applied, "applied"); + if (!plan.binding().equals(application.plan().binding()) + || !application.operation().equals(applied.application().operation())) { + throw new IllegalArgumentException("World APPLIED graph does not match its selected plan"); + } + } + + public DraftCommitBinding selectedCommit() { + return plan.binding(); + } + } + + /** + * Applies and freezes the exact already-retained GDS selection in current World owners. + * + *

The supplied selection is read from GDS's synchronized Version/commit owner before this + * method is called. The callback supplies only controlled upstream Account authorization bytes; + * its selected binding must be byte-for-byte that retained selection. + */ + public static Result applyFreezeAndCapture( + DSLContext worldDsl, + PlatformTransactionManager worldTransactions, + String namespace, + AuthoredDraftPublishSelectionBinding selection, + AppliedGraph worldGraph, + Function + controlledAccountBindingFactory) { + Objects.requireNonNull(worldDsl, "worldDsl"); + Objects.requireNonNull(worldTransactions, "worldTransactions"); + Objects.requireNonNull(selection, "selection"); + Objects.requireNonNull(worldGraph, "worldGraph"); + Objects.requireNonNull(controlledAccountBindingFactory, "controlledAccountBindingFactory"); + + var target = selection.target(); + DraftCommitBinding binding = selection.selectedCommit(); + if (!binding.equals(worldGraph.selectedCommit()) + || !namespace.equals(worldGraph.sourceIntake().targetNamespace()) + || !target.canonicalTenantId().equals(worldGraph.sourceIntake().canonicalTenantId()) + || !target.canonicalVersionId().equals(worldGraph.versionIdentity().canonicalVersionId()) + || target.gameDesignVersionRowId() != worldGraph.versionIdentity().gameDesignVersionId()) { + throw new IllegalArgumentException( + "World freeze does not target the exact previously applied GDS Draft and World identity"); + } + long expectedStateEpoch = Long.parseLong(selection.intent().expectedVersionStateEpoch()); + var intake = worldGraph.sourceIntake(); + var version = worldGraph.versionIdentity(); + requireExactVersionIdentity(selection, intake, version); + var controlledWorldSource = worldGraph.controlledWorldSource(); + var plan = worldGraph.plan(); + var application = worldGraph.application(); + var intakeRepository = new WorldAuthoredSourceIntakeRepository(worldDsl); + var fence = new WorldDesignPublicationFenceRepository(worldDsl, intakeRepository); + var topology = new WorldDraftTopologyCommitRepository(worldDsl, fence, JSON); + var applications = new WorldDraftGraphApplicationRepository(worldDsl, fence, JSON); + var applied = worldGraph.applied(); + requireExactAppliedReadback(applications, topology, application, plan, applied); + + AccountPublicationAuthorizationBinding accountBinding = + Objects.requireNonNull( + controlledAccountBindingFactory.apply(selection), "controlled Account binding"); + if (!selection.equals(accountBinding.input().selection())) { + throw new IllegalArgumentException( + "Controlled Account binding does not retain the exact GDS synchronized selection"); + } + String publicationId = selection.intent().publishRequestId(); + String workflow = + PublicationDigestRequestBinding.full( + target.canonicalTenantId().toString(), + Long.toString(target.gameDesignVersionRowId()), + publicationId) + .derivedWorkflowIdentity(); + var freeze = + new WorldDesignPublicationFenceEvidence( + namespace, + target.canonicalTenantId(), + target.canonicalVersionId(), + version.operationId(), + target.gameDesignVersionRowId(), + intake.intakeRequestId(), + intake.operationId(), + intake.requestDigest(), + controlledWorldSource.operationId(), + controlledWorldSource.evidenceDigest(), + intake.receiptDigest(), + publicationId, + selection.digest().substring("sha256:".length()), + expectedStateEpoch, + workflow); + var digestService = digestService(worldDsl); + var authorizationRepository = + new WorldSelectedDraftPublicationAuthorizationRepository(worldDsl); + var inventoryRepository = new WorldSelectedPublicationArtifactInventoryRepository(worldDsl); + var checkpointRepository = + new WorldSelectedDraftPublicationCheckpointRepository( + fence, applications, topology, digestService); + var capturedCheckpoint = + new java.util.concurrent.atomic.AtomicReference< + WorldSelectedDraftPublicationCheckpointRepository.CapturedCheckpoint>(); + var createdCheckpointInTransaction = new java.util.concurrent.atomic.AtomicBoolean(); + var frozenAttempt = + Objects.requireNonNull( + new TransactionTemplate(worldTransactions) + .execute( + status -> { + createdCheckpointInTransaction.set(false); + var attempt = + fence.claimFreeze( + freeze, + () -> { + var captured = checkpointRepository.captureWithSource(freeze, plan); + capturedCheckpoint.set(captured); + createdCheckpointInTransaction.set(true); + return captured.checkpoint(); + }); + var retainedAccount = + authorizationRepository.retainOrRequireExact( + attempt, accountBinding, createdCheckpointInTransaction.get()); + if (!java.util.Arrays.equals( + retainedAccount.canonicalBytes(), accountBinding.canonicalBytes())) { + throw new IllegalStateException( + "World did not retain the exact original Account publication binding"); + } + inventoryRepository.retainOrRequireExact( + attempt, + retainedAccount, + createdCheckpointInTransaction.get(), + capturedCheckpoint.get()); + return attempt; + })); + + var checkpoint = + Objects.requireNonNull( + capturedCheckpoint.get(), + "World selected freeze reused an existing checkpoint; fixture requires a fresh capture"); + var retainedAccount = authorizationRepository.readCommitted(frozenAttempt).orElseThrow(); + if (!java.util.Arrays.equals( + retainedAccount.canonicalBytes(), accountBinding.canonicalBytes())) { + throw new IllegalStateException("Committed World Account-binding readback changed bytes"); + } + var freezeRequest = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( + namespace, + target.canonicalTenantId(), + target.canonicalVersionId(), + publicationId, + expectedStateEpoch, + selection.digest().substring("sha256:".length()), + accountBinding); + var acknowledgement = + new WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement( + freezeRequest, + intake.intakeRequestId(), + expectedStateEpoch, + frozenAttempt.publicationFence(), + OwnerFreezePhase.FROZEN, + frozenAttempt.checkpoint().appliedCommitId(), + frozenAttempt.checkpoint().contentDigest(), + frozenAttempt.checkpoint().digestSchemaVersion()); + var freezeEvidence = + WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + freezeRequest, + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + var inventoryEvidence = + new WorldSelectedPublicationArtifactInventoryReadService( + namespace, fence, authorizationRepository, inventoryRepository) + .readRetained(freezeEvidence); + + var captureRequest = captureRequest(plan, freeze, frozenAttempt); + var frozenRepository = + new WorldCanonicalFrozenTopologyRepository( + worldDsl, new WorldAuthoredGraphSnapshotRepository(worldDsl), topology, digestService); + var captured = + new WorldCanonicalFrozenTopologyService(frozenRepository, worldTransactions) + .capture(new WorldCanonicalFrozenTopology.Request(plan, captureRequest)); + var committedCapture = frozenRepository.readCommitted(captureRequest).orElseThrow(); + if (!java.util.Arrays.equals(committedCapture.graphBytes(), captured.graphBytes())) { + throw new IllegalStateException("Committed World frozen-graph readback changed bytes"); + } + var publishedSource = + new WorldPublishedStartLocationRepository(worldDsl, frozenRepository, applications) + .readCommitted(captureRequest) + .orElseThrow(); + var worldEvidence = publishedStartLocationEvidence(publishedSource); + var worldDigest = + new WorldDraftDesignDigestService.WorldDraftDesignDigest( + Long.toString(checkpoint.owner().localTenantKey()), + Long.toString(checkpoint.owner().localVersionKey()), + frozenAttempt.checkpoint().appliedCommitId(), + frozenAttempt.checkpoint().contentDigest(), + frozenAttempt.checkpoint().digestSchemaVersion()); + if (worldDigest.digestSchemaVersion() != 4) { + throw new IllegalStateException( + "World selected freeze did not retain current digest schema 4"); + } + + var committedIntake = intakeRepository.read(namespace, intake.intakeRequestId()).orElseThrow(); + var sourceReadRequest = + new ByIdReadRequest( + 1, + namespace, + UUID.randomUUID(), + committedIntake.intakeRequestId(), + target.canonicalTenantId()); + var sourceReadReceipt = + new PublicReceipt( + committedIntake.schemaVersion(), + committedIntake.targetNamespace(), + committedIntake.intakeRequestId(), + committedIntake.operationId(), + committedIntake.canonicalTenantId(), + committedIntake.worldSlug(), + committedIntake.sourceOperationId(), + committedIntake.sourceEvidenceDigest(), + committedIntake.requestDigest(), + committedIntake.receiptDigest(), + committedIntake.source()); + WorldAuthoredSourceIntakeGrpcCodec.toReadByIdResponse(sourceReadRequest, sourceReadReceipt); + + return new Result( + selection, + accountBinding, + freezeEvidence, + inventoryEvidence, + worldEvidence, + sourceReadRequest, + sourceReadReceipt, + worldDigest, + applied.canonicalBytes(), + captured.graphBytes()); + } + + /** + * Applies the exact World payloads in a selected GDS binding before its sync fence is advanced. + */ + public static AppliedGraph applyGraph( + DSLContext worldDsl, + PlatformTransactionManager worldTransactions, + String namespace, + DraftCommitBinding selectedCommit, + AuthoredWorldSourceEvidence controlledWorldSource) { + Objects.requireNonNull(worldDsl, "worldDsl"); + Objects.requireNonNull(worldTransactions, "worldTransactions"); + Objects.requireNonNull(selectedCommit, "selectedCommit"); + Objects.requireNonNull(controlledWorldSource, "controlledWorldSource"); + requireExactControlledSource(namespace, selectedCommit.target(), controlledWorldSource); + var intakeRepository = new WorldAuthoredSourceIntakeRepository(worldDsl); + var versionRepository = new WorldAuthoredVersionIdentityRepository(worldDsl); + var write = new TransactionTemplate(worldTransactions); + var intake = + Objects.requireNonNull( + write.execute( + status -> + intakeRepository.acceptFresh( + namespace, UUID.randomUUID(), controlledWorldSource))); + var versionStateRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + namespace, + UUID.randomUUID(), + selectedCommit.target().canonicalTenantId(), + controlledWorldSource.worldSlug(), + controlledWorldSource.operationId(), + controlledWorldSource.evidenceDigest(), + selectedCommit.target().gameDesignVersionRowId()); + var versionState = + AuthoredWorldVersionStateEvidence.create( + versionStateRequest, + controlledWorldSource, + selectedCommit.target().canonicalVersionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 1L); + var version = + Objects.requireNonNull( + write.execute(status -> versionRepository.acceptFresh(intake, versionState))); + if (!selectedCommit.target().canonicalTenantId().equals(version.canonicalTenantId()) + || !selectedCommit.target().canonicalVersionId().equals(version.canonicalVersionId()) + || selectedCommit.target().gameDesignVersionRowId() != version.gameDesignVersionId()) { + throw new IllegalStateException( + "World source/version owner rows differ from the selected GDS target mapping"); + } + var ownerBinding = + new WorldDesignPublicationFenceEvidence.OwnerBinding( + namespace, + selectedCommit.target().canonicalTenantId(), + selectedCommit.target().canonicalVersionId(), + version.operationId(), + selectedCommit.target().gameDesignVersionRowId(), + intake.intakeRequestId(), + intake.operationId(), + intake.requestDigest(), + controlledWorldSource.operationId(), + controlledWorldSource.evidenceDigest(), + intake.receiptDigest()); + var plan = WorldDraftTopologyCommitPlan.create(selectedCommit, ownerBinding); + var application = controlledGraphApplication(plan); + var fence = new WorldDesignPublicationFenceRepository(worldDsl, intakeRepository); + var topology = new WorldDraftTopologyCommitRepository(worldDsl, fence, JSON); + var applications = new WorldDraftGraphApplicationRepository(worldDsl, fence, JSON); + var applied = + new WorldDraftGraphApplicationService( + applications, + worldTransactions, + operation -> new WorldDraftGraphApplicationService.CommitOrderProof(operation)) + .apply(application); + requireExactAppliedReadback(applications, topology, application, plan, applied); + return new AppliedGraph(controlledWorldSource, intake, version, plan, application, applied); + } + + private static void requireExactControlledSource( + String namespace, DraftCommitBinding.TargetProof target, AuthoredWorldSourceEvidence source) { + if (!namespace.equals(source.targetNamespace()) + || !target.canonicalTenantId().equals(source.canonicalTenantId()) + || target.sourceGameRowId() != source.sourceGameRowId() + || !target.sourceGameTenantKey().equals(source.sourceGameTenantKey()) + || !target.sourceProvenanceKind().equals(source.provenanceKind())) { + throw new IllegalArgumentException( + "Controlled World source differs from the exact retained GDS selected target"); + } + } + + private static void requireExactVersionIdentity( + AuthoredDraftPublishSelectionBinding selection, + WorldAuthoredSourceIntakeReceipt intake, + WorldAuthoredVersionIdentityReceipt version) { + if (!selection.target().canonicalTenantId().equals(version.canonicalTenantId()) + || !selection.target().canonicalVersionId().equals(version.canonicalVersionId()) + || selection.target().gameDesignVersionRowId() != version.gameDesignVersionId() + || !intake.operationId().equals(version.sourceIntakeReceipt().operationId()) + || !selection.target().canonicalTenantId().equals(intake.canonicalTenantId())) { + throw new IllegalStateException( + "World retained source/Version rows differ from the selected GDS target mapping"); + } + } + + private static WorldDraftGraphApplication controlledGraphApplication( + WorldDraftTopologyCommitPlan plan) { + DraftCommitBinding binding = plan.binding(); + UUID operationId = UUID.randomUUID(); + UUID authorizationFenceId = UUID.randomUUID(); + UUID actorId = UUID.randomUUID(); + byte[] accountBytes = + new DraftAuthorizationFenceBinding( + operationId, + binding.requestId(), + binding.commitId(), + authorizationFenceId, + actorId, + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.baseCommitId(), + "0", + binding.canonicalBytes(), + binding.canonicalBytes(), + binding.digest(), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.GLOBAL_ROLES, + actorId.toString(), + null, + "1", + null, + null, + "TEST_ONLY controlled original COMMIT_ORDER input" + .getBytes(java.nio.charset.StandardCharsets.UTF_8)))) + .withRequiredOwners() + .canonicalBytes(); + var operation = + new WorldDraftTerminalOperation( + operationId, + binding.requestId(), + binding.commitId(), + authorizationFenceId, + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding, + plan.ownerBinding(), + accountBytes); + return new WorldDraftGraphApplication(operation, plan); + } + + private static void requireExactAppliedReadback( + WorldDraftGraphApplicationRepository applications, + WorldDraftTopologyCommitRepository topology, + WorldDraftGraphApplication application, + WorldDraftTopologyCommitPlan plan, + WorldDraftGraphAppliedResult applied) { + var committedApplication = applications.readCommitted(application).orElseThrow(); + var committedTopology = topology.readCommitted(plan).orElseThrow(); + if (!java.util.Arrays.equals(committedApplication.canonicalBytes(), applied.canonicalBytes()) + || !java.util.Arrays.equals(committedTopology.graphBytes(), applied.graphBytes())) { + throw new IllegalStateException("World graph application committed readback changed bytes"); + } + } + + private static WorldAuthoredGraphSnapshot.CaptureRequest captureRequest( + WorldDraftTopologyCommitPlan plan, + WorldDesignPublicationFenceEvidence freeze, + WorldDesignPublicationFenceEvidence.FrozenAttempt attempt) { + List tuples = + plan.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + return new WorldAuthoredGraphSnapshot.CaptureRequest( + freeze.targetNamespace(), + freeze.canonicalTenantId(), + freeze.canonicalVersionId(), + freeze.intakeRequestId(), + attempt.publicationFence(), + freeze.publicationRequestId(), + freeze.requestDigest(), + freeze.versionStateEpoch(), + freeze.publishWorkflowId(), + plan.binding().commitId().toString(), + attempt.checkpoint().contentDigest(), + attempt.checkpoint().digestSchemaVersion(), + tuples); + } + + private static WorldDraftDesignDigestServiceImpl digestService(DSLContext dsl) { + return new WorldDraftDesignDigestServiceImpl( + new RegionRepository(dsl), + new ZoneRepository(dsl), + new RoomRepository(dsl), + new RoomExitRepository(dsl), + new GenerationRuleRepository(dsl), + new WorldEntitySpawnBindingRepository(dsl)); + } + + private static WorldPublishedStartLocationEvidence publishedStartLocationEvidence( + WorldPublishedStartLocationSource source) { + var freeze = source.frozenTopology().request().freeze(); + var tuples = + freeze.suppliedOwnedAffectedTuples().stream() + .map( + tuple -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + tuple.owner(), + tuple.aggregateType(), + tuple.aggregateId(), + tuple.scopeType(), + tuple.scopeId(), + tuple.expectedEpoch())) + .toList(); + var request = + new WorldPublishedStartLocationEvidence.Request( + freeze.targetNamespace(), + freeze.canonicalTenantId(), + freeze.canonicalVersionId(), + freeze.intakeRequestId(), + freeze.publicationFence(), + freeze.publicationRequestId(), + freeze.requestDigest(), + freeze.versionStateEpoch(), + freeze.publishWorkflowId(), + freeze.appliedCommitId(), + freeze.contentDigest(), + freeze.digestSchemaVersion(), + tuples); + return new WorldPublishedStartLocationEvidence( + request, + source.selectorReceipt().canonicalBytes(), + source.appliedResult().application().operation().accountBindingBytes(), + source.appliedResult().canonicalBytes()); + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixtureTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixtureTest.java new file mode 100644 index 0000000000..9689dbbce2 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixtureTest.java @@ -0,0 +1,78 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +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.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.UUID; +import java.util.function.Function; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; + +class WorldSelectedFullPublicationEvidenceFixtureTest { + @Test + void rejectsVersionWithDifferentSourceIntakeOperationBeforeSqlOrAccountCallback() { + UUID tenant = UUID.fromString("11111111-1111-4111-8111-111111111111"); + UUID versionId = UUID.fromString("22222222-2222-4222-8222-222222222222"); + UUID intakeOperationId = UUID.fromString("33333333-3333-4333-8333-333333333333"); + UUID versionIntakeOperationId = UUID.fromString("44444444-4444-4444-8444-444444444444"); + var target = + new TargetProof(tenant, versionId, 17L, "tenant-key", 23L, "tenant-key", "NEW_GAME_ROW"); + var intent = + new PublishIntent( + tenant, + versionId, + "publication-1", + "1", + "controlled test", + UUID.fromString("55555555-5555-4555-8555-555555555555"), + UUID.fromString("66666666-6666-4666-8666-666666666666"), + "sha256:" + "a".repeat(64)); + var selection = mock(AuthoredDraftPublishSelectionBinding.class); + var commit = mock(DraftCommitBinding.class); + var intake = mock(WorldAuthoredSourceIntakeReceipt.class); + var versionIntake = mock(WorldAuthoredSourceIntakeReceipt.class); + var version = mock(WorldAuthoredVersionIdentityReceipt.class); + var graph = mock(WorldSelectedFullPublicationEvidenceFixture.AppliedGraph.class); + var worldDsl = mock(DSLContext.class); + var transactions = mock(PlatformTransactionManager.class); + @SuppressWarnings("unchecked") + Function + accountBindingFactory = mock(Function.class); + + when(selection.target()).thenReturn(target); + when(selection.intent()).thenReturn(intent); + when(selection.selectedCommit()).thenReturn(commit); + when(graph.selectedCommit()).thenReturn(commit); + when(graph.sourceIntake()).thenReturn(intake); + when(graph.versionIdentity()).thenReturn(version); + when(intake.targetNamespace()).thenReturn("test"); + when(intake.canonicalTenantId()).thenReturn(tenant); + when(intake.operationId()).thenReturn(intakeOperationId); + when(version.canonicalTenantId()).thenReturn(tenant); + when(version.canonicalVersionId()).thenReturn(versionId); + when(version.gameDesignVersionId()).thenReturn(17L); + when(version.sourceIntakeReceipt()).thenReturn(versionIntake); + when(versionIntake.operationId()).thenReturn(versionIntakeOperationId); + + assertThatThrownBy( + () -> + WorldSelectedFullPublicationEvidenceFixture.applyFreezeAndCapture( + worldDsl, transactions, "test", selection, graph, accountBindingFactory)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("World retained source/Version rows differ"); + + verifyNoInteractions(worldDsl, transactions); + verify(accountBindingFactory, never()).apply(any()); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepositoryTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepositoryTest.java index a7065eb698..6f920c1eb3 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepositoryTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepositoryTest.java @@ -218,6 +218,29 @@ void rejectsUnsupportedOrMixedCurrentSelectorAttestationProfiles() throws Except .hasMessageContaining("Participant digest schema is unsupported"); } + @Test + void selectedFullAttestationUsesTheExistingWorld4FrozenGraphProfile() throws Exception { + var full = release(AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); + assertThat(full.participantDigests()) + .extracting(AuthoredWorldReleaseAttestationEvidence.Participant::digestSchemaVersion) + .containsExactly(4, 3, 1, 6, 2); + assertThat(full.worldStartLocationEvidence().request().digestSchemaVersion()).isEqualTo(4); + assertThat(expectedFrozenGraphSchemaVersion(full)).isEqualTo(3); + + for (String owner : List.of("WORLD_MANAGEMENT", "ENTITY_MANAGEMENT", "AUTOMATION_SCRIPTING")) { + int staleSchema = + switch (owner) { + case "WORLD_MANAGEMENT" -> 3; + case "ENTITY_MANAGEMENT" -> 2; + default -> 5; + }; + assertThatThrownBy( + () -> selectedFull(full, participantDigestsWithSchema(full, owner, staleSchema))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Participant digest schema is unsupported"); + } + } + private static int expectedFrozenGraphSchemaVersion( AuthoredWorldReleaseAttestationEvidence release) { try { @@ -239,8 +262,11 @@ private static AuthoredWorldReleaseAttestationEvidence release(int schemaVersion WorldPublishedStartLocationEvidence selector = AuthoredWorldReleaseAttestationEvidence.requiresWorldStartLocationEvidence(schemaVersion) ? selectedWorldEvidence( - schemaVersion - == AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION + (schemaVersion + == AuthoredWorldReleaseAttestationEvidence + .CLOSURE_SELECTOR_SCHEMA_VERSION + || schemaVersion + == AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION) ? 4 : 3) : null; @@ -347,6 +373,28 @@ private static AuthoredWorldReleaseAttestationEvidence release(int schemaVersion List.of(), "test-generation-config", selector); + case AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION -> + AuthoredWorldReleaseAttestationEvidence.createSelectedFull( + namespace, + descriptorDigest, + tenantId, + versionId, + "synthetic-world", + UUID.fromString("33333333-3333-4333-8333-333333333333"), + "sha256:" + "e".repeat(64), + "test-descriptor", + "test-release", + 1, + workflow, + commitId, + participants, + manifestHash, + 1, + List.of(), + List.of(), + List.of(), + "test-generation-config", + selector); default -> throw new IllegalArgumentException("Unsupported test release schema"); }; } @@ -427,6 +475,32 @@ private static AuthoredWorldReleaseAttestationEvidence closureSelector( basis.worldStartLocationEvidence()); } + private static AuthoredWorldReleaseAttestationEvidence selectedFull( + AuthoredWorldReleaseAttestationEvidence basis, + List participants) { + return AuthoredWorldReleaseAttestationEvidence.createSelectedFull( + basis.targetNamespace(), + basis.descriptorResultDigest(), + basis.canonicalTenantId(), + basis.canonicalVersionId(), + basis.worldSlug(), + basis.authoredWorldSourceOperationId(), + basis.authoredWorldSourceEvidenceDigest(), + basis.launchDescriptorId(), + basis.publishedReleaseBundleRef(), + basis.versionStateEpoch(), + basis.publishWorkflowId(), + basis.commitId(), + participants, + basis.manifestHash(), + basis.manifestSchemaVersion(), + basis.requiredManifestAssetKeys(), + basis.artifactDigests(), + basis.commandDefinitions(), + basis.generationConfigRevision(), + basis.worldStartLocationEvidence()); + } + private static void validateFrozenGraphProfile(JsonNode graph, int expectedSchemaVersion) { try { Method validator = diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadGrpcServiceTest.java new file mode 100644 index 0000000000..dfe9b27e1f --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadGrpcServiceTest.java @@ -0,0 +1,76 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedSpawnRequirementsRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedSpawnRequirementsResponse; +import org.junit.jupiter.api.Test; + +class WorldPublishedSpawnRequirementsReadGrpcServiceTest { + @Test + void mapsOwnerFailureToBoundedStatusWithoutReturningInternalDetails() { + var owner = mock(WorldPublishedSpawnRequirementsReadOwner.class); + when(owner.read(any())) + .thenThrow( + new WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException( + Status.Code.FAILED_PRECONDITION, "secret database row detail")); + var service = new WorldPublishedSpawnRequirementsReadGrpcService(owner); + var observer = new Collector(); + + service.readWorldPublishedSpawnRequirements( + ReadWorldPublishedSpawnRequirementsRequest.newBuilder().build(), observer); + + assertThat(observer.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(observer.description) + .isEqualTo("Published World source evidence is incomplete or inconsistent"); + assertThat(observer.description).doesNotContain("secret database row detail"); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + } + + @Test + void unexpectedOwnerFailureReturnsRedactedInternalAndNeverMasksObserverDelivery() { + var owner = mock(WorldPublishedSpawnRequirementsReadOwner.class); + when(owner.read(any())).thenThrow(new IllegalStateException("private exception detail")); + var service = new WorldPublishedSpawnRequirementsReadGrpcService(owner); + var observer = new Collector(); + + service.readWorldPublishedSpawnRequirements( + ReadWorldPublishedSpawnRequirementsRequest.newBuilder().build(), observer); + + assertThat(observer.error).isEqualTo(Status.Code.INTERNAL); + assertThat(observer.description).isEqualTo("Published World source read failed"); + assertThat(observer.description).doesNotContain("private exception detail"); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + } + + private static final class Collector + implements StreamObserver { + private ReadWorldPublishedSpawnRequirementsResponse value; + private Status.Code error; + private String description; + private boolean completed; + + @Override + public void onNext(ReadWorldPublishedSpawnRequirementsResponse next) { + value = next; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + description = Status.fromThrowable(failure).getDescription(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwnerTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwnerTest.java new file mode 100644 index 0000000000..62667189de --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwnerTest.java @@ -0,0 +1,1317 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; +import io.grpc.Context; +import io.grpc.Metadata; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; +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.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence.EntityTemplateReference; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence.FamilyCount; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence.GenerationRequirement; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence.SpawnRequirement; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.OwnedAffectedTuple; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Family; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Row; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Template; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.FreshGraphDeclaration; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.Node; +import net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType; +import net.firedevops.firemud.worldmanagement.v1.GenerationRuleDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedSpawnRequirementsRequest; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import net.firedevops.firemud.worldmanagement.v1.WorldEntitySpawnBindingDesignMutation; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.dao.RecoverableDataAccessException; +import org.springframework.dao.TransientDataAccessResourceException; +import org.springframework.jdbc.BadSqlGrammarException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldPublishedSpawnRequirementsReadOwnerTest { + private static final String NAMESPACE = "test"; + private static final UUID READ_ID = uuid(1); + private static final UUID TENANT = uuid(2); + private static final UUID VERSION = uuid(3); + private final AuthoredWorldLaunchDescriptorClient gameDesign = + mock(AuthoredWorldLaunchDescriptorClient.class); + private final WorldPublishedStartLocationRepository published = + mock(WorldPublishedStartLocationRepository.class); + private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + + @AfterEach + void clearThreadState() { + TransactionSynchronizationManager.clear(); + SessionContext.clear(); + } + + @Test + void rejectsWrongPeerAndEndUserBeforeRequestDecodingOrOwnerAccess() { + var malformed = + ReadWorldPublishedSpawnRequirementsRequest.newBuilder().setSchemaVersion(-1).build(); + for (GrpcPeerIdentity identity : + List.of( + peer("game-design-service", NAMESPACE), peer("entity-management-service", "other"))) { + try (var ignored = attach(identity)) { + assertThatThrownBy(() -> owner().read(malformed)) + .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) + .satisfies( + failure -> + assertThat( + ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) + failure) + .code()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } + } + SessionContext.setContext(TENANT.toString(), List.of(), java.util.Map.of()); + try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { + assertThatThrownBy(() -> owner().read(malformed)) + .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) + .satisfies( + failure -> + assertThat( + ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) + .code()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } + verifyNoInteractions(gameDesign, published, transactions); + } + + @Test + void ambientTransactionIsRejectedBeforeDecodingOrGameDesignRead() { + TransactionSynchronizationManager.setActualTransactionActive(true); + try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { + assertThatThrownBy( + () -> + owner() + .read( + ReadWorldPublishedSpawnRequirementsRequest.newBuilder() + .setSchemaVersion(-1) + .build())) + .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) + .satisfies( + failure -> + assertThat( + ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) + .code()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + } + verifyNoInteractions(gameDesign, published, transactions); + } + + @Test + void requestNamespaceMustMatchConfiguredOwnerBeforeGameDesignRead() { + try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { + assertThatThrownBy(() -> owner().read(wireRequest("other"))) + .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) + .satisfies( + failure -> + assertThat( + ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) + .code()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } + verifyNoInteractions(gameDesign, published, transactions); + } + + @Test + void unavailableGameDesignReadNeverOpensWorldSnapshot() { + var wire = wireRequest(NAMESPACE); + when(gameDesign.getComplete(any(GetLaunchDescriptorRequest.class))) + .thenThrow(Status.UNAVAILABLE.asRuntimeException()); + var owner = owner(); + try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { + assertThatThrownBy(() -> owner.read(wire)) + .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) + .satisfies( + failure -> + assertThat( + ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) + .code()) + .isEqualTo(Status.Code.UNAVAILABLE)); + } + verify(gameDesign).getComplete(any(GetLaunchDescriptorRequest.class)); + verifyNoInteractions(published, transactions); + } + + @ParameterizedTest + @EnumSource(Status.Code.class) + void gameDesignStatusCodesAreMappedAndSanitizedBeforeWorldRead(Status.Code foreignCode) { + var wire = wireRequest(NAMESPACE); + Metadata foreignTrailers = new Metadata(); + foreignTrailers.put( + Metadata.Key.of("x-private-detail", Metadata.ASCII_STRING_MARSHALLER), "secret"); + StatusRuntimeException foreignFailure = + Status.fromCode(foreignCode) + .withDescription("foreign private description") + .withCause(new IllegalStateException("private cause")) + .asRuntimeException(foreignTrailers); + when(gameDesign.getComplete(any(GetLaunchDescriptorRequest.class))).thenThrow(foreignFailure); + var owner = owner(); + + try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { + assertThatThrownBy(() -> owner.read(wire)) + .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) + .satisfies( + failure -> { + var rejected = + (WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure; + Status.Code expected = + switch (foreignCode) { + case UNAVAILABLE, + DEADLINE_EXCEEDED, + CANCELLED, + RESOURCE_EXHAUSTED, + INTERNAL, + UNKNOWN -> + foreignCode; + default -> Status.Code.FAILED_PRECONDITION; + }; + assertThat(rejected.code()).isEqualTo(expected); + assertThat(rejected.getMessage()) + .isEqualTo("Authenticated Game Design release read could not complete") + .doesNotContain("foreign", "private", "secret"); + assertThat(rejected.getCause()).isNull(); + }); + } + + verify(gameDesign).getComplete(any(GetLaunchDescriptorRequest.class)); + verifyNoInteractions(published, transactions); + } + + @ParameterizedTest + @EnumSource(InvalidCarrierFailure.class) + void invalidOrUnexpectedGameDesignRuntimeFailureIsSanitizedInternal( + InvalidCarrierFailure failureKind) { + RuntimeException foreignFailure = + switch (failureKind) { + case ILLEGAL_ARGUMENT -> new IllegalArgumentException("private carrier detail"); + case ILLEGAL_STATE -> new IllegalStateException("private carrier detail"); + case UNEXPECTED -> new UnsupportedOperationException("private runtime detail"); + }; + when(gameDesign.getComplete(any(GetLaunchDescriptorRequest.class))).thenThrow(foreignFailure); + + try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { + assertThatThrownBy(() -> owner().read(wireRequest(NAMESPACE))) + .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) + .satisfies( + failure -> { + var rejected = + (WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure; + assertThat(rejected.code()).isEqualTo(Status.Code.INTERNAL); + assertThat(rejected.getMessage()) + .isEqualTo( + failureKind == InvalidCarrierFailure.UNEXPECTED + ? "Authenticated Game Design release read failed" + : "Authenticated Game Design release evidence is invalid"); + assertThat(rejected.getCause()).isNull(); + }); + } + + verify(gameDesign).getComplete(any(GetLaunchDescriptorRequest.class)); + verifyNoInteractions(published, transactions); + } + + @Test + void readsRequirementsFromTheExactReleaseAndOwnedFrozenSource() throws Exception { + var fixture = publishedReadFixture(); + when(gameDesign.getComplete(eq(fixture.request().getLaunchBindingRequest()))) + .thenReturn(fixture.launchBinding()); + when(published.readInOwnedSnapshot(eq(fixture.readCaptureRequest()))) + .thenReturn(Optional.of(fixture.source())); + + WorldPublishedSpawnRequirementsEvidence evidence; + try (var ignored = attach(peer("entity-management-service", fixture.namespace()))) { + evidence = owner(fixture.namespace()).read(fixture.request()); + } + + assertThat(evidence.request().targetNamespace()).isEqualTo(fixture.namespace()); + assertThat(evidence.launchBinding()).isEqualTo(fixture.launchBinding()); + assertThat(evidence.captureId()).isEqualTo(fixture.source().frozenTopology().captureId()); + assertThat(evidence.graphDigest()) + .isEqualTo( + WorldDraftGraphAppliedResult.digest(fixture.source().frozenTopology().graphBytes())); + assertThat(evidence.familyCounts()) + .extracting(FamilyCount::count) + .containsExactly(1, 1, 2, 1, 1, 1); + assertThat(evidence.spawnRequirements()) + .singleElement() + .satisfies( + spawn -> { + assertThat(spawn.roomTemplate()) + .isEqualTo( + fixture.plan().graph().freshGraphDeclaration().orElseThrow().startLocation()); + assertThat(spawn.entityTemplate().kind()) + .isEqualTo(EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC); + assertThat(spawn.spawnCount()).isEqualTo(3); + assertThat(spawn.respawnDelaySeconds()).isEqualTo(90); + }); + assertThat(evidence.generationRequirements()) + .singleElement() + .satisfies( + generation -> { + assertThat(generation.name()).isEqualTo("density"); + assertThat(generation.value()).isEqualTo("sparse"); + }); + + verify(gameDesign).getComplete(eq(fixture.request().getLaunchBindingRequest())); + verify(published).readInOwnedSnapshot(eq(fixture.readCaptureRequest())); + } + + @ParameterizedTest + @EnumSource(ReleaseSourceMismatch.class) + void releaseAndFrozenSourceMismatchesFailAfterTheOwnedRead(ReleaseSourceMismatch mismatch) + throws Exception { + var fixture = mismatchedPublishedReadFixture(mismatch); + when(gameDesign.getComplete(eq(fixture.request().getLaunchBindingRequest()))) + .thenReturn(fixture.launchBinding()); + when(published.readInOwnedSnapshot(eq(fixture.readCaptureRequest()))) + .thenReturn(Optional.of(fixture.source())); + + try (var ignored = attach(peer("entity-management-service", fixture.namespace()))) { + assertThatThrownBy(() -> owner(fixture.namespace()).read(fixture.request())) + .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) + .satisfies( + failure -> { + var rejected = + (WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure; + assertThat(rejected.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(rejected.getMessage()) + .isEqualTo("Frozen World source differs from authenticated release evidence") + .doesNotContain("private", "SQL", "receipt"); + assertThat(rejected.getCause()).isNull(); + }); + } + + verify(gameDesign).getComplete(eq(fixture.request().getLaunchBindingRequest())); + verify(published).readInOwnedSnapshot(eq(fixture.readCaptureRequest())); + } + + private enum ReleaseSourceMismatch { + CONTENT_DIGEST, + APPLIED_COMMIT, + WORLD_PARTICIPANT_SCOPE, + WORLD_PARTICIPANT_DIGEST_SCHEMA, + SELECTOR_RECEIPT_BINDING_DIGEST, + SELECTED_ROOM_COUNT + } + + private enum InvalidCarrierFailure { + ILLEGAL_ARGUMENT, + ILLEGAL_STATE, + UNEXPECTED + } + + @Test + void changedReleaseAttestationDigestFailsBeforeWorldRead() { + var wire = wireRequest(NAMESPACE); + var pair = mock(CompleteLaunchBindingEvidence.class); + var descriptor = mock(AuthoredWorldLaunchDescriptorEvidence.class); + var release = mock(AuthoredWorldReleaseAttestationEvidence.class); + when(gameDesign.getComplete(any(GetLaunchDescriptorRequest.class))).thenReturn(pair); + when(pair.descriptor()).thenReturn(descriptor); + when(pair.releaseAttestation()).thenReturn(release); + when(descriptor.targetNamespace()).thenReturn(NAMESPACE); + when(release.targetNamespace()).thenReturn(NAMESPACE); + when(release.evidenceDigest()).thenReturn("sha256:" + "f".repeat(64)); + when(release.schemaVersion()) + .thenReturn(AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION); + when(release.worldStartLocationEvidence()) + .thenReturn(mock(WorldPublishedStartLocationEvidence.class)); + try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { + assertThatThrownBy(() -> owner().read(wire)) + .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) + .satisfies( + failure -> + assertThat( + ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) + .code()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + } + verifyNoInteractions(published, transactions); + } + + @Test + void unselectedLegacyReleaseCannotBeUsedAsPublishedSpawnSelector() { + var wire = wireRequest(NAMESPACE); + var pair = mock(CompleteLaunchBindingEvidence.class); + var descriptor = mock(AuthoredWorldLaunchDescriptorEvidence.class); + var release = mock(AuthoredWorldReleaseAttestationEvidence.class); + when(gameDesign.getComplete(any(GetLaunchDescriptorRequest.class))).thenReturn(pair); + when(pair.descriptor()).thenReturn(descriptor); + when(pair.releaseAttestation()).thenReturn(release); + when(descriptor.targetNamespace()).thenReturn(NAMESPACE); + when(release.targetNamespace()).thenReturn(NAMESPACE); + when(release.evidenceDigest()).thenReturn(wire.getExpectedReleaseAttestationDigest()); + when(release.schemaVersion()) + .thenReturn(AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION); + try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { + assertThatThrownBy(() -> owner().read(wire)) + .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) + .satisfies( + failure -> + assertThat( + ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) + .code()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + } + verifyNoInteractions(published, transactions); + } + + @ParameterizedTest + @EnumSource(SnapshotFailure.class) + void snapshotFailuresMapOnlyRecoverableDataAccessFailuresToUnavailable( + SnapshotFailure failureKind) { + var wire = wireRequest(NAMESPACE); + var selector = mock(WorldPublishedStartLocationEvidence.class); + when(selector.request()).thenReturn(selectorRequest()); + var pair = mock(CompleteLaunchBindingEvidence.class); + var descriptor = mock(AuthoredWorldLaunchDescriptorEvidence.class); + var release = mock(AuthoredWorldReleaseAttestationEvidence.class); + when(gameDesign.getComplete(any(GetLaunchDescriptorRequest.class))).thenReturn(pair); + when(pair.descriptor()).thenReturn(descriptor); + when(pair.releaseAttestation()).thenReturn(release); + when(descriptor.targetNamespace()).thenReturn(NAMESPACE); + when(release.targetNamespace()).thenReturn(NAMESPACE); + when(release.evidenceDigest()).thenReturn(wire.getExpectedReleaseAttestationDigest()); + when(release.schemaVersion()) + .thenReturn(AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION); + when(release.worldStartLocationEvidence()).thenReturn(selector); + when(published.readInOwnedSnapshot(any())).thenThrow(snapshotFailure(failureKind)); + + try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { + assertThatThrownBy(() -> owner().read(wire)) + .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) + .satisfies( + failure -> { + var rejected = + (WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure; + var expectedCode = + switch (failureKind) { + case TRANSIENT, RECOVERABLE -> Status.Code.UNAVAILABLE; + case BAD_SQL, INTEGRITY, UNRELATED_RUNTIME -> Status.Code.INTERNAL; + }; + assertThat(rejected.code()).isEqualTo(expectedCode); + assertThat(rejected.getMessage()) + .isEqualTo( + expectedCode == Status.Code.UNAVAILABLE + ? "World published source is temporarily unavailable" + : "World published source read failed") + .doesNotContain("private", "SQL", "integrity"); + assertThat(rejected.getCause()).isNull(); + }); + } + + verify(gameDesign).getComplete(any(GetLaunchDescriptorRequest.class)); + verify(published).readInOwnedSnapshot(any()); + } + + private enum SnapshotFailure { + TRANSIENT, + RECOVERABLE, + BAD_SQL, + INTEGRITY, + UNRELATED_RUNTIME + } + + private static RuntimeException snapshotFailure(SnapshotFailure failureKind) { + return switch (failureKind) { + case TRANSIENT -> new TransientDataAccessResourceException("private transient detail"); + case RECOVERABLE -> new RecoverableDataAccessException("private recoverable detail"); + case BAD_SQL -> + new BadSqlGrammarException("snapshot", "select private", new SQLException("private SQL")); + case INTEGRITY -> new DataIntegrityViolationException("private integrity detail"); + case UNRELATED_RUNTIME -> new IllegalStateException("private runtime detail"); + }; + } + + @Test + void malformedFrozenSourceFailsClosedAfterTheOwnedRead() { + var wire = wireRequest(NAMESPACE); + var selector = mock(WorldPublishedStartLocationEvidence.class); + when(selector.request()).thenReturn(selectorRequest()); + var pair = mock(CompleteLaunchBindingEvidence.class); + var descriptor = mock(AuthoredWorldLaunchDescriptorEvidence.class); + var release = mock(AuthoredWorldReleaseAttestationEvidence.class); + when(gameDesign.getComplete(any(GetLaunchDescriptorRequest.class))).thenReturn(pair); + when(pair.descriptor()).thenReturn(descriptor); + when(pair.releaseAttestation()).thenReturn(release); + when(descriptor.targetNamespace()).thenReturn(NAMESPACE); + when(release.targetNamespace()).thenReturn(NAMESPACE); + when(release.evidenceDigest()).thenReturn(wire.getExpectedReleaseAttestationDigest()); + when(release.schemaVersion()) + .thenReturn(AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION); + when(release.worldStartLocationEvidence()).thenReturn(selector); + + var source = mock(WorldPublishedStartLocationSource.class); + var frozen = mock(WorldCanonicalFrozenTopology.class); + when(source.frozenTopology()).thenReturn(frozen); + when(frozen.status()).thenReturn("CHANGED"); + when(published.readInOwnedSnapshot(any())).thenReturn(Optional.of(source)); + try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { + assertThatThrownBy(() -> owner().read(wire)) + .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) + .satisfies( + failure -> + assertThat( + ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) + .code()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + } + verify(published).readInOwnedSnapshot(any()); + } + + @Test + void projectsRetainedSpawnAndGenerationFieldsAndFamilyCountsInRevisionOrder() { + UUID spawnRevision = uuid(20); + UUID generationRevision = uuid(21); + UUID secondSpawnRevision = uuid(22); + UUID spawnId = uuid(30); + UUID ruleId = uuid(31); + UUID secondSpawnId = uuid(32); + UUID roomId = uuid(40); + UUID entityId = uuid(41); + UUID secondRoomId = uuid(42); + UUID secondEntityId = uuid(43); + var spawnMutation = + base( + spawnRevision, + spawnId, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE, + uuid(50)) + .setWorldEntitySpawnBinding( + WorldEntitySpawnBindingDesignMutation.newBuilder() + .setRoomId(roomId.toString()) + .setEntityTemplateType( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC) + .setEntityTemplateId(entityId.toString()) + .setSpawnCount(0) + .setRespawnDelaySeconds(77)) + .build(); + var generationMutation = + base( + generationRevision, + ruleId, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_ZONE_SUBTREE, + uuid(51)) + .setGenerationRule( + GenerationRuleDesignMutation.newBuilder() + .setName("authored-name") + .setValue("unchanged-value")) + .build(); + var secondSpawnMutation = + base( + secondSpawnRevision, + secondSpawnId, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_ZONE_SUBTREE, + uuid(52)) + .setWorldEntitySpawnBinding( + WorldEntitySpawnBindingDesignMutation.newBuilder() + .setRoomId(secondRoomId.toString()) + .setEntityTemplateType( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM) + .setEntityTemplateId(secondEntityId.toString()) + .setSpawnCount(4) + .setRespawnDelaySeconds(9)) + .build(); + var entityRef = + new WorldDraftTopologyInputGraph.EntityTemplateReference( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC, + TENANT, + VERSION, + entityId); + var declaration = + new FreshGraphDeclaration( + TENANT, + VERSION, + new RoomTemplateRef(TENANT, VERSION, roomId), + List.of( + new WorldDraftTopologyInputGraph.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION, 0), + new WorldDraftTopologyInputGraph.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, 0), + new WorldDraftTopologyInputGraph.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, 0), + new WorldDraftTopologyInputGraph.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT, 0), + new WorldDraftTopologyInputGraph.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE, 1), + new WorldDraftTopologyInputGraph.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING, + 2))); + var graph = + new WorldDraftTopologyInputGraph( + TENANT, + VERSION, + List.of( + new Node("0", spawnRevision, spawnId, uuid(50), spawnMutation, entityRef), + new Node("1", generationRevision, ruleId, uuid(51), generationMutation, null), + new Node( + "2", + secondSpawnRevision, + secondSpawnId, + uuid(52), + secondSpawnMutation, + new WorldDraftTopologyInputGraph.EntityTemplateReference( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM, + TENANT, + VERSION, + secondEntityId))), + declaration); + + List frozenRows = new java.util.ArrayList<>(); + long privateKey = 1L; + for (Node node : graph.nodes()) { + var family = + switch (node.mutation().getAggregateType()) { + case WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING -> + Family.WORLD_ENTITY_SPAWN_BINDING; + case WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE -> Family.GENERATION_RULE; + default -> throw new IllegalArgumentException("Unexpected test family"); + }; + var retainedContent = node.mutation(); + if (node.revisionId().equals(spawnRevision)) { + retainedContent = + retainedContent.toBuilder() + .setWorldEntitySpawnBinding( + retainedContent.getWorldEntitySpawnBinding().toBuilder().setSpawnCount(1)) + .build(); + } + frozenRows.add( + new WorldCanonicalAuthoredGraph.Row( + new Template(family, node.templateId()), + privateKey, + privateKey, + node, + retainedContent)); + privateKey++; + } + var frozenGraph = new WorldCanonicalAuthoredGraph(TENANT, VERSION, 1L, 1L, frozenRows); + var projection = + WorldPublishedSpawnRequirementsReadOwner.projectRequirements(graph, frozenGraph); + + assertThat(projection.familyCounts()) + .extracting(FamilyCount::count) + .containsExactly(0, 0, 0, 0, 1, 2); + assertThat(projection.spawnRequirements()) + .containsExactly( + new SpawnRequirement( + "0", + spawnRevision, + spawnId, + new RoomTemplateRef(TENANT, VERSION, roomId), + new EntityTemplateReference( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC, + TENANT, + VERSION, + entityId), + 1, + 77), + new SpawnRequirement( + "2", + secondSpawnRevision, + secondSpawnId, + new RoomTemplateRef(TENANT, VERSION, secondRoomId), + new EntityTemplateReference( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM, + TENANT, + VERSION, + secondEntityId), + 4, + 9)); + assertThat(projection.generationRequirements()) + .containsExactly( + new GenerationRequirement( + "1", + generationRevision, + ruleId, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, + uuid(51), + "authored-name", + "unchanged-value")); + } + + private static PublishedReadFixture publishedReadFixture() throws Exception { + var plan = + includeControlPlaneOwner(WorldDraftTopologyCommitPlanTest.selectedPlanWithAllFamilies()); + var capture = captureRequest(plan, 4, plan.binding().commitId().toString(), "e".repeat(64)); + var applied = appliedSelection(plan, capture); + var frozen = frozenTopology(plan, capture, applied, uuid(800)); + var source = + new WorldPublishedStartLocationSource( + frozen, + applied.appliedResult(), + applied.appliedResult().startLocationReceipt().orElseThrow()); + var launchBinding = launchBinding(capture, applied.selectorEvidence(), 901, 3); + return new PublishedReadFixture( + plan, + capture, + source, + launchBinding, + wireRequest(launchBinding), + applied.selectorEvidence()); + } + + private static PublishedReadFixture mismatchedPublishedReadFixture(ReleaseSourceMismatch mismatch) + throws Exception { + var baseline = publishedReadFixture(); + return switch (mismatch) { + case CONTENT_DIGEST -> { + var request = copyCaptureRequest(baseline.readCaptureRequest(), 4, null, "f".repeat(64)); + var selector = selectorEvidence(baseline.source().appliedResult(), request); + var binding = launchBinding(request, selector, 901, 3); + yield new PublishedReadFixture( + baseline.plan(), request, baseline.source(), binding, wireRequest(binding), selector); + } + case APPLIED_COMMIT -> { + UUID changedCommit = uuid(801); + var plan = rebindPlan(baseline.plan(), changedCommit, false); + var request = + copyCaptureRequest(baseline.readCaptureRequest(), 4, changedCommit.toString(), null); + var applied = appliedSelection(plan, request); + var binding = launchBinding(request, applied.selectorEvidence(), 901, 3); + yield new PublishedReadFixture( + baseline.plan(), + request, + baseline.source(), + binding, + wireRequest(binding), + applied.selectorEvidence()); + } + case WORLD_PARTICIPANT_SCOPE -> { + var binding = + launchBinding(baseline.readCaptureRequest(), baseline.releaseSelector(), 902, 3); + yield new PublishedReadFixture( + baseline.plan(), + baseline.readCaptureRequest(), + baseline.source(), + binding, + wireRequest(binding), + baseline.releaseSelector()); + } + case WORLD_PARTICIPANT_DIGEST_SCHEMA -> { + var request = copyCaptureRequest(baseline.readCaptureRequest(), 3, null, null); + var selector = selectorEvidence(baseline.source().appliedResult(), request); + var binding = + launchBinding( + request, + selector, + 901, + AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + yield new PublishedReadFixture( + baseline.plan(), request, baseline.source(), binding, wireRequest(binding), selector); + } + case SELECTOR_RECEIPT_BINDING_DIGEST -> { + var plan = rebindPlan(baseline.plan(), null, true); + var applied = appliedSelection(plan, baseline.readCaptureRequest()); + var binding = + launchBinding(baseline.readCaptureRequest(), applied.selectorEvidence(), 901, 3); + yield new PublishedReadFixture( + baseline.plan(), + baseline.readCaptureRequest(), + baseline.source(), + binding, + wireRequest(binding), + applied.selectorEvidence()); + } + case SELECTED_ROOM_COUNT -> { + var source = withDuplicateSelectedRoom(baseline.source()); + yield new PublishedReadFixture( + baseline.plan(), + baseline.readCaptureRequest(), + source, + baseline.launchBinding(), + baseline.request(), + baseline.releaseSelector()); + } + }; + } + + private static WorldDraftTopologyCommitPlan includeControlPlaneOwner( + WorldDraftTopologyCommitPlan source) { + var binding = source.binding(); + List revisions = new ArrayList<>(binding.revisions()); + revisions.add( + new RevisionPayload( + Integer.toString(revisions.size()), + uuid(802), + Owner.GAME_DESIGN_CONTROL_PLANE, + "complete-release-owner-binding")); + List affectedUnits = new ArrayList<>(binding.affectedUnits()); + affectedUnits.add( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "RELEASE", + "selected-release", + "VERSION", + Long.toString(binding.target().gameDesignVersionRowId()), + "0")); + var completeBinding = + DraftCommitBinding.create( + binding.target(), + binding.requestId(), + binding.commitId(), + binding.baseCommitId(), + revisions, + affectedUnits); + return WorldDraftTopologyCommitPlan.create(completeBinding, source.ownerBinding()); + } + + private static CaptureRequest captureRequest( + WorldDraftTopologyCommitPlan plan, + int digestSchemaVersion, + String appliedCommitId, + String contentDigest) { + var owner = plan.ownerBinding(); + return new CaptureRequest( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.intakeRequestId(), + uuid(803), + "published-spawn-read-publication", + "a".repeat(64), + 6, + PublicationDigestRequestBinding.full( + owner.canonicalTenantId().toString(), + Long.toString(owner.gameDesignVersionId()), + "published-spawn-read-publication") + .derivedWorkflowIdentity(), + appliedCommitId, + contentDigest, + digestSchemaVersion, + plan.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList()); + } + + private static CaptureRequest copyCaptureRequest( + CaptureRequest source, + int digestSchemaVersion, + String appliedCommitId, + String contentDigest) { + return new CaptureRequest( + source.targetNamespace(), + source.canonicalTenantId(), + source.canonicalVersionId(), + source.intakeRequestId(), + source.publicationFence(), + source.publicationRequestId(), + source.requestDigest(), + source.versionStateEpoch(), + source.publishWorkflowId(), + appliedCommitId == null ? source.appliedCommitId() : appliedCommitId, + contentDigest == null ? source.contentDigest() : contentDigest, + digestSchemaVersion, + source.suppliedOwnedAffectedTuples()); + } + + private static AppliedSelection appliedSelection( + WorldDraftTopologyCommitPlan plan, CaptureRequest captureRequest) throws Exception { + byte[] graphBytes = canonicalGraphBytes(plan); + var graph = new WorldCanonicalAuthoredGraphReader().read(plan, graphBytes); + var binding = plan.binding(); + var accountBinding = + new DraftAuthorizationFenceBinding( + uuid(804), + binding.requestId(), + binding.commitId(), + uuid(805), + uuid(806), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.baseCommitId(), + "0", + binding.canonicalBytes(), + binding.canonicalBytes(), + binding.digest(), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + uuid(807).toString(), + null, + "1", + null, + null, + new byte[] {1}))) + .withRequiredOwners(); + var operation = + new WorldDraftTerminalOperation( + accountBinding.operationId(), + accountBinding.requestId(), + accountBinding.commitId(), + accountBinding.fenceId(), + accountBinding.tenantId(), + accountBinding.versionId(), + binding, + plan.ownerBinding(), + accountBinding.canonicalBytes()); + var appliedResult = + WorldDraftGraphAppliedResult.create( + new WorldDraftGraphApplication(operation, plan), graphBytes); + var selectorEvidence = selectorEvidence(appliedResult, captureRequest); + return new AppliedSelection(graphBytes, graph, appliedResult, selectorEvidence); + } + + private static WorldPublishedStartLocationEvidence selectorEvidence( + WorldDraftGraphAppliedResult appliedResult, CaptureRequest captureRequest) { + var receipt = appliedResult.startLocationReceipt().orElseThrow(); + return new WorldPublishedStartLocationEvidence( + selectorRequest(captureRequest), + receipt.canonicalBytes(), + appliedResult.application().operation().accountBindingBytes(), + appliedResult.canonicalBytes()); + } + + private static WorldPublishedStartLocationEvidence.Request selectorRequest( + CaptureRequest captureRequest) { + return new WorldPublishedStartLocationEvidence.Request( + captureRequest.targetNamespace(), + captureRequest.canonicalTenantId(), + captureRequest.canonicalVersionId(), + captureRequest.intakeRequestId(), + captureRequest.publicationFence(), + captureRequest.publicationRequestId(), + captureRequest.requestDigest(), + captureRequest.versionStateEpoch(), + captureRequest.publishWorkflowId(), + captureRequest.appliedCommitId(), + captureRequest.contentDigest(), + captureRequest.digestSchemaVersion(), + captureRequest.suppliedOwnedAffectedTuples().stream() + .map( + tuple -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + tuple.owner(), + tuple.aggregateType(), + tuple.aggregateId(), + tuple.scopeType(), + tuple.scopeId(), + tuple.expectedEpoch())) + .toList()); + } + + private static WorldCanonicalFrozenTopology frozenTopology( + WorldDraftTopologyCommitPlan plan, + CaptureRequest captureRequest, + AppliedSelection applied, + UUID captureId) { + return new WorldCanonicalFrozenTopology( + captureId, + new WorldCanonicalFrozenTopology.Request(plan, captureRequest), + mock(WorldAuthoredVersionIdentityReceipt.class), + applied.graph(), + applied.graphBytes(), + applied.appliedResult().canonicalBytes(), + applied.appliedResult().canonicalBytes()); + } + + private static CompleteLaunchBindingEvidence launchBinding( + CaptureRequest captureRequest, + WorldPublishedStartLocationEvidence selectorEvidence, + int descriptorVersionId, + int attestationSchemaVersion) { + String namespace = captureRequest.targetNamespace(); + UUID sourceOperationId = uuid(808); + String sourceEvidenceDigest = "sha256:" + "b".repeat(64); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + namespace, + "control-plane-request", + captureRequest.canonicalTenantId(), + "world", + sourceOperationId, + sourceEvidenceDigest, + 77, + false, + null, + false, + null, + true, + (long) descriptorVersionId, + false, + null); + var descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "launch-descriptor", + descriptorVersionId, + false, + null, + "{}", + "generation-config-v1", + captureRequest.versionStateEpoch(), + 8, + "published-release-bundle", + false, + null); + String commitId = selectorEvidence.request().appliedCommitId(); + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + participant -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + participant, + Integer.toString(descriptorVersionId), + false, + null, + commitId, + "WORLD_MANAGEMENT".equals(participant) + ? selectorEvidence.request().contentDigest() + : "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + participant, attestationSchemaVersion), + "GAME_LOGIC".equals(participant), + "GAME_LOGIC".equals(participant) ? "sha256:" + "d".repeat(64) : null)) + .toList(); + var release = + attestationSchemaVersion == AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION + ? AuthoredWorldReleaseAttestationEvidence.create( + namespace, + descriptor.resultDigest(), + captureRequest.canonicalTenantId(), + captureRequest.canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + captureRequest.publishWorkflowId(), + commitId, + participants, + "sha256:" + "e".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision(), + selectorEvidence) + : AuthoredWorldReleaseAttestationEvidence.createClosureSelector( + namespace, + descriptor.resultDigest(), + captureRequest.canonicalTenantId(), + captureRequest.canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + captureRequest.publishWorkflowId(), + commitId, + participants, + "sha256:" + "e".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision(), + selectorEvidence); + return new CompleteLaunchBindingEvidence(descriptor, release); + } + + private static ReadWorldPublishedSpawnRequirementsRequest wireRequest( + CompleteLaunchBindingEvidence launchBinding) { + var descriptor = launchBinding.descriptor(); + var bindingRequest = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId(READ_ID.toString()) + .setCanonicalTenantId(descriptor.canonicalTenantId().toString()) + .setWorldSlug(descriptor.worldSlug()) + .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) + .setExpectedRequestDigest(descriptor.requestDigest()) + .setExpectedResultDigest(descriptor.resultDigest()) + .build(); + return ReadWorldPublishedSpawnRequirementsRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(descriptor.targetNamespace()) + .setReadRequestId(READ_ID.toString()) + .setLaunchBindingRequest(bindingRequest) + .setExpectedReleaseAttestationDigest(launchBinding.releaseAttestation().evidenceDigest()) + .build(); + } + + private static byte[] canonicalGraphBytes(WorldDraftTopologyCommitPlan plan) throws Exception { + Map privateKeys = new LinkedHashMap<>(); + long privateKey = 100; + for (Node node : plan.graph().nodes()) { + privateKeys.put( + WorldDraftTopologyCommitRepository.family(node) + ":" + node.templateId(), privateKey++); + } + + List> rows = new ArrayList<>(); + long mappingId = 1; + for (Node node : plan.graph().nodes()) { + String family = WorldDraftTopologyCommitRepository.family(node); + Map mapping = new LinkedHashMap<>(); + mapping.put("id", mappingId++); + mapping.put("target_namespace", plan.ownerBinding().targetNamespace()); + mapping.put("canonical_tenant_id", plan.graph().tenantId().toString()); + mapping.put("canonical_version_id", plan.graph().versionId().toString()); + mapping.put("family", family); + mapping.put("template_id", node.templateId().toString()); + mapping.put("private_row_key", privateKeys.get(family + ":" + node.templateId())); + mapping.put("tenant_id", 17); + mapping.put("version_id", 29); + mapping.put( + "version_identity_operation_id", + plan.ownerBinding().versionIdentityOperationId().toString()); + mapping.put("request_id", plan.binding().requestId().toString()); + mapping.put("commit_id", plan.binding().commitId().toString()); + mapping.put("revision_id", node.revisionId().toString()); + mapping.put("revision_order", node.revisionOrder()); + Map row = new LinkedHashMap<>(); + row.put("mapping", mapping); + row.put( + "content", WorldDraftTopologyCommitRepository.expectedContent(node, privateKeys, 17, 29)); + rows.add(row); + } + + Map graph = new LinkedHashMap<>(); + graph.put("schemaVersion", "3"); + graph.put("canonicalTenantId", plan.graph().tenantId().toString()); + graph.put("canonicalVersionId", plan.graph().versionId().toString()); + graph.put( + "inboundSourceClosure", + plan.graph() + .freshGraphDeclaration() + .orElseThrow() + .inboundSourceClosure() + .orElseThrow() + .content()); + graph.put("rows", rows); + return new tools.jackson.databind.ObjectMapper().writeValueAsBytes(graph); + } + + private static WorldDraftTopologyCommitPlan rebindPlan( + WorldDraftTopologyCommitPlan source, UUID commitId, boolean changeGenerationInput) { + var binding = source.binding(); + List revisions = new ArrayList<>(); + for (RevisionPayload revision : binding.revisions()) { + if (revision.owner() != Owner.WORLD_MANAGEMENT) { + revisions.add(revision); + continue; + } + var mutation = WorldDesignMutationRevision.newBuilder(); + try { + JsonFormat.parser().merge(revision.payload(), mutation); + } catch (InvalidProtocolBufferException invalid) { + throw new IllegalStateException("Test World revision could not be decoded", invalid); + } + if (commitId != null) { + mutation.setCommitId(commitId.toString()); + } + if (changeGenerationInput + && mutation.getAggregateType() + == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE) { + mutation.setGenerationRule( + mutation.getGenerationRule().toBuilder().setValue("changed-generation-input")); + } + try { + revisions.add( + new RevisionPayload( + revision.revisionOrder(), + revision.revisionId(), + revision.owner(), + JsonFormat.printer().print(mutation.build()))); + } catch (InvalidProtocolBufferException invalid) { + throw new IllegalStateException("Test World revision could not be encoded", invalid); + } + } + var changedBinding = + DraftCommitBinding.create( + binding.target(), + binding.requestId(), + commitId == null ? binding.commitId() : commitId, + binding.baseCommitId(), + revisions, + binding.affectedUnits()); + return WorldDraftTopologyCommitPlan.create(changedBinding, source.ownerBinding()); + } + + private static WorldPublishedStartLocationSource withDuplicateSelectedRoom( + WorldPublishedStartLocationSource source) { + var frozen = source.frozenTopology(); + UUID selectedRoom = source.selectorReceipt().startLocation().roomTemplateId(); + var rows = new ArrayList<>(frozen.graph().rows()); + Row selectedRow = + frozen.graph().family(Family.ROOM).stream() + .filter(row -> row.template().templateId().equals(selectedRoom)) + .findFirst() + .orElseThrow(); + rows.add(selectedRow); + var duplicateRoomGraph = + new WorldCanonicalAuthoredGraph( + frozen.graph().tenantId(), + frozen.graph().versionId(), + frozen.graph().localTenantKey(), + frozen.graph().localVersionKey(), + rows, + frozen.graph().inboundSourceClosure()); + var duplicateRoomFrozen = + new WorldCanonicalFrozenTopology( + frozen.captureId(), + frozen.request(), + frozen.sourceIdentity(), + duplicateRoomGraph, + frozen.graphBytes(), + frozen.storageResultBytes(), + frozen.resultBytes()); + return new WorldPublishedStartLocationSource( + duplicateRoomFrozen, source.appliedResult(), source.selectorReceipt()); + } + + private record AppliedSelection( + byte[] graphBytes, + WorldCanonicalAuthoredGraph graph, + WorldDraftGraphAppliedResult appliedResult, + WorldPublishedStartLocationEvidence selectorEvidence) {} + + private record PublishedReadFixture( + WorldDraftTopologyCommitPlan plan, + CaptureRequest readCaptureRequest, + WorldPublishedStartLocationSource source, + CompleteLaunchBindingEvidence launchBinding, + ReadWorldPublishedSpawnRequirementsRequest request, + WorldPublishedStartLocationEvidence releaseSelector) { + String namespace() { + return launchBinding.descriptor().targetNamespace(); + } + } + + private WorldPublishedSpawnRequirementsReadOwner owner() { + return new WorldPublishedSpawnRequirementsReadOwner( + NAMESPACE, gameDesign, published, transactions); + } + + private WorldPublishedSpawnRequirementsReadOwner owner(String namespace) { + return new WorldPublishedSpawnRequirementsReadOwner( + namespace, gameDesign, published, transactions); + } + + private static ReadWorldPublishedSpawnRequirementsRequest wireRequest(String namespace) { + var binding = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId(READ_ID.toString()) + .setCanonicalTenantId(TENANT.toString()) + .setWorldSlug("world") + .setControlPlaneRequestId("control-plane-request") + .setExpectedRequestDigest("sha256:" + "a".repeat(64)) + .setExpectedResultDigest("sha256:" + "b".repeat(64)) + .build(); + return ReadWorldPublishedSpawnRequirementsRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(namespace) + .setReadRequestId(READ_ID.toString()) + .setLaunchBindingRequest(binding) + .setExpectedReleaseAttestationDigest("sha256:" + "c".repeat(64)) + .build(); + } + + private static WorldPublishedStartLocationEvidence.Request selectorRequest() { + return new WorldPublishedStartLocationEvidence.Request( + NAMESPACE, + TENANT, + VERSION, + uuid(4), + uuid(5), + "publication", + "d".repeat(64), + 6, + "workflow", + uuid(6).toString(), + "e".repeat(64), + 4, + List.of()); + } + + private static WorldDesignMutationRevision.Builder base( + UUID revision, + UUID aggregateId, + WorldDesignAggregateType aggregate, + WorldDesignScopeType scopeType, + UUID scopeId) { + return WorldDesignMutationRevision.newBuilder() + .setLogicalRevisionId(revision.toString()) + .setCommitId(uuid(7).toString()) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setAggregateType(aggregate) + .setAggregateId(aggregateId.toString()) + .setScopeType(scopeType) + .setScopeId(scopeId.toString()); + } + + private static UUID uuid(int value) { + return UUID.fromString("00000000-0000-4000-8000-%012d".formatted(value)); + } + + private static GrpcPeerIdentity peer(String service, String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static ContextScope attach(GrpcPeerIdentity peer) { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + return new ContextScope(context.attach()); + } + + private record ContextScope(Context previous) implements AutoCloseable { + @Override + public void close() { + Context.current().detach(previous); + } + } +}