diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index e2b50698be..1100f1bb04 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -1856,12 +1856,16 @@ jobs: registry_digest() { local image="$1" + local inspect_output inspect_status local digest - if ! digest="$(docker buildx imagetools inspect "$image" | - awk '$1 == "Digest:" { print $2; exit }')"; then - echo "Unable to inspect exact registry digest for $image; refusing to publish." >&2 - return 1 + if inspect_output="$(docker buildx imagetools inspect "$image")"; then + : + else + inspect_status=$? + echo "Unable to inspect exact registry digest for $image (imagetools exit $inspect_status); refusing to publish." >&2 + return "$inspect_status" fi + digest="$(awk '$1 == "Digest:" && $2 ~ /^sha256:[0-9a-f]{64}$/ { print $2; exit }' <<<"$inspect_output")" [[ "$digest" =~ ^sha256:[0-9a-f]{64}$ ]] || { echo "Registry manifest for $image has no exact digest." >&2 return 1 diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 9732ad700b..3745c959ad 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -59,6 +59,8 @@ For a `SaveRevision` request carrying `worldDesignMutation`, the same authorizat ## Implementation Status +The first authored-world source-retention cut includes passive `GetAuthoredWorldVersionState` and `ResolveAuthoredWorldSource` reads for World Management, implemented by the owner-local `AuthoredWorldVersionStateService` and `GameAuthoredWorldSourceRepository`. Their RPC adapters (`AuthoredWorldVersionStateGrpcService` and `AuthoredWorldSourceReadGrpcService`) are standalone and unregistered, authenticate the exact same-namespace World workload, and use no caller-context propagation. They do not replace or alter the registered `TenantIdentityService.ResolveFreshTenantCreation` contract above, and introduce no registration or activation path. World proof status and exact scope are recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). Graph snapshot capture is a later World owner-digest/topology stage, not part of these reads. No external source application, runtime activation, or gameplay-admission claim is made. + The owner-local foundation persists authored-world source operations and delivery outbox rows, canonical Version and bundle identity, opaque release references, optional manifest/artifact metadata, and additive launch-descriptor bindings. There is no creator source-registration RPC. The complete fixture successor activates only the claimed run-owned producer and source-bound descriptor handlers described above; production launch-read authorization remains deny-only. Ordinary new Version and bundle writes derive identity from the exact persisted Game row; retained all-null descriptor reads and inserts remain supported. State-changing `CompareAndSetVersionState` calls return `VERSION_STATE_MUTATION_UNAVAILABLE` after tenant/version and expected-epoch checks; exact same-state requests remain no-ops. This containment does not establish legal lifecycle transitions, Account authorization, or database CAS proof. The fresh-tenant owner source includes V29 canonical UUID/provenance storage, V30 exact creation-operation persistence, the owner-local transaction producer and source readback, and the exact Account/Game Session peer receipt read RPC. Validation evidence and remaining gaps belong to the linked implementation tracker. No creator RPC or authenticated creator authority is wired, and no Account association, membership, JOIN, or runtime admission is enabled by this source. @@ -88,9 +90,9 @@ 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 current SaveRevision ordering is verified in `RevisionServiceImpl` and its focused tests: after Draft/version and payload validation, an optional `worldDesignMutation` is sent to World Management before the Game Design revision entity is mapped and saved. World Management applies the mutation, advances its owner epochs, and writes its revision ledger in its own transaction. A World Management validation or Draft-epoch failure therefore reaches no Game Design revision save; the focused tests verify invalid Game Design payloads and published-version rejection before the client call, while World Management tests verify stale-epoch failure without an aggregate write. If World Management applies successfully but the later Game Design revision save fails, the World mutation, epochs, and ledger can remain committed while the Game Design revision is absent: the separate service transactions provide no cross-owner rollback. This is a current partial-application gap, not an atomicity guarantee. +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). -For retries, World Management's ledger lookup makes the same mutation identity (`tenantId`, version, commit, revision, operation, aggregate type, and requested aggregate) return `NO_OP_ALREADY_APPLIED` without reapplying the world rows; the focused World Management test verifies that replay. SaveRevision then proceeds to its Game Design revision save, which has no matching deduplication lookup or uniqueness constraint (only an index on tenant/version/kind/logical revision), so a completed request retried with the same mutation can create another Game Design revision even though World converges to the existing mutation. A World failure before apply leaves no Game Design revision and retry repeats the failure until its cause is corrected. The repository does not contain focused proof for a Game Design repository failure or an indeterminate transport result after a remote World commit, so those outcomes are not promoted beyond this ordering analysis. Exact retry convergence and synchronized multi-owner visibility remain gaps under ADR 0129. +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). The live `FinalizePurgeVersionAssets` failure handler also saves `PURGE_FAILED`/failed-workflow markers and then rethrows inside its `@Transactional` method. Spring transaction rollback can therefore discard those markers; if object deletion already succeeded, the durable row may remain `PURGE_IN_PROGRESS` without resumable failure evidence. This is not current retry/resume proof and remains blocked pending an independent durable failure/reconciliation boundary (or equivalent non-rollback record) plus focused proof for deletion and post-delete database-save failures. @@ -101,7 +103,7 @@ The Temporal owner-authorization seam is implemented at the receiver boundary: e ## 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` – currently persists a version-scoped design revision and can optionally apply a typed World Management design mutation in the same control-plane path, including scoped multi-row `WORLD_GENERATION_SUBTREE` payloads for generated room, exit, generation-rule, and spawn-binding changes. It is an implementation seam, not proof that a multi-owner commit is synchronized. +- `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. - `PublishVersion` – denies fresh/PENDING full-version publication before mutation while no production version-to-Draft association source exists, and replays exact terminal outcomes. The configured Temporal orchestrator delegates to the same command guard without starting a new workflow; registered activities propagate the same refusal without writes or synthesizing a terminal publication outcome. - `PublishScriptPatchVersion` – creates a script-only patch version referencing a base version. - `GetPublishedScriptPatchVersion` – target-authoritative design-time read API for script-patch publication lifecycle and digest identity; current reads reject non-script-only rows and rows outside retained `PUBLISHED`, `ACTIVE`, or `RETIRED` states, while new Game Session pin admission remains independently `PUBLISHED`-only and the remaining publication/readiness gaps are recorded in Implementation Status. @@ -153,7 +155,9 @@ Detailed request and response schemas are defined in the [OpenAPI specification] - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in [`game_design_service.proto`](../../../../protos/game-design/v1/game_design_service.proto). - `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. -- `SaveRevision(SaveRevisionRequest) returns (SaveRevisionResponse)` – persists a version-scoped design change and can return the typed result of an applied world-design mutation when the request carries `worldDesignMutation`, including scoped world-generation-subtree writes. +- `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. - `PublishVersion(PublishVersionRequest) returns (PublishVersionResponse)` – callers provide a stable `publish_request_id`, which binds exact terminal replay. The shared Game Design command guard denies fresh and `PENDING` requests before mutation, whether or not Temporal is available, because no production source creates a genuine version-to-Draft association. Exact terminal replay remains available: `FAILED` returns its stored attempt result, while `SUCCEEDED` requires exact immutable release readback. The public and registered Temporal paths do not start publication mechanics for fresh or pending requests. No live-positive publication proof exists; the current boundary is denial plus exact terminal replay. - `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/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index b36cf025c6..d52e8ebb65 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -4,11 +4,12 @@ This API contract is target-state canonical; implementation coverage is partial and must not be inferred from target examples alone. +- The authored-world source-retention cut adds the publication-attempt owner association to source intake and immutable receipt storage, canonical tenant-key protection, UUID-backed version identity, complete launch binding, and publication-fence binding. Focused physical PostgreSQL and mTLS proof is recorded for the tracked World boundary; the exact source revision, check scope, and limitations are recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). This does not implement graph snapshot capture, frozen topology, canonical preparation/execution artifacts (including V62/V63), runtime activation, or gameplay admission, and does not claim external database application. Graph snapshot capture and V28 remain deferred to the next owner-digest/topology stage because capture requires digest schema 3 while the current World digest producer emits schema 2. The graph implementation is preserved locally; its duplicate publication-binding clauses must be reconciled when V28 is resumed. The canonical persistence boundary is recorded in [Runtime and Data](./runtime-and-data.md#authored-world-source-retention). - The current World Management gameplay bridge serializes runtime room ids as `R-` and rejects scoped decimal `roomInstanceId` values such as `1021`. That storage-derived encoding is not the canonical target identity defined by the [Identifier Glossary](../../system-architecture-identifier-glossary.md). - The bridge, cross-service callers, examples, and focused proof have not migrated together to the scoped decimal `roomInstanceId` contract. The checked-in proof still exercises the legacy encoding. - The typed `ApplyRoomAmbientStatePatch` contract below is target-state: the current service has no complete handler or durable operation/digest-bound guard, so player-significant ambient mutations remain on the fenced Game Session admission/reconciliation path and are not direct table writes. - `GetDraftDesignDigest` currently has only shared bearer parsing and no owner/method authorization or exact Game Design publication binding. The current `GetDraftDesignDigestRequest` proto carries only `tenant_id` plus a `oneof` `version_id`/`script_patch_version`; neither the proto nor handler carries or validates the target `publishRequestId`, derived workflow identity, or canonical `requestDigest`, and no wrong-workload, cross-tenant, or exact-replay proof exists. The target exact Game Design workload, tenant/scope/request/workflow/digest context and denial proof are canonical in [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity). -- The current typed `ApplyWorldDesignMutation` owner-write boundary also has no method/workload or tenant authorization beyond shared JWT parsing: its gRPC handler forwards any authenticated bearer to the mutation service, whose current checks cover request shape and Draft state but not caller identity or tenant access. This is separate from the digest-read gap and the legacy REST generation-rule gap; the target authenticated Game Design caller and tenant authorization remain defined by the design-time contract below, and wrong-workload/cross-tenant denial is not implemented or proved. +- The registered `ApplyWorldDesignMutation` RPC now fails closed with an error-only `FAILED_PRECONDITION` before request parsing, remote reads, or mutation-service dispatch because complete Draft caller/tenant authorization and owner publication proof are unavailable. The owner-local mutation algorithm remains present but is unreachable through this registered ingress. This containment does not implement the target authenticated Game Design caller/tenant authorization or the owner freeze below; the separate digest-read gap and legacy REST generation-rule gap remain open. - Required executable migration/proof gate: `./gradlew :world-management-service:test :game-logic-service:test :game-session-service:test :tcp-proxy-service:crossServiceTest`. This gate must update the bridge, callers, examples, and checked-in proof together and pass before the target examples below may be treated as current. This document does not claim that the gate exists or passes. ## gRPC APIs @@ -18,6 +19,9 @@ This API contract is target-state canonical; implementation coverage is partial - `ListRoomOccupants` – **target state:** returns the authoritative typed occupant list for actors in a room, scoped by `RoomInstanceRef`. The current LOOK path is fixture-backed and has no World-owned location/occupancy persistence or authoritative read/write surface; it must not be treated as gameplay occupancy truth. - `ApplyRoomAmbientStatePatch` – applies a typed ambient fact patch to the target runtime scope under expected epoch/version preconditions and an operation/aggregate/request-digest-bound guard derived from the root `EffectId`; matching replay returns the durable prior result and a conflicting identity or payload fails closed. - `GetDraftDesignDigest` – returns the publish-gating digest for Draft world templates using the typed scope request `GetDraftDesignDigestRequest { tenantId, scope: oneof { versionId, scriptPatchVersion } }`. World Management supports `versionId` scope only and must return `UNSUPPORTED_SCOPE` for `scriptPatchVersion`. +- Complete authored-world launch binding retains immutable source/version/release evidence under the publication fence and supplements the existing launch descriptor contract. Graph snapshot capture is a subsequent owner-digest/topology stage; the current authored-source cut does not make a descriptor or graph an activation or admission decision. +- `WorldAuthoredVersionIdentityService.AssociateAuthoredWorldVersion` – associates an intaked source with one Game Design UUID version identity after exact same-namespace Game Design version-state evidence is checked and durably captured. This standalone service is unregistered and does not make the version playable. +- `WorldAuthoredSourceIntakeService.IntakeAuthoredWorldSource` – accepts exact same-namespace Game Design authored-source evidence for one canonical tenant/world selector and persists an immutable World receipt. `ReadAuthoredWorldSourceIntake` and `ReadAuthoredWorldSourceIntakeById` are read-only exact receipt lookups. This standalone service is unregistered and is not part of the runtime `WorldManagementService` surface. - `BeginVersionPublicationFreeze` – **Target state:** starts or exactly replays the durable WMS owner freeze for one `(tenantId, versionId)` publication request and returns the request/fence/epoch/digest checkpoint acknowledgement defined below. It is not present in the current proto or implementation. - `CompleteVersionPublication` – **Target state:** exactly replays or terminalizes the same WMS freeze with a `PUBLISHED` or `ABORTED` outcome and matching bundle/digest evidence. It is not present in the current proto or implementation. - `ValidateWorldUpgradeMappings` – validates world-owned durable references and approved remap sets for replacement-instance cutover to a target `(tenantId, versionId)`. diff --git a/design/architecture/microservices/world-management-service/runtime-and-data.md b/design/architecture/microservices/world-management-service/runtime-and-data.md index 69c5ecd7a3..a0a97a2368 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -2,13 +2,14 @@ ## Implementation Status +- The authored-world source-retention cut adds source intake and immutable receipts, protection for canonical UUID-to-legacy World tenant-key associations, UUID-backed Game Design version identity, complete launch binding, publication-fence linkage, and the publication-owner association specified below. Its forward-only migrations are `V23.1` and `V24`–`V27.2`; they preserve existing `V1`–`V23` history and do not establish that any external database has applied them. Focused physical PostgreSQL and mTLS proof for the tracked World boundary, including its exact revision and scope, is recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). Graph snapshot capture remains deferred to the next V29–V32 owner-digest/topology stage: capture requires digest schema 3, but the current World digest producer emits schema 2. The graph implementation and V28 are preserved locally for that follow-up and are not part of this cut. No frozen topology, canonical preparation/execution artifact (including V62/V63), activation, gameplay-admission readiness, or external database application is claimed. See [World API Contracts](./api-contracts.md#grpc-apis). - The current room-cache implementation remains an unversioned TTL-only payload and must use authoritative reads until the target opaque component-version and invalidation proof exists. - World V22 directly renames `room_instance` and `room_instance_exit` columns and renames `idx_room_instance_exit_from` to `idx_room_instance_exit_from_record`; older-binary compatibility and retained-data rollout proof remain open in [Shared Runtime Contracts and Persistence](../../../project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md#unit-5b-persistence-review-consequences). - Historical migration status is incomplete: `V16__runtime_world_event_scope.sql` dropped and recreated `world_event` while changing its legacy template-region reference to a runtime-instance reference, without recorded retained-row mapping or backfill evidence. The current repository cannot reconstruct rows already dropped. This is a retained-data deployment blocker: an affected deployment must first record either a verified no-data boundary or an explicit owner disposition/mapping, with exact readback and lifecycle/admission-isolation evidence; future remediation must add migration and focused proof before contraction is claimed. - Legacy topology scope/version introduction is also not mapped: `V2__add_tenant_and_expiration.sql` assigns `tenant_id = 0` to existing zone, room, and instance rows, while `V18__version_scoped_world_templates.sql` assigns `version_id = 1` across existing template tables without hierarchy/version-graph backfill evidence. Positive tenant/version reads can orphan or misattribute those rows. A retained-data deployment remains blocked until the owner records a verified no-data boundary or explicit retained-row disposition/mapping and exact readback; this remains migration/proof drift rather than a new identity authority. - The live versioned topology and spawn schemas carry tenant/version columns, but parent references remain scalar-ID foreign keys, so SQL does not enforce child/parent tenant/version equality. Normal typed mutation guards resolve parents with tenant/version predicates, but that is not database integrity and does not protect retained or direct-written rows. Target convergence requires composite parent keys/foreign keys or an equivalent owner-local guard, plus database integration and readback proof. This is separate from the sentinel-default and hierarchy/version-graph backfill drift above. -- The live `ApplyWorldDesignMutation` path performs a remote Game Design Draft-state read before its local transaction, but carries no Game Design `versionStateEpoch` or owner publication fence and has no durable WMS version-freeze row. A concurrent Game Design publish can therefore pass its digest read and transition the version while the pre-checked WMS mutation is still able to commit. This is a current lifecycle-handoff gap, not proof of Published-template immutability; the target freeze/acknowledgement protocol is canonical in [Game Design Version Control](../game-design-service/version-control.md#publication-freeze-and-owner-handoff). -- The target WMS publication owner contract, including `BeginVersionPublicationFreeze` and the outcome-typed `CompleteVersionPublication` terminal handoff, is specified in [World Management API Contracts](./api-contracts.md#publication-freeze-and-terminal-handoff-target-state). The current proto, DTOs, client adapter, persistence schema, handlers, and focused race/retry proof do not implement those surfaces: `ApplyWorldDesignMutation` still has no publication request, Game Design epoch, or WMS `publicationFence` fields. This remains a publication-readiness blocker; no digest, preflight state read, or Temporal completion may be promoted to freeze or terminal owner evidence. +- The registered `ApplyWorldDesignMutation` handler now fails closed before its former remote Game Design Draft-state read or local mutation dispatch. The owner-local mutation algorithm remains in `WorldDesignMutationServiceImpl`, but no registered ingress reaches it; the owner has no durable version-freeze row, Game Design `versionStateEpoch`, or `publicationFence`. This is containment, not proof of Published-template immutability or completed write authorization. The target freeze/acknowledgement protocol is canonical in [Game Design Version Control](../game-design-service/version-control.md#publication-freeze-and-owner-handoff). +- The target WMS publication owner contract, including `BeginVersionPublicationFreeze` and the outcome-typed `CompleteVersionPublication` terminal handoff, is specified in [World Management API Contracts](./api-contracts.md#publication-freeze-and-terminal-handoff-target-state). The current proto, DTOs, client adapter, persistence schema, handlers, and focused race/retry proof do not implement those surfaces: `ApplyWorldDesignMutation` still has no publication request, Game Design epoch, or WMS `publicationFence` fields. The registered RPC remains closed until the complete caller/tenant authorization and owner publication proof are implemented; no digest, preflight state read, or Temporal completion may be promoted to freeze or terminal owner evidence. - Procedural-generation persistence has a current identity gap: `V21__scoped_generation_rules.sql` creates a unique index over nullable `scope_type`/`scope_id`. Under PostgreSQL, multiple NULLs are distinct, so unscoped rows can duplicate the same `(tenant_id, version_id, name)` and destabilize deterministic generation-rule identity/digests. The current scope-aware repository lookup also compares nullable scope columns with SQL `=`, so it cannot retrieve an unscoped row. The target schema and mutation path must either prohibit unscoped rows or provide an explicit null-safe schema/query uniqueness contract, with focused proof; procedural-generation readiness remains blocked until that contract is enforced. - The current termination command returns a `TERMINATED` snapshot before comparing the supplied `terminationRequestId`. A different request identity therefore appears successful instead of conflicting with the terminal operation. The target requires exact request-identity replay and fail-closed mismatch handling, with focused terminal retry/conflict proof; this remains an implementation/proof blocker. - The current termination orchestration keeps the Entity Management cleanup RPC outside an open World transaction, preserves `TERMINATING` while remote cleanup or local finalization is incomplete, and commits local runtime-row cleanup with the `TERMINATED` lifecycle state in one local transaction. [WorldLifecycleCommandServiceImplTest](../../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java) covers the owner-local control flow and RPC/transaction separation at unit level; it does not provide live PostgreSQL rollback, crash, or concurrency proof. This does not close the terminal request-identity mismatch above or the Temporal lost-response gaps below. @@ -19,6 +20,16 @@ ## Template and Runtime Ownership +### Authored-world source retention + +A fresh intake completes its authenticated Game Design source read before opening the short World owner transaction. The allocator retains its association and legacy-table safety locks, with a transaction-local one-second limit for each lock wait that preserves a tighter positive caller limit. Lock timeout and deadlock failures return `UNAVAILABLE` without committed intake evidence; exact retries retain the original request identity. This does not register or activate the passive service. + +World Management retains exact authored-source evidence as owner-local source data. The intake receipt binds the target namespace, canonical tenant UUID, world selector, source operation and evidence digest, and immutable request/receipt identities. World reserves numeric tenant keys already present in its data and prevents those legacy keys from being reused for a canonical authored tenant association; it does not reinterpret or migrate existing `V1`–`V23` rows into the new UUID identity. + +The version identity joins that source receipt to the exact Game Design version and its captured state evidence. A complete launch binding retains the resolved descriptor and release-attestation evidence under the same source/version identity. The publication fence in this cut binds that source/version identity to its exact publication attempt; it does not capture or freeze the authored graph. Graph snapshot storage is deferred until the World digest schema is upgraded from 2 to the schema 3 required by capture, in the next V29–V32 owner-digest/topology stage. These records are evidence and retention boundaries, not a second Game Design version authority or a runtime lifecycle/admission state. + +The original six forward-only migrations are `V23.1__world_authored_source_intake.sql` for canonical source association, legacy-key reservations, and intake receipts; `V24__world_canonical_tenant_mutation_guard.sql` for owner-qualified row mutation; `V25__world_design_publication_fence.sql` for the publication fence and attempt binding; `V26__world_complete_launch_binding.sql` for complete launch binding; `V27__world_authored_version_identity.sql` for UUID-backed version identity and exact Game Design state evidence; and `V27.1__world_publication_owner_binding.sql` for the exact publication-attempt association to that identity. V27.1 adds the version-identity unique tuple required by the composite foreign key and five publication-attempt owner-binding columns: schema version, canonical version UUID, version-identity operation UUID, Game Design version id, and intake request digest. Its closed check constraint permits only schema 0 with all four identity fields null or schema 1 with every field present and valid; the composite foreign key binds the attempt's complete source, intake, tenant, namespace, and version tuple to the exact version-identity row. Retained V25–V27 attempts acquire the schema-0/null representation and remain immutable and nonpromotable. No UUID is inferred from a numeric key or coincidence, and V25's checksum is unchanged. The V27.1 clauses were extracted from the deferred V28 graph-snapshot migration; when V28 is later integrated, reconcile its duplicate publication-binding clauses while preserving its graph-snapshot additions. The additive `V27.2__world_legacy_tenant_claim_concurrency.sql` correction preserves canonical-tenant refusal checks while allowing unchanged-tenant legacy updates without serializing them on the tenant claim row; new or changed legacy tenant claims use insert-if-absent followed by claim-kind validation. Existing migrations are not rewritten. `V28__world_authored_graph_snapshot.sql` and its graph-capture implementation remain preserved locally for the next V29–V32 owner-digest/topology stage; no physical snapshot proof is claimed in this cut. Focused physical PostgreSQL and mTLS proof for the tracked World boundary is linked in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). See [V27.1 migration](../../../../services/world-management-service/src/main/resources/db/migration/V27.1__world_publication_owner_binding.sql). + World Management owns both version-scoped template topology and runtime world-instance state, but the two surfaces are strictly separated. Stable playable identity and replacement classification are governed by [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); this document records only World Management's storage and owner-local consequences: - Target contract: template tables are keyed by `(tenantId, versionId)` and updated only through design-time workflows coordinated by Game Design. Current migration drift remains because the live legacy `POST /generation/rules` endpoint directly persists `generation_rule` after only a tenant-access check, defaults `versionId` to `1`, and does not enforce Draft/version authority; see [Procedural Generation Control](./procedural-generation-control.md). diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 72ceed00a1..a05b93d5a4 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -195,3 +195,37 @@ Entry format: - Context: The #3155 second Hosted request reported a predecessor terminal-capture warning after the earlier Hosted run had already been captured and finalized. - Observation: `HostedCaptureError` reported unmarked content after a finding comment's final `cr-comment:v1` marker. The warning retained a diagnostic and did not prevent the new request from being posted; the exact content or actor responsible remains unverified. - Expected pattern: Preserve the completed checkpoint and frozen counts, distinguish a recapture warning from a failed new provider request, and report the diagnostic to controller maintenance. Do not invent replacement findings or spend another review to repair historical capture metadata. + +- `2026-10-13`: Certificate fixture validity can mask the intended negative assertion + - Context: the #3156 local Game Design PostgreSQL gate failed the descriptor-readback mismatch fixture before reaching that boundary because its newly issued certificate raised `CertificateNotYetValidException`. + - Observation: certificate readiness and live validation time disagreed transiently; the exact operating-system clock cause remains unproven. Successful certificate generation alone did not establish that the fixture was valid for the next consumer check. + - Expected pattern: verify generated fixture certificates with the same actual validity check before exercising a later boundary, use a short monotonic readiness budget, and propagate expired or malformed certificates immediately. Preserve production certificate validation and the intended negative assertion. + - Current status: the test-only readiness correction passed the 75-case local Game Design PostgreSQL suite, including the intended descriptor-readback negative case. No production validity check, certificate lifetime, or required proof has been relaxed. + +- `2026-10-13`: Compact selected-PR JSON still includes large inventories + - Context: Gameplay closeout used controller `reviews status --pr 3183 --compact --json` and the equivalent #3156 request. + - Observation: their JSON captures were approximately 251 KB and 172 KB, including check inventories and historical transition details; printing the complete selected response consumed substantial context despite requesting compact output. + - Expected pattern: a compact selected-PR projection should retain identity, review obligations, required-check outcomes, routes and readiness reasons, with detailed inventories available separately. Until then, capture JSON and print only the fields needed for the current decision. + - Current status: reported to Overseer for controller improvement; no controller implementation change was made in this lane. + +- `2026-10-13`: Follow-up to compact selected-PR output + - Context: the 2026-10-13 compact selected-PR output entry requested a smaller routine status projection after printing large detailed captures. + - Observation: that entry confused the roles of the existing summary and compact options; the detailed capture size did not establish a missing controller projection. + - Outcome: Overseer identified the existing `reviews status --pr N --summary --json` projection, which retains the same safety result without ancestor rows or check inventories. `--compact` intentionally keeps the selected PR's detailed evidence; the earlier expectation conflated the two options. + - Expected pattern: use `--summary --json` for routine identity and readiness; use full status, history, and routes for needed finding/provenance drilldown. No missing projection or controller implementation defect is established by the earlier large capture. + +- `2026-10-13`: Workflow-run PR metadata is not frozen base provenance + - Context: after #3183 merged and #3156 was retargeted, an observer initially treated the associated `pull_requests[].base.sha` on an older workflow run as its original event base. + - Observation: that field reflected the new PR base, while the completed checkout log proved the run had merged the same head into the previous base. The initial exact-base claim was withdrawn. + - Expected pattern: attribute execution to immutable event/proof metadata or the actual checkout/merge log; qualify unchanged-source reuse separately. A current associated PR tuple does not rewrite historical execution provenance. + - Current status: the observer corrected its report; the front was reconciled and published on the merged develop parent for replacement CI. The post-retarget runtime/preview guards correctly refused stale test-merge parents. + +- `2026-10-13`: Clarification of the summary status projection + - Context: the compact-output follow-up describes the existing `--summary --json` option for routine PR identity and readiness. + - Observation: the summary omits ancestor rows and detailed check inventories while retaining verdict and readiness fields, pending and failed check names, the observed-check count, optional-check counts, and inventory availability/status. Omitting detailed inventories does not mean omitting all check information. + - Expected pattern: use the summary for routine identity and readiness, then read detailed status, history, or routes when check inventory or finding/provenance evidence is needed. + +- `2026-10-13`: CI matrix failure discovery requires every jobs page + - Context: the shared Gameplay observer monitored a large Validation matrix through `gh run view --json jobs`. + - Observation: the returned jobs view omitted failed Buf and Game Logic rows. Their completion timestamps were 01:04:25 and 01:08:08 UTC, but the observer first discovered them around 01:16 UTC through the fully paginated Jobs API; the exact time the API exposed each failure was not recorded. This delayed front-PR failure reporting by roughly 12 and 8 minutes; no GitHub API or FireController failure was established. + - Expected pattern: inspect the complete paginated source-run jobs inventory before metadata callbacks and report failed jobs while other jobs remain active. Do not wait for the whole workflow to finish or treat a partial jobs view as exhaustive. 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 713c2c954c..4f56846aa2 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 @@ -46,13 +46,13 @@ The live `CompareAndSetVersionState` path now preserves tenant/version lookup, e - `AR-1.1` / `AR-2.2`: [ADR 0124](../../architecture/decisions/adr-0124-materialized-starter-profiles-with-conservative-draft-upgrades.md) is the target for materialized starter-profile content. The current tracker does not claim profile materialization, conservative upgrades, or the no-runtime-fallback rule as implemented or proved; the existing creator/editor and Draft gaps remain. - `AR-1.2`: [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md) records the current non-support boundary for whole-game portability. No external package import/export or portable snapshot implementation/proof is implied by existing asset or authoring seams. - `AR-1.2`: [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) records optional model-assisted proposals through scoped creator tooling. LLM-assisted authoring remains an implementation and focused-proof gap; current procedural-generation evidence does not upgrade it. -- `AR-1.1` / `AR-1.2`: The typed Game Design revision-to-World generation mutation is the bounded current path, but legacy `POST /generation/rules` remains a live tenant-only direct persistence path that defaults `versionId` to `1` and does not enforce Game Design Draft/version authority. Its existence means typed generation proof does not cover all current generation-input ingress; procedural-generation readiness remains blocked until the endpoint is removed or fails closed. +- `AR-1.1` / `AR-1.2`: The owner-local typed World generation mutation algorithm has focused unit proof, but the registered `ApplyWorldDesignMutation` ingress fails closed before decoding, remote reads, or dispatch, so there is no live typed revision-to-World generation path. Legacy `POST /generation/rules` remains a live tenant-only direct persistence path that defaults `versionId` to `1` and does not enforce Game Design Draft/version authority. Procedural-generation readiness remains blocked until the legacy path is removed or fails closed and the registered typed ingress is implemented. - `AR-1.3`: [ADR 0127](../../architecture/decisions/adr-0127-game-authored-equipment-layouts-with-fail-closed-publication.md) makes the complete game-authored equipment vocabulary/body-layout publication gate a target obligation. [ADR 0130](../../architecture/decisions/adr-0130-historical-equipment-body-layout-authority.md) is superseded by it. Existing equipment/editor and publication caveats remain unchanged. - `AR-1.3`: [ADR 0128](../../architecture/decisions/adr-0128-game-design-plugin-trust-provenance.md) records Game Design's accepted local provenance record under [ADR 0111](../../architecture/decisions/adr-0111-unified-dsl-with-distinct-embedded-script-and-plugin-lifecycles.md); it does not upgrade current signed intake, runtime readiness, compatibility, or activation proof. - `AR-1.5`: [ADR 0129](../../architecture/decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md) records exact-base/digest Draft proposals and owner-local CAS/read-fence obligations. The current implementation and focused proof remain partial, with no silent-merge or distributed-transaction claim. -- `AR-1.5`: Full-version publication currently has no WMS owner-local publication-freeze acknowledgement: WMS performs only a remote Draft-state pre-check before its local mutation commit. The target exact `versionStateEpoch`/`publicationFence` handoff, post-freeze rejection or drain, and interleaved mutation/publish retry proof are canonical in [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#publication-freeze-and-owner-handoff); current status remains partial. +- `AR-1.5`: Full-version publication currently has no WMS owner-local publication-freeze acknowledgement. The registered Draft mutation ingress now fails closed before the former remote Draft-state pre-check or mutation commit; the owner-local freeze and write fence remain unimplemented. The target exact `versionStateEpoch`/`publicationFence` handoff, post-freeze rejection or drain, and interleaved mutation/publish retry proof are canonical in [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#publication-freeze-and-owner-handoff); current status remains partial. - `AR-1.5`: Publish participant authorization and identity remain blocked across the owner seam. Automation is currently admin-role-only while WMS, Entity, and Game Logic digest handlers are bearer-only; the live Game Design participant DTO/client/gate omit and do not compare `tenantId`, and Game Logic accepts a blank tenant with a tenant/version-independent empty manifest. The shared target owner allowlist, exact publication binding, tenant comparison, and wrong-workload/cross-tenant/identity proof are canonical in [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity). -- `AR-1.5`: The typed WMS `ApplyWorldDesignMutation` write path has the same unrecorded owner-boundary gap: its live gRPC handler accepts any shared-JWT bearer and does not enforce the target tenant or an allowlisted Game Design caller before mutation. This is distinct from participant digest authorization and the legacy REST generation-rule ingress; cross-tenant/wrong-workload denial remains unimplemented and unproved, while the target Game Design caller/tenant authorization remains canonical in the WMS API contract. +- `AR-1.5`: The registered WMS `ApplyWorldDesignMutation` handler now denies every request before owner reads or mutation dispatch with an error-only `FAILED_PRECONDITION`, because complete Draft caller/tenant authorization and owner publication proof are unavailable. The unit proof covers Game Design, other workload, missing identity, and a cross-tenant-shaped request; physical mTLS integration execution remains pending. This containment does not implement the authorized Game Design write path or the owner freeze, which remain canonical in the WMS API contract. It is distinct from participant digest authorization and the legacy REST generation-rule ingress. These links add decision provenance only; they do not change existing implementation or gap status. The `EA-3.2` verification state is separately corrected from `proven` to `audited` to match its bounded backend evidence. @@ -64,8 +64,8 @@ The published `888f` GDS foundation slice contains source-operation/outbox stora | --- | --- | --- | --- | --- | --- | --- | --- | | Fresh-tenant identity prerequisite | `partial` | `proven` for bounded fresh-creation persistence and exact Account/Game Session receipt read only | [Canonical tenant identity and fresh-creation readback](../../architecture/microservices/game-design-service/api-contracts.md#canonical-tenant-identity-and-fresh-creation-readback) | [GameTenantCreationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepository.java); [TenantIdentityGrpcService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java); [V29 canonical game tenant identity](../../../services/game-design-service/src/main/resources/db/migration/V29__canonical_game_tenant_identity.sql); [V30 game tenant creation operations](../../../services/game-design-service/src/main/resources/db/migration/V30__game_tenant_creation_operations.sql) | [GameTenantCreationRepositoryIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryIntegrationTest.java); [GameTenantIdentityRepositoryIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java); [TenantIdentityGrpcServiceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java); [TenantIdentityGrpcAuthWiringTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java); [GrpcServerPeerIdentityClientInterceptorTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptorTest.java); [GameTenantCreationRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryTest.java); [FreshTenantCreationEvidenceTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreationEvidenceTest.java) | [Account identity and enrollment](./player-access-and-session.md); [realm routing and playable state](./realm-routing-and-playable-state.md) | Partial: bounded owner-local persistence and exact mTLS receipt read exist. Authenticated creator authorization, Account enrollment, runtime admission, and a playable environment remain unavailable. No creation RPC or activation is introduced. | | `EA-3.2` Creator authoring applications | `partial` | `audited` | [Frontend architecture](../../architecture/system-architecture-frontend.md); [creator journeys](../../product/user-journeys/creators.md); [world editing tools](../../architecture/microservices/game-design-service/world-editing-tools.md) | [App.tsx](../../../web-client/src/App.tsx); [GameEditor.tsx](../../../web-client/src/GameEditor.tsx); [ScriptEditor.tsx](../../../web-client/src/ScriptEditor.tsx); [GameDesignGrpcService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java) | [GameDesignGrpcServiceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java); [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [automation](./automation-and-scheduler-runtime.md); [gameplay](./gameplay-rules-entities-and-effects.md); [player experience](./player-experience-commands-and-communication.md) | Partial: the [web-client README](../../../web-client/README.md) records a starter React surface and backend authoring APIs exist, but the designed creator application, accessible editor workflows, preview, conflict resolution, and focused frontend proof are absent. ADR 0124, ADR 0126, and ADR 0129 define the profile, scoped-proposal, and Draft-fence target behavior; implementation and focused proof remain absent. | -| `AR-1.1` World, entity, rule, and content authoring | `partial` | `proven` for the typed revision-to-World mutation, authored help/command, and entity-template validation seams; complete world, entity, rule, and content authoring remains unproved. | [Game Design ownership](../../architecture/microservices/game-design-service/README.md); [world editing tools](../../architecture/microservices/game-design-service/world-editing-tools.md); [ability/action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [item and equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.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) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [GameAuthoredHelpTopicServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredHelpTopicServiceImpl.java); [V23 published commands](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql); [EntityTemplateReferenceServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityTemplateReferenceServiceImpl.java) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [GameAuthoredHelpTopicServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredHelpTopicServiceImplTest.java); [EntityTemplateReferenceServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityTemplateReferenceServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md) | Partial: typed revision-to-World mutation, authored help/commands, and entity template/runtime validation seams exist, but complete rule/action/effect catalogs and creator-facing authoring workflows are not implemented. Accepted procedural-generation decisions now define World-owned typed ingress and preview-bound replacement, but typed generation ingress, destructive plan protocol, and identity/reference proof remain incomplete. | -| `AR-1.2` Procedural, LLM-assisted, and external authoring tools | `partial` | `proven` for bounded procedural generation and typed generation mutation seams; LLM-assisted authoring, typed generation ingress, destructive plans, staging bounds, and large-grid behavior remain unproved. Whole-game package import/export, filesystem/Git interchange, and portable snapshots are outside the current target per [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md), not merely unproved. The [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) typed creator-API/scoped-proposal path is target-only and remains unimplemented/unproved. | [LLM content tools](../../architecture/system-architecture-llm-content-tools.md); [procedural generation](../../architecture/system-architecture-procedural-generation.md); [generation control](../../architecture/microservices/world-management-service/procedural-generation-control.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 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md); [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) | [GenerationServiceImpl.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImpl.java); [DungeonGenerator.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/DungeonGenerator.java); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java) | [GenerationServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImplTest.java); [DungeonGeneratorTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/DungeonGeneratorTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [automation](./automation-and-scheduler-runtime.md) | Partial: bounded procedural generation and typed generation mutations exist. Whole-game portability remains non-target under ADR 0125; model-assisted authoring remains target-only under ADR 0126 with no production contract or focused proof. Accepted procedural-generation decisions now define one World-owned engine, request-bounded replay, bounded persistence, previewed replacement, and sparse/full-grid semantics; typed ingress, destructive plans, staging bounds, and large-grid proof remain incomplete. | +| `AR-1.1` World, entity, rule, and content authoring | `partial` | `proven` for the owner-local World mutation algorithm, authored help/command, and entity-template validation seams; the registered revision-to-World ingress is denied, and complete world, entity, rule, and content authoring remains unproved. | [Game Design ownership](../../architecture/microservices/game-design-service/README.md); [world editing tools](../../architecture/microservices/game-design-service/world-editing-tools.md); [ability/action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [item and equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.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) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [GameAuthoredHelpTopicServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredHelpTopicServiceImpl.java); [V23 published commands](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql); [EntityTemplateReferenceServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityTemplateReferenceServiceImpl.java) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [GameAuthoredHelpTopicServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredHelpTopicServiceImplTest.java); [EntityTemplateReferenceServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityTemplateReferenceServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md) | Partial: authored help/commands and entity template/runtime validation seams exist, but the registered typed World mutation ingress is denied, and complete rule/action/effect catalogs and creator-facing authoring workflows are not implemented. Accepted procedural-generation decisions now define World-owned typed ingress and preview-bound replacement, but typed generation ingress, destructive plan protocol, and identity/reference proof remain incomplete. | +| `AR-1.2` Procedural, LLM-assisted, and external authoring tools | `partial` | `proven` for bounded procedural generation and the owner-local typed generation mutation algorithm; registered typed generation ingress, LLM-assisted authoring, destructive plans, staging bounds, and large-grid behavior remain unproved. Whole-game package import/export, filesystem/Git interchange, and portable snapshots are outside the current target per [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md), not merely unproved. The [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) typed creator-API/scoped-proposal path is target-only and remains unimplemented/unproved. | [LLM content tools](../../architecture/system-architecture-llm-content-tools.md); [procedural generation](../../architecture/system-architecture-procedural-generation.md); [generation control](../../architecture/microservices/world-management-service/procedural-generation-control.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 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md); [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) | [GenerationServiceImpl.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImpl.java); [DungeonGenerator.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/DungeonGenerator.java); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java) | [GenerationServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImplTest.java); [DungeonGeneratorTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/DungeonGeneratorTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [automation](./automation-and-scheduler-runtime.md) | Partial: bounded procedural generation and owner-local typed generation mutation tests exist, but registered typed generation ingress, destructive plan protocol, staging bounds, and large-grid proof remain incomplete. Whole-game portability remains non-target under ADR 0125; model-assisted authoring remains target-only under ADR 0126 with no production contract or focused proof. | | `AR-1.3` Script, plugin, mod, and extension packaging | `partial` | `proven` only for signed plugin intake, design-time script-patch publication, and bounded local activation-preflight/control-plane seams; full activation admission and canonical compatibility remain unproved because the dedicated Game Logic ability-schema attestation, tenant runtime readiness, and exact instance pin/epoch gates are not wired. Broader mod/extension packaging, creator tooling, and distribution lifecycle also remain unproved. | [Modding framework](../../architecture/microservices/game-design-service/modding-framework.md); [scripting control-plane API](../../architecture/system-architecture-scripting-control-plane-api.md); [scripting rollout and rollback](../../architecture/system-architecture-scripting-rollout-and-rollback.md) | [PluginBundleIntakeServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleIntakeServiceImpl.java); [PluginBundleStorageServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleStorageServiceImpl.java); [AutomationPluginControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneService.java); [AutomationPatchControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java); [V18 published plugins](../../../services/game-design-service/src/main/resources/db/migration/V18__published_plugin_versions.sql) | [AutomationPluginControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneServiceTest.java); [PluginActivationPreflightServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginActivationPreflightServiceImplTest.java); [AutomationPatchControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneServiceTest.java); [AutomationScriptingControlPlaneGrpcServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingControlPlaneGrpcServiceTest.java) | [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: signed plugin and script-patch publication/readiness seams exist, but live compatibility preflight uses Automation's aggregate participant digest instead of the required dedicated Game Logic-owned ability-schema attestation. Canonical ability-schema compatibility, broader mod/extension package formats, creator tooling, distribution lifecycle, complete runtime readiness convergence, and complete target signature-set persistence/exposure remain incomplete. Current live intake selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set. ADR 0111 owns the accepted target provenance and lifecycle boundary. | | `AR-1.4` Game-authored assets, branding, and release manifests | `partial` | `proven` for the bounded frozen-origin, snapshot-integrity, candidate export/readback, and release-v2 selector migration slice at the pinned head; complete Draft mapping, production publication, purge, and runtime delivery remain unproved. | [Game Design asset storage](../../architecture/microservices/game-design-service/asset-storage.md); [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md); [game customization](../../architecture/system-architecture-game-customization.md); [versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md) | [AssetExportServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java); [VersionAssetArtifactServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java); [VersionAssetExportCandidateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java); [VersionAssetPublicationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [PublishedReleaseBundleContract.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java); [V8 release bundle](../../../services/game-design-service/src/main/resources/db/migration/V8__published_release_bundle.sql); [V10 asset artifact](../../../services/game-design-service/src/main/resources/db/migration/V10__version_asset_artifact.sql); [V35.2 canonical release version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql); [V36 opaque bundle reference](../../../services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql); [V37 mapping and export snapshot](../../../services/game-design-service/src/main/resources/db/migration/V37__version_asset_export_snapshot.sql); [V38 published asset digest evidence](../../../services/game-design-service/src/main/resources/db/migration/V38__published_asset_digest_evidence.sql); [V49 published-world selector evidence](../../../services/game-design-service/src/main/resources/db/migration/V49__published_world_start_location_evidence.sql); [V49.1 selected-world release participant schema](../../../services/game-design-service/src/main/resources/db/migration/V49.1__selected_world_release_participant_schema.sql); [V50 frozen candidate origin](../../../services/game-design-service/src/main/resources/db/migration/V50__freeze_asset_export_candidate_public_origin.sql); [PublishedReleaseBundleRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java) | [AssetExportServiceImplTest.java](../../../services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java); [VersionAssetExportCandidateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java); [VersionAssetArtifactServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [PublishedReleaseBundleContractTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [PublishedWorldSelectorSchemaMigrationIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java) | [platform operations](./platform-operations-and-delivery.md); [player experience](./player-experience-commands-and-communication.md) | Partial: the current source includes Draft `version_asset` mappings, a durable version-scoped export snapshot with independent readback, candidate export/readback, and immutable v1 bundle storage with canonical identity, opaque reference, manifest-schema metadata, and artifact digests. Release-v2 selector binding is enforced by `PublishedReleaseBundleContract.requireSelectorBinding`; current pinned-source physical proof covers V49 and V49.1, the frozen V50 candidate origin, and database-computed snapshot hash/length verification. Normal export consumes the frozen snapshot and records candidate manifest/artifact digest evidence before object writes; published repair independently reads the immutable candidate and checks it against the exact release bundle before object writes. The production Draft mapping caller remains absent, so public and registered Temporal full-version ingress fails closed before mutation. Complete Draft quota admission, unbounded whole-selection hash work, durable object-store candidate isolation, integrated lifecycle migration closure, global publication/purge fencing, destructive lifecycle safety, complete creator UX, approved external delivery, and runtime launch readiness remain incomplete or unproved. | | `AR-1.5` Revisions, versions, publishing, validation, and attestation | `partial` | `proven` only for the fail-closed publish gate, exact terminal replay, release-bundle readback, and bounded participant-digest seams; current happy-path full-version publication and bundle creation are refused, and private finalization tests substitute a mocked bundle service; this does not prove historical revision/version lineage. Post-bundle failure reconciliation and same-commit attestation convergence, complete digest/attestation tuples, and the end-to-end publication-bound generation proof remain unproved. Historical lineage remains a retained-data deployment blocker: the owner must record a verified no-data boundary or explicit retained-row disposition/mapping with exact readback before migration cleanup or any completion claim. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.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) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [VersionPublishCommandServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java); [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [TemporalVersionPublishWorkflowImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishWorkflowImpl.java); [V9 publish attempt](../../../services/game-design-service/src/main/resources/db/migration/V9__publish_attempt_framework.sql); [V14 recorded digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql); [V35.1 canonical Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.1__canonical_version_identity.sql); [V35.2 canonical release Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql); [V36 opaque bundle reference](../../../services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql); [V39 publication evidence text](../../../services/game-design-service/src/main/resources/db/migration/V39__publication_evidence_text_storage.sql); [PublishedReleaseBundleRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java); [VersionRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [VersionPublishCommandServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [ControlPlaneDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImplTest.java); [RecordedParticipantDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [LaunchDescriptorRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: fresh and PENDING full-version publication and legacy bundle creation fail closed; exact terminal replay and bundle readback seams exist. Participant tokens remain synthetic; World emits digest schema 2, which the gate supports. The bundle read projects optional manifest-schema and artifact-digest fields, but canonical target-commit provenance and actual-byte producer population remain unproved, so same-commit attestation convergence is not established. Historical revision/version lineage remains a retained-data deployment blocker requiring exact readback before migration cleanup or any completion claim. Complete digest/attestation tuples and the end-to-end publication-bound generation proof remain incomplete. | @@ -175,7 +175,7 @@ Design-time revoke is explicit through `RevokePluginVersion`. Upload verificatio ### World Design Authoring Handoff -Game Design owns revision history, commits, version state, and publish orchestration; World Management owns authoritative Draft and Published world template rows. `SaveRevision` is version-scoped and carries typed `worldDesignMutation` payloads, including `WORLD_GENERATION_SUBTREE`, through the canonical World Management API. The first caller path saves revision history and applies the concrete change through that API rather than directly mutating World tables or treating opaque revision JSON as the authoritative world graph. The current seam permits only Draft version design-time writes; Published, Active, Failed, and Retired scopes are rejected. 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. +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. ### Validation and Proof @@ -196,13 +196,13 @@ Game Design owns revision history, commits, version state, and publish orchestra - The broader authored-action model remains incomplete: the `ActionAdmissionTag` catalog and ordered `admissionTags` actor-admission metadata, generic target selection, costs, cooldowns, timing, ordered multi-effect steps, additional effect kinds, required/optional outcomes, and explicit cross-region compensation/refund behavior are not live. - Rich help-authoring UI, localization-aware authored help, fuzzy or semantic search, related-topic graphs, moderation/versioning beyond ordinary authored-content ownership, and dynamic authored-action help integration remain deferred product work. - The broader authoring and publication domain remains in progress. Participant digests still need actual target-commit provenance and coordinated schema adoption. The v1 release-bundle schema/read projection carries optional manifest-schema and artifact-digest fields, but canonical target-commit provenance, actual-byte producer proof, integrated migration closure, and focused database proof remain pending. Future domain-template families must join the version-scoped digest gate; future release-bundle consumers must apply missing-attestation, unsupported-schema, and exact-asset-proof hard failures. -- Publish/version synchronization remains incomplete across downstream domain-owned schemas. Game Design owns revision history, version metadata, and publish orchestration, while Entity Management and World Management retain authoritative entity and world rows; the current participant observations and first World mutation handoff do not yet establish actual same-commit convergence or cover every future editor caller or template family. +- Publish/version synchronization remains incomplete across downstream domain-owned schemas. Game Design owns revision history, version metadata, and publish orchestration, while Entity Management and World Management retain authoritative entity and world rows; the registered World mutation ingress currently fails closed, and participant observations plus owner-local mutation logic do not establish actual same-commit convergence or cover every future editor caller or template family. - Asset lifecycle follow-through remains incomplete. At the pinned #3151 head, physical PostgreSQL proof covers the V49/V49.1 selector migration and snapshot hash/length slice; it does not close the integrated migration set or establish production Draft mapping, quota admission, durable operation handling, lifecycle CAS, purge, object-store, or exact recovery proof. The canonical lifecycle and operation contracts are owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#implementation-status) and [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md); this tracker records the status and proof gaps without repeating those normative details. - Snapshot integrity work across the complete mapped set remains unbounded in total set size: repeated source hash verification during private freeze and candidate readbacks uses configured 15-second transactions and a 25 MiB per-asset limit, but has no bounded-batch implementation. Preserve independent byte/hash verification and admitted-input semantics. Reconsider bounded batching before enabling production Draft mapping/export, or when representative mapped-set measurement shows deadline pressure; no total-set cap is defined by this tracker. - Launch/activation follow-through includes broader cutover and retirement consumers, later runtime-state families, exact Entity target-template validation once version-scoped entity-template tables exist, and replacement of remaining placeholder runtime topology/state rows. - Normalized-template cutover phase is target-only: no tenant-scoped `GetTemplateReferencePhase` RPC, durable phase authority, or `BACKFILLING`/`VALIDATED`/`ENFORCED` consumer contract exists in the current slice; live launch checks only the per-template `ENFORCED`/`LEGACY` field. The target API and fail-before-launch behavior remain unimplemented and unproved. - StartSession still needs to validate same-base `PUBLISHED` patch identity and join Automation's tenant-scoped script-patch status, failing closed unless the pinned patch is runtime `READY`; current descriptor validation proves neither publication identity nor readiness. -- World design authoring currently has the first typed revision-to-World handoff, including the transactional applied-revision ledger, idempotent replay, expected aggregate/scope epoch checks, and reference/scope validation for supported mutations. Broader editor callers and concrete mutation coverage, publish-reconciliation replay, and actual digest commit-token convergence remain outside the current seam. +- World design authoring has an owner-local mutation algorithm with a transactional applied-revision ledger, idempotent replay, expected aggregate/scope epoch checks, and reference/scope validation for supported mutations. The registered `ApplyWorldDesignMutation` RPC denies every request before a remote Draft read or local dispatch, so there is no live typed revision-to-World handoff. Producer/admission integration, broader editor callers and concrete mutation coverage, publish-reconciliation replay, and actual digest commit-token convergence remain open; publication freeze, commit-bound `versionStateEpoch`/`publicationFence`, and complete caller/tenant authorization also remain absent. See the partial status and target handoff in [World Management Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status) and [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#publication-freeze-and-owner-handoff). ## To Discuss 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 9e6301d08e..9d11840f0a 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,20 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status +### Authored World Source Retention Status + +The six forward migrations `V23.1`, `V24`–`V27`, and `V27.1` define World intake and immutable source receipts, legacy numeric tenant-key reservation, UUID-backed version identity, complete launch binding, publication-fence linkage, and the publication-attempt owner association. The V27.1 correction compiled and passed selected checks. An earlier 1,148-unit/99-skipped result is historical only; its two PostgreSQL migration cases and five mTLS integration cases were skipped locally. A bounded clean detached proof at `ca8165bcdb73f1f6a635ddf8544e9ca4650ac19d` passed `:world-management-service:generateJooq :world-management-service:check -PfullCheck linkCheck lintMarkdown` in 3m11s. Fresh World XML reported 261 unit and 58 integration tests, with zero failures, errors, or skips, including authored-source intake, mTLS, version identity, and publication-fence suites. The later carry to `1140adcad5f236baf1edecf320513191cb4f0a64` changed only three Account paths and preserved all World postimages and the six SQL migrations, so the clean proof applies to the unchanged tracked World cut. This establishes focused physical PostgreSQL and mTLS integration proof for that cut; it does not claim application to an external database or by itself validate the V27.2 correction described below. Graph snapshot capture and `V28` remain deferred to the next V29–V32 owner-digest/topology stage because capture requires World digest schema 3 while the producer currently emits schema 2; the graph implementation is preserved locally, with duplicate publication-binding clauses to reconcile when V28 is resumed. The nine untracked graph/snapshot files in the original source worktree were excluded from the clean proof and remain untouched. No physical V28 graph-snapshot proof, deployed runtime behavior, runtime-owner activation, runtime admission, frozen topology, canonical preparation/execution artifacts (including V62/V63), or playable-world claim is established. The canonical owner-local storage boundary and API status are recorded in [World API Contracts](../../architecture/microservices/world-management-service/api-contracts.md#implementation-status) and [World Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#authored-world-source-retention); Game Design's source/version read adapters are described in [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#implementation-status). + +The additive `V27.2` review correction removes shared legacy-tenant row serialization while retaining canonical-tenant refusal. The earlier clean local candidate at `a9531a9eeff374f5c23971cb6f1111a15668d354` remains attributable to that candidate: it reported 471 Core unit cases, 415 Game Design unit cases and 75 PostgreSQL integration cases, and 262 World unit cases and 59 PostgreSQL integration cases, all with zero failures, errors, or skips. The 59 World PostgreSQL cases were executed on the preceding `fecf8efd59e9aa8d7d4375a0322c37852bebe1fd` candidate and reused unchanged in that gate, including the same-tenant disjoint-update concurrency case and canonical-reservation protections. The final 75-case Game Design PostgreSQL suite executed after the test-only certificate-readiness correction; unchanged unit outputs were reused. At `42296c26c91459c229a6822c5a6fc81c8b0da4d1`, the focused World proof reports 263 unit cases, reused unchanged from the freshly executed unit suite at `c62de7bf127908cece54e6d97f4565b3147be9be`, including its SQL-state classification regression and 61 fresh PostgreSQL integration cases, with zero failures, errors, or skips. The PostgreSQL cases include timeout rollback, exact retry, and tighter-limit reset coverage. The clean World formatter/check/linkCheck run reported 10,822 links checked and the Markdown lint reported 550 files with zero issues. These results are focused local proof only; they do not establish a new combined Core/Game Design/World gate, full CI, external database application, runtime registration, or activation. + +The subsequent review-fix candidate `819d6d3ed93c19695d53c727c9d6932d099806c5` passed the focused World formatter and `:world-management-service:check -PfullCheck linkCheck lintMarkdown` gate with 266 freshly executed unit cases and 61 freshly executed PostgreSQL integration cases, zero failures, errors or skips. This includes retryable Version-state read failures without owner mutation, safe RPC errors without upstream descriptions or trailers, isolated publication-fence negative inputs, and a second canonical tenant allocation above the existing legacy, reservation and association maximum. The allocator query retains all 18 sources using separate scalar `MAX` subqueries; no query-plan or deployed performance measurement is claimed. The five shared mTLS client postimages had already passed 471 freshly executed Core unit cases, and the unchanged Game Design postimages passed 415 unit and 75 PostgreSQL cases at `f4e7b5eb3ed23935197ad10d58bdb4e4b075652f`. The combined gate at that earlier candidate stopped on a throwing Mockito stub being invoked during replacement; the two-line test setup correction was then proved by the complete World gate. These are qualified affected-boundary results across the stated phases, not one successful combined gate or new-head CI/runtime proof. Documentation checks reported 10,826 links OK and 550 Markdown files with zero issues. + +A subsequent passive-RPC correction at `e28bcf6b0c3028bd2e5e7e5099e43f6b8d1327f1` passed both Game Design and World `check` tasks, including static analysis, and the documentation gate. Game Design's 417 unit cases executed fresh; its 75 PostgreSQL cases and World's 267 unit and 61 PostgreSQL cases were reused unchanged from their fresh successful execution at `ed2f9cbab40e081da50cd662cb8dbb213700bb1a`, all with zero failures, errors or skips. The focused cases now classify connection versus permanent owner-read storage failures, retain safe World intake error codes without upstream descriptions or trailers, and require exactly one owner and attempt for each version before and after replay reads. The earlier static gate rejected test observers retaining mutable exceptions; they now snapshot immutable descriptions and trailer-presence evidence. Core's unchanged 471-case proof remains separately qualified. These checks establish neither later-head CI nor activation or genuine owner authority. + +The later storage-classification and typed launch-scope correction `6d41311efe75d1bbc04d23f6ac30b92f7fc1927b` retains the canonical SHARED-only launch association using the existing protobuf scope enum and rejects unspecified, isolated and unknown numeric wire values. Its identical five code postimages were verified in the clean proof mirror based on `e96a0695a1747f8215598b12479654f194bb31e5`: 471 Core unit cases, 268 World unit cases and 61 World PostgreSQL cases executed fresh with zero failures, errors or skips; both service/static gates and the actual pinned remote Buf generation and generated-Java compilation passed. The source candidate also carries only the three permission-document changes from develop `a2e36e5f66ad0ab776b500ef5ff808a051cbf7c8`. Safe association errors distinguish retryable connection/lock failures from permanent storage errors without upstream details or trailers. The qualification covers these source postimages, not later-head CI, a registered launch-read producer, deployed activation or genuine external owner authority. + +### Current Runtime and Lifecycle + This tracker is the permanent reader-facing implementation record for world runtime, room reads, movement, lifecycle orchestration, and Draft topology mutation. Canonical target-state design remains under [design/architecture](../../architecture/README.md). The initial-admission implementation now includes the typed Game Session workload-only acquire RPC, a durable World hold, lifecycle-row termination serialization, scheduled fail-closed reconciliation, and a method-specific authenticated Game Session owner-read adapter. The opt-in run-owned local Compose coordinator now drives the hold from Game Session’s durable initial-bind intent and resolves it only through exact authenticated owner proof. Its separate World launch-evidence provider rereads the immutable capability and receipt, verifies the caller and both recipient pins, and reads the real Game Design descriptor before World mutation. World persists a binding digest and original preparing epoch on `world_instance`; exact ACTIVE replay at that epoch with identical evidence does not cause another transition. Historical original-source compositional proof for the bounded fixture lifecycle was accepted at `f330c8721824d063a5eba09afd5388631ae184b9`: unchanged `d44429e683a80271d3a03e0e31e2f80fe5b33a4c` World socket (2), PostgreSQL (3), provider (5), and lifecycle unit (22) cases passed without skips, complemented by rebuilt positive Smoke run `38174536549` on merge `763d96cafe10037b9d2ebe3fb250e99261ca2f0e` (`ec16942` plus `f330`). The current private reconstruction has separate consolidated local checks: its two authenticated socket cases pass, while three World PostgreSQL cases skip without Docker and rebuilt packaged Smoke/restart remain unrun. Historical Smoke does not prove startup refusal (skipped), packaged process restart, per-RPC counters, later protected activation, or hold race/restart; exact provenance and complementary producer/denial proof are recorded in [the Game Design fixture status](game-authoring-publishing-and-activation.md#run-owned-authored-world-fixture-repair). Raw Game Session `RUNNING` and World `ACTIVE` runtime seeds have been removed; local World metadata seeding retains versioned template rooms `1021` and `2045` for the current transitional movement contract. See the [World initial-bind contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract), [run-owned launch-evidence contract](../../architecture/system-architecture-testing.md#run-owned-v1-launch-read-evidence), and the [Game Session implementation status](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind). @@ -17,7 +31,7 @@ The initial-admission implementation now includes the typed Game Session workloa - `GR-2.1` / `AR-3.1`: World termination keeps Entity Management cleanup outside an open World transaction, retains `TERMINATING` while cleanup is pending or fails, and commits local runtime-row cleanup with the `TERMINATED` lifecycle state in one local transaction. [World Management Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status) owns this current consequence. [WorldLifecycleCommandServiceImplTest](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java) covers the local control flow and RPC/transaction separation; live PostgreSQL rollback/crash/concurrency proof is not claimed. The separate terminal fast path still does not compare `terminationRequestId`, as recorded below. - `GR-2.1` / `SF-2.3`: The synchronous termination seam returns a `TERMINATED` snapshot before checking a supplied `terminationRequestId`; mismatched terminal retries therefore are not fail-closed, and exact identity/conflict proof remains incomplete. See [World Management Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status). - `GR-2.1` / `SF-2.1`: Versioned topology and spawn schemas carry tenant/version columns but use scalar parent foreign keys, so the database does not enforce child/parent scope equality. Composite ownership enforcement (or an equivalent owner-local guard) and database readback proof remain incomplete; this is separate from sentinel-default and hierarchy/version-graph backfill drift. See [World Management Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status). -- `GR-2.1` / `AR-1.5`: The WMS design handoff performs only a remote Game Design Draft-state check before its local mutation transaction. Durable owner-freeze acknowledgement and commit-bound `versionStateEpoch`/`publicationFence` evidence are absent, so a pre-check can race publication; the target handoff and race semantics belong to [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#publication-freeze-and-owner-handoff), with local status and proof consequences in [World Management Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status). +- `GR-2.1` / `AR-1.5`: The registered `ApplyWorldDesignMutation` handler fails closed before any remote Game Design Draft read or local mutation dispatch. The owner-local mutation algorithm exists, but the live handoff is unavailable while complete caller/tenant authorization and publication proof are missing. World has no durable version-freeze row or commit-bound `versionStateEpoch`/`publicationFence` evidence; the registered ingress remains closed. The target handoff and race semantics belong to [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#publication-freeze-and-owner-handoff), with local status and proof consequences in [World Management Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status). - `GR-2.1` / `AR-3.1`: The current Temporal lifecycle signal implementation keeps one mutable pending slot per operation and can overwrite repeated requests or process activate plus terminate against a stale epoch; this race and its focused proof remain incomplete. The target durable signal/update contract and conflict semantics are owned by [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md). These links add decision provenance only; they do not upgrade world runtime, lifecycle, or Draft mutation status. @@ -26,7 +40,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`: version-scoped topology, Draft mutation, and instance lifecycle exist, but generation still has hardcoded inputs, initial event scheduling is absent, and lifecycle prepare/activate retain blocking attestation calls. The World-owned initial-admission hold is a lifecycle sub-boundary under `GR-2.1` that contributes to the `AR-3.1` runtime lifecycle handoff: exact hold acquisition, serialized termination blocking, fail-closed reconciliation, authenticated Game Session owner readback, and the run-owned local Compose caller are wired; general `StartSession` retry integration is not claimed. The opt-in run-owned launch path validates its immutable capability and receipt, then stores their binding digest and original preparing epoch through [RunOwnedWorldLaunchEvidenceProvider](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java) and [V23.0.1](../../../services/world-management-service/src/main/resources/db/migration/V23.0.1__world_run_owned_fixture_launch_binding.sql). 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`: focused unit tests cover topology, lifecycle, hold acquisition, termination blocking, and reconciliation; PostgreSQL hold/termination race and restart proof and live Compose execution are not established for this boundary. Focused provider, workload-mTLS, and fixture PostgreSQL test anchors are listed; candidate PostgreSQL/restart and production-activation proof remain unproved. | [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); [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); [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); [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) | [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 hold keeps ambiguous initial-admission outcomes fenced and does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. Run-owned fixture evidence binding is implemented, but candidate PostgreSQL, packaged restart, and production activation remain unproved. Initial-bind PostgreSQL race/restart proof and live Compose execution also remain open. | +| `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`; 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 World-owned initial-admission hold is a lifecycle sub-boundary under `GR-2.1` that contributes to the `AR-3.1` runtime lifecycle handoff: exact hold acquisition, serialized termination blocking, fail-closed reconciliation, authenticated Game Session owner readback, and the run-owned local Compose caller are wired; general `StartSession` retry integration is not claimed. The opt-in run-owned launch path validates its immutable capability and receipt, then stores their binding digest and original preparing epoch through [RunOwnedWorldLaunchEvidenceProvider](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java) and [V23.0.1](../../../services/world-management-service/src/main/resources/db/migration/V23.0.1__world_run_owned_fixture_launch_binding.sql). 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`: focused unit tests cover topology, lifecycle, hold acquisition, termination blocking, and reconciliation; PostgreSQL hold/termination race and restart proof and live Compose execution are not established for this boundary. Focused provider, workload-mTLS, and fixture PostgreSQL test anchors are listed; candidate PostgreSQL/restart and production-activation proof remain unproved. | [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); [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); [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); [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) | [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 hold keeps ambiguous initial-admission outcomes fenced and does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. Run-owned fixture evidence binding is implemented, but candidate PostgreSQL, packaged restart, and production activation remain unproved. Initial-bind PostgreSQL race/restart proof and live Compose execution also remain open. | | `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. | @@ -104,7 +118,7 @@ These links add decision provenance only; they do not upgrade world runtime, lif - LOOK proof covers deterministic World room snapshots and exits, visible Entity room-ground data, authenticated command behavior, structured scope-marker composition, dependency failure propagation, and WebSocket/Telnet rendering parity. Target Game Session floor allocation, Game Logic propagation, participant served-through/component-version validation, stale-floor retry, and mixed-region/scope/epoch rejection remain unproved. DROP/PICKUP proof also lacks stale World `TargetingFactSnapshot` location/version rejection and same-root replay coverage. Movement proof covers valid directional exits, invalid or missing exits, missing-room behavior, downstream failures, unauthenticated commands, Game Session binding mutation, destination auto-LOOK, non-disconnecting failures, pipeline traversal, and reconnect-after-move. Focused automated proof now covers returning destination room context and obtaining a destination-bound `LOOK` before the local binding effect. Authoritative World Management location mutation is not yet proven because that write contract is not implemented. - Runtime-room convergence proof covers canonical World Management emission and malformed-id rejection, row/record exit mapping, canonical room cache keys, shared readers at Game Logic and Entity Management ingress, attestation issuance and claims, session-routing scrubbing, movement idempotency, automation event payloads, and Game Session outbound validation before transport dispatch. Ordinary fixtures use `R-...`; legacy `room-...`, bare numeric, uppercase, or malformed forms remain only in negative tests. - Lifecycle proof covers the durable world creation, activation, termination, and failure path plus the operator-facing lifecycle read surface; the extracted command path is the local non-Temporal fallback. It does not prove Temporal lost-response activity retries, ACTIVE-aware start compensation, exact terminal retries after workflow completion, or closed-workflow reconciliation. -- Draft mutation and digest proof covers first apply, duplicate replay, stale global and scope epochs, unresolved references, `REPLACE_SCOPE`, unsupported scopes, and `SEED_APPEND_ONLY` behavior. Additional focused proof passed for zero declared scope ids on room, room-exit, region, and zone mutations and for generation-rule scope-id normalization; focused Game Design revision and gRPC caller proof also passed. The current World Management module proof passed through `dev-tools/validation/run-locked-gradle.sh :world-management-service:check -PfullCheck`. +- Owner-local Draft mutation and digest proof covers first apply, duplicate replay, stale global and scope epochs, unresolved references, `REPLACE_SCOPE`, unsupported scopes, and `SEED_APPEND_ONLY` behavior. Registered `ApplyWorldDesignMutation` ingress proof now covers fixed error-only denial before owner reads or mutation dispatch for missing identity, Game Design, another workload, and a cross-tenant-shaped request. Its mTLS integration cases also assert unchanged World rows and no owner-client calls; physical execution remains subject to the Docker-backed integration environment. Additional focused proof passed for zero declared scope ids on room, room-exit, region, and zone mutations and for generation-rule scope-id normalization; focused Game Design revision and gRPC caller proof also passed. The current World Management module proof passed through `dev-tools/validation/run-locked-gradle.sh :world-management-service:check -PfullCheck`. - The current walkability checkpoint passed `./gradlew :game-logic-service:check :game-session-service:check :world-management-service:check -PfullCheck`. Focused proof covers canonical destination room context, a destination-bound `LOOK` before the local Game Session binding update, and the seeded `NORTH`/`SOUTH` round trip. Authoritative World Management character/session location mutation remains unproved because its write contract is not implemented. ## Active Gaps diff --git a/dev-tools/tests/gradle_supervisor_test.py b/dev-tools/tests/gradle_supervisor_test.py index 1e867401d2..9ed5abd1d7 100644 --- a/dev-tools/tests/gradle_supervisor_test.py +++ b/dev-tools/tests/gradle_supervisor_test.py @@ -407,9 +407,14 @@ def test_timeout_cleans_separate_session_worker_before_unlock(self): def running(pid): try: return Path(f"/proc/{pid}/stat").read_bytes().rsplit(b")", 1)[1].split()[0] != b"Z" - except FileNotFoundError: + except (FileNotFoundError, ProcessLookupError): return False + def test_running_treats_disappearing_process_as_not_running(self): + for error in (FileNotFoundError, ProcessLookupError): + with self.subTest(error=error), mock.patch.object(Path, "read_bytes", side_effect=error): + self.assertFalse(self.running(12345)) + def test_wrapper_sigkill_supervisor_retains_guard_until_cleanup(self): process, fixture, _ = self.launch("worker", FIXTURE_MODE="worker") worker = self.ready(fixture, "worker") diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 82f59254bf..1fded45e8a 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -832,7 +832,15 @@ if [[ "${1:-}" == buildx && "${2:-}" == imagetools && "${3:-}" == inspect ]]; th if [[ "${RUNTIME_TARGET_MODE:-}" == different && "$tag" == "$HEAD_SHA" ]]; then digest='sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb' fi - printf 'Digest: %s\n' "$digest" + python3 - "$digest" <<'PY' +import sys + +print(f"Digest: {sys.argv[1]}") +print("manifest detail " * 8192) +PY + if [[ "${RUNTIME_TARGET_MODE:-}" == inspect-failure ]]; then + exit 42 + fi exit 0 fi if [[ "${1:-}" == buildx && "${2:-}" == imagetools && "${3:-}" == create ]]; then @@ -883,6 +891,24 @@ if [[ -e "$fixture_dir/runtime-registry-marker" ]]; then exit 1 fi +rm -f "$fixture_dir/runtime-registry-marker" +inspect_status=0 +if run_runtime inspect-failure >"$fixture_dir/inspect-failure-output" 2>"$fixture_dir/inspect-failure-error"; then + echo "runtime publisher accepted an imagetools inspection with a nonzero exit" >&2 + exit 1 +else + inspect_status=$? +fi +if [[ "$inspect_status" -ne 42 ]]; then + echo "runtime publisher changed the imagetools inspection exit status (expected 42, got $inspect_status)" >&2 + exit 1 +fi +grep -Fq 'imagetools exit 42' "$fixture_dir/inspect-failure-error" +if [[ -e "$fixture_dir/runtime-registry-marker" ]]; then + echo "runtime publisher created an alias after imagetools inspection failed" >&2 + exit 1 +fi + rm -f "$fixture_dir/runtime-registry-marker" if run_runtime non404; then echo "runtime publisher treated a registry failure as an absent tag" >&2 diff --git a/protos/game-design/v1/game_design_service.proto b/protos/game-design/v1/game_design_service.proto index c59681c8af..91483b3661 100644 --- a/protos/game-design/v1/game_design_service.proto +++ b/protos/game-design/v1/game_design_service.proto @@ -70,6 +70,12 @@ service GameDesignService { rpc DeleteHelpTopic(DeleteHelpTopicRequest) returns (DeleteHelpTopicResponse); } +// Standalone, unregistered exact version-state read for an already-intaken authored-world source. +service AuthoredWorldVersionStateService { + rpc GetAuthoredWorldVersionState(GetAuthoredWorldVersionStateRequest) + returns (GetAuthoredWorldVersionStateResponse); +} + message SaveRevisionRequest { string data = 1; string tenant_id = 2; @@ -325,6 +331,54 @@ message GetVersionStateResponse { shared.v1.ErrorDetail error = 2; } +message GetAuthoredWorldVersionStateRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + string canonical_tenant_id = 4; + string world_slug = 5; + string source_operation_id = 6; + string expected_source_evidence_digest = 7; + int64 version_id = 8; +} + +message GetAuthoredWorldVersionStateResponse { + AuthoredWorldVersionStateEvidence evidence = 1; +} + +message AuthoredWorldVersionStateEvidence { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + string canonical_tenant_id = 4; + string world_slug = 5; + string source_operation_id = 6; + string expected_source_evidence_digest = 7; + int64 version_id = 8; + AuthoredWorldSourceReceipt source_evidence = 9; + VersionLifecycleState version_state = 10; + int64 version_state_epoch = 11; + string evidence_digest = 12; + string canonical_version_id = 13; +} + +// Complete immutable registration receipt, without another RPC's transient read request ID. +message AuthoredWorldSourceReceipt { + int32 schema_version = 1; + string target_namespace = 2; + string registration_request_id = 3; + string operation_id = 4; + string request_digest = 5; + string canonical_tenant_id = 6; + string tenant_slug = 7; + string world_slug = 8; + string world_display_name = 9; + int64 source_game_row_id = 10; + string source_game_tenant_key = 11; + string provenance_kind = 12; + string evidence_digest = 13; +} + message CompareAndSetVersionStateRequest { string tenant_id = 1; int64 version_id = 2; diff --git a/protos/game-design/v1/tenant_identity_service.proto b/protos/game-design/v1/tenant_identity_service.proto index 1aedc3deb7..7b0043de91 100644 --- a/protos/game-design/v1/tenant_identity_service.proto +++ b/protos/game-design/v1/tenant_identity_service.proto @@ -11,6 +11,12 @@ service TenantIdentityService { returns (ResolveFreshTenantCreationResponse); } +// Standalone, unregistered exact authored-world source read; no mutation or admission permission. +service AuthoredWorldSourceReadService { + rpc ResolveAuthoredWorldSource(ResolveAuthoredWorldSourceRequest) + returns (ResolveAuthoredWorldSourceResponse); +} + message ResolveFreshTenantCreationRequest { string creation_request_id = 1; string expected_request_digest = 2; @@ -28,3 +34,27 @@ message ResolveFreshTenantCreationResponse { string provenance_kind = 9; string evidence_digest = 10; } + +message ResolveAuthoredWorldSourceRequest { + string request_id = 1; + string operation_id = 2; + string canonical_tenant_id = 3; + string world_slug = 4; +} + +message ResolveAuthoredWorldSourceResponse { + int32 schema_version = 1; + string target_namespace = 2; + string request_id = 3; + string registration_request_id = 4; + string operation_id = 5; + string request_digest = 6; + string canonical_tenant_id = 7; + string tenant_slug = 8; + string world_slug = 9; + string world_display_name = 10; + int64 source_game_row_id = 11; + string source_game_tenant_key = 12; + string provenance_kind = 13; + string evidence_digest = 14; +} diff --git a/protos/game-session/v1/game_session_service.proto b/protos/game-session/v1/game_session_service.proto index 010eec9f8a..3f4a39b31d 100644 --- a/protos/game-session/v1/game_session_service.proto +++ b/protos/game-session/v1/game_session_service.proto @@ -44,6 +44,10 @@ service GameSessionControlPlaneService { // Read exact durable owner proof for a World-owned initial-admission hold. rpc GetInitialAdmissionBindProof(GetInitialAdmissionBindProofRequest) returns (GetInitialAdmissionBindProofResponse); + // Read the exact Game Session-owned STARTING launch association for World composition. + rpc GetCanonicalGameInstanceLaunchAssociation( + GetCanonicalGameInstanceLaunchAssociationRequest) + returns (GetCanonicalGameInstanceLaunchAssociationResponse); rpc ValidateBuiltInCommandAlias(ValidateBuiltInCommandAliasRequest) returns (ValidateBuiltInCommandAliasResponse); rpc ListAdmissionPointers(ListAdmissionPointersRequest) @@ -604,6 +608,44 @@ message GetCanonicalInitialAdmissionOwnerProofResponse { google.protobuf.Timestamp terminal_at = 23; } +// A transport retry has a separate read identity and cannot create a new launch operation. +message GetCanonicalGameInstanceLaunchAssociationRequest { + string read_request_id = 1; + string target_namespace = 2; + string canonical_tenant_id = 3; + string world_slug = 4; + string game_instance_uuid = 5; + string control_plane_request_id = 6; + string launch_descriptor_id = 7; + string expected_descriptor_request_digest = 8; + string expected_descriptor_result_digest = 9; + string expected_release_attestation_evidence_digest = 10; +} + +message GetCanonicalGameInstanceLaunchAssociationResponse { + string read_request_id = 1; + string target_namespace = 2; + string canonical_tenant_id = 3; + string world_slug = 4; + string game_instance_uuid = 5; + string control_plane_request_id = 6; + string launch_descriptor_id = 7; + string descriptor_request_digest = 8; + string descriptor_result_digest = 9; + string release_attestation_evidence_digest = 10; + string playable_state_namespace_id = 11; + entity_management.v1.PlayableStateScope playable_state_scope = 12; + // Current Game Session row projection only; World lifecycle authority remains separate. + string current_game_instance_status = 13; + int64 current_row_version = 14; + gamedesign.v1.LaunchDescriptor launch_descriptor = 15; + gamedesign.v1.AuthoredWorldReleaseAttestationEvidence release_attestation = 16; + shared.v1.ErrorDetail error = 17; + bool public_production = 18; + string owner_attempt_id = 19; + int64 owner_fence = 20; +} + message GetGameplayCommandStatusRequest { string command_id = 1; string tenant_id = 2; diff --git a/protos/world-management/v1/world_authored_version_identity_service.proto b/protos/world-management/v1/world_authored_version_identity_service.proto new file mode 100644 index 0000000000..62851921ea --- /dev/null +++ b/protos/world-management/v1/world_authored_version_identity_service.proto @@ -0,0 +1,31 @@ +syntax = "proto3"; +package world_management.v1; +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +import "game-design/v1/game_design_service.proto"; +import "world-management/v1/world_management_service.proto"; + +// Standalone, unregistered, same-namespace Game Design association construction. +service WorldAuthoredVersionIdentityService { + rpc AssociateAuthoredWorldVersion(AssociateAuthoredWorldVersionRequest) + returns (AssociateAuthoredWorldVersionResponse); +} +message AssociateAuthoredWorldVersionRequest { + int32 schema_version = 1; + string target_namespace = 2; + string canonical_tenant_id = 3; + string world_slug = 4; + string source_operation_id = 5; + string source_evidence_digest = 6; + string expected_canonical_version_id = 7; + int64 game_design_version_id = 8; + string read_request_id = 9; +} +message AssociateAuthoredWorldVersionResponse { + AssociateAuthoredWorldVersionRequest request = 1; + string operation_id = 2; + IntakeAuthoredWorldSourceResponse source_intake_receipt = 3; + // Original committed proof, including its historical read correlation on retry. + gamedesign.v1.GetAuthoredWorldVersionStateResponse version_state_evidence = 4; +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityClient.java new file mode 100644 index 0000000000..91329c39d8 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityClient.java @@ -0,0 +1,133 @@ +package net.firedevops.firemud.common.authoring; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.FileBackedGrpcMtlsPolicy; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.worldmanagement.v1.WorldAuthoredVersionIdentityServiceGrpc; + +/** Opt-in file-backed mTLS client for exact authored Version identity association. */ +public final class WorldAuthoredVersionIdentityClient + extends AbstractReloadingBlockingGrpcClient< + WorldAuthoredVersionIdentityServiceGrpc.WorldAuthoredVersionIdentityServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public WorldAuthoredVersionIdentityClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + WorldAuthoredVersionIdentityClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when the owning Game Design service explicitly starts this opt-in client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("World authored Version association client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("World authored Version association client has no gRPC stub"); + } + initialized = true; + } + + /** + * Applies or recovers the unchanged association request; transport failures propagate unchanged. + */ + public WorldAuthoredVersionIdentityEvidence.Result associate( + WorldAuthoredVersionIdentityEvidence.Request request) { + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "World authored Version association request must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .associateAuthoredWorldVersion( + WorldAuthoredVersionIdentityGrpcCodec.toRequest(request)); + try { + return WorldAuthoredVersionIdentityGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "World returned invalid authored Version association evidence", exception); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected WorldAuthoredVersionIdentityServiceGrpc.WorldAuthoredVersionIdentityServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + return WorldAuthoredVersionIdentityServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(WorldAuthoredVersionIdentityGrpcCodec.MAX_RESPONSE_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + public String workloadNamespace() { + return workloadNamespace; + } + + private WorldAuthoredVersionIdentityServiceGrpc.WorldAuthoredVersionIdentityServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "World authored Version association client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + return FileBackedGrpcMtlsPolicy.require( + tlsProperties, + "World authored Version association", + "World authored Version association requires workload mTLS", + "World authored Version association requires workload mTLS"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityEvidence.java new file mode 100644 index 0000000000..284a68a9b8 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityEvidence.java @@ -0,0 +1,140 @@ +package net.firedevops.firemud.common.authoring; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; + +/** + * Public committed association evidence; private World numeric identities never cross this + * boundary. + */ +public final class WorldAuthoredVersionIdentityEvidence { + private WorldAuthoredVersionIdentityEvidence() {} + + public record Request( + int schemaVersion, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest, + UUID expectedCanonicalVersionId, + long gameDesignVersionId, + UUID readRequestId) { + public Request { + new AuthoredWorldVersionStateEvidence.Request( + schemaVersion, + targetNamespace, + readRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + sourceEvidenceDigest, + gameDesignVersionId); + requireNonNil(expectedCanonicalVersionId); + if (expectedCanonicalVersionId.equals(readRequestId)) { + throw new IllegalArgumentException( + "Version read correlation must differ from Version identity"); + } + } + + public AuthoredWorldVersionStateEvidence.Request versionReadRequest() { + return new AuthoredWorldVersionStateEvidence.Request( + schemaVersion, + targetNamespace, + readRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + sourceEvidenceDigest, + gameDesignVersionId); + } + } + + public record Result( + Request request, + UUID operationId, + WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt sourceIntakeReceipt, + AuthoredWorldVersionStateEvidence versionStateEvidence) { + public Result { + Objects.requireNonNull(request, "request"); + requireNonNil(operationId); + Objects.requireNonNull(sourceIntakeReceipt, "sourceIntakeReceipt"); + Objects.requireNonNull(versionStateEvidence, "versionStateEvidence"); + versionStateEvidence.requireValid(); + var original = versionStateEvidence.request(); + var source = versionStateEvidence.sourceEvidence(); + if (sourceIntakeReceipt.schemaVersion() != request.schemaVersion() + || !sourceIntakeReceipt.targetNamespace().equals(request.targetNamespace()) + || !sourceIntakeReceipt.canonicalTenantId().equals(request.canonicalTenantId()) + || !sourceIntakeReceipt.worldSlug().equals(request.worldSlug()) + || !sourceIntakeReceipt.sourceOperationId().equals(request.sourceOperationId()) + || !sourceIntakeReceipt.sourceEvidenceDigest().equals(request.sourceEvidenceDigest()) + || original.schemaVersion() != request.schemaVersion() + || !original.targetNamespace().equals(request.targetNamespace()) + || !original.canonicalTenantId().equals(request.canonicalTenantId()) + || !original.worldSlug().equals(request.worldSlug()) + || !original.sourceOperationId().equals(request.sourceOperationId()) + || !original.expectedSourceEvidenceDigest().equals(request.sourceEvidenceDigest()) + || original.versionId() != request.gameDesignVersionId() + || !versionStateEvidence.canonicalVersionId().equals(request.expectedCanonicalVersionId()) + || !"NEW_GAME_ROW".equals(source.provenanceKind())) { + throw new IllegalArgumentException( + "Association must retain the exact fresh source and Version"); + } + var state = versionStateEvidence.versionState(); + if (state != VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT + && state != VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED + && state != VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE) { + throw new IllegalArgumentException( + "Association requires eligible original Version evidence"); + } + requireReadCorrelation( + original.readRequestId(), + request, + operationId, + sourceIntakeReceipt, + source.registrationRequestId()); + requireReadCorrelation( + request.readRequestId(), + request, + null, + sourceIntakeReceipt, + source.registrationRequestId()); + } + } + + private static void requireReadCorrelation( + UUID readId, + Request request, + UUID operationId, + WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt intake, + UUID registrationId) { + if (readId.equals(request.expectedCanonicalVersionId()) + || readId.equals(operationId) + || readId.equals(intake.operationId()) + || readId.equals(intake.intakeRequestId()) + || readId.equals(intake.sourceOperationId()) + || readId.equals(registrationId)) { + throw new IllegalArgumentException( + "Version read correlation overlaps owner/source identities"); + } + } + + static UUID parseUuid(String text) { + UUID value = UUID.fromString(text); + requireNonNil(value); + if (!value.toString().equals(text)) { + throw new IllegalArgumentException("Canonical UUID required"); + } + return value; + } + + private static void requireNonNil(UUID value) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Non-nil UUID required"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityGrpcCodec.java new file mode 100644 index 0000000000..fd8a507fd2 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityGrpcCodec.java @@ -0,0 +1,128 @@ +package net.firedevops.firemud.common.authoring; + +import com.google.protobuf.Message; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.worldmanagement.v1.AssociateAuthoredWorldVersionRequest; +import net.firedevops.firemud.worldmanagement.v1.AssociateAuthoredWorldVersionResponse; + +/** Closed association transport reusing the immutable source and Version evidence codecs. */ +public final class WorldAuthoredVersionIdentityGrpcCodec { + public static final int MAX_REQUEST_WIRE_BYTES = 4096; + public static final int MAX_RESPONSE_WIRE_BYTES = 32768; + + private WorldAuthoredVersionIdentityGrpcCodec() {} + + public static AssociateAuthoredWorldVersionRequest toRequest( + WorldAuthoredVersionIdentityEvidence.Request request) { + Objects.requireNonNull(request, "request"); + var wire = + AssociateAuthoredWorldVersionRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .setSourceOperationId(request.sourceOperationId().toString()) + .setSourceEvidenceDigest(request.sourceEvidenceDigest()) + .setExpectedCanonicalVersionId(request.expectedCanonicalVersionId().toString()) + .setGameDesignVersionId(request.gameDesignVersionId()) + .setReadRequestId(request.readRequestId().toString()) + .build(); + requireClosed(wire, MAX_REQUEST_WIRE_BYTES); + return wire; + } + + public static WorldAuthoredVersionIdentityEvidence.Request fromRequest( + AssociateAuthoredWorldVersionRequest wire) { + requireClosed(wire, MAX_REQUEST_WIRE_BYTES); + return new WorldAuthoredVersionIdentityEvidence.Request( + wire.getSchemaVersion(), + wire.getTargetNamespace(), + WorldAuthoredVersionIdentityEvidence.parseUuid(wire.getCanonicalTenantId()), + wire.getWorldSlug(), + WorldAuthoredVersionIdentityEvidence.parseUuid(wire.getSourceOperationId()), + wire.getSourceEvidenceDigest(), + WorldAuthoredVersionIdentityEvidence.parseUuid(wire.getExpectedCanonicalVersionId()), + wire.getGameDesignVersionId(), + WorldAuthoredVersionIdentityEvidence.parseUuid(wire.getReadRequestId())); + } + + public static AssociateAuthoredWorldVersionResponse toResponse( + WorldAuthoredVersionIdentityEvidence.Result result) { + Objects.requireNonNull(result, "result"); + var intake = result.sourceIntakeReceipt(); + var binding = + new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( + intake.schemaVersion(), + intake.targetNamespace(), + intake.intakeRequestId(), + intake.canonicalTenantId(), + intake.worldSlug(), + intake.sourceOperationId(), + intake.sourceEvidenceDigest()); + var wire = + AssociateAuthoredWorldVersionResponse.newBuilder() + .setRequest(toRequest(result.request())) + .setOperationId(result.operationId().toString()) + .setSourceIntakeReceipt( + WorldAuthoredSourceIntakeGrpcCodec.toIntakeResponse(binding, intake)) + .setVersionStateEvidence( + AuthoredWorldVersionStateGrpcCodec.toResponse(result.versionStateEvidence())) + .build(); + requireClosed(wire, MAX_RESPONSE_WIRE_BYTES); + return wire; + } + + public static WorldAuthoredVersionIdentityEvidence.Result fromResponse( + WorldAuthoredVersionIdentityEvidence.Request request, + AssociateAuthoredWorldVersionResponse wire) { + Objects.requireNonNull(request, "request"); + requireClosed(wire, MAX_RESPONSE_WIRE_BYTES); + if (!wire.hasRequest() + || !request.equals(fromRequest(wire.getRequest())) + || !wire.hasSourceIntakeReceipt() + || !wire.hasVersionStateEvidence() + || !wire.getVersionStateEvidence().hasEvidence()) { + throw new IllegalArgumentException("Complete association and exact request echo required"); + } + var intakeWire = wire.getSourceIntakeReceipt(); + var intakeBinding = + new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( + intakeWire.getSchemaVersion(), + intakeWire.getTargetNamespace(), + WorldAuthoredVersionIdentityEvidence.parseUuid(intakeWire.getIntakeRequestId()), + WorldAuthoredVersionIdentityEvidence.parseUuid(intakeWire.getCanonicalTenantId()), + intakeWire.getWorldSlug(), + WorldAuthoredVersionIdentityEvidence.parseUuid(intakeWire.getSourceOperationId()), + intakeWire.getExpectedSourceEvidenceDigest()); + var intake = WorldAuthoredSourceIntakeGrpcCodec.fromIntakeResponse(intakeBinding, intakeWire); + // On immutable retry, decode the ORIGINAL stored read correlation, never rewrite it. + var retained = wire.getVersionStateEvidence().getEvidence(); + var originalRequest = + new net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence.Request( + retained.getSchemaVersion(), + retained.getTargetNamespace(), + WorldAuthoredVersionIdentityEvidence.parseUuid(retained.getReadRequestId()), + WorldAuthoredVersionIdentityEvidence.parseUuid(retained.getCanonicalTenantId()), + retained.getWorldSlug(), + WorldAuthoredVersionIdentityEvidence.parseUuid(retained.getSourceOperationId()), + retained.getExpectedSourceEvidenceDigest(), + retained.getVersionId()); + var version = + AuthoredWorldVersionStateGrpcCodec.fromResponse( + originalRequest, wire.getVersionStateEvidence()); + return new WorldAuthoredVersionIdentityEvidence.Result( + request, + WorldAuthoredVersionIdentityEvidence.parseUuid(wire.getOperationId()), + intake, + version); + } + + private static void requireClosed(Message wire, int maximum) { + Objects.requireNonNull(wire, "wire"); + if (!wire.getUnknownFields().asMap().isEmpty() || wire.getSerializedSize() > maximum) { + throw new IllegalArgumentException("Unsupported association fields or size"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateClient.java new file mode 100644 index 0000000000..b39d740f2c --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateClient.java @@ -0,0 +1,132 @@ +package net.firedevops.firemud.common.gamedesign; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.FileBackedGrpcMtlsPolicy; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.gamedesign.v1.AuthoredWorldVersionStateServiceGrpc; + +/** Explicit mTLS client for exact source-qualified current Game Design version-state reads. */ +public final class AuthoredWorldVersionStateClient + extends AbstractReloadingBlockingGrpcClient< + AuthoredWorldVersionStateServiceGrpc.AuthoredWorldVersionStateServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public AuthoredWorldVersionStateClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + AuthoredWorldVersionStateClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when an owning service explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Authored-world version-state client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException( + "Authored-world version-state client did not initialize a gRPC stub"); + } + initialized = true; + } + + /** Reads current state for the exact already-intaken source and source-owned version. */ + public AuthoredWorldVersionStateEvidence read(AuthoredWorldVersionStateEvidence.Request request) { + Objects.requireNonNull(request, "request"); + requireNamespace(request.targetNamespace()); + AuthoredWorldVersionStateServiceGrpc.AuthoredWorldVersionStateServiceBlockingStub currentStub = + requireStub(); + var response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .getAuthoredWorldVersionState(AuthoredWorldVersionStateGrpcCodec.toRequest(request)); + try { + return AuthoredWorldVersionStateGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Design returned invalid authored-world version-state evidence", exception); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameDesignService(); + } + + @Override + protected String defaultTarget() { + return "game-design-service:6565"; + } + + @Override + protected AuthoredWorldVersionStateServiceGrpc.AuthoredWorldVersionStateServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedGameDesignPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service"; + return AuthoredWorldVersionStateServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedGameDesignPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedGameDesignPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private AuthoredWorldVersionStateServiceGrpc.AuthoredWorldVersionStateServiceBlockingStub + requireStub() { + AuthoredWorldVersionStateServiceGrpc.AuthoredWorldVersionStateServiceBlockingStub currentStub = + stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Authored-world version-state client is not initialized and available"); + } + return currentStub; + } + + private void requireNamespace(String targetNamespace) { + if (!workloadNamespace.equals(targetNamespace)) { + throw new IllegalArgumentException( + "Version-state request must use the configured workload namespace"); + } + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + return FileBackedGrpcMtlsPolicy.require( + tlsProperties, + "Version-state reads", + "gRPC mTLS configuration is required", + "Version-state reads require workload mTLS"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateEvidence.java new file mode 100644 index 0000000000..ec95c8bd6a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateEvidence.java @@ -0,0 +1,218 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; + +/** Closed, source-qualified current Game Design version-state evidence for World Management. */ +public record AuthoredWorldVersionStateEvidence( + Request request, + AuthoredWorldSourceEvidence sourceEvidence, + UUID canonicalVersionId, + VersionLifecycleState versionState, + long versionStateEpoch, + String evidenceDigest) { + private 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 String EVIDENCE_DOMAIN = "game-design-authored-world-version-state/v1"; + + /** The exact selector and caller-owned read identity for one current version-state read. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String expectedSourceEvidenceDigest, + long versionId) { + public Request { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported authored-world version-state schema"); + } + Objects.requireNonNull(readRequestId, "readRequestId"); + Objects.requireNonNull(sourceOperationId, "sourceOperationId"); + if (NIL_UUID.equals(readRequestId) || NIL_UUID.equals(sourceOperationId)) { + throw new IllegalArgumentException("Read and source operation IDs must be non-nil UUIDs"); + } + if (readRequestId.equals(sourceOperationId)) { + throw new IllegalArgumentException("readRequestId must be separate from sourceOperationId"); + } + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + if (expectedSourceEvidenceDigest == null + || !SHA256.matcher(expectedSourceEvidenceDigest).matches()) { + throw new IllegalArgumentException( + "Expected source evidence digest must be canonical SHA-256 text"); + } + if (versionId <= 0) { + throw new IllegalArgumentException("versionId must be positive"); + } + } + } + + public AuthoredWorldVersionStateEvidence { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(sourceEvidence, "sourceEvidence"); + requireCanonicalVersionId(canonicalVersionId); + requireLifecycleState(versionState); + if (versionStateEpoch <= 0) { + throw new IllegalArgumentException("versionStateEpoch must be positive"); + } + if (!request.targetNamespace().equals(sourceEvidence.targetNamespace()) + || !request.canonicalTenantId().equals(sourceEvidence.canonicalTenantId()) + || !request.worldSlug().equals(sourceEvidence.worldSlug()) + || !request.sourceOperationId().equals(sourceEvidence.operationId()) + || !request.expectedSourceEvidenceDigest().equals(sourceEvidence.evidenceDigest())) { + throw new IllegalArgumentException( + "Complete authored-world source receipt does not match the exact version-state request"); + } + if (request.readRequestId().equals(sourceEvidence.registrationRequestId())) { + throw new IllegalArgumentException( + "readRequestId must be separate from the original source registration request"); + } + if (evidenceDigest == null || !SHA256.matcher(evidenceDigest).matches()) { + throw new IllegalArgumentException("evidenceDigest must be canonical SHA-256 text"); + } + if (!evidenceDigest.equals( + evidenceDigest(request, canonicalVersionId, versionState, versionStateEpoch))) { + throw new IllegalArgumentException( + "Version-state evidence digest does not match the exact current-state tuple"); + } + } + + public static AuthoredWorldVersionStateEvidence create( + Request request, + AuthoredWorldSourceEvidence sourceEvidence, + UUID canonicalVersionId, + VersionLifecycleState versionState, + long versionStateEpoch) { + Objects.requireNonNull(request, "request"); + requireCanonicalVersionId(canonicalVersionId); + requireLifecycleState(versionState); + return new AuthoredWorldVersionStateEvidence( + request, + sourceEvidence, + canonicalVersionId, + versionState, + versionStateEpoch, + evidenceDigest(request, canonicalVersionId, versionState, versionStateEpoch)); + } + + /** Recomputes the complete outer binding after construction or wire decoding. */ + public void requireValid() { + if (!evidenceDigest.equals( + evidenceDigest(request, canonicalVersionId, versionState, versionStateEpoch))) { + throw new IllegalArgumentException("Version-state evidence digest is invalid"); + } + } + + public static String evidenceDigest( + Request request, + UUID canonicalVersionId, + VersionLifecycleState versionState, + long versionStateEpoch) { + Objects.requireNonNull(request, "request"); + requireCanonicalVersionId(canonicalVersionId); + requireLifecycleState(versionState); + if (versionStateEpoch <= 0) { + throw new IllegalArgumentException("versionStateEpoch must be positive"); + } + return sha256(evidencePreimage(request, canonicalVersionId, versionState, versionStateEpoch)); + } + + /** Fixed-order UTF-8 length-framed preimage owned by the Game Design API contract. */ + public static byte[] evidencePreimage( + Request request, + UUID canonicalVersionId, + VersionLifecycleState versionState, + long versionStateEpoch) { + Objects.requireNonNull(request, "request"); + requireCanonicalVersionId(canonicalVersionId); + requireLifecycleState(versionState); + if (versionStateEpoch <= 0) { + throw new IllegalArgumentException("versionStateEpoch must be positive"); + } + return frame( + EVIDENCE_DOMAIN, + Integer.toString(request.schemaVersion()), + request.targetNamespace(), + request.readRequestId().toString(), + request.canonicalTenantId().toString(), + request.worldSlug(), + request.sourceOperationId().toString(), + request.expectedSourceEvidenceDigest(), + Long.toString(request.versionId()), + canonicalVersionId.toString(), + lifecycleStateName(versionState), + Long.toString(versionStateEpoch)); + } + + private static String lifecycleStateName(VersionLifecycleState value) { + return value.name().substring("VERSION_LIFECYCLE_STATE_".length()); + } + + private static byte[] frame(String... segments) { + ByteArrayOutputStream preimage = new ByteArrayOutputStream(); + for (String segment : segments) { + byte[] bytes = strictUtf8(segment); + preimage.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.UTF_8)); + preimage.write(':'); + preimage.writeBytes(bytes); + } + return preimage.toByteArray(); + } + + private static byte[] strictUtf8(String value) { + Objects.requireNonNull(value, "digest segment"); + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("Digest segments must contain valid Unicode", exception); + } + } + + private static String sha256(byte[] value) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static void requireLifecycleState(VersionLifecycleState value) { + if (value == null + || value == VersionLifecycleState.VERSION_LIFECYCLE_STATE_UNSPECIFIED + || value == VersionLifecycleState.UNRECOGNIZED) { + throw new IllegalArgumentException("A recognized version lifecycle state is required"); + } + } + + private static void requireCanonicalVersionId(UUID value) { + Objects.requireNonNull(value, "canonicalVersionId"); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException("canonicalVersionId must be a non-nil UUID"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateGrpcCodec.java new file mode 100644 index 0000000000..21ca27f45e --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateGrpcCodec.java @@ -0,0 +1,191 @@ +package net.firedevops.firemud.common.gamedesign; + +import com.google.protobuf.Message; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.AuthoredWorldSourceReceipt; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateRequest; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateResponse; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; + +/** Closed request mapping and exact response validation for authored-world version-state reads. */ +public final class AuthoredWorldVersionStateGrpcCodec { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private AuthoredWorldVersionStateGrpcCodec() {} + + /** Encodes exactly the schema-v1 source-qualified read tuple. */ + public static GetAuthoredWorldVersionStateRequest toRequest( + AuthoredWorldVersionStateEvidence.Request request) { + Objects.requireNonNull(request, "request"); + return GetAuthoredWorldVersionStateRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .setSourceOperationId(request.sourceOperationId().toString()) + .setExpectedSourceEvidenceDigest(request.expectedSourceEvidenceDigest()) + .setVersionId(request.versionId()) + .build(); + } + + /** Decodes a strict request after the authenticated handler has checked its peer. */ + public static AuthoredWorldVersionStateEvidence.Request fromRequest( + GetAuthoredWorldVersionStateRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "GetAuthoredWorldVersionStateRequest"); + try { + return new AuthoredWorldVersionStateEvidence.Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + parseCanonicalNonNilUuid(request.getReadRequestId(), "readRequestId"), + parseCanonicalNonNilUuid(request.getCanonicalTenantId(), "canonicalTenantId"), + request.getWorldSlug(), + parseCanonicalNonNilUuid(request.getSourceOperationId(), "sourceOperationId"), + request.getExpectedSourceEvidenceDigest(), + request.getVersionId()); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException( + "Authored-world version-state request is invalid", exception); + } + } + + /** Encodes the complete validated source receipt and exact current-state evidence. */ + public static GetAuthoredWorldVersionStateResponse toResponse( + net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + evidence.requireValid(); + AuthoredWorldSourceEvidence source = evidence.sourceEvidence(); + var request = evidence.request(); + AuthoredWorldSourceReceipt sourceReceipt = + AuthoredWorldSourceReceipt.newBuilder() + .setSchemaVersion(source.schemaVersion()) + .setTargetNamespace(source.targetNamespace()) + .setRegistrationRequestId(source.registrationRequestId().toString()) + .setOperationId(source.operationId().toString()) + .setRequestDigest(source.requestDigest()) + .setCanonicalTenantId(source.canonicalTenantId().toString()) + .setTenantSlug(source.tenantSlug()) + .setWorldSlug(source.worldSlug()) + .setWorldDisplayName(source.worldDisplayName()) + .setSourceGameRowId(source.sourceGameRowId()) + .setSourceGameTenantKey(source.sourceGameTenantKey()) + .setProvenanceKind(source.provenanceKind()) + .setEvidenceDigest(source.evidenceDigest()) + .build(); + return GetAuthoredWorldVersionStateResponse.newBuilder() + .setEvidence( + net.firedevops.firemud.gamedesign.v1.AuthoredWorldVersionStateEvidence.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .setSourceOperationId(request.sourceOperationId().toString()) + .setExpectedSourceEvidenceDigest(request.expectedSourceEvidenceDigest()) + .setVersionId(request.versionId()) + .setCanonicalVersionId(evidence.canonicalVersionId().toString()) + .setSourceEvidence(sourceReceipt) + .setVersionState(evidence.versionState()) + .setVersionStateEpoch(evidence.versionStateEpoch()) + .setEvidenceDigest(evidence.evidenceDigest())) + .build(); + } + + /** Validates every response carrier and binds every echo to the exact read request. */ + public static net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence + fromResponse( + AuthoredWorldVersionStateEvidence.Request request, + GetAuthoredWorldVersionStateResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "GetAuthoredWorldVersionStateResponse"); + if (!response.hasEvidence()) { + throw new IllegalArgumentException("Version-state response has no evidence"); + } + var wireEvidence = response.getEvidence(); + requireNoUnknownFields(wireEvidence, "AuthoredWorldVersionStateEvidence"); + if (!wireEvidence.hasSourceEvidence()) { + throw new IllegalArgumentException("Version-state evidence has no complete source receipt"); + } + AuthoredWorldSourceReceipt wireSource = wireEvidence.getSourceEvidence(); + requireNoUnknownFields(wireSource, "AuthoredWorldSourceReceipt"); + + net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence evidence; + try { + var echoedRequest = + new AuthoredWorldVersionStateEvidence.Request( + wireEvidence.getSchemaVersion(), + wireEvidence.getTargetNamespace(), + parseCanonicalNonNilUuid(wireEvidence.getReadRequestId(), "readRequestId"), + parseCanonicalNonNilUuid(wireEvidence.getCanonicalTenantId(), "canonicalTenantId"), + wireEvidence.getWorldSlug(), + parseCanonicalNonNilUuid(wireEvidence.getSourceOperationId(), "sourceOperationId"), + wireEvidence.getExpectedSourceEvidenceDigest(), + wireEvidence.getVersionId()); + if (!request.equals(echoedRequest)) { + throw new IllegalArgumentException( + "Version-state response does not echo the exact read request"); + } + AuthoredWorldSourceEvidence sourceEvidence = + new AuthoredWorldSourceEvidence( + wireSource.getSchemaVersion(), + wireSource.getTargetNamespace(), + parseCanonicalNonNilUuid( + wireSource.getRegistrationRequestId(), "registrationRequestId"), + parseCanonicalNonNilUuid(wireSource.getOperationId(), "source operationId"), + wireSource.getRequestDigest(), + parseCanonicalNonNilUuid( + wireSource.getCanonicalTenantId(), "source canonicalTenantId"), + wireSource.getTenantSlug(), + wireSource.getWorldSlug(), + wireSource.getWorldDisplayName(), + wireSource.getSourceGameRowId(), + wireSource.getSourceGameTenantKey(), + wireSource.getProvenanceKind(), + wireSource.getEvidenceDigest()); + VersionLifecycleState versionState = + VersionLifecycleState.forNumber(wireEvidence.getVersionStateValue()); + if (versionState == null) { + throw new IllegalArgumentException("Version-state enum value is unsupported"); + } + evidence = + new net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence( + echoedRequest, + sourceEvidence, + parseCanonicalNonNilUuid(wireEvidence.getCanonicalVersionId(), "canonicalVersionId"), + versionState, + wireEvidence.getVersionStateEpoch(), + wireEvidence.getEvidenceDigest()); + evidence.requireValid(); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException( + "Game Design authored-world version-state response is invalid", exception); + } + return evidence; + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + if (value == null) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required"); + } + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required", exception); + } + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required"); + } + return parsed; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationClient.java new file mode 100644 index 0000000000..0d20a38e20 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationClient.java @@ -0,0 +1,127 @@ +package net.firedevops.firemud.common.gamesession; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.Result; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.FileBackedGrpcMtlsPolicy; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.gamesession.v1.GameSessionControlPlaneServiceGrpc; + +/** Explicit file-backed mTLS client for the exact Game Session launch-association owner read. */ +public final class CanonicalGameInstanceLaunchAssociationClient + extends AbstractReloadingBlockingGrpcClient< + GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public CanonicalGameInstanceLaunchAssociationClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + CanonicalGameInstanceLaunchAssociationClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when an owning service explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Canonical launch association client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Canonical launch association client has no gRPC stub"); + } + initialized = true; + } + + /** Reads a single exact owner association; the response is not World lifecycle evidence. */ + public Result read(Request request) { + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Launch association request must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .getCanonicalGameInstanceLaunchAssociation( + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toRequest(request)); + try { + return CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Game Session returned invalid canonical launch association evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameSessionService(); + } + + @Override + protected String defaultTarget() { + return "game-session-service:6565"; + } + + @Override + protected GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub buildStub( + ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"; + return GameSessionControlPlaneServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Canonical launch association client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + return FileBackedGrpcMtlsPolicy.require( + tlsProperties, + "Canonical launch association reads", + "Canonical launch association reads require workload mTLS", + "Canonical launch association reads require workload mTLS"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodec.java new file mode 100644 index 0000000000..207371eb3d --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodec.java @@ -0,0 +1,194 @@ +package net.firedevops.firemud.common.gamesession; + +import com.google.protobuf.Descriptors; +import com.google.protobuf.Message; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.Result; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.gamedesign.v1.GetCompleteLaunchBindingResponse; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameInstanceLaunchAssociationRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameInstanceLaunchAssociationResponse; + +/** Closed request mapping and strict exact-readback validation for the Game Session owner API. */ +public final class CanonicalGameInstanceLaunchAssociationReadGrpcCodec { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private CanonicalGameInstanceLaunchAssociationReadGrpcCodec() {} + + public static GetCanonicalGameInstanceLaunchAssociationRequest toRequest(Request request) { + Objects.requireNonNull(request, "request"); + return GetCanonicalGameInstanceLaunchAssociationRequest.newBuilder() + .setReadRequestId(request.readRequestId().toString()) + .setTargetNamespace(request.targetNamespace()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .setGameInstanceUuid(request.gameInstanceUuid().toString()) + .setControlPlaneRequestId(request.controlPlaneRequestId()) + .setLaunchDescriptorId(request.launchDescriptorId()) + .setExpectedDescriptorRequestDigest(request.expectedDescriptorRequestDigest()) + .setExpectedDescriptorResultDigest(request.expectedDescriptorResultDigest()) + .setExpectedReleaseAttestationEvidenceDigest( + request.expectedReleaseAttestationEvidenceDigest()) + .build(); + } + + /** Validates all ten request echoes and the complete unchanged descriptor/release evidence. */ + public static Result fromResponse( + Request expectedRequest, GetCanonicalGameInstanceLaunchAssociationResponse response) { + Objects.requireNonNull(expectedRequest, "expectedRequest"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "GetCanonicalGameInstanceLaunchAssociation response"); + if (response.hasError()) { + requireNoUnknownFields( + response.getError(), "GetCanonicalGameInstanceLaunchAssociation error"); + throw new IllegalArgumentException( + "Game Session rejected the exact canonical launch association read"); + } + + requireEcho( + expectedRequest.readRequestId().toString(), response.getReadRequestId(), "readRequestId"); + requireEcho( + expectedRequest.targetNamespace(), response.getTargetNamespace(), "targetNamespace"); + requireEcho( + expectedRequest.canonicalTenantId().toString(), + response.getCanonicalTenantId(), + "canonicalTenantId"); + requireEcho(expectedRequest.worldSlug(), response.getWorldSlug(), "worldSlug"); + requireEcho( + expectedRequest.gameInstanceUuid().toString(), + response.getGameInstanceUuid(), + "gameInstanceUuid"); + requireEcho( + expectedRequest.controlPlaneRequestId(), + response.getControlPlaneRequestId(), + "controlPlaneRequestId"); + requireEcho( + expectedRequest.launchDescriptorId(), + response.getLaunchDescriptorId(), + "launchDescriptorId"); + requireEcho( + expectedRequest.expectedDescriptorRequestDigest(), + response.getDescriptorRequestDigest(), + "descriptorRequestDigest"); + requireEcho( + expectedRequest.expectedDescriptorResultDigest(), + response.getDescriptorResultDigest(), + "descriptorResultDigest"); + requireEcho( + expectedRequest.expectedReleaseAttestationEvidenceDigest(), + response.getReleaseAttestationEvidenceDigest(), + "releaseAttestationEvidenceDigest"); + + if (!response.hasLaunchDescriptor() || !response.hasReleaseAttestation()) { + throw new IllegalArgumentException( + "Game Session must return the complete descriptor and release attestation pair"); + } + var completeRequest = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId(expectedRequest.readRequestId().toString()) + .setCanonicalTenantId(expectedRequest.canonicalTenantId().toString()) + .setWorldSlug(expectedRequest.worldSlug()) + .setControlPlaneRequestId(expectedRequest.controlPlaneRequestId()) + .setExpectedRequestDigest(expectedRequest.expectedDescriptorRequestDigest()) + .setExpectedResultDigest(expectedRequest.expectedDescriptorResultDigest()) + .build(); + var completeResponse = + GetCompleteLaunchBindingResponse.newBuilder() + .setRequestId(response.getReadRequestId()) + .setLaunchDescriptor(response.getLaunchDescriptor()) + .setReleaseAttestation(response.getReleaseAttestation()) + .build(); + CompleteLaunchBindingEvidence binding = + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + completeRequest, completeResponse); + + UUID playableStateNamespaceId = + parseCanonicalNonNilUuid( + response.getPlayableStateNamespaceId(), "playableStateNamespaceId"); + RealmEntryPolicy.StateScope scope = + switch (response.getPlayableStateScope()) { + case PLAYABLE_STATE_SCOPE_SHARED -> RealmEntryPolicy.StateScope.SHARED; + case PLAYABLE_STATE_SCOPE_ISOLATED -> + throw new IllegalArgumentException( + "Canonical launch association requires SHARED scope"); + case PLAYABLE_STATE_SCOPE_UNSPECIFIED, UNRECOGNIZED -> + throw new IllegalArgumentException("Unknown playable state scope"); + }; + if (!response.getPublicProduction()) { + throw new IllegalArgumentException("Canonical launch association requires public production"); + } + + CurrentGameInstanceStatus status; + try { + status = CurrentGameInstanceStatus.valueOf(response.getCurrentGameInstanceStatus()); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException("Unknown current Game Session instance status", invalid); + } + if (response.getCurrentRowVersion() < 0) { + throw new IllegalArgumentException("Current Game Session row version is missing or invalid"); + } + UUID ownerAttemptId = parseCanonicalNonNilUuid(response.getOwnerAttemptId(), "ownerAttemptId"); + if (response.getOwnerFence() <= 0) { + throw new IllegalArgumentException("ownerFence must be positive"); + } + return new Result( + expectedRequest, + playableStateNamespaceId, + scope, + response.getPublicProduction(), + status, + response.getCurrentRowVersion(), + ownerAttemptId, + response.getOwnerFence(), + binding); + } + + private static void requireEcho(String expected, String actual, String field) { + if (actual.isEmpty() || !expected.equals(actual)) { + throw new IllegalArgumentException( + "Game Session launch association " + field + " echo changed"); + } + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + if (value.isEmpty()) { + throw new IllegalArgumentException("Missing " + label); + } + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException("Invalid " + label, invalid); + } + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + return parsed; + } + + 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/tenant/AuthoredWorldSourceClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceClient.java new file mode 100644 index 0000000000..2b70389f2e --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceClient.java @@ -0,0 +1,132 @@ +package net.firedevops.firemud.common.tenant; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.FileBackedGrpcMtlsPolicy; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.gamedesign.v1.AuthoredWorldSourceReadServiceGrpc; + +/** Explicit mTLS client for exact, non-mutating Game Design authored-world source reads. */ +public final class AuthoredWorldSourceClient + extends AbstractReloadingBlockingGrpcClient< + AuthoredWorldSourceReadServiceGrpc.AuthoredWorldSourceReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public AuthoredWorldSourceClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + AuthoredWorldSourceClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when an owning service explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Authored-world source client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException( + "Authored-world source client did not initialize a gRPC stub"); + } + initialized = true; + } + + /** Reads the exact persisted source receipt without registering a World association. */ + public AuthoredWorldSourceEvidence read(AuthoredWorldSourceGrpcCodec.ReadRequest request) { + Objects.requireNonNull(request, "request"); + requireNamespace(request.targetNamespace()); + AuthoredWorldSourceReadServiceGrpc.AuthoredWorldSourceReadServiceBlockingStub currentStub = + requireStub(); + var response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .resolveAuthoredWorldSource(AuthoredWorldSourceGrpcCodec.toReadRequest(request)); + try { + return AuthoredWorldSourceGrpcCodec.fromReadResponse(request, response); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Design returned invalid authored-world source evidence", exception); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameDesignService(); + } + + @Override + protected String defaultTarget() { + return "game-design-service:6565"; + } + + @Override + protected AuthoredWorldSourceReadServiceGrpc.AuthoredWorldSourceReadServiceBlockingStub buildStub( + ManagedChannel channel) { + String expectedGameDesignPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service"; + return AuthoredWorldSourceReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedGameDesignPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedGameDesignPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private AuthoredWorldSourceReadServiceGrpc.AuthoredWorldSourceReadServiceBlockingStub + requireStub() { + AuthoredWorldSourceReadServiceGrpc.AuthoredWorldSourceReadServiceBlockingStub currentStub = + stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Authored-world source client is not initialized and available"); + } + return currentStub; + } + + private void requireNamespace(String targetNamespace) { + if (!workloadNamespace.equals(targetNamespace)) { + throw new IllegalArgumentException( + "Authored-world source request must use the configured workload namespace"); + } + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + return FileBackedGrpcMtlsPolicy.require( + tlsProperties, + "Authored-world source reads", + "gRPC mTLS configuration is required", + "Authored-world source reads require workload mTLS"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceGrpcCodec.java new file mode 100644 index 0000000000..760f4f5351 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceGrpcCodec.java @@ -0,0 +1,164 @@ +package net.firedevops.firemud.common.tenant; + +import com.google.protobuf.Message; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; + +/** Closed request mapping and exact readback validation for authored-world source RPCs. */ +public final class AuthoredWorldSourceGrpcCodec { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + /** Exact, non-mutating source read selector and caller-owned read identity. */ + public record ReadRequest( + String targetNamespace, + UUID requestId, + UUID operationId, + UUID canonicalTenantId, + String worldSlug) { + public ReadRequest { + Objects.requireNonNull(requestId, "requestId"); + Objects.requireNonNull(operationId, "operationId"); + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(requestId, "requestId"); + requireNonNil(operationId, "operationId"); + } + } + + private AuthoredWorldSourceGrpcCodec() {} + + /** Encodes exactly the owner read identity and source selector. */ + public static ResolveAuthoredWorldSourceRequest toReadRequest(ReadRequest request) { + Objects.requireNonNull(request, "request"); + return ResolveAuthoredWorldSourceRequest.newBuilder() + .setRequestId(request.requestId().toString()) + .setOperationId(request.operationId().toString()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .build(); + } + + /** Decodes the exact owner-read selector using the receiver's locally configured namespace. */ + public static ReadRequest fromReadRequest( + String trustedNamespace, ResolveAuthoredWorldSourceRequest request) { + Objects.requireNonNull(request, "request"); + if (!request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException( + "Authored-world source request contains unsupported fields"); + } + try { + return new ReadRequest( + trustedNamespace, + parseCanonicalNonNilUuid(request.getRequestId(), "requestId"), + parseCanonicalNonNilUuid(request.getOperationId(), "operationId"), + parseCanonicalNonNilUuid(request.getCanonicalTenantId(), "canonicalTenantId"), + request.getWorldSlug()); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Authored-world source request is invalid", exception); + } + } + + /** Encodes the exact immutable source receipt and the independent read identity. */ + public static ResolveAuthoredWorldSourceResponse toReadResponse( + ReadRequest request, AuthoredWorldSourceEvidence evidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(evidence, "evidence"); + requireExactSelector(request, evidence); + return ResolveAuthoredWorldSourceResponse.newBuilder() + .setSchemaVersion(evidence.schemaVersion()) + .setTargetNamespace(evidence.targetNamespace()) + .setRequestId(request.requestId().toString()) + .setRegistrationRequestId(evidence.registrationRequestId().toString()) + .setOperationId(evidence.operationId().toString()) + .setRequestDigest(evidence.requestDigest()) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setTenantSlug(evidence.tenantSlug()) + .setWorldSlug(evidence.worldSlug()) + .setWorldDisplayName(evidence.worldDisplayName()) + .setSourceGameRowId(evidence.sourceGameRowId()) + .setSourceGameTenantKey(evidence.sourceGameTenantKey()) + .setProvenanceKind(evidence.provenanceKind()) + .setEvidenceDigest(evidence.evidenceDigest()) + .build(); + } + + /** Decodes the complete closed receipt and binds all echoed fields to the exact read request. */ + public static AuthoredWorldSourceEvidence fromReadResponse( + ReadRequest request, ResolveAuthoredWorldSourceResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response); + + AuthoredWorldSourceEvidence evidence; + try { + UUID echoedRequestId = parseCanonicalNonNilUuid(response.getRequestId(), "requestId"); + if (!request.requestId().equals(echoedRequestId)) { + throw new IllegalArgumentException("Authored-world source read request echo changed"); + } + evidence = + new AuthoredWorldSourceEvidence( + response.getSchemaVersion(), + response.getTargetNamespace(), + parseCanonicalNonNilUuid( + response.getRegistrationRequestId(), "registrationRequestId"), + parseCanonicalNonNilUuid(response.getOperationId(), "operationId"), + response.getRequestDigest(), + parseCanonicalNonNilUuid(response.getCanonicalTenantId(), "canonicalTenantId"), + response.getTenantSlug(), + response.getWorldSlug(), + response.getWorldDisplayName(), + response.getSourceGameRowId(), + response.getSourceGameTenantKey(), + response.getProvenanceKind(), + response.getEvidenceDigest()); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Authored-world source response is invalid", exception); + } + + requireExactSelector(request, evidence); + return evidence; + } + + private static void requireExactSelector( + ReadRequest request, AuthoredWorldSourceEvidence evidence) { + if (!request.targetNamespace().equals(evidence.targetNamespace()) + || !request.operationId().equals(evidence.operationId()) + || !request.canonicalTenantId().equals(evidence.canonicalTenantId()) + || !request.worldSlug().equals(evidence.worldSlug())) { + throw new IllegalArgumentException( + "Authored-world source response does not match the exact request"); + } + } + + private static void requireNoUnknownFields(Message message) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException( + "Authored-world source response contains unsupported fields"); + } + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + if (value == null) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); + } + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required", exception); + } + requireNonNil(parsed, label); + if (!parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); + } + return parsed; + } + + private static void requireNonNil(UUID value, String label) { + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClient.java new file mode 100644 index 0000000000..28d0f5aa4f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClient.java @@ -0,0 +1,166 @@ +package net.firedevops.firemud.common.tenant; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.FileBackedGrpcMtlsPolicy; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.worldmanagement.v1.WorldAuthoredSourceIntakeServiceGrpc; + +/** Explicit mTLS client for World's authenticated authored-source intake and exact readback. */ +public final class WorldAuthoredSourceIntakeClient + extends AbstractReloadingBlockingGrpcClient< + WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public WorldAuthoredSourceIntakeClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + WorldAuthoredSourceIntakeClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when an owning service explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("World authored-source intake client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException( + "World authored-source intake client did not initialize a gRPC stub"); + } + initialized = true; + } + + /** Sends one bounded intake request; transport failures are never retried blindly. */ + public WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt intake( + WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest request) { + Objects.requireNonNull(request, "request"); + requireNamespace(request.targetNamespace()); + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .intakeAuthoredWorldSource(WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(request)); + try { + return WorldAuthoredSourceIntakeGrpcCodec.fromIntakeResponse(request, response); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "World returned an invalid authored-source intake receipt", exception); + } + } + + /** Reads one exact committed World receipt with its separate caller-owned read identity. */ + public WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt read( + WorldAuthoredSourceIntakeGrpcCodec.ReadRequest request) { + Objects.requireNonNull(request, "request"); + requireNamespace(request.binding().targetNamespace()); + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readAuthoredWorldSourceIntake( + WorldAuthoredSourceIntakeGrpcCodec.toReadRequest(request)); + try { + return WorldAuthoredSourceIntakeGrpcCodec.fromReadResponse(request, response); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "World returned an invalid authored-source intake readback", exception); + } + } + + /** Reads a complete immutable source receipt by its retained intake identity. */ + public WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt readById( + WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest request) { + Objects.requireNonNull(request, "request"); + requireNamespace(request.targetNamespace()); + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readAuthoredWorldSourceIntakeById( + WorldAuthoredSourceIntakeGrpcCodec.toReadByIdRequest(request)); + try { + return WorldAuthoredSourceIntakeGrpcCodec.fromReadByIdResponse(request, response); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "World returned an invalid authored-source intake by-ID readback", exception); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedWorldPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + return WorldAuthoredSourceIntakeServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedWorldPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedWorldPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "World authored-source intake client is not initialized and available"); + } + return currentStub; + } + + private void requireNamespace(String targetNamespace) { + if (!workloadNamespace.equals(targetNamespace)) { + throw new IllegalArgumentException( + "World authored-source intake request must use the configured workload namespace"); + } + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + return FileBackedGrpcMtlsPolicy.require( + tlsProperties, + "World authored-source intake", + "gRPC mTLS configuration is required", + "World authored-source intake requires workload mTLS"); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityClientTest.java new file mode 100644 index 0000000000..b7ba3a3a01 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityClientTest.java @@ -0,0 +1,152 @@ +package net.firedevops.firemud.common.authoring; + +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.doThrow; +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 io.grpc.Status; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.concurrent.TimeUnit; +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.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.worldmanagement.v1.WorldAuthoredVersionIdentityServiceGrpc; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class WorldAuthoredVersionIdentityClientTest { + @Test + void refusesPlaintextMissingMaterialAndClasspathBeforeTransport(@TempDir Path directory) + throws Exception { + var factory = mock(GrpcChannelFactory.class); + var tls = tls(directory); + tls.setPlaintext(true); + assertThatThrownBy( + () -> + new WorldAuthoredVersionIdentityClient( + new ServiceEndpointsProperties(), tls, factory, "test")) + .isInstanceOf(IllegalArgumentException.class); + tls.setPlaintext(false); + tls.setCaCert("classpath:ca.crt"); + assertThatThrownBy( + () -> + new WorldAuthoredVersionIdentityClient( + new ServiceEndpointsProperties(), tls, factory, "test")) + .isInstanceOf(IllegalArgumentException.class); + tls.setCaCert(directory.resolve("missing.crt").toString()); + assertThatThrownBy( + () -> + new WorldAuthoredVersionIdentityClient( + new ServiceEndpointsProperties(), tls, factory, "test")) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(factory); + } + + @Test + void refusesWrongNamespaceUninitializedAndClosedUse(@TempDir Path directory) throws Exception { + var factory = mock(GrpcChannelFactory.class); + var client = + new WorldAuthoredVersionIdentityClient( + new ServiceEndpointsProperties(), tls(directory), factory, "test"); + try { + assertThatThrownBy( + () -> client.associate(WorldAuthoredVersionIdentityGrpcCodecTest.request("other"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> client.associate(WorldAuthoredVersionIdentityGrpcCodecTest.request("test"))) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(factory); + } finally { + client.close(); + } + assertThatThrownBy(client::init).isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> client.associate(WorldAuthoredVersionIdentityGrpcCodecTest.request("test"))) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void configuresWorldEndpointAndExactPeerAndDecodesOnlyClosedResults(@TempDir Path directory) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("world.internal:6565"); + var factory = mock(GrpcChannelFactory.class); + when(factory.buildChannel( + eq("world.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(mock(ManagedChannel.class)); + var client = new WorldAuthoredVersionIdentityClient(endpoints, tls(directory), factory, "test"); + try { + client.init(); + var field = stubField(); + var actual = + (WorldAuthoredVersionIdentityServiceGrpc.WorldAuthoredVersionIdentityServiceBlockingStub) + field.get(client); + assertThat(actual.getCallOptions().getMaxInboundMessageSize()) + .isEqualTo(WorldAuthoredVersionIdentityGrpcCodec.MAX_RESPONSE_WIRE_BYTES); + assertThat(client.workloadNamespace()).isEqualTo("test"); + assertThat(actual.getCallOptions().getCredentials()) + .isInstanceOf(GrpcServerPeerIdentityCallCredentials.class); + var peerField = + GrpcServerPeerIdentityCallCredentials.class.getDeclaredField("expectedPeerUri"); + peerField.setAccessible(true); + assertThat(peerField.get(actual.getCallOptions().getCredentials())) + .isEqualTo("spiffe://firemud/ns/test/sa/world-management-service"); + verify(factory) + .buildChannel( + eq("world.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true)); + var stub = + mock( + WorldAuthoredVersionIdentityServiceGrpc + .WorldAuthoredVersionIdentityServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + field.set(client, stub); + var request = WorldAuthoredVersionIdentityGrpcCodecTest.request("test"); + var response = + WorldAuthoredVersionIdentityGrpcCodec.toResponse( + WorldAuthoredVersionIdentityGrpcCodecTest.committed(request)); + when(stub.associateAuthoredWorldVersion(any())).thenReturn(response); + assertThat(client.associate(request).request()).isEqualTo(request); + verify(stub) + .associateAuthoredWorldVersion(WorldAuthoredVersionIdentityGrpcCodec.toRequest(request)); + when(stub.associateAuthoredWorldVersion(any())) + .thenReturn(response.toBuilder().clearVersionStateEvidence().build()); + assertThatThrownBy(() -> client.associate(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored Version association evidence"); + var unavailable = Status.UNAVAILABLE.withDescription("lost response").asRuntimeException(); + when(stub.associateAuthoredWorldVersion(any())).thenThrow(unavailable); + assertThatThrownBy(() -> client.associate(request)).isSameAs(unavailable); + var lostAck = + Status.DEADLINE_EXCEEDED.withDescription("owner may have committed").asRuntimeException(); + doThrow(lostAck).when(stub).associateAuthoredWorldVersion(any()); + assertThatThrownBy(() -> client.associate(request)).isSameAs(lostAck); + } finally { + client.close(); + } + } + + private static Field stubField() throws ReflectiveOperationException { + var field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + return field; + } + + private static CommonGrpcClientProperties tls(Path directory) throws Exception { + var tls = new CommonGrpcClientProperties(); + tls.setCertChain(Files.writeString(directory.resolve("client.crt"), "fixture").toString()); + tls.setPrivateKey(Files.writeString(directory.resolve("client.key"), "fixture").toString()); + tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "fixture").toString()); + return tls; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityGrpcCodecTest.java new file mode 100644 index 0000000000..193fdd81f0 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityGrpcCodecTest.java @@ -0,0 +1,212 @@ +package net.firedevops.firemud.common.authoring; + +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.AuthoredWorldVersionStateEvidence; +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.VersionLifecycleState; +import net.firedevops.firemud.worldmanagement.v1.AssociateAuthoredWorldVersionResponse; +import org.junit.jupiter.api.Test; + +/** Structural transport proof with synthetic valid values, not real owner storage proof. */ +class WorldAuthoredVersionIdentityGrpcCodecTest { + @Test + void roundTripsCompletePublicCommittedEvidenceAndPreservesHistoricalRetryRead() { + var request = request("test"); + var result = committed(request); + var wire = WorldAuthoredVersionIdentityGrpcCodec.toResponse(result); + assertThat(WorldAuthoredVersionIdentityGrpcCodec.fromResponse(request, wire)).isEqualTo(result); + assertThat(wire.getDescriptorForType().findFieldByName("local_version_key")).isNull(); + assertThat( + wire.getSourceIntakeReceipt() + .getDescriptorForType() + .findFieldByName("local_tenant_key")) + .isNull(); + var retry = + new WorldAuthoredVersionIdentityEvidence.Request( + 1, + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.sourceOperationId(), + request.sourceEvidenceDigest(), + request.expectedCanonicalVersionId(), + request.gameDesignVersionId(), + id(9)); + var retried = + new WorldAuthoredVersionIdentityEvidence.Result( + retry, + result.operationId(), + result.sourceIntakeReceipt(), + result.versionStateEvidence()); + var decoded = + WorldAuthoredVersionIdentityGrpcCodec.fromResponse( + retry, WorldAuthoredVersionIdentityGrpcCodec.toResponse(retried)); + assertThat(decoded.request().readRequestId()).isEqualTo(id(9)); + assertThat(decoded.versionStateEvidence()).isEqualTo(result.versionStateEvidence()); + assertThat(decoded.versionStateEvidence().request().readRequestId()) + .isEqualTo(request.readRequestId()); + } + + @Test + void rejectsUnknownMissingCorruptAndCrossBoundEvidence() { + var request = request("test"); + var wire = WorldAuthoredVersionIdentityGrpcCodec.toResponse(committed(request)); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + for (var invalid : + List.of( + AssociateAuthoredWorldVersionResponse.getDefaultInstance(), + wire.toBuilder().setUnknownFields(unknown).build(), + wire.toBuilder() + .setRequest(wire.getRequest().toBuilder().setWorldSlug("other")) + .build(), + wire.toBuilder() + .setRequest(wire.getRequest().toBuilder().setReadRequestId(id(9).toString())) + .build(), + wire.toBuilder() + .setRequest(wire.getRequest().toBuilder().setUnknownFields(unknown)) + .build(), + wire.toBuilder().clearSourceIntakeReceipt().build(), + wire.toBuilder().clearVersionStateEvidence().build(), + wire.toBuilder().setOperationId("00000000-0000-0000-0000-000000000000").build(), + wire.toBuilder() + .setSourceIntakeReceipt( + wire.getSourceIntakeReceipt().toBuilder().setUnknownFields(unknown)) + .build(), + wire.toBuilder() + .setVersionStateEvidence( + wire.getVersionStateEvidence().toBuilder().setUnknownFields(unknown)) + .build(), + wire.toBuilder() + .setVersionStateEvidence( + wire.getVersionStateEvidence().toBuilder() + .setEvidence( + wire.getVersionStateEvidence().getEvidence().toBuilder() + .setUnknownFields(unknown))) + .build(), + wire.toBuilder() + .setVersionStateEvidence( + wire.getVersionStateEvidence().toBuilder() + .setEvidence( + wire.getVersionStateEvidence().getEvidence().toBuilder() + .setEvidenceDigest("sha256:" + "0".repeat(64)))) + .build(), + wire.toBuilder() + .setVersionStateEvidence( + wire.getVersionStateEvidence().toBuilder() + .setEvidence( + wire.getVersionStateEvidence().getEvidence().toBuilder() + .setSourceEvidence( + wire + .getVersionStateEvidence() + .getEvidence() + .getSourceEvidence() + .toBuilder() + .setUnknownFields(unknown)))) + .build())) { + assertThatThrownBy(() -> WorldAuthoredVersionIdentityGrpcCodec.fromResponse(request, invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsUnsupportedOversizedAndNonCanonicalRequest() { + var wire = WorldAuthoredVersionIdentityGrpcCodec.toRequest(request("test")); + for (var invalid : + List.of( + wire.toBuilder().setSchemaVersion(2).build(), + wire.toBuilder().setGameDesignVersionId(0).build(), + wire.toBuilder().setCanonicalTenantId("1-1-1-1-1").build(), + wire.toBuilder() + .setExpectedCanonicalVersionId("00000000-0000-0000-0000-000000000000") + .build(), + wire.toBuilder().setReadRequestId(wire.getExpectedCanonicalVersionId()).build(), + wire.toBuilder().setWorldSlug("x".repeat(40000)).build())) { + assertThatThrownBy(() -> WorldAuthoredVersionIdentityGrpcCodec.fromRequest(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + static WorldAuthoredVersionIdentityEvidence.Request request(String namespace) { + var source = source(namespace); + return new WorldAuthoredVersionIdentityEvidence.Request( + 1, namespace, id(1), "north-star", id(3), source.evidenceDigest(), id(4), 42L, id(5)); + } + + static WorldAuthoredVersionIdentityEvidence.Result committed( + WorldAuthoredVersionIdentityEvidence.Request request) { + var intakeBinding = + new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( + 1, + request.targetNamespace(), + id(6), + request.canonicalTenantId(), + request.worldSlug(), + request.sourceOperationId(), + request.sourceEvidenceDigest()); + var intake = + new WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt( + 1, + request.targetNamespace(), + id(6), + id(7), + request.canonicalTenantId(), + request.worldSlug(), + request.sourceOperationId(), + request.sourceEvidenceDigest(), + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(intakeBinding), + "sha256:" + "a".repeat(64)); + var version = + AuthoredWorldVersionStateEvidence.create( + request.versionReadRequest(), + source(request.targetNamespace()), + request.expectedCanonicalVersionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 1L); + return new WorldAuthoredVersionIdentityEvidence.Result(request, id(8), intake, version); + } + + static AuthoredWorldSourceEvidence source(String namespace) { + var digest = + AuthoredWorldSourceDigest.requestDigest( + namespace, id(2), id(1), "north-star", "north-star", "North Star"); + return new AuthoredWorldSourceEvidence( + 1, + namespace, + id(2), + id(3), + digest, + id(1), + "north-star", + "north-star", + "North Star", + 42L, + "game-tenant-42", + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + namespace, + id(2), + id(3), + digest, + id(1), + "north-star", + "north-star", + "North Star", + 42L, + "game-tenant-42", + "NEW_GAME_ROW")); + } + + static UUID id(int suffix) { + return UUID.fromString("11111111-1111-4111-8111-" + String.format("%012d", suffix)); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateClientTest.java new file mode 100644 index 0000000000..fb62cfed6a --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateClientTest.java @@ -0,0 +1,138 @@ +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.nio.file.Files; +import java.nio.file.Path; +import java.util.UUID; +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; + +class AuthoredWorldVersionStateClientTest { + private static final String NAMESPACE = "test"; + private static final UUID READ_REQUEST_ID = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + + @Test + void rejectsPlaintextClasspathAndUnreadableTlsBeforeChannelCreation(@TempDir Path directory) + throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + + CommonGrpcClientProperties plaintext = fileBackedMtls(directory); + plaintext.setPlaintext(true); + assertThatThrownBy(() -> newClient(plaintext, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + assertThatThrownBy(() -> newClient(new CommonGrpcClientProperties(), channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + CommonGrpcClientProperties classpath = fileBackedMtls(directory); + classpath.setPrivateKey("classpath:certs/client.key"); + assertThatThrownBy(() -> newClient(classpath, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + CommonGrpcClientProperties missingFiles = new CommonGrpcClientProperties(); + missingFiles.setCertChain(directory.resolve("missing-client.crt").toString()); + missingFiles.setPrivateKey(directory.resolve("missing-client.key").toString()); + missingFiles.setCaCert(directory.resolve("missing-ca.crt").toString()); + assertThatThrownBy(() -> newClient(missingFiles, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("existing readable file"); + + verifyNoInteractions(channelFactory); + } + + @Test + void requiresExplicitInitializationAndRejectsOtherNamespaces(@TempDir Path directory) + throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + AuthoredWorldVersionStateClient client = newClient(fileBackedMtls(directory), channelFactory); + try { + assertThatThrownBy(() -> client.read(request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + assertThatThrownBy(() -> client.read(request("other"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + verifyNoInteractions(channelFactory); + } finally { + client.close(); + } + } + + @Test + void initializesOnlyConfiguredTargetFromFileBackedTls(@TempDir Path directory) throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("game-design.internal:6565"); + CommonGrpcClientProperties tls = fileBackedMtls(directory); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + ManagedChannel channel = mock(ManagedChannel.class); + when(channelFactory.buildChannel( + eq("game-design.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true))) + .thenReturn(channel); + AuthoredWorldVersionStateClient client = + new AuthoredWorldVersionStateClient(endpoints, tls, channelFactory, NAMESPACE); + + try { + client.init(); + verify(channelFactory) + .buildChannel( + eq("game-design.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true)); + } finally { + client.close(); + } + } + + private static AuthoredWorldVersionStateClient newClient( + CommonGrpcClientProperties tls, GrpcChannelFactory channelFactory) { + return new AuthoredWorldVersionStateClient( + new ServiceEndpointsProperties(), tls, channelFactory, NAMESPACE); + } + + private static CommonGrpcClientProperties fileBackedMtls(Path directory) throws Exception { + 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; + } + + private static AuthoredWorldVersionStateEvidence.Request request() { + return request(NAMESPACE); + } + + private static AuthoredWorldVersionStateEvidence.Request request(String namespace) { + return new AuthoredWorldVersionStateEvidence.Request( + 1, + namespace, + READ_REQUEST_ID, + TENANT_ID, + "cafe-coast", + SOURCE_OPERATION_ID, + "sha256:" + "a".repeat(64), + 19L); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodecTest.java new file mode 100644 index 0000000000..21c6f4499d --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodecTest.java @@ -0,0 +1,115 @@ +package net.firedevops.firemud.common.gamesession; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.Request; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.testing.AuthoringFixtures; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameInstanceLaunchAssociationResponse; +import org.junit.jupiter.api.Test; + +class CanonicalGameInstanceLaunchAssociationReadGrpcCodecTest { + private static final UUID READ_REQUEST_ID = + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID GAME_INSTANCE_ID = + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID OWNER_ATTEMPT_ID = + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + + @Test + void roundTripsOwnerAttemptAndFenceAndRejectsMissingMalformedOrNonpositiveProof() + throws Exception { + var launchBinding = AuthoringFixtures.lifecycleEvidence("ACTIVE", 3L).launchBinding(); + var descriptor = launchBinding.descriptor(); + var request = + new Request( + READ_REQUEST_ID, + descriptor.targetNamespace(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + GAME_INSTANCE_ID, + descriptor.controlPlaneRequestId(), + descriptor.launchDescriptorId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + launchBinding.releaseAttestation().evidenceDigest()); + var response = response(request, launchBinding); + + var result = + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse(request, response); + + assertThat(result.ownerAttemptId()).isEqualTo(OWNER_ATTEMPT_ID); + assertThat(result.ownerFence()).isEqualTo(4L); + assertThat(result.playableStateScope()).isEqualTo(RealmEntryPolicy.StateScope.SHARED); + assertThat(result.launchBindingEvidence()).isEqualTo(launchBinding); + for (var invalid : + new GetCanonicalGameInstanceLaunchAssociationResponse[] { + response.toBuilder().clearOwnerAttemptId().build(), + response.toBuilder().setOwnerAttemptId("not-a-uuid").build(), + response.toBuilder().setOwnerAttemptId("00000000-0000-0000-0000-000000000000").build(), + response.toBuilder().setOwnerFence(0).build(), + response.toBuilder().setOwnerFence(-1).build() + }) { + assertThatThrownBy( + () -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse( + request, invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + + for (var invalidScope : + new GetCanonicalGameInstanceLaunchAssociationResponse[] { + response.toBuilder().clearPlayableStateScope().build(), + response.toBuilder() + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED) + .build(), + response.toBuilder() + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) + .build(), + response.toBuilder().setPlayableStateScopeValue(999).build() + }) { + var wireResponse = + GetCanonicalGameInstanceLaunchAssociationResponse.parseFrom(invalidScope.toByteArray()); + assertThatThrownBy( + () -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse( + request, wireResponse)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + private static GetCanonicalGameInstanceLaunchAssociationResponse response( + Request request, + net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence launchBinding) { + return GetCanonicalGameInstanceLaunchAssociationResponse.newBuilder() + .setReadRequestId(request.readRequestId().toString()) + .setTargetNamespace(request.targetNamespace()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .setGameInstanceUuid(request.gameInstanceUuid().toString()) + .setControlPlaneRequestId(request.controlPlaneRequestId()) + .setLaunchDescriptorId(request.launchDescriptorId()) + .setDescriptorRequestDigest(request.expectedDescriptorRequestDigest()) + .setDescriptorResultDigest(request.expectedDescriptorResultDigest()) + .setReleaseAttestationEvidenceDigest(request.expectedReleaseAttestationEvidenceDigest()) + .setPlayableStateNamespaceId("dddddddd-dddd-4ddd-8ddd-dddddddddddd") + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .setPublicProduction(true) + .setCurrentGameInstanceStatus(CurrentGameInstanceStatus.STARTING.name()) + .setCurrentRowVersion(1L) + .setLaunchDescriptor( + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage( + launchBinding.descriptor())) + .setReleaseAttestation( + AuthoredWorldLaunchDescriptorGrpcCodec.toReleaseAttestation( + launchBinding.releaseAttestation())) + .setOwnerAttemptId(OWNER_ATTEMPT_ID.toString()) + .setOwnerFence(4L) + .build(); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceClientTest.java new file mode 100644 index 0000000000..426acefd79 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceClientTest.java @@ -0,0 +1,248 @@ +package net.firedevops.firemud.common.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.anyLong; +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.UnknownFieldSet; +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +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.gamedesign.v1.AuthoredWorldSourceReadServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class AuthoredWorldSourceClientTest { + private static final String NAMESPACE = "test"; + private static final UUID READ_REQUEST_ID = + UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID OPERATION_ID = UUID.fromString("22345678-1234-4234-8234-123456789abc"); + private static final UUID TENANT_ID = UUID.fromString("32345678-1234-4234-8234-123456789abc"); + private static final UUID REGISTRATION_REQUEST_ID = + UUID.fromString("42345678-1234-4234-8234-123456789abc"); + private static final AuthoredWorldSourceGrpcCodec.ReadRequest READ_REQUEST = + new AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, READ_REQUEST_ID, OPERATION_ID, TENANT_ID, "silver-march"); + + @Test + void requiresFileBackedMtlsBeforeCreatingAChannel(@TempDir Path directory) throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + + CommonGrpcClientProperties plaintext = fileBackedMtls(directory); + plaintext.setPlaintext(true); + assertThatThrownBy(() -> newClient(plaintext, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + CommonGrpcClientProperties classpath = fileBackedMtls(directory); + classpath.setPrivateKey("classpath:client.key"); + assertThatThrownBy(() -> newClient(classpath, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + CommonGrpcClientProperties missing = new CommonGrpcClientProperties(); + missing.setCertChain(directory.resolve("missing.crt").toString()); + missing.setPrivateKey(directory.resolve("missing.key").toString()); + missing.setCaCert(directory.resolve("missing-ca.crt").toString()); + assertThatThrownBy(() -> newClient(missing, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("existing readable file"); + + verifyNoInteractions(channelFactory); + } + + @Test + void requiresExplicitInitializationAndConfiguredNamespace(@TempDir Path directory) + throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + AuthoredWorldSourceClient client = newClient(fileBackedMtls(directory), channelFactory); + try { + assertThatThrownBy(() -> client.read(READ_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + + AuthoredWorldSourceGrpcCodec.ReadRequest otherNamespace = + new AuthoredWorldSourceGrpcCodec.ReadRequest( + "other", READ_REQUEST_ID, OPERATION_ID, TENANT_ID, "silver-march"); + assertThatThrownBy(() -> client.read(otherNamespace)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + verifyNoInteractions(channelFactory); + } finally { + client.close(); + } + } + + @Test + void initializesTheConfiguredGameDesignTargetOnceAndCannotRestartAfterClose( + @TempDir Path directory) throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("design.internal:7676"); + CommonGrpcClientProperties tls = fileBackedMtls(directory); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + ManagedChannel channel = mock(ManagedChannel.class); + when(channelFactory.buildChannel( + eq("design.internal:7676"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(channel); + AuthoredWorldSourceClient client = + new AuthoredWorldSourceClient(endpoints, tls, channelFactory, NAMESPACE); + + client.init(); + client.init(); + client.close(); + + verify(channelFactory) + .buildChannel( + eq("design.internal:7676"), eq(6565), any(CommonGrpcClientProperties.class), eq(true)); + assertThatThrownBy(client::init) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("is closed"); + } + + @Test + void readsAndReturnsOnlyTheExactValidatedSourceReceipt(@TempDir Path directory) throws Exception { + AuthoredWorldSourceReadServiceGrpc.AuthoredWorldSourceReadServiceBlockingStub stub = + mock(AuthoredWorldSourceReadServiceGrpc.AuthoredWorldSourceReadServiceBlockingStub.class); + AuthoredWorldSourceClient client = clientWithStub(directory, stub); + ResolveAuthoredWorldSourceResponse response = + AuthoredWorldSourceGrpcCodec.toReadResponse(READ_REQUEST, source()); + when(stub.withDeadlineAfter(anyLong(), eq(TimeUnit.SECONDS))).thenReturn(stub); + when(stub.resolveAuthoredWorldSource(any())).thenReturn(response); + + AuthoredWorldSourceEvidence result = client.read(READ_REQUEST); + + assertThat(result).isEqualTo(source()); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub) + .resolveAuthoredWorldSource(AuthoredWorldSourceGrpcCodec.toReadRequest(READ_REQUEST)); + } + + @Test + void rejectsSubstitutedCorruptOrOpenResponsesAndPropagatesTransportFailure( + @TempDir Path directory) throws Exception { + AuthoredWorldSourceReadServiceGrpc.AuthoredWorldSourceReadServiceBlockingStub stub = + mock(AuthoredWorldSourceReadServiceGrpc.AuthoredWorldSourceReadServiceBlockingStub.class); + AuthoredWorldSourceClient client = clientWithStub(directory, stub); + when(stub.withDeadlineAfter(anyLong(), eq(TimeUnit.SECONDS))).thenReturn(stub); + + when(stub.resolveAuthoredWorldSource(any())) + .thenReturn( + AuthoredWorldSourceGrpcCodec.toReadResponse(READ_REQUEST, source()).toBuilder() + .setWorldSlug("other-world") + .build()); + assertThatThrownBy(() -> client.read(READ_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-world source evidence"); + + when(stub.resolveAuthoredWorldSource(any())) + .thenReturn( + AuthoredWorldSourceGrpcCodec.toReadResponse(READ_REQUEST, source()).toBuilder() + .setUnknownFields(unknownField()) + .build()); + assertThatThrownBy(() -> client.read(READ_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-world source evidence"); + + when(stub.resolveAuthoredWorldSource(any())) + .thenThrow(new StatusRuntimeException(Status.UNAVAILABLE)); + StatusRuntimeException exception = + Assertions.assertThrows(StatusRuntimeException.class, () -> client.read(READ_REQUEST)); + assertThat(exception.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE); + } + + private static AuthoredWorldSourceClient clientWithStub( + Path directory, + AuthoredWorldSourceReadServiceGrpc.AuthoredWorldSourceReadServiceBlockingStub stub) + throws Exception { + AuthoredWorldSourceClient client = + newClient(fileBackedMtls(directory), mock(GrpcChannelFactory.class)); + setField(AbstractReloadingBlockingGrpcClient.class, client, "stub", stub); + setField(AuthoredWorldSourceClient.class, client, "initialized", true); + return client; + } + + private static AuthoredWorldSourceClient newClient( + CommonGrpcClientProperties tls, GrpcChannelFactory channelFactory) { + return new AuthoredWorldSourceClient( + new ServiceEndpointsProperties(), tls, channelFactory, NAMESPACE); + } + + private static CommonGrpcClientProperties fileBackedMtls(Path directory) throws Exception { + Path certificate = Files.writeString(directory.resolve("client.crt"), "certificate"); + Path key = Files.writeString(directory.resolve("client.key"), "private-key"); + Path ca = Files.writeString(directory.resolve("ca.crt"), "authority"); + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(key.toString()); + properties.setCaCert(ca.toString()); + return properties; + } + + private static AuthoredWorldSourceEvidence source() { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + REGISTRATION_REQUEST_ID, + TENANT_ID, + "new-kingdom", + "silver-march", + "Silver March"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION_REQUEST_ID, + OPERATION_ID, + requestDigest, + TENANT_ID, + "new-kingdom", + "silver-march", + "Silver March", + 17L, + "legacy-tenant-7", + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + REGISTRATION_REQUEST_ID, + OPERATION_ID, + requestDigest, + TENANT_ID, + "new-kingdom", + "silver-march", + "Silver March", + 17L, + "legacy-tenant-7", + "NEW_GAME_ROW", + evidenceDigest); + } + + private static UnknownFieldSet unknownField() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } + + private static void setField(Class declaringClass, Object target, String name, Object value) + throws Exception { + Field field = declaringClass.getDeclaredField(name); + field.setAccessible(true); + field.set(target, value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceGrpcCodecTest.java new file mode 100644 index 0000000000..8ccace27a6 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceGrpcCodecTest.java @@ -0,0 +1,149 @@ +package net.firedevops.firemud.common.tenant; + +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.gamedesign.v1.ResolveAuthoredWorldSourceRequest; +import org.junit.jupiter.api.Test; + +class AuthoredWorldSourceGrpcCodecTest { + private static final String NAMESPACE = "test"; + private static final UUID READ_REQUEST_ID = + UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID OPERATION_ID = UUID.fromString("22345678-1234-4234-8234-123456789abc"); + private static final UUID TENANT_ID = UUID.fromString("32345678-1234-4234-8234-123456789abc"); + private static final UUID REGISTRATION_REQUEST_ID = + UUID.fromString("42345678-1234-4234-8234-123456789abc"); + private static final String TENANT_SLUG = "new-kingdom"; + private static final String WORLD_SLUG = "silver-march"; + private static final String WORLD_DISPLAY_NAME = "Silver March"; + private static final String SOURCE_KEY = "legacy-tenant-7"; + private static final AuthoredWorldSourceGrpcCodec.ReadRequest READ_REQUEST = + readRequest(NAMESPACE, TENANT_ID, WORLD_SLUG); + + @Test + void requestRoundTripCarriesOnlyReadCorrelationAndExactSourceSelector() { + ResolveAuthoredWorldSourceRequest encoded = + AuthoredWorldSourceGrpcCodec.toReadRequest(READ_REQUEST); + + assertThat(AuthoredWorldSourceGrpcCodec.fromReadRequest(NAMESPACE, encoded)) + .isEqualTo(READ_REQUEST); + assertThat(encoded.getDescriptorForType().getFields()) + .extracting(field -> field.getName()) + .containsExactly("request_id", "operation_id", "canonical_tenant_id", "world_slug"); + assertThat(encoded.getRequestId()).isEqualTo(READ_REQUEST_ID.toString()); + assertThat(encoded.getOperationId()).isEqualTo(OPERATION_ID.toString()); + assertThat(encoded.getCanonicalTenantId()).isEqualTo(TENANT_ID.toString()); + assertThat(encoded.getWorldSlug()).isEqualTo(WORLD_SLUG); + } + + @Test + void requestDecoderRejectsMalformedSelectorsAndUnknownFields() { + ResolveAuthoredWorldSourceRequest valid = + AuthoredWorldSourceGrpcCodec.toReadRequest(READ_REQUEST); + for (ResolveAuthoredWorldSourceRequest malformed : + new ResolveAuthoredWorldSourceRequest[] { + valid.toBuilder().setRequestId("not-a-uuid").build(), + valid.toBuilder().setOperationId("00000000-0000-0000-0000-000000000000").build(), + valid.toBuilder().setCanonicalTenantId("not-a-uuid").build(), + valid.toBuilder().setWorldSlug("Silver March").build(), + valid.toBuilder().setUnknownFields(unknownField()).build() + }) { + assertThatThrownBy(() -> AuthoredWorldSourceGrpcCodec.fromReadRequest(NAMESPACE, malformed)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy(() -> AuthoredWorldSourceGrpcCodec.fromReadRequest("Bad_Namespace", valid)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void responseRoundTripVerifiesCompleteImmutableReceiptAndSelector() { + AuthoredWorldSourceEvidence source = source(READ_REQUEST); + var response = AuthoredWorldSourceGrpcCodec.toReadResponse(READ_REQUEST, source); + + assertThat(AuthoredWorldSourceGrpcCodec.fromReadResponse(READ_REQUEST, response)) + .isEqualTo(source); + assertThat(response.getRequestId()).isEqualTo(READ_REQUEST_ID.toString()); + assertThat(response.getRegistrationRequestId()).isEqualTo(REGISTRATION_REQUEST_ID.toString()); + assertThat(response.getOperationId()).isEqualTo(OPERATION_ID.toString()); + assertThat(response.getEvidenceDigest()).isEqualTo(source.evidenceDigest()); + } + + @Test + void responseDecoderRejectsChangedEchoReceiptDigestsAndUnknownFields() { + var response = AuthoredWorldSourceGrpcCodec.toReadResponse(READ_REQUEST, source(READ_REQUEST)); + for (var malformed : + new net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse[] { + response.toBuilder().setRequestId("52345678-1234-4234-8234-123456789abc").build(), + response.toBuilder().setOperationId("52345678-1234-4234-8234-123456789abc").build(), + response.toBuilder().setCanonicalTenantId("52345678-1234-4234-8234-123456789abc").build(), + response.toBuilder().setRequestDigest("0".repeat(64)).build(), + response.toBuilder().setEvidenceDigest("0".repeat(64)).build(), + response.toBuilder().setSourceGameRowId(0L).build(), + response.toBuilder().setProvenanceKind("GUESSED").build(), + response.toBuilder().setUnknownFields(unknownField()).build() + }) { + assertThatThrownBy( + () -> AuthoredWorldSourceGrpcCodec.fromReadResponse(READ_REQUEST, malformed)) + .isInstanceOf(IllegalArgumentException.class); + } + + AuthoredWorldSourceEvidence substituted = source(readRequest(NAMESPACE, TENANT_ID, "other")); + assertThatThrownBy(() -> AuthoredWorldSourceGrpcCodec.toReadResponse(READ_REQUEST, substituted)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact request"); + } + + private static AuthoredWorldSourceGrpcCodec.ReadRequest readRequest( + String namespace, UUID canonicalTenantId, String worldSlug) { + return new AuthoredWorldSourceGrpcCodec.ReadRequest( + namespace, READ_REQUEST_ID, OPERATION_ID, canonicalTenantId, worldSlug); + } + + private static AuthoredWorldSourceEvidence source( + AuthoredWorldSourceGrpcCodec.ReadRequest request) { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + REGISTRATION_REQUEST_ID, + request.canonicalTenantId(), + TENANT_SLUG, + request.worldSlug(), + WORLD_DISPLAY_NAME); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION_REQUEST_ID, + OPERATION_ID, + requestDigest, + request.canonicalTenantId(), + TENANT_SLUG, + request.worldSlug(), + WORLD_DISPLAY_NAME, + 17L, + SOURCE_KEY, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + REGISTRATION_REQUEST_ID, + OPERATION_ID, + requestDigest, + request.canonicalTenantId(), + TENANT_SLUG, + request.worldSlug(), + WORLD_DISPLAY_NAME, + 17L, + SOURCE_KEY, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static UnknownFieldSet unknownField() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClientTest.java new file mode 100644 index 0000000000..c3504af025 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClientTest.java @@ -0,0 +1,505 @@ +package net.firedevops.firemud.common.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.anyLong; +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.UnknownFieldSet; +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +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.worldmanagement.v1.IntakeAuthoredWorldSourceRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeByIdRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeByIdResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldAuthoredSourceIntakeServiceGrpc; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class WorldAuthoredSourceIntakeClientTest { + private static final String NAMESPACE = "test"; + private static final String SOURCE_DIGEST = "sha256:" + "a".repeat(64); + private static final String RECEIPT_DIGEST = "sha256:" + "b".repeat(64); + private static final WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest INTAKE_REQUEST = + new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( + 1, + NAMESPACE, + UUID.fromString("12345678-1234-4234-8234-123456789abc"), + UUID.fromString("22345678-1234-4234-8234-123456789abc"), + "world-one", + UUID.fromString("32345678-1234-4234-8234-123456789abc"), + SOURCE_DIGEST); + private static final WorldAuthoredSourceIntakeGrpcCodec.ReadRequest READ_REQUEST = + new WorldAuthoredSourceIntakeGrpcCodec.ReadRequest( + INTAKE_REQUEST, UUID.fromString("42345678-1234-4234-8234-123456789abc")); + private static final WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest BY_ID_READ_REQUEST = + new WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest( + 1, + NAMESPACE, + UUID.fromString("52345678-1234-4234-8234-123456789abc"), + INTAKE_REQUEST.intakeRequestId(), + INTAKE_REQUEST.canonicalTenantId()); + + @Test + void rejectsPlaintextClasspathAndUnreadableTlsMaterialBeforeChannelCreation(@TempDir Path dir) + throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + + CommonGrpcClientProperties plaintext = fileBackedMtls(dir); + plaintext.setPlaintext(true); + assertThatThrownBy(() -> newClient(plaintext, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + assertThatThrownBy(() -> newClient(new CommonGrpcClientProperties(), channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + CommonGrpcClientProperties classpath = fileBackedMtls(dir); + classpath.setCaCert("classpath:certs/ca.crt"); + assertThatThrownBy(() -> newClient(classpath, channelFactory)) + .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, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("existing readable file"); + + verifyNoInteractions(channelFactory); + } + + @Test + void requiresExplicitLifecycleAndExactConfiguredNamespace(@TempDir Path dir) throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + WorldAuthoredSourceIntakeClient client = newClient(fileBackedMtls(dir), channelFactory); + try { + assertThatThrownBy(() -> client.intake(INTAKE_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + assertThatThrownBy( + () -> + client.intake( + new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( + 1, + "other", + INTAKE_REQUEST.intakeRequestId(), + INTAKE_REQUEST.canonicalTenantId(), + INTAKE_REQUEST.worldSlug(), + INTAKE_REQUEST.sourceOperationId(), + INTAKE_REQUEST.expectedSourceEvidenceDigest()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + assertThatThrownBy(() -> client.read(READ_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + assertThatThrownBy(() -> client.readById(BY_ID_READ_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + assertThatThrownBy( + () -> + client.readById( + new WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest( + 1, + "other", + BY_ID_READ_REQUEST.readRequestId(), + BY_ID_READ_REQUEST.intakeRequestId(), + BY_ID_READ_REQUEST.canonicalTenantId()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + verifyNoInteractions(channelFactory); + } finally { + client.close(); + } + } + + @Test + void initializesConfiguredWorldTargetOnceAndCannotRestartAfterClose(@TempDir Path dir) + throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("world.internal:7676"); + CommonGrpcClientProperties tls = fileBackedMtls(dir); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + ManagedChannel channel = mock(ManagedChannel.class); + when(channelFactory.buildChannel( + eq("world.internal:7676"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(channel); + WorldAuthoredSourceIntakeClient client = + new WorldAuthoredSourceIntakeClient(endpoints, tls, channelFactory, NAMESPACE); + + client.init(); + client.init(); + client.close(); + + verify(channelFactory) + .buildChannel( + eq("world.internal:7676"), eq(6565), any(CommonGrpcClientProperties.class), eq(true)); + assertThatThrownBy(() -> client.intake(INTAKE_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + assertThatThrownBy(client::init) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("is closed"); + } + + @Test + void sendsOneIntakeAndReturnsOnlyAValidatedExactWorldReceipt(@TempDir Path dir) throws Exception { + WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub stub = + mock( + WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub + .class); + WorldAuthoredSourceIntakeClient client = clientWithStub(dir, stub); + IntakeAuthoredWorldSourceResponse response = intakeResponse(INTAKE_REQUEST); + when(stub.intakeAuthoredWorldSource(any(IntakeAuthoredWorldSourceRequest.class))) + .thenReturn(response); + when(stub.withDeadlineAfter(anyLong(), eq(TimeUnit.SECONDS))).thenReturn(stub); + + WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt receipt = client.intake(INTAKE_REQUEST); + + assertThat(receipt.intakeRequestId()).isEqualTo(INTAKE_REQUEST.intakeRequestId()); + assertThat(receipt.operationId()) + .isEqualTo(UUID.fromString("52345678-1234-4234-8234-123456789abc")); + assertThat(receipt.receiptDigest()).isEqualTo(RECEIPT_DIGEST); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub) + .intakeAuthoredWorldSource( + WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(INTAKE_REQUEST)); + assertThat( + WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(INTAKE_REQUEST) + .getDescriptorForType() + .getFields()) + .extracting(field -> field.getName()) + .doesNotContain("world_tenant_key", "local_tenant_key", "tenant_id"); + } + + @Test + void rejectsChangedEchoesAndUnknownResponseFields(@TempDir Path dir) throws Exception { + WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub stub = + mock( + WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub + .class); + WorldAuthoredSourceIntakeClient client = clientWithStub(dir, stub); + when(stub.withDeadlineAfter(anyLong(), eq(TimeUnit.SECONDS))).thenReturn(stub); + + when(stub.intakeAuthoredWorldSource(any(IntakeAuthoredWorldSourceRequest.class))) + .thenReturn(intakeResponse(INTAKE_REQUEST).toBuilder().setWorldSlug("other-world").build()); + assertThatThrownBy(() -> client.intake(INTAKE_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-source intake receipt"); + + when(stub.intakeAuthoredWorldSource(any(IntakeAuthoredWorldSourceRequest.class))) + .thenReturn( + intakeResponse(INTAKE_REQUEST).toBuilder().setUnknownFields(unknownField()).build()); + assertThatThrownBy(() -> client.intake(INTAKE_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-source intake receipt"); + + ReadAuthoredWorldSourceIntakeResponse alteredRead = + readResponse(READ_REQUEST).toBuilder() + .setRequestId(INTAKE_REQUEST.intakeRequestId().toString()) + .build(); + when(stub.readAuthoredWorldSourceIntake(any(ReadAuthoredWorldSourceIntakeRequest.class))) + .thenReturn(alteredRead); + assertThatThrownBy(() -> client.read(READ_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-source intake readback"); + + when(stub.intakeAuthoredWorldSource(any(IntakeAuthoredWorldSourceRequest.class))) + .thenThrow(new StatusRuntimeException(Status.UNAVAILABLE)); + assertThatThrownBy(() -> client.intake(INTAKE_REQUEST)) + .isInstanceOf(StatusRuntimeException.class); + verify(stub, org.mockito.Mockito.times(3)) + .intakeAuthoredWorldSource(any(IntakeAuthoredWorldSourceRequest.class)); + } + + @Test + void readRequiresAndReturnsTheSeparateExactReadIdentity(@TempDir Path dir) throws Exception { + WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub stub = + mock( + WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub + .class); + WorldAuthoredSourceIntakeClient client = clientWithStub(dir, stub); + when(stub.withDeadlineAfter(anyLong(), eq(TimeUnit.SECONDS))).thenReturn(stub); + when(stub.readAuthoredWorldSourceIntake(any(ReadAuthoredWorldSourceIntakeRequest.class))) + .thenReturn(readResponse(READ_REQUEST)); + + WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt receipt = client.read(READ_REQUEST); + + assertThat(receipt.intakeRequestId()).isEqualTo(INTAKE_REQUEST.intakeRequestId()); + assertThat(receipt.sourceOperationId()).isEqualTo(INTAKE_REQUEST.sourceOperationId()); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub) + .readAuthoredWorldSourceIntake( + WorldAuthoredSourceIntakeGrpcCodec.toReadRequest(READ_REQUEST)); + } + + @Test + void byIdReadReturnsTheFullValidatedPublicReceiptWithBoundedDeadline(@TempDir Path dir) + throws Exception { + WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub stub = + mock( + WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub + .class); + WorldAuthoredSourceIntakeClient client = clientWithStub(dir, stub); + when(stub.withDeadlineAfter(anyLong(), eq(TimeUnit.SECONDS))).thenReturn(stub); + when(stub.readAuthoredWorldSourceIntakeById( + any(ReadAuthoredWorldSourceIntakeByIdRequest.class))) + .thenReturn(byIdReadResponse(BY_ID_READ_REQUEST)); + + var receipt = client.readById(BY_ID_READ_REQUEST); + + assertThat(receipt.intakeRequestId()).isEqualTo(BY_ID_READ_REQUEST.intakeRequestId()); + assertThat(receipt.canonicalTenantId()).isEqualTo(BY_ID_READ_REQUEST.canonicalTenantId()); + assertThat(receipt.worldSlug()).isEqualTo(INTAKE_REQUEST.worldSlug()); + assertThat(receipt.source()).isEqualTo(sourceEvidence()); + assertThat(receipt.receiptDigest()).isEqualTo(RECEIPT_DIGEST); + assertThat(byIdReadResponse(BY_ID_READ_REQUEST).getReceipt().getAllFields().keySet()) + .extracting(field -> field.getName()) + .doesNotContain("local_tenant_key", "local_version_key", "world_tenant_key"); + assertThat( + byIdReadResponse(BY_ID_READ_REQUEST).getReceipt().getSource().getAllFields().keySet()) + .extracting(field -> field.getName()) + .containsExactlyInAnyOrder( + "schema_version", + "target_namespace", + "registration_request_id", + "operation_id", + "request_digest", + "canonical_tenant_id", + "tenant_slug", + "world_slug", + "world_display_name", + "source_game_row_id", + "source_game_tenant_key", + "provenance_kind", + "evidence_digest") + .doesNotContain("world_tenant_key", "local_tenant_key", "local_version_key"); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub) + .readAuthoredWorldSourceIntakeById( + WorldAuthoredSourceIntakeGrpcCodec.toReadByIdRequest(BY_ID_READ_REQUEST)); + assertThat( + WorldAuthoredSourceIntakeGrpcCodec.toReadByIdRequest(BY_ID_READ_REQUEST) + .getDescriptorForType() + .getFields()) + .extracting(field -> field.getName()) + .containsExactly( + "schema_version", + "target_namespace", + "read_request_id", + "intake_request_id", + "canonical_tenant_id") + .doesNotContain("world_slug", "source_operation_id", "expected_source_evidence_digest"); + } + + @Test + void byIdReadRejectsChangedEchoUnknownFieldsAndCorruptFullSource(@TempDir Path dir) + throws Exception { + WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub stub = + mock( + WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub + .class); + WorldAuthoredSourceIntakeClient client = clientWithStub(dir, stub); + when(stub.withDeadlineAfter(anyLong(), eq(TimeUnit.SECONDS))).thenReturn(stub); + + when(stub.readAuthoredWorldSourceIntakeById( + any(ReadAuthoredWorldSourceIntakeByIdRequest.class))) + .thenReturn( + byIdReadResponse(BY_ID_READ_REQUEST).toBuilder() + .setReadRequestId(BY_ID_READ_REQUEST.intakeRequestId().toString()) + .build()); + assertThatThrownBy(() -> client.readById(BY_ID_READ_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-source intake by-ID readback"); + + when(stub.readAuthoredWorldSourceIntakeById( + any(ReadAuthoredWorldSourceIntakeByIdRequest.class))) + .thenReturn( + byIdReadResponse(BY_ID_READ_REQUEST).toBuilder() + .setUnknownFields(unknownField()) + .build()); + assertThatThrownBy(() -> client.readById(BY_ID_READ_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-source intake by-ID readback"); + + var valid = byIdReadResponse(BY_ID_READ_REQUEST); + var corruptReceipt = + valid.getReceipt().toBuilder() + .setSource( + valid.getReceipt().getSource().toBuilder().setWorldDisplayName("substituted")) + .build(); + when(stub.readAuthoredWorldSourceIntakeById( + any(ReadAuthoredWorldSourceIntakeByIdRequest.class))) + .thenReturn(valid.toBuilder().setReceipt(corruptReceipt).build()); + assertThatThrownBy(() -> client.readById(BY_ID_READ_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-source intake by-ID readback"); + + var unknownSource = + valid.getReceipt().getSource().toBuilder().setUnknownFields(unknownField()).build(); + when(stub.readAuthoredWorldSourceIntakeById( + any(ReadAuthoredWorldSourceIntakeByIdRequest.class))) + .thenReturn( + valid.toBuilder() + .setReceipt(valid.getReceipt().toBuilder().setSource(unknownSource)) + .build()); + assertThatThrownBy(() -> client.readById(BY_ID_READ_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-source intake by-ID readback"); + } + + private static WorldAuthoredSourceIntakeClient clientWithStub( + Path directory, + WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub stub) + throws Exception { + WorldAuthoredSourceIntakeClient client = + newClient(fileBackedMtls(directory), mock(GrpcChannelFactory.class)); + setField(AbstractReloadingBlockingGrpcClient.class, client, "stub", stub); + setField(WorldAuthoredSourceIntakeClient.class, client, "initialized", true); + return client; + } + + private static IntakeAuthoredWorldSourceResponse intakeResponse( + WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest request) { + return WorldAuthoredSourceIntakeGrpcCodec.toIntakeResponse(request, receipt(request)); + } + + private static ReadAuthoredWorldSourceIntakeResponse readResponse( + WorldAuthoredSourceIntakeGrpcCodec.ReadRequest request) { + return WorldAuthoredSourceIntakeGrpcCodec.toReadResponse(request, receipt(request.binding())); + } + + private static ReadAuthoredWorldSourceIntakeByIdResponse byIdReadResponse( + WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest request) { + return WorldAuthoredSourceIntakeGrpcCodec.toReadByIdResponse(request, publicReceipt()); + } + + private static WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt publicReceipt() { + var source = sourceEvidence(); + var binding = + new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( + 1, + NAMESPACE, + INTAKE_REQUEST.intakeRequestId(), + INTAKE_REQUEST.canonicalTenantId(), + INTAKE_REQUEST.worldSlug(), + INTAKE_REQUEST.sourceOperationId(), + source.evidenceDigest()); + return new WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt( + 1, + NAMESPACE, + INTAKE_REQUEST.intakeRequestId(), + UUID.fromString("62345678-1234-4234-8234-123456789abc"), + INTAKE_REQUEST.canonicalTenantId(), + INTAKE_REQUEST.worldSlug(), + INTAKE_REQUEST.sourceOperationId(), + source.evidenceDigest(), + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(binding), + RECEIPT_DIGEST, + source); + } + + private static AuthoredWorldSourceEvidence sourceEvidence() { + UUID registrationRequestId = UUID.fromString("72345678-1234-4234-8234-123456789abc"); + String tenantSlug = "north-star"; + String worldDisplayName = "World One"; + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + registrationRequestId, + INTAKE_REQUEST.canonicalTenantId(), + tenantSlug, + INTAKE_REQUEST.worldSlug(), + worldDisplayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + INTAKE_REQUEST.sourceOperationId(), + sourceRequestDigest, + INTAKE_REQUEST.canonicalTenantId(), + tenantSlug, + INTAKE_REQUEST.worldSlug(), + worldDisplayName, + 42L, + "legacy-game-tenant-42", + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + INTAKE_REQUEST.sourceOperationId(), + sourceRequestDigest, + INTAKE_REQUEST.canonicalTenantId(), + tenantSlug, + INTAKE_REQUEST.worldSlug(), + worldDisplayName, + 42L, + "legacy-game-tenant-42", + "NEW_GAME_ROW", + evidenceDigest); + } + + private static WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt receipt( + WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest request) { + return new WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt( + request.schemaVersion(), + request.targetNamespace(), + request.intakeRequestId(), + UUID.fromString("52345678-1234-4234-8234-123456789abc"), + request.canonicalTenantId(), + request.worldSlug(), + request.sourceOperationId(), + request.expectedSourceEvidenceDigest(), + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(request), + RECEIPT_DIGEST); + } + + private static UnknownFieldSet unknownField() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } + + private static void setField(Class declaringClass, Object target, String name, Object value) + throws Exception { + Field field = declaringClass.getDeclaredField(name); + field.setAccessible(true); + field.set(target, value); + } + + private static WorldAuthoredSourceIntakeClient newClient( + CommonGrpcClientProperties tls, GrpcChannelFactory channelFactory) { + return new WorldAuthoredSourceIntakeClient( + new ServiceEndpointsProperties(), tls, channelFactory, NAMESPACE); + } + + private static CommonGrpcClientProperties fileBackedMtls(Path directory) throws Exception { + 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/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcService.java new file mode 100644 index 0000000000..9b01b0ca02 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcService.java @@ -0,0 +1,151 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.sql.SQLException; +import java.util.Optional; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.v1.AuthoredWorldSourceReadServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.TransientDataAccessException; + +/** Standalone exact authored-source owner read; deliberately not registered as a gRPC service. */ +public final class AuthoredWorldSourceReadGrpcService + extends AuthoredWorldSourceReadServiceGrpc.AuthoredWorldSourceReadServiceImplBase { + private final GameAuthoredWorldSourceRepository authoredWorldSourceRepository; + private final String workloadNamespace; + + public AuthoredWorldSourceReadGrpcService( + GameAuthoredWorldSourceRepository authoredWorldSourceRepository, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this.authoredWorldSourceRepository = authoredWorldSourceRepository; + this.workloadNamespace = workloadNamespace; + } + + @Override + public void resolveAuthoredWorldSource( + ResolveAuthoredWorldSourceRequest request, + StreamObserver responseObserver) { + if (SessionContext.hasAuthenticatedCallerContext() || !isWorldManagementPeer()) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription( + "Verified same-namespace World Management workload identity without caller " + + "context is required") + .asRuntimeException()); + return; + } + + final AuthoredWorldSourceGrpcCodec.ReadRequest readRequest; + try { + readRequest = AuthoredWorldSourceGrpcCodec.fromReadRequest(workloadNamespace, request); + } catch (IllegalArgumentException exception) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical exact authored-world source request is required") + .asRuntimeException()); + return; + } + + Optional resolved; + try { + resolved = + authoredWorldSourceRepository.read( + readRequest.operationId(), + readRequest.canonicalTenantId(), + readRequest.worldSlug(), + workloadNamespace); + } catch (GameAuthoredWorldSourceRepository.InvalidSourceEvidenceException + | GameAuthoredWorldSourceRepository.RegistrationConflictException + | org.jooq.exception.TooManyRowsException exception) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Authored-world source evidence is incomplete or inconsistent") + .asRuntimeException()); + return; + } catch (DataAccessResourceFailureException + | TransientDataAccessException + | org.springframework.transaction.TransactionException exception) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Authored-world source evidence is temporarily unavailable") + .asRuntimeException()); + return; + } catch (org.springframework.dao.DataAccessException exception) { + Status.Code code = + hasConnectionFailureSqlState(exception) ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL; + responseObserver.onError( + Status.fromCode(code) + .withDescription( + code == Status.Code.UNAVAILABLE + ? "Authored-world source evidence is temporarily unavailable" + : "Authored-world source evidence could not be read") + .asRuntimeException()); + return; + } catch (org.jooq.exception.DataAccessException exception) { + Status.Code code = + hasConnectionFailureSqlState(exception) ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL; + responseObserver.onError( + Status.fromCode(code) + .withDescription( + code == Status.Code.UNAVAILABLE + ? "Authored-world source evidence is temporarily unavailable" + : "Authored-world source evidence could not be read") + .asRuntimeException()); + return; + } catch (RuntimeException exception) { + responseObserver.onError( + Status.INTERNAL + .withDescription("Authored-world source evidence could not be read") + .asRuntimeException()); + return; + } + if (resolved.isEmpty()) { + responseObserver.onError( + Status.NOT_FOUND + .withDescription("No authored-world source matches the exact selector") + .asRuntimeException()); + return; + } + + final ResolveAuthoredWorldSourceResponse response; + try { + response = AuthoredWorldSourceGrpcCodec.toReadResponse(readRequest, resolved.orElseThrow()); + } catch (IllegalArgumentException exception) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Authored-world source readback does not match the exact request") + .asRuntimeException()); + return; + } + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + private boolean isWorldManagementPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + return peer != null + && GrpcPeerIdentity.isValidNamespace(workloadNamespace) + && peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"); + } + + private static boolean hasConnectionFailureSqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException exception) { + String sqlState = exception.getSQLState(); + if (sqlState != null && sqlState.startsWith("08")) { + return true; + } + } + } + return false; + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcService.java new file mode 100644 index 0000000000..338defa01c --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcService.java @@ -0,0 +1,146 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.sql.SQLException; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.v1.AuthoredWorldVersionStateServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateRequest; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateResponse; +import org.springframework.dao.DataAccessException; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.TransientDataAccessException; +import org.springframework.transaction.TransactionException; + +/** + * Standalone handler for the source-qualified version-state RPC. + * + *

This handler is deliberately not registered as a Spring gRPC service. The authenticated World + * intake remains disabled until the owning orchestrator explicitly wires and proves this boundary. + */ +public final class AuthoredWorldVersionStateGrpcService + extends AuthoredWorldVersionStateServiceGrpc.AuthoredWorldVersionStateServiceImplBase { + private final AuthoredWorldVersionStateService service; + private final String workloadNamespace; + + public AuthoredWorldVersionStateGrpcService( + AuthoredWorldVersionStateService service, String workloadNamespace) { + this.service = Objects.requireNonNull(service, "service"); + this.workloadNamespace = workloadNamespace; + } + + @Override + public void getAuthoredWorldVersionState( + GetAuthoredWorldVersionStateRequest request, + StreamObserver responseObserver) { + if (SessionContext.hasAuthenticatedCallerContext() || !isWorldManagementPeer()) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Verified same-namespace World Management identity is required") + .asRuntimeException()); + return; + } + + final net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence.Request + decodedRequest; + try { + decodedRequest = AuthoredWorldVersionStateGrpcCodec.fromRequest(request); + if (!workloadNamespace.equals(decodedRequest.targetNamespace())) { + throw new IllegalArgumentException( + "Target namespace does not match this Game Design owner"); + } + } catch (IllegalArgumentException exception) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical authored-world version-state request is required") + .asRuntimeException()); + return; + } + + try { + var evidence = service.read(decodedRequest); + responseObserver.onNext(AuthoredWorldVersionStateGrpcCodec.toResponse(evidence)); + responseObserver.onCompleted(); + } catch (AuthoredWorldVersionStateService.NotFoundException exception) { + responseObserver.onError( + Status.NOT_FOUND + .withDescription("No version state exists for the exact authored-world source") + .asRuntimeException()); + } catch (GameAuthoredWorldSourceRepository.InvalidSourceEvidenceException + | IllegalArgumentException exception) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Authored-world source or version ownership is inconsistent") + .asRuntimeException()); + } catch (org.jooq.exception.TooManyRowsException exception) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Authored-world source or version ownership is ambiguous") + .asRuntimeException()); + } catch (DataAccessResourceFailureException | TransientDataAccessException exception) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Game Design owner storage is temporarily unavailable") + .asRuntimeException()); + } catch (DataAccessException exception) { + Status.Code code = + hasConnectionFailureSqlState(exception) ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL; + responseObserver.onError( + Status.fromCode(code) + .withDescription( + code == Status.Code.UNAVAILABLE + ? "Game Design owner storage is temporarily unavailable" + : "Game Design owner storage could not be read") + .asRuntimeException()); + } catch (org.jooq.exception.DataAccessException exception) { + Status.Code code = + hasConnectionFailureSqlState(exception) ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL; + responseObserver.onError( + Status.fromCode(code) + .withDescription( + code == Status.Code.UNAVAILABLE + ? "Game Design owner storage is temporarily unavailable" + : "Game Design owner storage could not be read") + .asRuntimeException()); + } catch (TransactionException exception) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Game Design owner snapshot is temporarily unavailable") + .asRuntimeException()); + } catch (IllegalStateException exception) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Authored-world source or version state is invalid") + .asRuntimeException()); + } catch (RuntimeException exception) { + responseObserver.onError( + Status.INTERNAL + .withDescription("Game Design could not read authored-world version state") + .asRuntimeException()); + } + } + + private boolean isWorldManagementPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + return peer != null + && GrpcPeerIdentity.isValidNamespace(workloadNamespace) + && peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"); + } + + private static boolean hasConnectionFailureSqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException exception) { + String sqlState = exception.getSQLState(); + if (sqlState != null && sqlState.startsWith("08")) { + return true; + } + } + } + return false; + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateService.java new file mode 100644 index 0000000000..82ce26c230 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateService.java @@ -0,0 +1,72 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository.AuthoredWorldVersionStateSnapshot; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** Reads current version state only through the exact persisted authored-world source owner. */ +public final class AuthoredWorldVersionStateService { + private final GameAuthoredWorldSourceRepository sourceRepository; + private final TransactionTemplate ownerSnapshot; + + public AuthoredWorldVersionStateService( + PlatformTransactionManager transactionManager, + GameAuthoredWorldSourceRepository sourceRepository) { + this.sourceRepository = Objects.requireNonNull(sourceRepository, "sourceRepository"); + this.ownerSnapshot = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + this.ownerSnapshot.setName("authored-world-version-state-read"); + this.ownerSnapshot.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerSnapshot.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + this.ownerSnapshot.setReadOnly(true); + this.ownerSnapshot.setTimeout(5); + } + + /** Reads source provenance, selector binding, and exact version state from one fresh snapshot. */ + public AuthoredWorldVersionStateEvidence read(AuthoredWorldVersionStateEvidence.Request request) { + Objects.requireNonNull(request, "request"); + Optional snapshot = + ownerSnapshot.execute( + status -> + sourceRepository.readVersionStateSnapshot( + request.targetNamespace(), + request.readRequestId(), + request.canonicalTenantId(), + request.worldSlug(), + request.sourceOperationId(), + request.expectedSourceEvidenceDigest(), + request.versionId())); + if (snapshot == null || snapshot.isEmpty()) { + throw new NotFoundException( + "No authored-world source or version exists for the exact requested owner tuple"); + } + AuthoredWorldVersionStateSnapshot result = snapshot.orElseThrow(); + return AuthoredWorldVersionStateEvidence.create( + request, + result.sourceEvidence(), + result.canonicalVersionId(), + toProtoState(result.versionState()), + result.versionStateEpoch()); + } + + private static VersionLifecycleState toProtoState( + net.firedevops.firemud.gamedesign.model.VersionLifecycleState state) { + Objects.requireNonNull(state, "state"); + try { + return VersionLifecycleState.valueOf("VERSION_LIFECYCLE_STATE_" + state.name()); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException("Persisted version state has no closed wire enum", exception); + } + } + + public static final class NotFoundException extends RuntimeException { + public NotFoundException(String message) { + super(message); + } + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java index dae3d01f10..71db99c203 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java @@ -13,6 +13,7 @@ import java.nio.file.attribute.PosixFilePermission; import java.security.MessageDigest; import java.security.cert.CertificateFactory; +import java.security.cert.CertificateNotYetValidException; import java.security.cert.X509Certificate; import java.util.Base64; import java.util.HashSet; @@ -22,6 +23,7 @@ import java.util.Optional; import java.util.Set; import java.util.UUID; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; @@ -858,6 +860,8 @@ private Fixture prepareFixture(Path testDirectory) throws Exception { PosixFilePermission.GROUP_READ, PosixFilePermission.OTHERS_READ)); + awaitFixtureCertificatesValid(sessionCertificate, worldManagementCertificate, caCertificate); + Path receiptDirectory = Files.createDirectory(testDirectory.resolve("run-owned-authored-world-source")); Files.setPosixFilePermissions( @@ -910,6 +914,30 @@ private String certificateDigest(Path path) throws Exception { } } + private void awaitFixtureCertificatesValid(Path... certificatePaths) throws Exception { + long deadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (true) { + try { + for (Path path : certificatePaths) { + try (var input = Files.newInputStream(path)) { + X509Certificate certificate = + (X509Certificate) + CertificateFactory.getInstance("X.509").generateCertificate(input); + certificate.checkValidity(); + } + } + return; + } catch (CertificateNotYetValidException exception) { + long remainingNanos = deadlineNanos - System.nanoTime(); + if (remainingNanos <= 0L) { + throw new IllegalStateException( + "Run-owned fixture certificates did not become valid within 5 seconds", exception); + } + TimeUnit.NANOSECONDS.sleep(Math.min(TimeUnit.MILLISECONDS.toNanos(10), remainingNanos)); + } + } + } + private AuthoredWorldSourceEvidence changedSourceEvidence(AuthoredWorldSourceEvidence source) { String changedWorldSlug = source.worldSlug() + "-changed"; String requestDigest = diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java new file mode 100644 index 0000000000..0455f09e6f --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldSourceReadGrpcServiceTest.java @@ -0,0 +1,301 @@ +package unit.net.firedevops.firemud.gamedesign.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.sql.SQLException; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldSourceReadGrpcService; +import net.firedevops.firemud.gamedesign.v1.AuthoredWorldSourceReadServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; +import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; +import org.jooq.exception.DataAccessException; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DataAccessResourceFailureException; + +class AuthoredWorldSourceReadGrpcServiceTest { + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String WORLD_URI = "spiffe://firemud/ns/test/sa/world-management-service"; + private static final UUID REQUEST_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID REGISTRATION_REQUEST_ID = + UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final UUID WORLD_TENANT_ID = + UUID.fromString("77777777-7777-4777-8777-777777777777"); + private static final String WORLD_SLUG = "silver-march"; + private static final String WORLD_TENANT_SLUG = "new-kingdom"; + private static final String WORLD_DISPLAY_NAME = "Silver March"; + private static final String SOURCE_KEY = "fresh-owner-key-91"; + + private final GameAuthoredWorldSourceRepository authoredWorldSourceRepository = + mock(GameAuthoredWorldSourceRepository.class); + private final AuthoredWorldSourceReadGrpcService service = + new AuthoredWorldSourceReadGrpcService(authoredWorldSourceRepository, "test"); + + @Test + void usesASeparateServiceIdentityFromRegisteredTenantIdentityRpcSurface() { + assertThat(TenantIdentityServiceGrpc.getServiceDescriptor().getName()) + .isEqualTo("gamedesign.v1.TenantIdentityService"); + assertThat( + TenantIdentityServiceGrpc.getServiceDescriptor().getMethods().stream() + .map(method -> method.getFullMethodName()) + .toList()) + .doesNotContain("gamedesign.v1.TenantIdentityService/ResolveAuthoredWorldSource"); + assertThat(AuthoredWorldSourceReadServiceGrpc.getServiceDescriptor().getName()) + .isEqualTo("gamedesign.v1.AuthoredWorldSourceReadService"); + assertThat( + AuthoredWorldSourceReadServiceGrpc.getServiceDescriptor().getMethods().stream() + .map(method -> method.getFullMethodName()) + .toList()) + .contains("gamedesign.v1.AuthoredWorldSourceReadService/ResolveAuthoredWorldSource"); + } + + @Test + void resolvesExactPersistedWorldSourceOnlyForSameNamespaceWorldManagementPeer() { + AuthoredWorldSourceEvidence source = authoredWorldSource("test"); + when(authoredWorldSourceRepository.read( + SOURCE_OPERATION_ID, WORLD_TENANT_ID, WORLD_SLUG, "test")) + .thenReturn(Optional.of(source)); + + WorldSourceObserver observer = callWorldSource(worldSourceRequest(), WORLD_URI); + + assertThat(observer.failure).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(observer.response) + .isEqualTo(AuthoredWorldSourceGrpcCodec.toReadResponse(worldSourceReadRequest(), source)); + verify(authoredWorldSourceRepository) + .read(SOURCE_OPERATION_ID, WORLD_TENANT_ID, WORLD_SLUG, "test"); + } + + @Test + void deniesNonWorldPeersCrossNamespaceAndCallerContextBeforeAuthoredSourceRead() { + for (String peer : + new String[] { + null, + ACCOUNT_URI, + GAME_SESSION_URI, + "spiffe://firemud/ns/test/sa/entity-management-service", + "spiffe://firemud/ns/other/sa/world-management-service" + }) { + assertThat(status(callWorldSource(worldSourceRequest(), peer))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } + + SessionContext.setContext("account-uuid", List.of("player"), Map.of()); + try { + assertThat(status(callWorldSource(worldSourceRequest(), WORLD_URI))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + SessionContext.clear(); + } + verifyNoInteractions(authoredWorldSourceRepository); + } + + @Test + void rejectsMalformedOrOpenAuthoredSourceRequestsBeforeOwnerRead() { + for (ResolveAuthoredWorldSourceRequest malformed : + new ResolveAuthoredWorldSourceRequest[] { + worldSourceRequest().toBuilder().setRequestId("not-a-uuid").build(), + worldSourceRequest().toBuilder() + .setOperationId("00000000-0000-0000-0000-000000000000") + .build(), + worldSourceRequest().toBuilder().setCanonicalTenantId("not-a-uuid").build(), + worldSourceRequest().toBuilder().setWorldSlug("Not A Slug").build(), + worldSourceRequest().toBuilder().setUnknownFields(unknownField()).build() + }) { + assertThat(status(callWorldSource(malformed, WORLD_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + } + verifyNoInteractions(authoredWorldSourceRepository); + } + + @Test + void missingOrSubstitutedAuthoredSourceFailsClosed() { + when(authoredWorldSourceRepository.read( + SOURCE_OPERATION_ID, WORLD_TENANT_ID, WORLD_SLUG, "test")) + .thenReturn(Optional.empty()) + .thenReturn(Optional.of(authoredWorldSource("other"))) + .thenReturn(Optional.of(authoredWorldSource("test", WORLD_TENANT_ID, "other-world"))); + + assertThat(status(callWorldSource(worldSourceRequest(), WORLD_URI))) + .isEqualTo(Status.Code.NOT_FOUND); + assertThat(status(callWorldSource(worldSourceRequest(), WORLD_URI))) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(status(callWorldSource(worldSourceRequest(), WORLD_URI))) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + } + + @Test + void mapsCorruptAndUnavailableAuthoredSourceReadsWithoutReturningEvidence() { + when(authoredWorldSourceRepository.read( + SOURCE_OPERATION_ID, WORLD_TENANT_ID, WORLD_SLUG, "test")) + .thenThrow(new GameAuthoredWorldSourceRepository.InvalidSourceEvidenceException("corrupt")) + .thenThrow(new DataAccessResourceFailureException("offline")); + + WorldSourceObserver corrupt = callWorldSource(worldSourceRequest(), WORLD_URI); + WorldSourceObserver offline = callWorldSource(worldSourceRequest(), WORLD_URI); + + assertThat(status(corrupt)).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(corrupt.response).isNull(); + assertThat(status(offline)).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(offline.response).isNull(); + } + + @Test + void classifiesJooqStorageFailuresByConnectionSqlStateWithoutLeakingDetails() { + when(authoredWorldSourceRepository.read( + SOURCE_OPERATION_ID, WORLD_TENANT_ID, WORLD_SLUG, "test")) + .thenThrow( + new DataAccessException( + "unique constraint failed", new SQLException("constraint", "23505"))) + .thenThrow( + new DataAccessException("relation missing", new SQLException("missing", "42P01"))) + .thenThrow(new DataAccessException("storage failed")) + .thenThrow( + new DataAccessException("connection dropped", new SQLException("dropped", "08006"))); + + assertStorageFailure(callWorldSource(worldSourceRequest(), WORLD_URI), Status.Code.INTERNAL); + assertStorageFailure(callWorldSource(worldSourceRequest(), WORLD_URI), Status.Code.INTERNAL); + assertStorageFailure(callWorldSource(worldSourceRequest(), WORLD_URI), Status.Code.INTERNAL); + assertStorageFailure(callWorldSource(worldSourceRequest(), WORLD_URI), Status.Code.UNAVAILABLE); + } + + private static void assertStorageFailure(WorldSourceObserver observer, Status.Code expectedCode) { + assertThat(observer.failure).isEqualTo(expectedCode); + assertThat(observer.response).isNull(); + assertThat(observer.completed).isFalse(); + assertThat(observer.failureDescription) + .isEqualTo( + expectedCode == Status.Code.UNAVAILABLE + ? "Authored-world source evidence is temporarily unavailable" + : "Authored-world source evidence could not be read"); + assertThat(observer.failureTrailersPresent).isFalse(); + } + + private WorldSourceObserver callWorldSource( + ResolveAuthoredWorldSourceRequest request, String peerUri) { + WorldSourceObserver observer = new WorldSourceObserver(); + Runnable invocation = () -> service.resolveAuthoredWorldSource(request, observer); + if (peerUri == null) { + invocation.run(); + } else { + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(peerUri).orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(invocation); + } + return observer; + } + + private static ResolveAuthoredWorldSourceRequest worldSourceRequest() { + return ResolveAuthoredWorldSourceRequest.newBuilder() + .setRequestId(REQUEST_ID.toString()) + .setOperationId(SOURCE_OPERATION_ID.toString()) + .setCanonicalTenantId(WORLD_TENANT_ID.toString()) + .setWorldSlug(WORLD_SLUG) + .build(); + } + + private static AuthoredWorldSourceGrpcCodec.ReadRequest worldSourceReadRequest() { + return new AuthoredWorldSourceGrpcCodec.ReadRequest( + "test", REQUEST_ID, SOURCE_OPERATION_ID, WORLD_TENANT_ID, WORLD_SLUG); + } + + private static AuthoredWorldSourceEvidence authoredWorldSource(String namespace) { + return authoredWorldSource(namespace, WORLD_TENANT_ID, WORLD_SLUG); + } + + private static AuthoredWorldSourceEvidence authoredWorldSource( + String namespace, UUID canonicalTenantId, String worldSlug) { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + namespace, + REGISTRATION_REQUEST_ID, + canonicalTenantId, + WORLD_TENANT_SLUG, + worldSlug, + WORLD_DISPLAY_NAME); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + namespace, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + canonicalTenantId, + WORLD_TENANT_SLUG, + worldSlug, + WORLD_DISPLAY_NAME, + 91L, + SOURCE_KEY, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + namespace, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + canonicalTenantId, + WORLD_TENANT_SLUG, + worldSlug, + WORLD_DISPLAY_NAME, + 91L, + SOURCE_KEY, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static UnknownFieldSet unknownField() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } + + private static Status.Code status(WorldSourceObserver observer) { + return observer.failure; + } + + private static final class WorldSourceObserver + implements StreamObserver { + private ResolveAuthoredWorldSourceResponse response; + private Status.Code failure; + private String failureDescription; + private boolean failureTrailersPresent; + private boolean completed; + + @Override + public void onNext(ResolveAuthoredWorldSourceResponse value) { + response = value; + } + + @Override + public void onError(Throwable throwable) { + failureDescription = Status.fromThrowable(throwable).getDescription(); + failureTrailersPresent = + throwable instanceof io.grpc.StatusRuntimeException statusFailure + && statusFailure.getTrailers() != null; + failure = Status.fromThrowable(throwable).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java new file mode 100644 index 0000000000..003f4ad7bf --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java @@ -0,0 +1,320 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.sql.SQLException; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.AuthoredWorldVersionStateServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateRequest; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateResponse; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DataAccessException; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.TransientDataAccessException; + +class AuthoredWorldVersionStateGrpcServiceTest { + private static final String NAMESPACE = "test"; + private static final UUID READ_REQUEST_ID = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION_ID = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID REGISTRATION_REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID CANONICAL_VERSION_ID = uuid("55555555-5555-4555-8555-555555555555"); + + @Test + void usesASeparateServiceIdentityFromRegisteredGameDesignRpcSurface() { + assertThat(GameDesignServiceGrpc.getServiceDescriptor().getName()) + .isEqualTo("gamedesign.v1.GameDesignService"); + assertThat( + GameDesignServiceGrpc.getServiceDescriptor().getMethods().stream() + .map(method -> method.getFullMethodName()) + .toList()) + .doesNotContain("gamedesign.v1.GameDesignService/GetAuthoredWorldVersionState"); + assertThat(AuthoredWorldVersionStateServiceGrpc.getServiceDescriptor().getName()) + .isEqualTo("gamedesign.v1.AuthoredWorldVersionStateService"); + assertThat( + AuthoredWorldVersionStateServiceGrpc.getServiceDescriptor().getMethods().stream() + .map(method -> method.getFullMethodName()) + .toList()) + .contains("gamedesign.v1.AuthoredWorldVersionStateService/GetAuthoredWorldVersionState"); + } + + @Test + void exactWorldPeerMayReadAndReceivesClosedEvidence() { + AuthoredWorldVersionStateService service = mock(AuthoredWorldVersionStateService.class); + var request = request(); + var evidence = + AuthoredWorldVersionStateEvidence.create( + request, + sourceEvidence(), + CANONICAL_VERSION_ID, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 7L); + when(service.read(request)).thenReturn(evidence); + var handler = new AuthoredWorldVersionStateGrpcService(service, NAMESPACE); + TestObserver observer = new TestObserver<>(); + + withPeer( + peer(NAMESPACE, "world-management-service"), + () -> + handler.getAuthoredWorldVersionState( + AuthoredWorldVersionStateGrpcCodec.toRequest(request), observer)); + + assertThat(observer.error).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(observer.value.getEvidence().getCanonicalVersionId()) + .isEqualTo(CANONICAL_VERSION_ID.toString()); + assertThat( + observer + .value + .getEvidence() + .getDescriptorForType() + .findFieldByName("canonical_version_id") + .getNumber()) + .isEqualTo(13); + assertThat(AuthoredWorldVersionStateGrpcCodec.fromResponse(request, observer.value)) + .isEqualTo(evidence); + verify(service).read(request); + } + + @Test + void exactPeerGuardRunsBeforeMalformedRequestDecodeOrOwnerAccess() { + AuthoredWorldVersionStateService service = mock(AuthoredWorldVersionStateService.class); + var handler = new AuthoredWorldVersionStateGrpcService(service, NAMESPACE); + GetAuthoredWorldVersionStateRequest malformed = + GetAuthoredWorldVersionStateRequest.newBuilder() + .setSchemaVersion(99) + .setReadRequestId("not-a-uuid") + .build(); + + TestObserver absent = new TestObserver<>(); + handler.getAuthoredWorldVersionState(malformed, absent); + assertStatus(absent, Status.Code.PERMISSION_DENIED); + + TestObserver wrongService = new TestObserver<>(); + withPeer( + peer(NAMESPACE, "game-session-service"), + () -> handler.getAuthoredWorldVersionState(malformed, wrongService)); + assertStatus(wrongService, Status.Code.PERMISSION_DENIED); + + TestObserver wrongNamespace = new TestObserver<>(); + withPeer( + peer("other", "world-management-service"), + () -> handler.getAuthoredWorldVersionState(malformed, wrongNamespace)); + assertStatus(wrongNamespace, Status.Code.PERMISSION_DENIED); + + verifyNoInteractions(service); + } + + @Test + void authenticatedCallerContextIsDeniedBeforeDecodeEvenForTheExactWorldPeer() { + AuthoredWorldVersionStateService service = mock(AuthoredWorldVersionStateService.class); + var handler = new AuthoredWorldVersionStateGrpcService(service, NAMESPACE); + GetAuthoredWorldVersionStateRequest malformed = + GetAuthoredWorldVersionStateRequest.newBuilder() + .setSchemaVersion(99) + .setReadRequestId("not-a-uuid") + .build(); + TestObserver observer = new TestObserver<>(); + + SessionContext.setContext("account", List.of(), Map.of()); + try { + withPeer( + peer(NAMESPACE, "world-management-service"), + () -> handler.getAuthoredWorldVersionState(malformed, observer)); + } finally { + SessionContext.clear(); + } + + assertStatus(observer, Status.Code.PERMISSION_DENIED); + verifyNoInteractions(service); + } + + @Test + void exactPeerGetsInvalidArgumentBeforeAnyOwnerReadForMalformedClosedRequest() { + AuthoredWorldVersionStateService service = mock(AuthoredWorldVersionStateService.class); + var handler = new AuthoredWorldVersionStateGrpcService(service, NAMESPACE); + GetAuthoredWorldVersionStateRequest malformed = + GetAuthoredWorldVersionStateRequest.newBuilder() + .setSchemaVersion(2) + .setTargetNamespace(NAMESPACE) + .setReadRequestId(READ_REQUEST_ID.toString()) + .build(); + TestObserver observer = new TestObserver<>(); + + withPeer( + peer(NAMESPACE, "world-management-service"), + () -> handler.getAuthoredWorldVersionState(malformed, observer)); + + assertStatus(observer, Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(service); + } + + @Test + void classifiesSpringAndJooqStorageFailuresWithoutLeakingDetails() { + AuthoredWorldVersionStateService service = mock(AuthoredWorldVersionStateService.class); + when(service.read(request())) + .thenThrow(new DataAccessResourceFailureException("database unavailable")) + .thenThrow(new TransientDataAccessException("database timed out") {}) + .thenThrow( + new DataAccessException( + "unique constraint failed", new SQLException("constraint", "23505")) {}) + .thenThrow( + new DataAccessException("connection dropped", new SQLException("dropped", "08006")) {}) + .thenThrow( + new org.jooq.exception.DataAccessException( + "relation missing", new SQLException("missing", "42P01"))) + .thenThrow(new org.jooq.exception.DataAccessException("permanent storage failure")) + .thenThrow( + new org.jooq.exception.DataAccessException( + "connection dropped", new SQLException("dropped", "08006"))); + var handler = new AuthoredWorldVersionStateGrpcService(service, NAMESPACE); + + assertStorageFailure(callRead(handler), Status.Code.UNAVAILABLE); + assertStorageFailure(callRead(handler), Status.Code.UNAVAILABLE); + assertStorageFailure(callRead(handler), Status.Code.INTERNAL); + assertStorageFailure(callRead(handler), Status.Code.UNAVAILABLE); + assertStorageFailure(callRead(handler), Status.Code.INTERNAL); + assertStorageFailure(callRead(handler), Status.Code.INTERNAL); + assertStorageFailure(callRead(handler), Status.Code.UNAVAILABLE); + } + + private static TestObserver callRead( + AuthoredWorldVersionStateGrpcService handler) { + TestObserver observer = new TestObserver<>(); + withPeer( + peer(NAMESPACE, "world-management-service"), + () -> + handler.getAuthoredWorldVersionState( + AuthoredWorldVersionStateGrpcCodec.toRequest(request()), observer)); + return observer; + } + + private static void assertStorageFailure(TestObserver observer, Status.Code expectedCode) { + assertStatus(observer, expectedCode); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + assertThat(observer.failureDescription) + .isEqualTo( + expectedCode == Status.Code.UNAVAILABLE + ? "Game Design owner storage is temporarily unavailable" + : "Game Design owner storage could not be read"); + assertThat(observer.failureTrailersPresent).isFalse(); + } + + private static void assertStatus(TestObserver observer, Status.Code expectedCode) { + assertThat(observer.error).isNotNull(); + assertThat(observer.error.type()).isEqualTo(StatusRuntimeException.class); + assertThat(observer.error.code()).isEqualTo(expectedCode); + } + + private static void withPeer(GrpcPeerIdentity peer, Runnable action) { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + action.run(); + } finally { + context.detach(previous); + } + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static AuthoredWorldVersionStateEvidence.Request request() { + AuthoredWorldSourceEvidence source = sourceEvidence(); + return new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + READ_REQUEST_ID, + TENANT_ID, + "cafe-coast", + SOURCE_OPERATION_ID, + source.evidenceDigest(), + 19L); + } + + private static AuthoredWorldSourceEvidence sourceEvidence() { + String displayName = "Café 🐉"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, REGISTRATION_REQUEST_ID, TENANT_ID, "tenant-one", "cafe-coast", displayName); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + "tenant-one", + "cafe-coast", + displayName, + 42L, + "game-owner-tenant", + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + "tenant-one", + "cafe-coast", + displayName, + 42L, + "game-owner-tenant", + "NEW_GAME_ROW")); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class TestObserver implements StreamObserver { + private T value; + private ErrorEvidence error; + private String failureDescription; + private boolean failureTrailersPresent; + private boolean completed; + + @Override + public void onNext(T next) { + value = next; + } + + @Override + public void onError(Throwable failure) { + failureDescription = Status.fromThrowable(failure).getDescription(); + failureTrailersPresent = + failure instanceof StatusRuntimeException statusFailure + && statusFailure.getTrailers() != null; + error = new ErrorEvidence(failure.getClass(), Status.fromThrowable(failure).getCode()); + } + + @Override + public void onCompleted() { + completed = true; + } + + private record ErrorEvidence(Class type, Status.Code code) {} + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateServiceTest.java new file mode 100644 index 0000000000..77743c83e2 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateServiceTest.java @@ -0,0 +1,227 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository.AuthoredWorldVersionStateSnapshot; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; + +class AuthoredWorldVersionStateServiceTest { + private static final String NAMESPACE = "test"; + private static final UUID READ_REQUEST_ID = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION_ID = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID REGISTRATION_REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID CANONICAL_VERSION_ID = uuid("55555555-5555-4555-8555-555555555555"); + + @Test + void readsCompleteSourceAndVersionInsideFreshReadOnlyRepeatableReadTransaction() { + RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + GameAuthoredWorldSourceRepository repository = mock(GameAuthoredWorldSourceRepository.class); + AuthoredWorldSourceEvidence source = sourceEvidence(); + when(repository.readVersionStateSnapshot( + NAMESPACE, + READ_REQUEST_ID, + TENANT_ID, + "cafe-coast", + SOURCE_OPERATION_ID, + source.evidenceDigest(), + 19L)) + .thenReturn( + Optional.of( + new AuthoredWorldVersionStateSnapshot( + source, + CANONICAL_VERSION_ID, + net.firedevops.firemud.gamedesign.model.VersionLifecycleState.PUBLISHED, + 7L))); + AuthoredWorldVersionStateService service = + new AuthoredWorldVersionStateService(transactionManager, repository); + + AuthoredWorldVersionStateEvidence evidence = service.read(request(source.evidenceDigest())); + + assertThat(evidence.sourceEvidence()).isEqualTo(source); + assertThat(evidence.canonicalVersionId()).isEqualTo(CANONICAL_VERSION_ID); + assertThat(evidence.versionState()) + .isEqualTo(VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED); + assertThat(evidence.versionStateEpoch()).isEqualTo(7L); + assertThat(transactionManager.definition).isNotNull(); + assertThat(transactionManager.definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(transactionManager.definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThat(transactionManager.definition.isReadOnly()).isTrue(); + verify(repository) + .readVersionStateSnapshot( + NAMESPACE, + READ_REQUEST_ID, + TENANT_ID, + "cafe-coast", + SOURCE_OPERATION_ID, + source.evidenceDigest(), + 19L); + } + + @Test + void missingExactSourceOrVersionFailsClosed() { + RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + GameAuthoredWorldSourceRepository repository = mock(GameAuthoredWorldSourceRepository.class); + when(repository.readVersionStateSnapshot( + eq(NAMESPACE), + eq(READ_REQUEST_ID), + eq(TENANT_ID), + eq("cafe-coast"), + eq(SOURCE_OPERATION_ID), + any(String.class), + eq(19L))) + .thenReturn(Optional.empty()); + AuthoredWorldVersionStateService service = + new AuthoredWorldVersionStateService(transactionManager, repository); + + assertThatThrownBy(() -> service.read(request("sha256:" + "a".repeat(64)))) + .isInstanceOf(AuthoredWorldVersionStateService.NotFoundException.class) + .hasMessageContaining("exact requested owner tuple"); + } + + @Test + void repositoryOwnerConsistencyFailuresDoNotBecomeEvidence() { + RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + GameAuthoredWorldSourceRepository repository = mock(GameAuthoredWorldSourceRepository.class); + when(repository.readVersionStateSnapshot( + eq(NAMESPACE), + eq(READ_REQUEST_ID), + eq(TENANT_ID), + eq("cafe-coast"), + eq(SOURCE_OPERATION_ID), + any(String.class), + eq(19L))) + .thenThrow( + new GameAuthoredWorldSourceRepository.InvalidSourceEvidenceException( + "source binding changed")); + AuthoredWorldVersionStateService service = + new AuthoredWorldVersionStateService(transactionManager, repository); + + assertThatThrownBy(() -> service.read(request("sha256:" + "a".repeat(64)))) + .isInstanceOf(GameAuthoredWorldSourceRepository.InvalidSourceEvidenceException.class) + .hasMessageContaining("source binding changed"); + } + + @Test + void missingOrNilPersistedCanonicalVersionIdFailsClosed() { + for (UUID canonicalVersionId : new UUID[] {null, new UUID(0L, 0L)}) { + RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + GameAuthoredWorldSourceRepository repository = mock(GameAuthoredWorldSourceRepository.class); + AuthoredWorldSourceEvidence source = sourceEvidence(); + when(repository.readVersionStateSnapshot( + NAMESPACE, + READ_REQUEST_ID, + TENANT_ID, + "cafe-coast", + SOURCE_OPERATION_ID, + source.evidenceDigest(), + 19L)) + .thenReturn( + Optional.of( + new AuthoredWorldVersionStateSnapshot( + source, + canonicalVersionId, + net.firedevops.firemud.gamedesign.model.VersionLifecycleState.PUBLISHED, + 7L))); + AuthoredWorldVersionStateService service = + new AuthoredWorldVersionStateService(transactionManager, repository); + + if (canonicalVersionId == null) { + assertThatThrownBy(() -> service.read(request(source.evidenceDigest()))) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("canonicalVersionId"); + } else { + assertThatThrownBy(() -> service.read(request(source.evidenceDigest()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("non-nil UUID"); + } + } + } + + private static AuthoredWorldVersionStateEvidence.Request request(String sourceDigest) { + return new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + READ_REQUEST_ID, + TENANT_ID, + "cafe-coast", + SOURCE_OPERATION_ID, + sourceDigest, + 19L); + } + + private static AuthoredWorldSourceEvidence sourceEvidence() { + String displayName = "Café 🐉"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, REGISTRATION_REQUEST_ID, TENANT_ID, "tenant-one", "cafe-coast", displayName); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + "tenant-one", + "cafe-coast", + displayName, + 42L, + "game-owner-tenant", + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + "tenant-one", + "cafe-coast", + displayName, + 42L, + "game-owner-tenant", + "NEW_GAME_ROW")); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class RecordingTransactionManager + extends AbstractPlatformTransactionManager { + private TransactionDefinition definition; + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition transactionDefinition) { + definition = transactionDefinition; + } + + @Override + protected void doCommit(DefaultTransactionStatus status) {} + + @Override + protected void doRollback(DefaultTransactionStatus status) {} + } +} diff --git a/services/world-management-service/build.gradle.kts b/services/world-management-service/build.gradle.kts index d6bd731255..ef04f9b498 100644 --- a/services/world-management-service/build.gradle.kts +++ b/services/world-management-service/build.gradle.kts @@ -14,4 +14,7 @@ firemudJooq { dependencies { implementation(project(":common-security")) + testImplementation(libs.bouncycastle.pkix) + testCompileOnly(libs.spotbugs.annotations) + add("integrationTestCompileOnly", libs.spotbugs.annotations) } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java index 39566abf51..d66a911be9 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java @@ -3,7 +3,6 @@ import io.grpc.stub.StreamObserver; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; -import java.util.List; import java.util.Optional; import net.firedevops.firemud.common.grpc.GrpcAppErrors; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; @@ -21,7 +20,6 @@ import net.firedevops.firemud.worldmanagement.dto.RoomSnapshotDto; import net.firedevops.firemud.worldmanagement.dto.RoomSnapshotDto.RoomExitSnapshotDto; import net.firedevops.firemud.worldmanagement.dto.RuntimeRoomDto; -import net.firedevops.firemud.worldmanagement.dto.WorldDesignMutationRequestDto; import net.firedevops.firemud.worldmanagement.service.InitialAdmissionBindHoldService; import net.firedevops.firemud.worldmanagement.service.PingService; import net.firedevops.firemud.worldmanagement.service.RoomService; @@ -37,10 +35,6 @@ import net.firedevops.firemud.worldmanagement.v1.ApplyWorldDesignMutationResponse; import net.firedevops.firemud.worldmanagement.v1.FailPreparedWorldInstanceRequest; import net.firedevops.firemud.worldmanagement.v1.FailPreparedWorldInstanceResponse; -import net.firedevops.firemud.worldmanagement.v1.GeneratedRoomDesignMutation; -import net.firedevops.firemud.worldmanagement.v1.GeneratedRoomExitDesignMutation; -import net.firedevops.firemud.worldmanagement.v1.GeneratedWorldEntitySpawnBindingDesignMutation; -import net.firedevops.firemud.worldmanagement.v1.GenerationRuleDesignMutation; import net.firedevops.firemud.worldmanagement.v1.GetDraftDesignDigestRequest; import net.firedevops.firemud.worldmanagement.v1.GetDraftDesignDigestResponse; import net.firedevops.firemud.worldmanagement.v1.GetRoomRequest; @@ -54,9 +48,6 @@ import net.firedevops.firemud.worldmanagement.v1.PingResponse; import net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceRequest; import net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse; -import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; -import net.firedevops.firemud.worldmanagement.v1.RoomDesignMutation; -import net.firedevops.firemud.worldmanagement.v1.RoomExitDesignMutation; import net.firedevops.firemud.worldmanagement.v1.RoomExitSnapshot; import net.firedevops.firemud.worldmanagement.v1.RoomSnapshot; import net.firedevops.firemud.worldmanagement.v1.RuntimeRoom; @@ -65,13 +56,9 @@ import net.firedevops.firemud.worldmanagement.v1.UpgradeValidationResult; import net.firedevops.firemud.worldmanagement.v1.ValidateWorldUpgradeMappingsRequest; import net.firedevops.firemud.worldmanagement.v1.ValidateWorldUpgradeMappingsResponse; -import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationResult; -import net.firedevops.firemud.worldmanagement.v1.WorldEntitySpawnBindingDesignMutation; -import net.firedevops.firemud.worldmanagement.v1.WorldGenerationSubtreeDesignMutation; import net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot; import net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus; import net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc; -import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -521,36 +508,16 @@ public void validateWorldUpgradeMappings( public void applyWorldDesignMutation( ApplyWorldDesignMutationRequest request, StreamObserver responseObserver) { - ApplyWorldDesignMutationResponse.Builder builder = - ApplyWorldDesignMutationResponse.newBuilder(); - try { - var result = worldDesignMutationService.applyMutation(toDto(request)); - builder - .setResult(toProtoMutationResult(result.result())) - .setTenantId(Long.toString(result.tenantId())) - .setVersionId(Long.toString(result.versionId())) - .setAggregateId(Long.toString(result.aggregateId())) - .setDraftRevisionEpoch(result.draftRevisionEpoch()); - if (result.draftScopeRevisionEpoch() != null) { - builder.setDraftScopeRevisionEpoch(result.draftScopeRevisionEpoch()); - } - } catch (NumberFormatException ex) { - builder.setError( - GrpcAppErrors.error( - meterRegistry, logger, "ApplyWorldDesignMutation", "INVALID_ARGUMENT", "invalid id")); - } catch (IllegalArgumentException ex) { - builder.setError( - GrpcAppErrors.error( - meterRegistry, - logger, - "ApplyWorldDesignMutation", - errorCodeFor(ex), - errorMessageFor(ex))); - } catch (Exception ex) { - builder.setError( - GrpcAppErrors.internal(meterRegistry, logger, "ApplyWorldDesignMutation", ex)); - } - responseObserver.onNext(builder.build()); + responseObserver.onNext( + ApplyWorldDesignMutationResponse.newBuilder() + .setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "ApplyWorldDesignMutation", + "FAILED_PRECONDITION", + "Complete Draft caller/tenant authorization and owner publication proof are unavailable.")) + .build()); responseObserver.onCompleted(); } @@ -880,163 +847,6 @@ private String errorMessageFor(IllegalArgumentException ex) { return message; } - private WorldDesignMutationRequestDto toDto(ApplyWorldDesignMutationRequest request) { - return new WorldDesignMutationRequestDto( - RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"), - RequestIdValidation.requirePositiveLong(request.getVersionId(), "versionId"), - request.getCommitId(), - request.getRevisionId(), - operationName(request), - aggregateTypeName(request), - request.getAggregateId(), - request.getExpectedDraftRevisionEpoch(), - request.getScopeType() - == net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType - .WORLD_DESIGN_SCOPE_TYPE_UNSPECIFIED - ? "" - : request.getScopeType().name().replace("WORLD_DESIGN_SCOPE_TYPE_", ""), - request.getScopeId(), - request.getExpectedDraftScopeRevisionEpoch(), - request.getScopeMutationPolicy() - == net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeMutationPolicy - .WORLD_DESIGN_SCOPE_MUTATION_POLICY_UNSPECIFIED - ? "" - : request - .getScopeMutationPolicy() - .name() - .replace("WORLD_DESIGN_SCOPE_MUTATION_POLICY_", ""), - request.hasRegion() ? toDto(request.getRegion()) : null, - request.hasZone() ? toDto(request.getZone()) : null, - request.hasRoom() ? toDto(request.getRoom()) : null, - request.hasRoomExit() ? toDto(request.getRoomExit()) : null, - request.hasGenerationRule() ? toDto(request.getGenerationRule()) : null, - request.hasWorldEntitySpawnBinding() ? toDto(request.getWorldEntitySpawnBinding()) : null, - request.hasWorldGenerationSubtree() ? toDto(request.getWorldGenerationSubtree()) : null); - } - - private String operationName(ApplyWorldDesignMutationRequest request) { - return switch (request.getOperation()) { - case WORLD_DESIGN_MUTATION_OPERATION_UPSERT -> "UPSERT"; - case WORLD_DESIGN_MUTATION_OPERATION_DELETE -> "DELETE"; - default -> ""; - }; - } - - private String aggregateTypeName(ApplyWorldDesignMutationRequest request) { - return switch (request.getAggregateType()) { - case WORLD_DESIGN_AGGREGATE_TYPE_REGION -> "REGION"; - case WORLD_DESIGN_AGGREGATE_TYPE_ZONE -> "ZONE"; - case WORLD_DESIGN_AGGREGATE_TYPE_ROOM -> "ROOM"; - case WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT -> "ROOM_EXIT"; - case WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE -> "GENERATION_RULE"; - case WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING -> "WORLD_ENTITY_SPAWN_BINDING"; - case WORLD_DESIGN_AGGREGATE_TYPE_WORLD_GENERATION_SUBTREE -> "WORLD_GENERATION_SUBTREE"; - default -> ""; - }; - } - - private WorldDesignMutationRequestDto.RegionMutationDto toDto(RegionDesignMutation mutation) { - return new WorldDesignMutationRequestDto.RegionMutationDto( - mutation.getName(), - mutation.getWeather(), - mutation.getShardId(), - mutation.getGenerationSeed(), - mutation.getGeneratorType(), - mutation.getGeneratorParams(), - mutation.getSpacingMultiplier()); - } - - private WorldDesignMutationRequestDto.ZoneMutationDto toDto(ZoneDesignMutation mutation) { - return new WorldDesignMutationRequestDto.ZoneMutationDto( - mutation.getName(), mutation.getRegionId()); - } - - private WorldDesignMutationRequestDto.RoomMutationDto toDto(RoomDesignMutation mutation) { - return new WorldDesignMutationRequestDto.RoomMutationDto( - mutation.getName(), - mutation.getDescription(), - mutation.getZoneId(), - mutation.getNameLocalizedVariantsJson(), - mutation.getDescriptionLocalizedVariantsJson()); - } - - private WorldDesignMutationRequestDto.RoomExitMutationDto toDto(RoomExitDesignMutation mutation) { - return new WorldDesignMutationRequestDto.RoomExitMutationDto( - mutation.getFromRoomId(), - mutation.getToRoomId(), - mutation.getDirection(), - mutation.getCost()); - } - - private WorldDesignMutationRequestDto.GenerationRuleMutationDto toDto( - GenerationRuleDesignMutation mutation) { - return new WorldDesignMutationRequestDto.GenerationRuleMutationDto( - mutation.getName(), mutation.getValue()); - } - - private WorldDesignMutationRequestDto.WorldEntitySpawnBindingMutationDto toDto( - WorldEntitySpawnBindingDesignMutation mutation) { - return new WorldDesignMutationRequestDto.WorldEntitySpawnBindingMutationDto( - mutation.getRoomId(), - mutation.getEntityTemplateType().name().replace("ENTITY_TEMPLATE_REFERENCE_TYPE_", ""), - mutation.getEntityTemplateId(), - mutation.getSpawnCount(), - mutation.getRespawnDelaySeconds()); - } - - private WorldDesignMutationRequestDto.WorldGenerationSubtreeMutationDto toDto( - WorldGenerationSubtreeDesignMutation mutation) { - List generationRules = - mutation.getGenerationRulesList().stream().map(this::toDto).toList(); - List rooms = - mutation.getRoomsList().stream().map(this::toDto).toList(); - List roomExits = - mutation.getRoomExitsList().stream().map(this::toDto).toList(); - List spawnBindings = - mutation.getWorldEntitySpawnBindingsList().stream().map(this::toDto).toList(); - return new WorldDesignMutationRequestDto.WorldGenerationSubtreeMutationDto( - generationRules, rooms, roomExits, spawnBindings); - } - - private WorldDesignMutationRequestDto.GeneratedRoomMutationDto toDto( - GeneratedRoomDesignMutation mutation) { - return new WorldDesignMutationRequestDto.GeneratedRoomMutationDto( - mutation.getClientRef(), - mutation.getName(), - mutation.getDescription(), - mutation.getZoneId(), - mutation.getNameLocalizedVariantsJson(), - mutation.getDescriptionLocalizedVariantsJson()); - } - - private WorldDesignMutationRequestDto.GeneratedRoomExitMutationDto toDto( - GeneratedRoomExitDesignMutation mutation) { - return new WorldDesignMutationRequestDto.GeneratedRoomExitMutationDto( - mutation.getFromRoomRef(), - mutation.getToRoomRef(), - mutation.getDirection(), - mutation.getCost()); - } - - private WorldDesignMutationRequestDto.GeneratedWorldEntitySpawnBindingMutationDto toDto( - GeneratedWorldEntitySpawnBindingDesignMutation mutation) { - return new WorldDesignMutationRequestDto.GeneratedWorldEntitySpawnBindingMutationDto( - mutation.getRoomRef(), - mutation.getEntityTemplateType().name().replace("ENTITY_TEMPLATE_REFERENCE_TYPE_", ""), - mutation.getEntityTemplateId(), - mutation.getSpawnCount(), - mutation.getRespawnDelaySeconds()); - } - - private WorldDesignMutationResult toProtoMutationResult(String result) { - return switch (result) { - case "APPLIED" -> WorldDesignMutationResult.WORLD_DESIGN_MUTATION_RESULT_APPLIED; - case "NO_OP_ALREADY_APPLIED" -> - WorldDesignMutationResult.WORLD_DESIGN_MUTATION_RESULT_NO_OP_ALREADY_APPLIED; - default -> WorldDesignMutationResult.WORLD_DESIGN_MUTATION_RESULT_UNSPECIFIED; - }; - } - private UpgradeValidationResult toUpgradeValidationResult(String result) { return switch (result) { case "COMPATIBLE" -> UpgradeValidationResult.UPGRADE_VALIDATION_RESULT_COMPATIBLE; diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeDigest.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeDigest.java new file mode 100644 index 0000000000..6b40dbf5ed --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeDigest.java @@ -0,0 +1,112 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; + +/** Versioned World-owned request and receipt digests for fresh authored-source intake. */ +public final class WorldAuthoredSourceIntakeDigest { + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private WorldAuthoredSourceIntakeDigest() {} + + public static String requestDigest( + String targetNamespace, UUID intakeRequestId, AuthoredWorldSourceEvidence source) { + requireNonNil(intakeRequestId, "intakeRequestId"); + requireFreshSource(targetNamespace, source); + return digest( + "world-authored-source-intake-request/v1", + targetNamespace, + intakeRequestId.toString(), + source.canonicalTenantId().toString(), + source.worldSlug(), + source.operationId().toString(), + source.evidenceDigest()); + } + + public static String receiptDigest( + String targetNamespace, + UUID operationId, + String requestDigest, + AuthoredWorldSourceEvidence source, + long localTenantKey) { + requireNonNil(operationId, "operationId"); + requireDigest(requestDigest, "requestDigest"); + requireFreshSource(targetNamespace, source); + if (localTenantKey <= 0) { + throw new IllegalArgumentException("localTenantKey must be positive"); + } + return digest( + "world-authored-source-intake-receipt/v1", + targetNamespace, + operationId.toString(), + requestDigest, + source.canonicalTenantId().toString(), + source.worldSlug(), + source.operationId().toString(), + source.evidenceDigest(), + Long.toString(localTenantKey)); + } + + static void requireFreshSource(String targetNamespace, AuthoredWorldSourceEvidence source) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + Objects.requireNonNull(source, "source"); + if (!"NEW_GAME_ROW".equals(source.provenanceKind())) { + throw new IllegalArgumentException( + "Fresh World authored-source intake requires NEW_GAME_ROW provenance"); + } + if (!targetNamespace.equals(source.targetNamespace())) { + throw new IllegalArgumentException("Source namespace differs from the intake namespace"); + } + AuthoredWorldSourceDigest.validateReadSelector( + targetNamespace, source.canonicalTenantId(), source.worldSlug()); + new AuthoredWorldSourceEvidence( + source.schemaVersion(), + source.targetNamespace(), + source.registrationRequestId(), + source.operationId(), + source.requestDigest(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest()); + } + + private static String digest(String... segments) { + try { + MessageDigest hash = MessageDigest.getInstance("SHA-256"); + for (String segment : segments) { + byte[] bytes = segment.getBytes(StandardCharsets.UTF_8); + hash.update(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + hash.update((byte) ':'); + hash.update(bytes); + } + return "sha256:" + HexFormat.of().formatHex(hash.digest()); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private static void requireDigest(String value, String label) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be a canonical SHA-256 digest"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcService.java new file mode 100644 index 0000000000..71625f2840 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcService.java @@ -0,0 +1,369 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.sql.SQLException; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ReadRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeByIdRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeByIdResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldAuthoredSourceIntakeServiceGrpc; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.DataAccessException; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.TransientDataAccessException; + +/** + * Opt-in gRPC adapter for authenticated authored-source intake and exact receipt readback. World + * binds the trusted namespace locally, and each method independently requires the exact same- + * namespace Game Design mTLS peer. + */ +public final class WorldAuthoredSourceIntakeGrpcService + extends WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceImplBase { + private final WorldAuthoredSourceIntakeService intakeService; + private final String trustedNamespace; + + public WorldAuthoredSourceIntakeGrpcService( + WorldAuthoredSourceIntakeService intakeService, + @Value("${firemud.grpc.workload-namespace:}") String trustedNamespace) { + this.intakeService = Objects.requireNonNull(intakeService, "intakeService"); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.trustedNamespace = trustedNamespace; + } + + @Override + public void intakeAuthoredWorldSource( + IntakeAuthoredWorldSourceRequest request, + StreamObserver responseObserver) { + if (!requireAuthenticatedGameDesignPeerWithoutCallerContext(responseObserver)) { + return; + } + IntakeRequest binding; + try { + binding = WorldAuthoredSourceIntakeGrpcCodec.fromIntakeRequest(request); + } catch (IllegalArgumentException exception) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical World intake request is required") + .asRuntimeException()); + return; + } + if (!trustedNamespace.equals(binding.targetNamespace())) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription( + "World intake target namespace must match the authenticated workload") + .asRuntimeException()); + return; + } + + WorldAuthoredSourceIntakeReceipt receipt; + try { + receipt = + intakeService.intake( + binding.schemaVersion(), + binding.targetNamespace(), + binding.intakeRequestId(), + binding.canonicalTenantId(), + binding.worldSlug(), + binding.sourceOperationId(), + binding.expectedSourceEvidenceDigest()); + } catch (RuntimeException exception) { + respondWithOwnerFailure(responseObserver, exception); + return; + } + + IntakeAuthoredWorldSourceResponse response; + try { + response = + WorldAuthoredSourceIntakeGrpcCodec.toIntakeResponse(binding, toCommittedReceipt(receipt)); + } catch (IllegalArgumentException exception) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Committed World intake receipt is inconsistent") + .asRuntimeException()); + return; + } + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + @Override + public void readAuthoredWorldSourceIntake( + ReadAuthoredWorldSourceIntakeRequest request, + StreamObserver responseObserver) { + if (!requireAuthenticatedGameDesignPeerWithoutCallerContext(responseObserver)) { + return; + } + ReadRequest readRequest; + try { + readRequest = WorldAuthoredSourceIntakeGrpcCodec.fromReadRequest(request); + } catch (IllegalArgumentException exception) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical World intake read request is required") + .asRuntimeException()); + return; + } + if (!trustedNamespace.equals(readRequest.binding().targetNamespace())) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription( + "World intake target namespace must match the authenticated workload") + .asRuntimeException()); + return; + } + + Optional stored; + try { + IntakeRequest binding = readRequest.binding(); + stored = + intakeService.readCommittedReceipt( + binding.schemaVersion(), + binding.targetNamespace(), + readRequest.requestId(), + binding.intakeRequestId(), + binding.canonicalTenantId(), + binding.worldSlug(), + binding.sourceOperationId(), + binding.expectedSourceEvidenceDigest()); + } catch (RuntimeException exception) { + respondWithOwnerFailure(responseObserver, exception); + return; + } + if (stored.isEmpty()) { + responseObserver.onError( + Status.NOT_FOUND + .withDescription("No committed World intake matches the exact request") + .asRuntimeException()); + return; + } + + ReadAuthoredWorldSourceIntakeResponse response; + try { + response = + WorldAuthoredSourceIntakeGrpcCodec.toReadResponse( + readRequest, toCommittedReceipt(stored.orElseThrow())); + } catch (IllegalArgumentException exception) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Committed World intake receipt is inconsistent") + .asRuntimeException()); + return; + } + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + @Override + public void readAuthoredWorldSourceIntakeById( + ReadAuthoredWorldSourceIntakeByIdRequest request, + StreamObserver responseObserver) { + if (!requireAuthenticatedGameDesignPeerWithoutCallerContext(responseObserver)) { + return; + } + ByIdReadRequest readRequest; + try { + readRequest = WorldAuthoredSourceIntakeGrpcCodec.fromReadByIdRequest(request); + } catch (IllegalArgumentException exception) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical World intake by-ID read request is required") + .asRuntimeException()); + return; + } + if (!trustedNamespace.equals(readRequest.targetNamespace())) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription( + "World intake target namespace must match the authenticated workload") + .asRuntimeException()); + return; + } + + Optional stored; + try { + stored = + intakeService.readCommittedReceiptById( + readRequest.schemaVersion(), + readRequest.targetNamespace(), + readRequest.readRequestId(), + readRequest.intakeRequestId(), + readRequest.canonicalTenantId()); + } catch (RuntimeException exception) { + respondWithOwnerFailure(responseObserver, exception); + return; + } + if (stored.isEmpty()) { + responseObserver.onError( + Status.NOT_FOUND + .withDescription("No committed World intake matches the exact request") + .asRuntimeException()); + return; + } + + ReadAuthoredWorldSourceIntakeByIdResponse response; + try { + response = + WorldAuthoredSourceIntakeGrpcCodec.toReadByIdResponse( + readRequest, toPublicReceipt(stored.orElseThrow())); + } catch (IllegalArgumentException exception) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Committed World intake receipt is inconsistent") + .asRuntimeException()); + return; + } + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + private static CommittedReceipt toCommittedReceipt(WorldAuthoredSourceIntakeReceipt receipt) { + if (receipt == null) { + throw new IllegalArgumentException("World owner returned no committed intake receipt"); + } + return new CommittedReceipt( + receipt.schemaVersion(), + receipt.targetNamespace(), + receipt.intakeRequestId(), + receipt.operationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + receipt.requestDigest(), + receipt.receiptDigest()); + } + + private static PublicReceipt toPublicReceipt(WorldAuthoredSourceIntakeReceipt receipt) { + if (receipt == null) { + throw new IllegalArgumentException("World owner returned no committed intake receipt"); + } + return new PublicReceipt( + receipt.schemaVersion(), + receipt.targetNamespace(), + receipt.intakeRequestId(), + receipt.operationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + receipt.requestDigest(), + receipt.receiptDigest(), + receipt.source()); + } + + private boolean requireAuthenticatedGameDesignPeerWithoutCallerContext( + StreamObserver responseObserver) { + if (!SessionContext.hasAuthenticatedCallerContext() + && GrpcPeerIdentity.current() != null + && GrpcPeerIdentity.current().isService("game-design-service") + && GrpcPeerIdentity.current().isInNamespace(trustedNamespace)) { + return true; + } + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription( + "Verified same-namespace Game Design workload without caller context is required") + .asRuntimeException()); + return false; + } + + private static void respondWithOwnerFailure( + StreamObserver responseObserver, RuntimeException exception) { + if (exception instanceof StatusRuntimeException statusException) { + Status.Code code = statusException.getStatus().getCode(); + if (code == Status.Code.UNAVAILABLE) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("World intake dependency is temporarily unavailable") + .asRuntimeException()); + } else if (code == Status.Code.DEADLINE_EXCEEDED) { + responseObserver.onError( + Status.DEADLINE_EXCEEDED + .withDescription("World intake dependency read timed out") + .asRuntimeException()); + } else { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("World authored-source intake has no exact committed proof") + .asRuntimeException()); + } + } else if (exception instanceof SecurityException) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Verified same-namespace Game Design workload is required") + .asRuntimeException()); + } else if (exception + instanceof WorldAuthoredSourceIntakeRepository.RegistrationConflictException + || exception + instanceof WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("World authored-source intake conflicts with committed evidence") + .asRuntimeException()); + } else if (exception instanceof IllegalArgumentException) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical World intake binding is required") + .asRuntimeException()); + } else if (hasUnavailableSqlState(exception)) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("World intake is temporarily unavailable") + .asRuntimeException()); + } else if (exception instanceof DataAccessResourceFailureException + || exception instanceof TransientDataAccessException) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("World intake is temporarily unavailable") + .asRuntimeException()); + } else if (exception instanceof DataAccessException + || exception instanceof org.jooq.exception.DataAccessException) { + responseObserver.onError( + Status.INTERNAL + .withDescription("World intake storage could not complete the request") + .asRuntimeException()); + } else if (exception instanceof IllegalStateException) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("World intake is unavailable in the current transaction state") + .asRuntimeException()); + } else { + responseObserver.onError( + Status.INTERNAL + .withDescription("World authored-source intake failed") + .asRuntimeException()); + } + } + + private static boolean hasUnavailableSqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException exception) { + String sqlState = exception.getSQLState(); + if (sqlState != null + && (sqlState.startsWith("08") + || "55P03".equals(sqlState) + || "40P01".equals(sqlState))) { + return true; + } + } + } + return false; + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeReceipt.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeReceipt.java new file mode 100644 index 0000000000..b25bbf5c34 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeReceipt.java @@ -0,0 +1,61 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; + +/** Complete immutable World-owned receipt for one fresh Game Design source intake. */ +public record WorldAuthoredSourceIntakeReceipt( + int schemaVersion, + String targetNamespace, + UUID intakeRequestId, + UUID operationId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest, + String requestDigest, + String receiptDigest, + long localTenantKey, + AuthoredWorldSourceEvidence source) { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public WorldAuthoredSourceIntakeReceipt { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported World authored-source receipt version"); + } + Objects.requireNonNull(targetNamespace, "targetNamespace"); + requireNonNil(intakeRequestId, "intakeRequestId"); + requireNonNil(operationId, "operationId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(worldSlug, "worldSlug"); + requireNonNil(sourceOperationId, "sourceOperationId"); + Objects.requireNonNull(sourceEvidenceDigest, "sourceEvidenceDigest"); + Objects.requireNonNull(requestDigest, "requestDigest"); + Objects.requireNonNull(receiptDigest, "receiptDigest"); + Objects.requireNonNull(source, "source"); + if (localTenantKey <= 0) { + throw new IllegalArgumentException("localTenantKey must be positive"); + } + WorldAuthoredSourceIntakeDigest.requireFreshSource(targetNamespace, source); + if (!targetNamespace.equals(source.targetNamespace()) + || !canonicalTenantId.equals(source.canonicalTenantId()) + || !worldSlug.equals(source.worldSlug()) + || !sourceOperationId.equals(source.operationId()) + || !sourceEvidenceDigest.equals(source.evidenceDigest()) + || !requestDigest.equals( + WorldAuthoredSourceIntakeDigest.requestDigest(targetNamespace, intakeRequestId, source)) + || !receiptDigest.equals( + WorldAuthoredSourceIntakeDigest.receiptDigest( + targetNamespace, operationId, requestDigest, source, localTenantKey))) { + throw new IllegalArgumentException("World authored-source receipt fields or digests differ"); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeRepository.java new file mode 100644 index 0000000000..ef5fd28ecc --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeRepository.java @@ -0,0 +1,698 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * World-owned immutable copy of authenticated, fresh Game Design authored-world source evidence. + */ +@Repository +public class WorldAuthoredSourceIntakeRepository { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Table TENANT_ASSOCIATION = + DSL.table(DSL.name("world_authored_source_tenant_association")); + private static final Table TENANT_KEY_RESERVATION = + DSL.table(DSL.name("world_authored_source_tenant_key_reservation")); + private static final Table INTAKE = DSL.table(DSL.name("world_authored_source_intake")); + + 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 TENANT_SLUG = DSL.field(DSL.name("tenant_slug"), String.class); + private static final Field SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("source_game_row_id"), Long.class); + private static final Field SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("source_game_tenant_key"), String.class); + private static final Field SOURCE_PROVENANCE_KIND = + DSL.field(DSL.name("source_provenance_kind"), String.class); + private static final Field LOCAL_TENANT_KEY = + DSL.field(DSL.name("local_tenant_key"), Long.class); + private static final Field RESERVED_TENANT_KEY = + DSL.field(DSL.name("tenant_key"), Long.class); + private static final Field RESERVATION_CLAIM_KIND = + DSL.field(DSL.name("claim_kind"), String.class); + private static final Field RESERVATION_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field RESERVATION_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + + private static final Field OPERATION_ID = DSL.field(DSL.name("operation_id"), UUID.class); + private static final Field STORED_SCHEMA_VERSION = + DSL.field(DSL.name("schema_version"), Short.class); + private static final Field INTAKE_REQUEST_ID = + DSL.field(DSL.name("intake_request_id"), UUID.class); + private static final Field REQUEST_DIGEST = + DSL.field(DSL.name("request_digest"), String.class); + private static final Field SOURCE_SCHEMA_VERSION = + DSL.field(DSL.name("source_schema_version"), Short.class); + private static final Field SOURCE_REGISTRATION_REQUEST_ID = + DSL.field(DSL.name("source_registration_request_id"), UUID.class); + private static final Field SOURCE_OPERATION_ID = + DSL.field(DSL.name("source_operation_id"), UUID.class); + private static final Field SOURCE_REQUEST_DIGEST = + DSL.field(DSL.name("source_request_digest"), String.class); + private static final Field WORLD_SLUG = DSL.field(DSL.name("world_slug"), String.class); + private static final Field WORLD_DISPLAY_NAME = + DSL.field(DSL.name("world_display_name"), String.class); + private static final Field SOURCE_EVIDENCE_DIGEST = + DSL.field(DSL.name("source_evidence_digest"), String.class); + private static final Field RECEIPT_DIGEST = + DSL.field(DSL.name("receipt_digest"), String.class); + + private static final String LOCK_LEGACY_TENANT_TABLES = + "LOCK TABLE generation_rule, instance, region, region_instance, room, room_exit, " + + "room_instance, room_instance_exit, world_design_aggregate_epoch, " + + "world_design_revision_ledger, world_design_scope_epoch, " + + "world_entity_spawn_binding, world_event, world_instance, zone, zone_instance " + + "IN SHARE MODE"; + private static final String SET_FRESH_INTAKE_LOCK_TIMEOUT = + "SELECT set_config('lock_timeout', " + + "LEAST(COALESCE(NULLIF(setting::integer, 0), 1000), 1000)::text || 'ms', true) " + + "FROM pg_settings WHERE name = 'lock_timeout'"; + private static final String MAX_OCCUPIED_TENANT_KEY = + "SELECT COALESCE(GREATEST(" + + "(SELECT MAX(tenant_id) FROM generation_rule), " + + "(SELECT MAX(tenant_id) FROM instance), " + + "(SELECT MAX(tenant_id) FROM region), " + + "(SELECT MAX(tenant_id) FROM region_instance), " + + "(SELECT MAX(tenant_id) FROM room), " + + "(SELECT MAX(tenant_id) FROM room_exit), " + + "(SELECT MAX(tenant_id) FROM room_instance), " + + "(SELECT MAX(tenant_id) FROM room_instance_exit), " + + "(SELECT MAX(tenant_id) FROM world_design_aggregate_epoch), " + + "(SELECT MAX(tenant_id) FROM world_design_revision_ledger), " + + "(SELECT MAX(tenant_id) FROM world_design_scope_epoch), " + + "(SELECT MAX(tenant_id) FROM world_entity_spawn_binding), " + + "(SELECT MAX(tenant_id) FROM world_event), " + + "(SELECT MAX(tenant_id) FROM world_instance), " + + "(SELECT MAX(tenant_id) FROM zone), " + + "(SELECT MAX(tenant_id) FROM zone_instance), " + + "(SELECT MAX(tenant_key) FROM world_authored_source_tenant_key_reservation), " + + "(SELECT MAX(local_tenant_key) FROM world_authored_source_tenant_association)), 0)"; + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The injected DSLContext is an internal Spring collaborator; construction acquires no resources and this repository has no finalizer.") + public WorldAuthoredSourceIntakeRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + } + + /** + * Retains the complete fresh Game Design receipt and its World-local tenant association. + * + *

The caller must already have authenticated Game Design and opened the World owner + * transaction. This method does not accept a forwarded digest in place of source evidence. + */ + @Transactional(propagation = Propagation.MANDATORY) + public WorldAuthoredSourceIntakeReceipt acceptFresh( + String namespace, UUID intakeRequestId, AuthoredWorldSourceEvidence source) { + requireActiveOwnerTransaction(); + requireWritableReadCommittedOwnerTransaction(); + AuthoredWorldSourceEvidence validatedSource = validateFreshSource(namespace, source); + String requestDigest = + WorldAuthoredSourceIntakeDigest.requestDigest(namespace, intakeRequestId, validatedSource); + + Record priorRequest = findByRequest(namespace, intakeRequestId); + if (priorRequest != null) { + return requireExactReplay(priorRequest, intakeRequestId, requestDigest, validatedSource); + } + + lockFreshIntakeAndExistingTenantRows(); + + priorRequest = findByRequest(namespace, intakeRequestId); + if (priorRequest != null) { + return requireExactReplay(priorRequest, intakeRequestId, requestDigest, validatedSource); + } + requireUnclaimedSourceAndWorld(namespace, validatedSource); + + long localTenantKey = ensureTenantAssociation(validatedSource); + UUID operationId = UUID.randomUUID(); + String receiptDigest = + WorldAuthoredSourceIntakeDigest.receiptDigest( + namespace, operationId, requestDigest, validatedSource, localTenantKey); + + int inserted = + dsl.insertInto(INTAKE) + .set(OPERATION_ID, operationId) + .set(STORED_SCHEMA_VERSION, (short) SCHEMA_VERSION) + .set(TARGET_NAMESPACE, namespace) + .set(INTAKE_REQUEST_ID, intakeRequestId) + .set(REQUEST_DIGEST, requestDigest) + .set(LOCAL_TENANT_KEY, localTenantKey) + .set(SOURCE_SCHEMA_VERSION, (short) validatedSource.schemaVersion()) + .set(SOURCE_REGISTRATION_REQUEST_ID, validatedSource.registrationRequestId()) + .set(SOURCE_OPERATION_ID, validatedSource.operationId()) + .set(SOURCE_REQUEST_DIGEST, validatedSource.requestDigest()) + .set(CANONICAL_TENANT_ID, validatedSource.canonicalTenantId()) + .set(TENANT_SLUG, validatedSource.tenantSlug()) + .set(WORLD_SLUG, validatedSource.worldSlug()) + .set(WORLD_DISPLAY_NAME, validatedSource.worldDisplayName()) + .set(SOURCE_GAME_ROW_ID, validatedSource.sourceGameRowId()) + .set(SOURCE_GAME_TENANT_KEY, validatedSource.sourceGameTenantKey()) + .set(SOURCE_PROVENANCE_KIND, validatedSource.provenanceKind()) + .set(SOURCE_EVIDENCE_DIGEST, validatedSource.evidenceDigest()) + .set(RECEIPT_DIGEST, receiptDigest) + .execute(); + if (inserted != 1) { + throw new RegistrationConflictException("World authored-source intake was not inserted"); + } + + Record persisted = findByRequest(namespace, intakeRequestId); + if (persisted == null) { + throw new InvalidIntakeEvidenceException( + "World authored-source intake disappeared before owner readback"); + } + WorldAuthoredSourceIntakeReceipt receipt = toReceipt(persisted); + requireExactReceipt(receipt, intakeRequestId, requestDigest, validatedSource); + requireTenantAssociation(receipt); + return receipt; + } + + /** Reads a committed World intake by its exact namespace and stable request identity. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional read(String namespace, UUID intakeRequestId) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World authored-source intake read requires a committed-outcome owner read"); + } + return readValidated(namespace, intakeRequestId); + } + + /** Reads the same immutable intake and tenant reservation within a verified owner snapshot. */ + Optional readInOwnerReadOnlyRepeatableRead( + String namespace, UUID intakeRequestId) { + requireReadOnlyRepeatableReadOwnerTransaction(); + return readValidated(namespace, intakeRequestId); + } + + /** + * Reconstructs the same immutable intake inside the writable canonical activation transaction. + */ + Optional readInOwnerActivationTransaction( + String namespace, UUID intakeRequestId) { + requireWritablePhysicalReadCommittedOwnerTransaction(); + return readValidated(namespace, intakeRequestId); + } + + /** Reads the same immutable intake inside the writable publication-owner transaction. */ + Optional readInOwnerPublicationTransaction( + String namespace, UUID intakeRequestId) { + requireWritablePhysicalReadCommittedOwnerTransaction(); + return readValidated(namespace, intakeRequestId); + } + + private Optional readValidated( + String namespace, UUID intakeRequestId) { + validateReadKey(namespace, intakeRequestId); + Record record = findByRequest(namespace, intakeRequestId); + if (record == null) { + return Optional.empty(); + } + WorldAuthoredSourceIntakeReceipt receipt = toReceipt(record); + requireTenantAssociation(receipt); + return Optional.of(receipt); + } + + /** Reads a committed World intake by its exact canonical source-owned binding. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readBySource( + String namespace, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World authored-source intake read requires a committed-outcome owner read"); + } + validateSourceReadKey( + namespace, canonicalTenantId, worldSlug, sourceOperationId, sourceEvidenceDigest); + Record record = + dsl.selectFrom(INTAKE) + .where( + TARGET_NAMESPACE + .eq(namespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(WORLD_SLUG.eq(worldSlug)) + .and(SOURCE_OPERATION_ID.eq(sourceOperationId)) + .and(SOURCE_EVIDENCE_DIGEST.eq(sourceEvidenceDigest))) + .fetchOne(); + if (record == null) { + return Optional.empty(); + } + WorldAuthoredSourceIntakeReceipt receipt = toReceipt(record); + requireTenantAssociation(receipt); + return Optional.of(receipt); + } + + private void lockFreshIntakeAndExistingTenantRows() { + // Serialize allocator owners, then keep every current tenant-bearing table stable while the + // candidate is checked. Legacy writers do not take this association lock; their database + // reservation trigger rejects selectors already claimed by a canonical source. + dsl.fetchOne(SET_FRESH_INTAKE_LOCK_TIMEOUT); + dsl.execute("LOCK TABLE world_authored_source_tenant_association IN SHARE ROW EXCLUSIVE MODE"); + dsl.execute(LOCK_LEGACY_TENANT_TABLES); + } + + private void requireUnclaimedSourceAndWorld( + String namespace, AuthoredWorldSourceEvidence source) { + if (findBySourceOperation(namespace, source.operationId()) != null) { + throw new RegistrationConflictException( + "Game Design source operation is already claimed by another World intake"); + } + if (findBySourceRegistrationRequest(namespace, source.registrationRequestId()) != null) { + throw new RegistrationConflictException( + "Game Design source registration request is already claimed by another World intake"); + } + if (findByWorldSelector(namespace, source.canonicalTenantId(), source.worldSlug()) != null) { + throw new RegistrationConflictException( + "World selector is already associated with different source evidence"); + } + } + + private long ensureTenantAssociation(AuthoredWorldSourceEvidence source) { + Record existing = findTenantAssociation(source.targetNamespace(), source.canonicalTenantId()); + if (existing != null) { + requireMatchingTenantAssociation(existing, source); + long existingKey = Objects.requireNonNull(existing.get(LOCAL_TENANT_KEY, Long.class)); + requireCanonicalTenantKeyReservation(source, existingKey); + return existingKey; + } + + if (findTenantSlugAssociation(source.targetNamespace(), source.tenantSlug()) != null) { + throw new RegistrationConflictException( + "Tenant selector is already associated with another canonical tenant"); + } + if (findSourceRowAssociation(source.targetNamespace(), source.sourceGameRowId()) != null) { + throw new RegistrationConflictException( + "Game Design source row is already associated with another canonical tenant"); + } + + long localTenantKey = nextUnclaimedTenantKey(); + int inserted = + dsl.insertInto(TENANT_ASSOCIATION) + .set(TARGET_NAMESPACE, source.targetNamespace()) + .set(CANONICAL_TENANT_ID, source.canonicalTenantId()) + .set(TENANT_SLUG, source.tenantSlug()) + .set(SOURCE_GAME_ROW_ID, source.sourceGameRowId()) + .set(SOURCE_GAME_TENANT_KEY, source.sourceGameTenantKey()) + .set(SOURCE_PROVENANCE_KIND, source.provenanceKind()) + .set(LOCAL_TENANT_KEY, localTenantKey) + .onConflictDoNothing() + .execute(); + if (inserted == 1) { + requireCanonicalTenantKeyReservation(source, localTenantKey); + return localTenantKey; + } + + existing = findTenantAssociation(source.targetNamespace(), source.canonicalTenantId()); + if (existing != null) { + requireMatchingTenantAssociation(existing, source); + long existingKey = Objects.requireNonNull(existing.get(LOCAL_TENANT_KEY, Long.class)); + requireCanonicalTenantKeyReservation(source, existingKey); + return existingKey; + } + if (findTenantSlugAssociation(source.targetNamespace(), source.tenantSlug()) != null) { + throw new RegistrationConflictException( + "Tenant selector is already associated with another canonical tenant"); + } + if (findSourceRowAssociation(source.targetNamespace(), source.sourceGameRowId()) != null) { + throw new RegistrationConflictException( + "Game Design source row is already associated with another canonical tenant"); + } + throw new RegistrationConflictException( + "World authored-source tenant association conflicts with an owner claim"); + } + + private long nextUnclaimedTenantKey() { + Record allocation = dsl.fetchOne(MAX_OCCUPIED_TENANT_KEY); + if (allocation == null) { + throw new IllegalStateException("World tenant-selector allocation aggregate returned no row"); + } + Long maxKey = allocation.get(0, Long.class); + if (maxKey == null) { + throw new IllegalStateException("World tenant-selector allocation aggregate returned null"); + } + long currentMax = maxKey; + if (currentMax == Long.MAX_VALUE) { + throw new IllegalStateException("World has no remaining positive local tenant selectors"); + } + return Math.max(currentMax, 0L) + 1L; + } + + private void requireCanonicalTenantKeyReservation( + AuthoredWorldSourceEvidence source, long localTenantKey) { + dsl.insertInto(TENANT_KEY_RESERVATION) + .set(RESERVED_TENANT_KEY, localTenantKey) + .set(RESERVATION_CLAIM_KIND, "CANONICAL_AUTHORED_SOURCE") + .set(RESERVATION_NAMESPACE, source.targetNamespace()) + .set(RESERVATION_CANONICAL_TENANT_ID, source.canonicalTenantId()) + .onConflictDoNothing() + .execute(); + Record reservation = findTenantKeyReservation(localTenantKey); + if (reservation == null + || !Objects.equals( + reservation.get(RESERVATION_CLAIM_KIND, String.class), "CANONICAL_AUTHORED_SOURCE") + || !Objects.equals( + reservation.get(RESERVATION_NAMESPACE, String.class), source.targetNamespace()) + || !Objects.equals( + reservation.get(RESERVATION_CANONICAL_TENANT_ID, UUID.class), + source.canonicalTenantId())) { + throw new RegistrationConflictException( + "World local tenant selector is already reserved by another claim"); + } + } + + private void requireTenantAssociation(WorldAuthoredSourceIntakeReceipt receipt) { + Record association = + findTenantAssociation(receipt.targetNamespace(), receipt.canonicalTenantId()); + if (association == null) { + throw new InvalidIntakeEvidenceException( + "World authored-source tenant association is missing"); + } + requireMatchingTenantAssociation(association, receipt.source()); + if (!Objects.equals(association.get(LOCAL_TENANT_KEY, Long.class), receipt.localTenantKey())) { + throw new InvalidIntakeEvidenceException( + "World authored-source private tenant selector differs from its association"); + } + Record reservation = findTenantKeyReservation(receipt.localTenantKey()); + if (reservation == null + || !Objects.equals( + reservation.get(RESERVATION_CLAIM_KIND, String.class), "CANONICAL_AUTHORED_SOURCE") + || !Objects.equals( + reservation.get(RESERVATION_NAMESPACE, String.class), receipt.targetNamespace()) + || !Objects.equals( + reservation.get(RESERVATION_CANONICAL_TENANT_ID, UUID.class), + receipt.canonicalTenantId())) { + throw new InvalidIntakeEvidenceException( + "World authored-source private tenant selector reservation is missing or changed"); + } + } + + private Record findTenantKeyReservation(long tenantKey) { + return dsl.selectFrom(TENANT_KEY_RESERVATION) + .where(RESERVED_TENANT_KEY.eq(tenantKey)) + .fetchOne(); + } + + private void requireMatchingTenantAssociation( + Record association, AuthoredWorldSourceEvidence source) { + if (!Objects.equals(association.get(TARGET_NAMESPACE, String.class), source.targetNamespace()) + || !Objects.equals( + association.get(CANONICAL_TENANT_ID, UUID.class), source.canonicalTenantId()) + || !Objects.equals(association.get(TENANT_SLUG, String.class), source.tenantSlug()) + || !Objects.equals( + association.get(SOURCE_GAME_ROW_ID, Long.class), source.sourceGameRowId()) + || !Objects.equals( + association.get(SOURCE_GAME_TENANT_KEY, String.class), source.sourceGameTenantKey()) + || !Objects.equals( + association.get(SOURCE_PROVENANCE_KIND, String.class), source.provenanceKind())) { + throw new RegistrationConflictException( + "Canonical tenant source or stable tenant selector conflicts with its World association"); + } + } + + private WorldAuthoredSourceIntakeReceipt requireExactReplay( + Record record, + UUID intakeRequestId, + String requestDigest, + AuthoredWorldSourceEvidence source) { + WorldAuthoredSourceIntakeReceipt receipt = toReceipt(record); + requireExactReceipt(receipt, intakeRequestId, requestDigest, source); + requireTenantAssociation(receipt); + return receipt; + } + + private void requireExactReceipt( + WorldAuthoredSourceIntakeReceipt receipt, + UUID intakeRequestId, + String requestDigest, + AuthoredWorldSourceEvidence source) { + if (!receipt.intakeRequestId().equals(intakeRequestId) + || !receipt.requestDigest().equals(requestDigest) + || !receipt.source().equals(source)) { + throw new RegistrationConflictException( + "World intake request identity was reused with changed scope or source evidence"); + } + } + + private AuthoredWorldSourceEvidence validateFreshSource( + String namespace, AuthoredWorldSourceEvidence source) { + Objects.requireNonNull(namespace, "namespace"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new InvalidIntakeEvidenceException( + "World authored-source target namespace must be one canonical DNS label"); + } + Objects.requireNonNull(source, "source"); + try { + AuthoredWorldSourceEvidence validated = + new AuthoredWorldSourceEvidence( + source.schemaVersion(), + source.targetNamespace(), + source.registrationRequestId(), + source.operationId(), + source.requestDigest(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest()); + WorldAuthoredSourceIntakeDigest.requireFreshSource(namespace, validated); + return validated; + } catch (IllegalArgumentException exception) { + throw new InvalidIntakeEvidenceException( + "Game Design authored-world source evidence is invalid or not fresh", exception); + } + } + + private void validateReadKey(String namespace, UUID intakeRequestId) { + if (namespace == null || !GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("namespace must be one canonical DNS label"); + } + requireNonNil(intakeRequestId, "intakeRequestId"); + } + + private void validateSourceReadKey( + String namespace, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest) { + AuthoredWorldSourceDigest.validateReadSelector(namespace, canonicalTenantId, worldSlug); + requireNonNil(sourceOperationId, "sourceOperationId"); + if (!GameTenantCreationDigest.isDigest(sourceEvidenceDigest)) { + throw new IllegalArgumentException( + "sourceEvidenceDigest must be a canonical lowercase SHA-256 digest"); + } + } + + private void requireActiveOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World authored-source intake requires an active World owner transaction"); + } + } + + private void requireReadOnlyRepeatableReadOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World authored-source snapshot read requires a read-only REPEATABLE READ owner transaction"); + } + Record state = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"), + "World transaction state query returned no row"); + if (!"repeatable read".equals(state.get("isolation", String.class)) + || !"on".equals(state.get("read_only", String.class))) { + throw new IllegalStateException( + "World authored-source snapshot read requires a read-only REPEATABLE READ owner transaction"); + } + } + + private void requireWritablePhysicalReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World authored-source owner read requires a writable READ COMMITTED owner transaction"); + } + Record state = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"), + "World transaction state query returned no row"); + if (!"read committed".equals(state.get("isolation", String.class)) + || !"off".equals(state.get("read_only", String.class))) { + throw new IllegalStateException( + "World authored-source owner read requires a writable READ COMMITTED owner transaction"); + } + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "World authored-source intake requires a writable owner transaction"); + } + Integer declaredIsolation = + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (declaredIsolation != null && declaredIsolation != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "World authored-source intake requires READ COMMITTED isolation"); + } + Record settings = + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS transaction_isolation, " + + "current_setting('transaction_read_only') AS transaction_read_only"); + if (settings == null + || !"read committed".equalsIgnoreCase(settings.get("transaction_isolation", String.class)) + || !"off".equalsIgnoreCase(settings.get("transaction_read_only", String.class))) { + throw new IllegalStateException( + "World authored-source intake requires a writable READ COMMITTED owner transaction"); + } + } + + private Record findByRequest(String namespace, UUID intakeRequestId) { + return dsl.selectFrom(INTAKE) + .where(TARGET_NAMESPACE.eq(namespace).and(INTAKE_REQUEST_ID.eq(intakeRequestId))) + .fetchOne(); + } + + private Record findBySourceOperation(String namespace, UUID sourceOperationId) { + return dsl.selectFrom(INTAKE) + .where(TARGET_NAMESPACE.eq(namespace).and(SOURCE_OPERATION_ID.eq(sourceOperationId))) + .fetchOne(); + } + + private Record findBySourceRegistrationRequest(String namespace, UUID sourceRequestId) { + return dsl.selectFrom(INTAKE) + .where( + TARGET_NAMESPACE.eq(namespace).and(SOURCE_REGISTRATION_REQUEST_ID.eq(sourceRequestId))) + .fetchOne(); + } + + private Record findByWorldSelector(String namespace, UUID tenantId, String worldSlug) { + return dsl.selectFrom(INTAKE) + .where( + TARGET_NAMESPACE + .eq(namespace) + .and(CANONICAL_TENANT_ID.eq(tenantId)) + .and(WORLD_SLUG.eq(worldSlug))) + .fetchOne(); + } + + private Record findTenantAssociation(String namespace, UUID canonicalTenantId) { + return dsl.selectFrom(TENANT_ASSOCIATION) + .where(TARGET_NAMESPACE.eq(namespace).and(CANONICAL_TENANT_ID.eq(canonicalTenantId))) + .fetchOne(); + } + + private Record findTenantSlugAssociation(String namespace, String tenantSlug) { + return dsl.selectFrom(TENANT_ASSOCIATION) + .where(TARGET_NAMESPACE.eq(namespace).and(TENANT_SLUG.eq(tenantSlug))) + .fetchOne(); + } + + private Record findSourceRowAssociation(String namespace, long sourceGameRowId) { + return dsl.selectFrom(TENANT_ASSOCIATION) + .where(TARGET_NAMESPACE.eq(namespace).and(SOURCE_GAME_ROW_ID.eq(sourceGameRowId))) + .fetchOne(); + } + + private WorldAuthoredSourceIntakeReceipt toReceipt(Record record) { + try { + Short schemaVersion = Objects.requireNonNull(record.get(STORED_SCHEMA_VERSION, Short.class)); + Short sourceSchemaVersion = + Objects.requireNonNull(record.get(SOURCE_SCHEMA_VERSION, Short.class)); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + sourceSchemaVersion.intValue(), + Objects.requireNonNull(record.get(TARGET_NAMESPACE, String.class)), + Objects.requireNonNull(record.get(SOURCE_REGISTRATION_REQUEST_ID, UUID.class)), + Objects.requireNonNull(record.get(SOURCE_OPERATION_ID, UUID.class)), + Objects.requireNonNull(record.get(SOURCE_REQUEST_DIGEST, String.class)), + Objects.requireNonNull(record.get(CANONICAL_TENANT_ID, UUID.class)), + Objects.requireNonNull(record.get(TENANT_SLUG, String.class)), + Objects.requireNonNull(record.get(WORLD_SLUG, String.class)), + Objects.requireNonNull(record.get(WORLD_DISPLAY_NAME, String.class)), + Objects.requireNonNull(record.get(SOURCE_GAME_ROW_ID, Long.class)), + Objects.requireNonNull(record.get(SOURCE_GAME_TENANT_KEY, String.class)), + Objects.requireNonNull(record.get(SOURCE_PROVENANCE_KIND, String.class)), + Objects.requireNonNull(record.get(SOURCE_EVIDENCE_DIGEST, String.class))); + if (schemaVersion.intValue() != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported local intake schema version"); + } + return new WorldAuthoredSourceIntakeReceipt( + schemaVersion.intValue(), + Objects.requireNonNull(record.get(TARGET_NAMESPACE, String.class)), + Objects.requireNonNull(record.get(INTAKE_REQUEST_ID, UUID.class)), + Objects.requireNonNull(record.get(OPERATION_ID, UUID.class)), + Objects.requireNonNull(record.get(CANONICAL_TENANT_ID, UUID.class)), + Objects.requireNonNull(record.get(WORLD_SLUG, String.class)), + source.operationId(), + source.evidenceDigest(), + Objects.requireNonNull(record.get(REQUEST_DIGEST, String.class)), + Objects.requireNonNull(record.get(RECEIPT_DIGEST, String.class)), + Objects.requireNonNull(record.get(LOCAL_TENANT_KEY, Long.class)), + source); + } catch (RuntimeException exception) { + if (exception instanceof InvalidIntakeEvidenceException) { + throw exception; + } + throw new InvalidIntakeEvidenceException( + "Persisted World authored-source intake evidence is invalid", exception); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + public static final class RegistrationConflictException extends IllegalStateException { + public RegistrationConflictException(String message) { + super(message); + } + } + + public static final class InvalidIntakeEvidenceException extends IllegalStateException { + public InvalidIntakeEvidenceException(String message) { + super(message); + } + + public InvalidIntakeEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeService.java new file mode 100644 index 0000000000..873d90e4bd --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeService.java @@ -0,0 +1,378 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec.ReadRequest; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unwired World owner intake. A fresh, authenticated Game Design source read precedes the local + * transaction that retains its complete evidence and private tenant association. + */ +public class WorldAuthoredSourceIntakeService { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final AuthoredWorldSourceClient sourceClient; + private final WorldAuthoredSourceIntakeRepository repository; + private final TransactionTemplate ownerTransaction; + private final String workloadNamespace; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Trusted owner configuration is validated before use; no resources or finalizer are " + + "acquired.") + public WorldAuthoredSourceIntakeService( + AuthoredWorldSourceClient sourceClient, + WorldAuthoredSourceIntakeRepository repository, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.sourceClient = Objects.requireNonNull(sourceClient, "sourceClient"); + this.repository = Objects.requireNonNull(repository, "repository"); + Objects.requireNonNull(transactionManager, "transactionManager"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.workloadNamespace = workloadNamespace; + this.ownerTransaction = new TransactionTemplate(transactionManager); + this.ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.ownerTransaction.setReadOnly(false); + } + + /** + * Retains one fresh source binding. The intake request identity is stable across exact retries; + * each first attempt gets a separate Game Design read identity. + */ + public WorldAuthoredSourceIntakeReceipt intake( + UUID intakeRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String expectedSourceEvidenceDigest) { + return intake( + SCHEMA_VERSION, + workloadNamespace, + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + expectedSourceEvidenceDigest); + } + + /** Accepts the complete wire binding after authenticating the exact Game Design workload. */ + public WorldAuthoredSourceIntakeReceipt intake( + int schemaVersion, + String targetNamespace, + UUID intakeRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String expectedSourceEvidenceDigest) { + requireAuthenticatedGameDesignCaller(); + validateSchemaAndNamespace(schemaVersion, targetNamespace); + requireNoAmbientTransaction(); + validateRequest( + targetNamespace, + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + expectedSourceEvidenceDigest); + + Optional prior = + repository.read(workloadNamespace, intakeRequestId); + if (prior.isPresent()) { + return requireReceiptForRequest( + prior.get(), + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + expectedSourceEvidenceDigest); + } + + AuthoredWorldSourceEvidence source = + sourceClient.read( + new ReadRequest( + workloadNamespace, + newReadRequestId(intakeRequestId), + sourceOperationId, + canonicalTenantId, + worldSlug)); + requireFreshSourceForRequest( + source, canonicalTenantId, worldSlug, sourceOperationId, expectedSourceEvidenceDigest); + + WorldAuthoredSourceIntakeReceipt accepted = + ownerTransaction.execute( + status -> repository.acceptFresh(workloadNamespace, intakeRequestId, source)); + if (accepted == null) { + throw new WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException( + "World owner transaction returned no authored-source receipt"); + } + requireReceiptForRequest( + accepted, + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + expectedSourceEvidenceDigest, + source); + + Optional committed = + repository.read(workloadNamespace, intakeRequestId); + if (committed.isEmpty()) { + throw new WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException( + "World authored-source intake is missing after commit readback"); + } + WorldAuthoredSourceIntakeReceipt readback = committed.get(); + requireReceiptForRequest( + readback, + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + expectedSourceEvidenceDigest, + source); + if (!accepted.equals(readback)) { + throw new WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException( + "World authored-source intake changed during commit readback"); + } + return readback; + } + + /** Reads only an exact committed receipt; it never re-reads Game Design or allocates state. */ + public Optional readCommittedReceipt( + int schemaVersion, + String targetNamespace, + UUID requestId, + UUID intakeRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String expectedSourceEvidenceDigest) { + requireAuthenticatedGameDesignCaller(); + validateSchemaAndNamespace(schemaVersion, targetNamespace); + requireNoAmbientTransaction(); + requireNonNil(requestId, "requestId"); + requireNonNil(intakeRequestId, "intakeRequestId"); + if (requestId.equals(intakeRequestId)) { + throw new IllegalArgumentException("Read requestId must differ from intakeRequestId"); + } + validateRequest( + targetNamespace, + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + expectedSourceEvidenceDigest); + + Optional receipt = + repository.read(targetNamespace, intakeRequestId); + if (receipt.isEmpty()) { + return Optional.empty(); + } + return Optional.of( + requireReceiptForRequest( + receipt.orElseThrow(), + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + expectedSourceEvidenceDigest)); + } + + /** Reads one committed receipt using only its retained request identity and canonical tenant. */ + public Optional readCommittedReceiptById( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + UUID intakeRequestId, + UUID canonicalTenantId) { + requireAuthenticatedGameDesignCallerWithoutCallerContext(); + validateSchemaAndNamespace(schemaVersion, targetNamespace); + requireNoAmbientTransaction(); + requireNonNil(readRequestId, "readRequestId"); + requireNonNil(intakeRequestId, "intakeRequestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + if (readRequestId.equals(intakeRequestId)) { + throw new IllegalArgumentException("Read requestId must differ from intakeRequestId"); + } + + Optional receipt = + repository.read(targetNamespace, intakeRequestId); + if (receipt.isEmpty()) { + return Optional.empty(); + } + WorldAuthoredSourceIntakeReceipt stored = receipt.orElseThrow(); + return Optional.of( + requireReceiptForRequest( + stored, + intakeRequestId, + canonicalTenantId, + stored.worldSlug(), + stored.sourceOperationId(), + stored.sourceEvidenceDigest())); + } + + private void requireAuthenticatedGameDesignCaller() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || !peer.isService("game-design-service") + || !peer.isInNamespace(workloadNamespace)) { + throw new SecurityException( + "World authored-source intake requires the authenticated Game Design workload"); + } + } + + private void requireAuthenticatedGameDesignCallerWithoutCallerContext() { + if (SessionContext.hasAuthenticatedCallerContext()) { + throw new SecurityException( + "World authored-source intake rejects authenticated end-user caller context"); + } + requireAuthenticatedGameDesignCaller(); + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World authored-source intake cannot enter from an ambient transaction"); + } + } + + private void validateSchemaAndNamespace(int schemaVersion, String targetNamespace) { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported World authored-source intake version"); + } + if (!workloadNamespace.equals(targetNamespace)) { + throw new SecurityException( + "World authored-source intake target namespace does not match this workload"); + } + } + + private void validateRequest( + String targetNamespace, + UUID intakeRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String expectedSourceEvidenceDigest) { + requireNonNil(intakeRequestId, "intakeRequestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(sourceOperationId, "sourceOperationId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + if (!GameTenantCreationDigest.isDigest(expectedSourceEvidenceDigest)) { + throw new IllegalArgumentException( + "expectedSourceEvidenceDigest must be a canonical SHA-256 digest"); + } + } + + private void requireFreshSourceForRequest( + AuthoredWorldSourceEvidence source, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String expectedSourceEvidenceDigest) { + if (source == null + || !workloadNamespace.equals(source.targetNamespace()) + || !canonicalTenantId.equals(source.canonicalTenantId()) + || !worldSlug.equals(source.worldSlug()) + || !sourceOperationId.equals(source.operationId()) + || !expectedSourceEvidenceDigest.equals(source.evidenceDigest())) { + throw new WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException( + "Authenticated Game Design source does not match the requested World intake"); + } + try { + WorldAuthoredSourceIntakeDigest.requireFreshSource(workloadNamespace, source); + } catch (IllegalArgumentException exception) { + throw new WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException( + "Authenticated Game Design source is invalid or not fresh", exception); + } + } + + private WorldAuthoredSourceIntakeReceipt requireReceiptForRequest( + WorldAuthoredSourceIntakeReceipt receipt, + UUID intakeRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String expectedSourceEvidenceDigest) { + return requireReceiptForRequest( + receipt, + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + expectedSourceEvidenceDigest, + null); + } + + private WorldAuthoredSourceIntakeReceipt requireReceiptForRequest( + WorldAuthoredSourceIntakeReceipt receipt, + UUID intakeRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String expectedSourceEvidenceDigest, + AuthoredWorldSourceEvidence expectedSource) { + if (receipt == null + || !workloadNamespace.equals(receipt.targetNamespace()) + || !intakeRequestId.equals(receipt.intakeRequestId()) + || !canonicalTenantId.equals(receipt.canonicalTenantId()) + || !worldSlug.equals(receipt.worldSlug()) + || !sourceOperationId.equals(receipt.sourceOperationId()) + || !expectedSourceEvidenceDigest.equals(receipt.sourceEvidenceDigest())) { + throw new WorldAuthoredSourceIntakeRepository.RegistrationConflictException( + "World intake request identity was reused with changed scope or source evidence"); + } + + AuthoredWorldSourceEvidence source = receipt.source(); + if (expectedSource != null && !expectedSource.equals(source)) { + throw new WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException( + "World authored-source receipt does not retain the complete source evidence"); + } + requireFreshSourceForRequest( + source, canonicalTenantId, worldSlug, sourceOperationId, expectedSourceEvidenceDigest); + String requestDigest = + WorldAuthoredSourceIntakeDigest.requestDigest(workloadNamespace, intakeRequestId, source); + String receiptDigest = + WorldAuthoredSourceIntakeDigest.receiptDigest( + workloadNamespace, + receipt.operationId(), + requestDigest, + source, + receipt.localTenantKey()); + if (!requestDigest.equals(receipt.requestDigest()) + || !receiptDigest.equals(receipt.receiptDigest())) { + throw new WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException( + "World authored-source receipt digest readback is invalid"); + } + return receipt; + } + + private static UUID newReadRequestId(UUID intakeRequestId) { + UUID readRequestId; + do { + readRequestId = UUID.randomUUID(); + } while (NIL_UUID.equals(readRequestId) || intakeRequestId.equals(readRequestId)); + return readRequestId; + } + + private static void requireNonNil(UUID value, String name) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityGrpcService.java new file mode 100644 index 0000000000..a01b1042bb --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityGrpcService.java @@ -0,0 +1,143 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.sql.SQLException; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.WorldAuthoredVersionIdentityEvidence; +import net.firedevops.firemud.common.authoring.WorldAuthoredVersionIdentityGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.worldmanagement.v1.AssociateAuthoredWorldVersionRequest; +import net.firedevops.firemud.worldmanagement.v1.AssociateAuthoredWorldVersionResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldAuthoredVersionIdentityServiceGrpc; +import org.springframework.dao.DataAccessException; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.TransientDataAccessException; + +/** Unregistered adapter to the existing immutable World authored-Version association owner. */ +public final class WorldAuthoredVersionIdentityGrpcService + extends WorldAuthoredVersionIdentityServiceGrpc.WorldAuthoredVersionIdentityServiceImplBase { + private final WorldAuthoredVersionIdentityService identities; + private final String namespace; + + public WorldAuthoredVersionIdentityGrpcService( + WorldAuthoredVersionIdentityService identities, String namespace) { + this.identities = Objects.requireNonNull(identities, "identities"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical World namespace required"); + } + this.namespace = namespace; + } + + @Override + public void associateAuthoredWorldVersion( + AssociateAuthoredWorldVersionRequest wire, + StreamObserver observer) { + var peer = GrpcPeerIdentity.current(); + if (peer == null + || !peer.isService("game-design-service") + || !peer.isInNamespace(namespace) + || SessionContext.hasAuthenticatedCallerContext()) { + deny( + observer, + Status.PERMISSION_DENIED, + "Verified same-namespace Game Design workload required"); + return; + } + WorldAuthoredVersionIdentityEvidence.Request request; + try { + request = WorldAuthoredVersionIdentityGrpcCodec.fromRequest(wire); + } catch (IllegalArgumentException invalid) { + deny( + observer, + Status.INVALID_ARGUMENT, + "Canonical World Version association request required"); + return; + } + if (!namespace.equals(request.targetNamespace())) { + deny(observer, Status.PERMISSION_DENIED, "World Version association namespace mismatch"); + return; + } + try { + var receipt = + identities.associate( + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.sourceOperationId(), + request.sourceEvidenceDigest(), + request.expectedCanonicalVersionId(), + request.gameDesignVersionId(), + request.readRequestId()); + var intake = receipt.sourceIntakeReceipt(); + var publicIntake = + new WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt( + intake.schemaVersion(), + intake.targetNamespace(), + intake.intakeRequestId(), + intake.operationId(), + intake.canonicalTenantId(), + intake.worldSlug(), + intake.sourceOperationId(), + intake.sourceEvidenceDigest(), + intake.requestDigest(), + intake.receiptDigest()); + var result = + new WorldAuthoredVersionIdentityEvidence.Result( + request, receipt.operationId(), publicIntake, receipt.versionStateEvidence()); + observer.onNext(WorldAuthoredVersionIdentityGrpcCodec.toResponse(result)); + observer.onCompleted(); + } catch (SecurityException denied) { + deny(observer, Status.PERMISSION_DENIED, "World Version association authorization denied"); + } catch (IllegalArgumentException invalid) { + deny(observer, Status.INVALID_ARGUMENT, "World Version association input is invalid"); + } catch (DataAccessException | org.jooq.exception.DataAccessException storageFailure) { + if (hasUnavailableSqlState(storageFailure) + || storageFailure instanceof DataAccessResourceFailureException + || storageFailure instanceof TransientDataAccessException) { + deny(observer, Status.UNAVAILABLE, "World Version association storage unavailable"); + } else { + deny(observer, Status.INTERNAL, "World Version association storage failed"); + } + } catch (StatusRuntimeException transportFailure) { + Status.Code code = transportFailure.getStatus().getCode(); + if (code == Status.Code.UNAVAILABLE) { + deny(observer, Status.UNAVAILABLE, "Game Design Version state is temporarily unavailable"); + } else if (code == Status.Code.DEADLINE_EXCEEDED) { + deny(observer, Status.DEADLINE_EXCEEDED, "Game Design Version state read timed out"); + } else { + deny( + observer, + Status.FAILED_PRECONDITION, + "World Version association has no exact committed proof"); + } + } catch (RuntimeException failure) { + deny( + observer, + Status.FAILED_PRECONDITION, + "World Version association has no exact committed proof"); + } + } + + private static void deny(StreamObserver observer, Status status, String description) { + observer.onError(status.withDescription(description).asRuntimeException()); + } + + private static boolean hasUnavailableSqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException exception) { + String sqlState = exception.getSQLState(); + if (sqlState != null + && (sqlState.startsWith("08") + || "55P03".equals(sqlState) + || "40P01".equals(sqlState))) { + return true; + } + } + } + return false; + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityReceipt.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityReceipt.java new file mode 100644 index 0000000000..2d70ec8b9d --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityReceipt.java @@ -0,0 +1,94 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; + +/** + * Immutable World-local identity association for one fresh authored Version. + * + *

This retains source-qualified identity evidence and allocates a private World version key. It + * does not materialize content, authorize a Draft write, or permit lifecycle preparation. + */ +public record WorldAuthoredVersionIdentityReceipt( + int schemaVersion, + UUID operationId, + long localVersionKey, + WorldAuthoredSourceIntakeReceipt sourceIntakeReceipt, + AuthoredWorldVersionStateEvidence versionStateEvidence) { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public WorldAuthoredVersionIdentityReceipt { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported World authored-Version identity version"); + } + requireNonNil(operationId, "operationId"); + if (localVersionKey <= 0) { + throw new IllegalArgumentException("localVersionKey must be positive"); + } + Objects.requireNonNull(sourceIntakeReceipt, "sourceIntakeReceipt"); + Objects.requireNonNull(versionStateEvidence, "versionStateEvidence"); + versionStateEvidence.requireValid(); + + var source = sourceIntakeReceipt.source(); + var request = versionStateEvidence.request(); + if (!"NEW_GAME_ROW".equals(source.provenanceKind()) + || !sourceIntakeReceipt.targetNamespace().equals(request.targetNamespace()) + || !sourceIntakeReceipt.canonicalTenantId().equals(request.canonicalTenantId()) + || !sourceIntakeReceipt.worldSlug().equals(request.worldSlug()) + || !sourceIntakeReceipt.sourceOperationId().equals(request.sourceOperationId()) + || !sourceIntakeReceipt + .sourceEvidenceDigest() + .equals(request.expectedSourceEvidenceDigest()) + || !source.equals(versionStateEvidence.sourceEvidence())) { + throw new IllegalArgumentException( + "World Version identity differs from its exact fresh source intake"); + } + UUID readRequestId = request.readRequestId(); + if (readRequestId.equals(versionStateEvidence.canonicalVersionId()) + || readRequestId.equals(operationId) + || readRequestId.equals(sourceIntakeReceipt.operationId()) + || readRequestId.equals(sourceIntakeReceipt.intakeRequestId()) + || readRequestId.equals(sourceIntakeReceipt.sourceOperationId()) + || readRequestId.equals(source.registrationRequestId())) { + throw new IllegalArgumentException( + "Version-state readRequestId must be separate from source and owner identities"); + } + if (versionStateEvidence.versionState() != VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT + && versionStateEvidence.versionState() + != VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED + && versionStateEvidence.versionState() + != VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE) { + throw new IllegalArgumentException( + "World Version identity requires DRAFT, PUBLISHED, or ACTIVE owner evidence"); + } + } + + public UUID canonicalVersionId() { + return versionStateEvidence.canonicalVersionId(); + } + + public long gameDesignVersionId() { + return versionStateEvidence.request().versionId(); + } + + public String targetNamespace() { + return sourceIntakeReceipt.targetNamespace(); + } + + public UUID canonicalTenantId() { + return sourceIntakeReceipt.canonicalTenantId(); + } + + public String worldSlug() { + return sourceIntakeReceipt.worldSlug(); + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityRepository.java new file mode 100644 index 0000000000..e6fafa944a --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityRepository.java @@ -0,0 +1,492 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +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; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Owner-local immutable association between a fresh authored Version UUID and a World key. */ +public class WorldAuthoredVersionIdentityRepository { + private static final Table VERSION_IDENTITY = + DSL.table(DSL.name("world_authored_version_identity")); + private static final JsonMapper CLOSED_JSON = + JsonMapper.builder() + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + + private static final Field OPERATION_ID = DSL.field(DSL.name("operation_id"), UUID.class); + 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 WORLD_SLUG = DSL.field(DSL.name("world_slug"), String.class); + private static final Field CANONICAL_VERSION_ID = + DSL.field(DSL.name("canonical_version_id"), UUID.class); + private static final Field GAME_DESIGN_VERSION_ID = + DSL.field(DSL.name("game_design_version_id"), Long.class); + private static final Field LOCAL_VERSION_KEY = + DSL.field(DSL.name("local_version_key"), Long.class); + private static final Field INTAKE_OPERATION_ID = + DSL.field(DSL.name("intake_operation_id"), UUID.class); + private static final Field INTAKE_REQUEST_ID = + DSL.field(DSL.name("intake_request_id"), UUID.class); + private static final Field LOCAL_TENANT_KEY = + DSL.field(DSL.name("local_tenant_key"), Long.class); + private static final Field INTAKE_REQUEST_DIGEST = + DSL.field(DSL.name("intake_request_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 INTAKE_RECEIPT_DIGEST = + DSL.field(DSL.name("intake_receipt_digest"), String.class); + private static final Field VERSION_STATE_SCHEMA_VERSION = + DSL.field(DSL.name("version_state_schema_version"), Short.class); + private static final Field VERSION_STATE_READ_REQUEST_ID = + DSL.field(DSL.name("version_state_read_request_id"), UUID.class); + private static final Field VERSION_STATE_STATE = + DSL.field(DSL.name("version_state_state"), String.class); + private static final Field VERSION_STATE_EPOCH = + DSL.field(DSL.name("version_state_epoch"), Long.class); + private static final Field VERSION_STATE_EVIDENCE_DIGEST = + DSL.field(DSL.name("version_state_evidence_digest"), String.class); + private static final Field VERSION_STATE_EVIDENCE_JSON = + DSL.field(DSL.name("version_state_evidence_json"), String.class); + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The injected DSLContext is an internal collaborator; construction acquires no resources and this repository has no finalizer.") + public WorldAuthoredVersionIdentityRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + } + + /** Reads the immutable identity by canonical Version UUID after the owner transaction commits. */ + public Optional readByCanonicalVersion( + String namespace, UUID canonicalTenantId, String worldSlug, UUID canonicalVersionId) { + requireNoActiveTransaction("World authored-Version identity read"); + return readByCanonicalVersionValidated( + namespace, canonicalTenantId, worldSlug, canonicalVersionId); + } + + /** Reads the exact immutable Version receipt within a verified owner snapshot. */ + Optional readByCanonicalVersionInOwnerReadOnlyRepeatableRead( + String namespace, UUID canonicalTenantId, String worldSlug, UUID canonicalVersionId) { + requireReadOnlyRepeatableReadOwnerTransaction(); + return readByCanonicalVersionValidated( + namespace, canonicalTenantId, worldSlug, canonicalVersionId); + } + + /** + * Reconstructs the same immutable Version receipt inside canonical activation's owner + * transaction. + */ + Optional readByCanonicalVersionInOwnerActivationTransaction( + String namespace, UUID canonicalTenantId, String worldSlug, UUID canonicalVersionId) { + requireWritableActivationTransaction(); + return readByCanonicalVersionValidated( + namespace, canonicalTenantId, worldSlug, canonicalVersionId); + } + + private Optional readByCanonicalVersionValidated( + String namespace, UUID canonicalTenantId, String worldSlug, UUID canonicalVersionId) { + validateIdentityKey(namespace, canonicalTenantId, worldSlug); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + Record row = + findByCanonicalVersion(namespace, canonicalTenantId, worldSlug, canonicalVersionId); + return row == null ? Optional.empty() : Optional.of(toReceipt(row)); + } + + /** Reads an immutable identity by the exact Game Design-owned numeric Version selector. */ + public Optional readByGameDesignVersion( + String namespace, UUID canonicalTenantId, String worldSlug, long gameDesignVersionId) { + requireNoActiveTransaction("World authored-Version identity read"); + validateIdentityKey(namespace, canonicalTenantId, worldSlug); + requirePositive(gameDesignVersionId, "gameDesignVersionId"); + Record row = + findByGameDesignVersion(namespace, canonicalTenantId, worldSlug, gameDesignVersionId); + return row == null ? Optional.empty() : Optional.of(toReceipt(row)); + } + + /** + * Reads the unique immutable identity for an exact canonical target and Game Design row. + * + *

This selector deliberately does not infer or accept a World slug. Multiple rows for the same + * canonical target are conflicting source associations, not a choice to resolve. + */ + public Optional readByCanonicalTarget( + String namespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + long gameDesignVersionRowId) { + requireNoActiveTransaction("World authored-Version identity read"); + if (namespace == null || !GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Target namespace must be one canonical DNS label"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + requirePositive(gameDesignVersionRowId, "gameDesignVersionRowId"); + + var rows = + dsl.selectFrom(VERSION_IDENTITY) + .where( + TARGET_NAMESPACE + .eq(namespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(CANONICAL_VERSION_ID.eq(canonicalVersionId)) + .and(GAME_DESIGN_VERSION_ID.eq(gameDesignVersionRowId))) + .fetch(); + if (rows.isEmpty()) { + return Optional.empty(); + } + if (rows.size() != 1) { + throw new InvalidIdentityEvidenceException( + "World authored-Version identity target has ambiguous World associations"); + } + return Optional.of(toReceipt(rows.getFirst())); + } + + /** + * Atomically claims the source-qualified Version identity with a World-allocated local key. + * + *

Concurrent requests for the same stable source, canonical UUID, and Game Design selector + * return the first stored receipt even when their transport read IDs or current state epochs + * differ. Changed source or selector evidence conflicts without replacing that receipt. + */ + public WorldAuthoredVersionIdentityReceipt acceptFresh( + WorldAuthoredSourceIntakeReceipt sourceReceipt, + AuthoredWorldVersionStateEvidence versionStateEvidence) { + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(sourceReceipt, "sourceReceipt"); + Objects.requireNonNull(versionStateEvidence, "versionStateEvidence"); + validateFreshEvidence(sourceReceipt, versionStateEvidence); + + AuthoredWorldVersionStateEvidence.Request request = versionStateEvidence.request(); + UUID operationId = newNonNilUuid(); + int inserted = + dsl.insertInto(VERSION_IDENTITY) + .set(OPERATION_ID, operationId) + .set(TARGET_NAMESPACE, sourceReceipt.targetNamespace()) + .set(CANONICAL_TENANT_ID, sourceReceipt.canonicalTenantId()) + .set(WORLD_SLUG, sourceReceipt.worldSlug()) + .set(CANONICAL_VERSION_ID, versionStateEvidence.canonicalVersionId()) + .set(GAME_DESIGN_VERSION_ID, request.versionId()) + .set(INTAKE_OPERATION_ID, sourceReceipt.operationId()) + .set(INTAKE_REQUEST_ID, sourceReceipt.intakeRequestId()) + .set(LOCAL_TENANT_KEY, sourceReceipt.localTenantKey()) + .set(INTAKE_REQUEST_DIGEST, sourceReceipt.requestDigest()) + .set(SOURCE_OPERATION_ID, sourceReceipt.sourceOperationId()) + .set(SOURCE_EVIDENCE_DIGEST, sourceReceipt.sourceEvidenceDigest()) + .set(INTAKE_RECEIPT_DIGEST, sourceReceipt.receiptDigest()) + .set(VERSION_STATE_SCHEMA_VERSION, (short) request.schemaVersion()) + .set(VERSION_STATE_READ_REQUEST_ID, request.readRequestId()) + .set(VERSION_STATE_STATE, lifecycleToken(versionStateEvidence.versionState())) + .set(VERSION_STATE_EPOCH, versionStateEvidence.versionStateEpoch()) + .set(VERSION_STATE_EVIDENCE_DIGEST, versionStateEvidence.evidenceDigest()) + .set(VERSION_STATE_EVIDENCE_JSON, writeJson(versionStateEvidence)) + .onConflictDoNothing() + .execute(); + + Record row = + findByCanonicalVersion( + sourceReceipt.targetNamespace(), + sourceReceipt.canonicalTenantId(), + sourceReceipt.worldSlug(), + versionStateEvidence.canonicalVersionId()); + if (row == null) { + row = + findByGameDesignVersion( + sourceReceipt.targetNamespace(), + sourceReceipt.canonicalTenantId(), + sourceReceipt.worldSlug(), + request.versionId()); + } + if (row == null) { + throw new InvalidIdentityEvidenceException( + "World authored-Version identity is missing after its owner claim"); + } + + WorldAuthoredVersionIdentityReceipt receipt = toReceipt(row); + requireSameIdentity(receipt, sourceReceipt, versionStateEvidence); + if (inserted == 0) { + // A duplicate request resolves only to the original immutable receipt; never rewrite it. + return receipt; + } + return receipt; + } + + private Record findByCanonicalVersion( + String namespace, UUID canonicalTenantId, String worldSlug, UUID canonicalVersionId) { + return dsl.selectFrom(VERSION_IDENTITY) + .where( + TARGET_NAMESPACE + .eq(namespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(WORLD_SLUG.eq(worldSlug)) + .and(CANONICAL_VERSION_ID.eq(canonicalVersionId))) + .fetchOne(); + } + + private Record findByGameDesignVersion( + String namespace, UUID canonicalTenantId, String worldSlug, long gameDesignVersionId) { + return dsl.selectFrom(VERSION_IDENTITY) + .where( + TARGET_NAMESPACE + .eq(namespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(WORLD_SLUG.eq(worldSlug)) + .and(GAME_DESIGN_VERSION_ID.eq(gameDesignVersionId))) + .fetchOne(); + } + + private WorldAuthoredVersionIdentityReceipt toReceipt(Record row) { + try { + UUID operationId = required(row, OPERATION_ID); + String namespace = required(row, TARGET_NAMESPACE); + UUID canonicalTenantId = required(row, CANONICAL_TENANT_ID); + String worldSlug = required(row, WORLD_SLUG); + UUID canonicalVersionId = required(row, CANONICAL_VERSION_ID); + Long gameDesignVersionId = required(row, GAME_DESIGN_VERSION_ID); + Long localVersionKey = required(row, LOCAL_VERSION_KEY); + UUID intakeOperationId = required(row, INTAKE_OPERATION_ID); + UUID intakeRequestId = required(row, INTAKE_REQUEST_ID); + Long localTenantKey = required(row, LOCAL_TENANT_KEY); + String intakeRequestDigest = required(row, INTAKE_REQUEST_DIGEST); + UUID sourceOperationId = required(row, SOURCE_OPERATION_ID); + String sourceEvidenceDigest = required(row, SOURCE_EVIDENCE_DIGEST); + String intakeReceiptDigest = required(row, INTAKE_RECEIPT_DIGEST); + Short versionStateSchemaVersion = required(row, VERSION_STATE_SCHEMA_VERSION); + UUID readRequestId = required(row, VERSION_STATE_READ_REQUEST_ID); + String versionStateToken = required(row, VERSION_STATE_STATE); + Long versionStateEpoch = required(row, VERSION_STATE_EPOCH); + String versionStateEvidenceDigest = required(row, VERSION_STATE_EVIDENCE_DIGEST); + AuthoredWorldVersionStateEvidence evidence = + readJson(required(row, VERSION_STATE_EVIDENCE_JSON)); + + if (versionStateSchemaVersion != evidence.request().schemaVersion() + || !readRequestId.equals(evidence.request().readRequestId()) + || !versionStateToken.equals(lifecycleToken(evidence.versionState())) + || !versionStateEpoch.equals(evidence.versionStateEpoch()) + || !versionStateEvidenceDigest.equals(evidence.evidenceDigest()) + || !canonicalVersionId.equals(evidence.canonicalVersionId()) + || gameDesignVersionId != evidence.request().versionId()) { + throw new IllegalArgumentException( + "Persisted World Version identity columns differ from their closed evidence"); + } + + WorldAuthoredSourceIntakeReceipt sourceReceipt = + new WorldAuthoredSourceIntakeReceipt( + 1, + namespace, + intakeRequestId, + intakeOperationId, + canonicalTenantId, + worldSlug, + sourceOperationId, + sourceEvidenceDigest, + intakeRequestDigest, + intakeReceiptDigest, + localTenantKey, + evidence.sourceEvidence()); + return new WorldAuthoredVersionIdentityReceipt( + 1, operationId, localVersionKey, sourceReceipt, evidence); + } catch (RuntimeException exception) { + if (exception instanceof InvalidIdentityEvidenceException) { + throw exception; + } + throw new InvalidIdentityEvidenceException( + "Persisted World authored-Version identity evidence is invalid", exception); + } + } + + private static void validateFreshEvidence( + WorldAuthoredSourceIntakeReceipt sourceReceipt, AuthoredWorldVersionStateEvidence evidence) { + evidence.requireValid(); + AuthoredWorldVersionStateEvidence.Request request = evidence.request(); + if (!"NEW_GAME_ROW".equals(sourceReceipt.source().provenanceKind()) + || !sourceReceipt.targetNamespace().equals(request.targetNamespace()) + || !sourceReceipt.canonicalTenantId().equals(request.canonicalTenantId()) + || !sourceReceipt.worldSlug().equals(request.worldSlug()) + || !sourceReceipt.sourceOperationId().equals(request.sourceOperationId()) + || !sourceReceipt.sourceEvidenceDigest().equals(request.expectedSourceEvidenceDigest()) + || !sourceReceipt.source().equals(evidence.sourceEvidence())) { + throw new RegistrationConflictException( + "World Version identity evidence differs from the exact fresh source intake"); + } + } + + private static void requireSameIdentity( + WorldAuthoredVersionIdentityReceipt receipt, + WorldAuthoredSourceIntakeReceipt sourceReceipt, + AuthoredWorldVersionStateEvidence candidate) { + if (!receipt.sourceIntakeReceipt().equals(sourceReceipt) + || !receipt.canonicalVersionId().equals(candidate.canonicalVersionId()) + || receipt.gameDesignVersionId() != candidate.request().versionId()) { + throw new RegistrationConflictException( + "World Version identity scope, source intake, or Game Design selector conflicts"); + } + } + + private static String writeJson(Object value) { + try { + return CLOSED_JSON.writeValueAsString(value); + } catch (Exception exception) { + throw new InvalidIdentityEvidenceException( + "World Version identity evidence could not be encoded", exception); + } + } + + private static AuthoredWorldVersionStateEvidence readJson(String json) { + try { + AuthoredWorldVersionStateEvidence evidence = + CLOSED_JSON.readValue(json, AuthoredWorldVersionStateEvidence.class); + if (!writeJson(evidence).equals(json)) { + throw new IllegalArgumentException( + "Persisted Version-state evidence JSON is not in its closed form"); + } + evidence.requireValid(); + return evidence; + } catch (Exception exception) { + throw new InvalidIdentityEvidenceException( + "Persisted Version-state JSON is not closed evidence", exception); + } + } + + private static String lifecycleToken(VersionLifecycleState state) { + return switch (state) { + case VERSION_LIFECYCLE_STATE_DRAFT -> "DRAFT"; + case VERSION_LIFECYCLE_STATE_PUBLISHED -> "PUBLISHED"; + case VERSION_LIFECYCLE_STATE_ACTIVE -> "ACTIVE"; + default -> + throw new InvalidIdentityEvidenceException( + "World Version identity requires DRAFT, PUBLISHED, or ACTIVE owner evidence"); + }; + } + + private static T required(Record row, Field field) { + return Objects.requireNonNull(row.get(field), "Persisted " + field.getName() + " is null"); + } + + private static void validateIdentityKey( + String namespace, UUID canonicalTenantId, String worldSlug) { + AuthoredWorldSourceDigest.validateReadSelector(namespace, canonicalTenantId, worldSlug); + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private static void requirePositive(long value, String label) { + if (value <= 0) { + throw new IllegalArgumentException(label + " must be positive"); + } + } + + private static UUID newNonNilUuid() { + UUID value; + do { + value = UUID.randomUUID(); + } while (value.equals(new UUID(0L, 0L))); + return value; + } + + private static void requireNoActiveTransaction(String label) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException(label + " requires an independent committed owner read"); + } + } + + private void requireReadOnlyRepeatableReadOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World authored-Version snapshot read requires a read-only REPEATABLE READ owner transaction"); + } + Record state = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"), + "World transaction state query returned no row"); + if (!"repeatable read".equals(state.get("isolation", String.class)) + || !"on".equals(state.get("read_only", String.class))) { + throw new IllegalStateException( + "World authored-Version snapshot read requires a read-only REPEATABLE READ owner transaction"); + } + } + + private void requireWritableActivationTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World authored-Version activation read requires a writable READ COMMITTED owner transaction"); + } + Record state = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"), + "World transaction state query returned no row"); + if (!"read committed".equals(state.get("isolation", String.class)) + || !"off".equals(state.get("read_only", String.class))) { + throw new IllegalStateException( + "World authored-Version activation read requires a writable READ COMMITTED owner transaction"); + } + } + + private static void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World authored-Version identity requires an active owner transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "World authored-Version identity requires a writable owner transaction"); + } + Integer declaredIsolation = + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (declaredIsolation != null && declaredIsolation != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "World authored-Version identity requires READ COMMITTED isolation"); + } + } + + public static final class RegistrationConflictException extends IllegalStateException { + public RegistrationConflictException(String message) { + super(message); + } + } + + public static final class InvalidIdentityEvidenceException extends IllegalStateException { + public InvalidIdentityEvidenceException(String message) { + super(message); + } + + public InvalidIdentityEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityService.java new file mode 100644 index 0000000000..778ab294e8 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityService.java @@ -0,0 +1,343 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.StatusRuntimeException; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Explicitly unwired World owner step that associates a fresh source-owned Version UUID with a + * private World identity key. + * + *

This identity receipt is non-admitting. It does not materialize content or authorize Draft + * writes, publication, lifecycle preparation, or runtime activation. + */ +public final class WorldAuthoredVersionIdentityService { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final AuthoredWorldVersionStateClient versionStateClient; + private final WorldAuthoredVersionIdentityRepository repository; + private final WorldAuthoredSourceIntakeRepository sourceIntakeRepository; + private final TransactionTemplate ownerTransaction; + private final String workloadNamespace; + + public WorldAuthoredVersionIdentityService( + AuthoredWorldVersionStateClient versionStateClient, + WorldAuthoredVersionIdentityRepository repository, + WorldAuthoredSourceIntakeRepository sourceIntakeRepository, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.versionStateClient = Objects.requireNonNull(versionStateClient, "versionStateClient"); + this.repository = Objects.requireNonNull(repository, "repository"); + this.sourceIntakeRepository = + Objects.requireNonNull(sourceIntakeRepository, "sourceIntakeRepository"); + Objects.requireNonNull(transactionManager, "transactionManager"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.workloadNamespace = workloadNamespace; + this.ownerTransaction = new TransactionTemplate(transactionManager); + this.ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.ownerTransaction.setReadOnly(false); + } + + /** + * Associates one source-owned Version selector and canonical UUID with a World-local key. + * + *

The stable identity is `(namespace, canonical tenant, world, canonical Version UUID)`. + * `readRequestId` is transport correlation only. Exact retries read the original stored receipt + * before calling Game Design again. + */ + public WorldAuthoredVersionIdentityReceipt associate( + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest, + UUID expectedCanonicalVersionId, + long gameDesignVersionId, + UUID readRequestId) { + requireAuthenticatedGameDesignCaller(); + requireNoAmbientTransaction(); + validateRequest( + targetNamespace, + canonicalTenantId, + worldSlug, + sourceOperationId, + sourceEvidenceDigest, + expectedCanonicalVersionId, + gameDesignVersionId, + readRequestId); + + WorldAuthoredSourceIntakeReceipt sourceReceipt = + readExactSourceIntake( + canonicalTenantId, worldSlug, sourceOperationId, sourceEvidenceDigest); + requireFreshReadRequestId(readRequestId, expectedCanonicalVersionId, sourceReceipt); + + Optional prior = + repository.readByCanonicalVersion( + workloadNamespace, canonicalTenantId, worldSlug, expectedCanonicalVersionId); + if (prior.isPresent()) { + return requireSameIdentity( + prior.orElseThrow(), sourceReceipt, expectedCanonicalVersionId, gameDesignVersionId); + } + Optional priorByGameDesignVersion = + repository.readByGameDesignVersion( + workloadNamespace, canonicalTenantId, worldSlug, gameDesignVersionId); + if (priorByGameDesignVersion.isPresent()) { + return requireSameIdentity( + priorByGameDesignVersion.orElseThrow(), + sourceReceipt, + expectedCanonicalVersionId, + gameDesignVersionId); + } + + AuthoredWorldVersionStateEvidence.Request currentRequest = + new AuthoredWorldVersionStateEvidence.Request( + SCHEMA_VERSION, + workloadNamespace, + readRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + sourceEvidenceDigest, + gameDesignVersionId); + AuthoredWorldVersionStateEvidence current; + try { + current = versionStateClient.read(currentRequest); + } catch (StatusRuntimeException transportFailure) { + throw transportFailure; + } catch (RuntimeException exception) { + throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "Game Design source-qualified Version identity evidence is unavailable or invalid", + exception); + } + requireCurrentEvidence(current, currentRequest, sourceReceipt, expectedCanonicalVersionId); + + WorldAuthoredVersionIdentityReceipt accepted; + try { + accepted = ownerTransaction.execute(status -> repository.acceptFresh(sourceReceipt, current)); + } catch (RuntimeException ownerFailure) { + Optional committed = + repository.readByCanonicalVersion( + workloadNamespace, canonicalTenantId, worldSlug, expectedCanonicalVersionId); + if (committed.isPresent()) { + requireSameSourceIntake( + sourceReceipt, + readExactSourceIntake( + canonicalTenantId, worldSlug, sourceOperationId, sourceEvidenceDigest)); + return requireSameIdentity( + committed.orElseThrow(), + sourceReceipt, + expectedCanonicalVersionId, + gameDesignVersionId); + } + Optional claimedSelector = + repository.readByGameDesignVersion( + workloadNamespace, canonicalTenantId, worldSlug, gameDesignVersionId); + if (claimedSelector.isPresent()) { + requireSameSourceIntake( + sourceReceipt, + readExactSourceIntake( + canonicalTenantId, worldSlug, sourceOperationId, sourceEvidenceDigest)); + return requireSameIdentity( + claimedSelector.orElseThrow(), + sourceReceipt, + expectedCanonicalVersionId, + gameDesignVersionId); + } + throw ownerFailure; + } + if (accepted == null) { + throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "World owner transaction returned no Version identity receipt"); + } + requireSameIdentity(accepted, sourceReceipt, expectedCanonicalVersionId, gameDesignVersionId); + + Optional committed = + repository.readByCanonicalVersion( + workloadNamespace, canonicalTenantId, worldSlug, expectedCanonicalVersionId); + if (committed.isEmpty()) { + throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "World Version identity is missing after its owner commit"); + } + WorldAuthoredVersionIdentityReceipt readback = committed.orElseThrow(); + requireSameSourceIntake( + sourceReceipt, + readExactSourceIntake( + canonicalTenantId, worldSlug, sourceOperationId, sourceEvidenceDigest)); + requireSameIdentity(readback, sourceReceipt, expectedCanonicalVersionId, gameDesignVersionId); + if (!accepted.equals(readback)) { + throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "World Version identity changed during independent commit readback"); + } + return readback; + } + + private WorldAuthoredVersionIdentityReceipt requireSameIdentity( + WorldAuthoredVersionIdentityReceipt receipt, + WorldAuthoredSourceIntakeReceipt sourceReceipt, + UUID expectedCanonicalVersionId, + long gameDesignVersionId) { + if (!receipt.targetNamespace().equals(workloadNamespace) + || !receipt.sourceIntakeReceipt().equals(sourceReceipt) + || !receipt.canonicalTenantId().equals(sourceReceipt.canonicalTenantId()) + || !receipt.worldSlug().equals(sourceReceipt.worldSlug()) + || !receipt.canonicalVersionId().equals(expectedCanonicalVersionId) + || receipt.gameDesignVersionId() != gameDesignVersionId) { + throw new WorldAuthoredVersionIdentityRepository.RegistrationConflictException( + "World Version identity scope, source intake, or selector conflicts with its first claim"); + } + return receipt; + } + + private void requireCurrentEvidence( + AuthoredWorldVersionStateEvidence evidence, + AuthoredWorldVersionStateEvidence.Request expectedRequest, + WorldAuthoredSourceIntakeReceipt sourceReceipt, + UUID expectedCanonicalVersionId) { + if (evidence == null) { + throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "Game Design returned no source-qualified Version identity evidence"); + } + try { + evidence.requireValid(); + } catch (RuntimeException exception) { + throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "Game Design source-qualified Version identity evidence is invalid", exception); + } + if (!expectedRequest.equals(evidence.request()) + || !sourceReceipt.source().equals(evidence.sourceEvidence()) + || !expectedCanonicalVersionId.equals(evidence.canonicalVersionId())) { + throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "Game Design Version identity evidence differs from the exact source and expected UUID"); + } + VersionLifecycleState state = evidence.versionState(); + if (state != VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT + && state != VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED + && state != VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE) { + throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "Game Design Version identity evidence must be DRAFT, PUBLISHED, or ACTIVE"); + } + } + + private void requireExactFreshSourceIntake( + WorldAuthoredSourceIntakeReceipt sourceReceipt, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest) { + if (!workloadNamespace.equals(sourceReceipt.targetNamespace()) + || !canonicalTenantId.equals(sourceReceipt.canonicalTenantId()) + || !worldSlug.equals(sourceReceipt.worldSlug()) + || !sourceOperationId.equals(sourceReceipt.sourceOperationId()) + || !sourceEvidenceDigest.equals(sourceReceipt.sourceEvidenceDigest()) + || !"NEW_GAME_ROW".equals(sourceReceipt.source().provenanceKind())) { + throw new WorldAuthoredVersionIdentityRepository.RegistrationConflictException( + "World Version identity requires the exact fresh NEW_GAME_ROW source intake"); + } + } + + private WorldAuthoredSourceIntakeReceipt readExactSourceIntake( + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest) { + WorldAuthoredSourceIntakeReceipt sourceReceipt = + sourceIntakeRepository + .readBySource( + workloadNamespace, + canonicalTenantId, + worldSlug, + sourceOperationId, + sourceEvidenceDigest) + .orElseThrow( + () -> + new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "World Version identity requires an exact committed fresh source intake")); + requireExactFreshSourceIntake( + sourceReceipt, canonicalTenantId, worldSlug, sourceOperationId, sourceEvidenceDigest); + return sourceReceipt; + } + + private static void requireSameSourceIntake( + WorldAuthoredSourceIntakeReceipt expected, WorldAuthoredSourceIntakeReceipt actual) { + if (!expected.equals(actual)) { + throw new WorldAuthoredVersionIdentityRepository.RegistrationConflictException( + "World source intake changed during Version identity readback"); + } + } + + private void requireAuthenticatedGameDesignCaller() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || !peer.isService("game-design-service") + || !peer.isInNamespace(workloadNamespace)) { + throw new SecurityException( + "World Version identity requires the authenticated same-namespace Game Design workload"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World Version identity cannot enter from an ambient transaction"); + } + } + + private void validateRequest( + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest, + UUID expectedCanonicalVersionId, + long gameDesignVersionId, + UUID readRequestId) { + if (!workloadNamespace.equals(targetNamespace)) { + throw new SecurityException("World Version identity namespace does not match this workload"); + } + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(sourceOperationId, "sourceOperationId"); + requireNonNil(expectedCanonicalVersionId, "expectedCanonicalVersionId"); + requireNonNil(readRequestId, "readRequestId"); + if (!GameTenantCreationDigest.isDigest(sourceEvidenceDigest)) { + throw new IllegalArgumentException("sourceEvidenceDigest must be a canonical SHA-256 digest"); + } + if (gameDesignVersionId <= 0) { + throw new IllegalArgumentException("gameDesignVersionId must be positive"); + } + } + + private static void requireFreshReadRequestId( + UUID readRequestId, + UUID expectedCanonicalVersionId, + WorldAuthoredSourceIntakeReceipt sourceReceipt) { + if (readRequestId.equals(expectedCanonicalVersionId) + || readRequestId.equals(sourceReceipt.operationId()) + || readRequestId.equals(sourceReceipt.intakeRequestId()) + || readRequestId.equals(sourceReceipt.sourceOperationId()) + || readRequestId.equals(sourceReceipt.source().registrationRequestId())) { + throw new IllegalArgumentException( + "Version-state readRequestId must be fresh and separate from source identities"); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || value.equals(NIL_UUID)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingReceipt.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingReceipt.java new file mode 100644 index 0000000000..31889f4382 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingReceipt.java @@ -0,0 +1,74 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; + +/** + * Internal World receipt for a retained authored-world descriptor and complete release pair. + * + *

This is non-admitting released-content evidence. It does not represent local content, + * PREPARING, ACTIVE/current authority, or activation. + */ +public record WorldCompleteLaunchBindingReceipt( + int schemaVersion, + UUID operationId, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + WorldAuthoredSourceIntakeReceipt sourceIntakeReceipt, + CompleteLaunchBindingEvidence evidence) { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public WorldCompleteLaunchBindingReceipt { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported World complete launch binding version"); + } + requireNonNil(operationId, "operationId"); + Objects.requireNonNull(targetNamespace, "targetNamespace"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(worldSlug, "worldSlug"); + Objects.requireNonNull(controlPlaneRequestId, "controlPlaneRequestId"); + Objects.requireNonNull(sourceIntakeReceipt, "sourceIntakeReceipt"); + Objects.requireNonNull(evidence, "evidence"); + + AuthoredWorldLaunchDescriptorEvidence descriptor = evidence.descriptor(); + descriptor.requireValid(); + evidence.releaseAttestation().requireValid(descriptor); + var selector = evidence.releaseAttestation().worldStartLocationEvidence(); + if (selector != null + && !selector.request().intakeRequestId().equals(sourceIntakeReceipt.intakeRequestId())) { + throw new IllegalArgumentException( + "World release selector differs from the exact original source intake"); + } + if (!targetNamespace.equals(descriptor.targetNamespace()) + || !canonicalTenantId.equals(descriptor.canonicalTenantId()) + || !worldSlug.equals(descriptor.worldSlug()) + || !controlPlaneRequestId.equals(descriptor.controlPlaneRequestId()) + || !targetNamespace.equals(sourceIntakeReceipt.targetNamespace()) + || !canonicalTenantId.equals(sourceIntakeReceipt.canonicalTenantId()) + || !worldSlug.equals(sourceIntakeReceipt.worldSlug()) + || !descriptor + .authoredWorldSourceOperationId() + .equals(sourceIntakeReceipt.sourceOperationId()) + || !descriptor + .authoredWorldSourceEvidenceDigest() + .equals(sourceIntakeReceipt.sourceEvidenceDigest())) { + throw new IllegalArgumentException( + "World complete launch binding differs from its exact authored-source intake"); + } + } + + public AuthoredWorldLaunchDescriptorEvidence descriptor() { + return evidence.descriptor(); + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingRepository.java new file mode 100644 index 0000000000..9a5b9509fe --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingRepository.java @@ -0,0 +1,491 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.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 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; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Owner-local immutable persistence for complete authored-world launch evidence. */ +public class WorldCompleteLaunchBindingRepository { + private static final Table BINDING = DSL.table(DSL.name("world_complete_launch_binding")); + private static final JsonMapper CLOSED_JSON = + JsonMapper.builder() + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + + private static final Field BINDING_OPERATION_ID = + DSL.field(DSL.name("binding_operation_id"), UUID.class); + 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 CANONICAL_VERSION_ID = + DSL.field(DSL.name("canonical_version_id"), UUID.class); + private static final Field WORLD_SLUG = DSL.field(DSL.name("world_slug"), String.class); + private static final Field CONTROL_PLANE_REQUEST_ID = + DSL.field(DSL.name("control_plane_request_id"), String.class); + private static final Field INTAKE_OPERATION_ID = + DSL.field(DSL.name("intake_operation_id"), UUID.class); + private static final Field INTAKE_REQUEST_ID = + DSL.field(DSL.name("intake_request_id"), UUID.class); + private static final Field LOCAL_TENANT_KEY = + DSL.field(DSL.name("local_tenant_key"), Long.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 INTAKE_RECEIPT_DIGEST = + DSL.field(DSL.name("intake_receipt_digest"), String.class); + private static final Field DESCRIPTOR_REQUEST_DIGEST = + DSL.field(DSL.name("descriptor_request_digest"), String.class); + private static final Field DESCRIPTOR_RESULT_DIGEST = + DSL.field(DSL.name("descriptor_result_digest"), String.class); + private static final Field RELEASE_ATTESTATION_DIGEST = + DSL.field(DSL.name("release_attestation_digest"), String.class); + private static final Field DESCRIPTOR_JSON = + DSL.field(DSL.name("descriptor_json"), String.class); + private static final Field RELEASE_ATTESTATION_JSON = + DSL.field(DSL.name("release_attestation_json"), String.class); + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The injected DSLContext is an internal collaborator; construction acquires no resources and this repository has no finalizer.") + public WorldCompleteLaunchBindingRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + } + + /** Reads the immutable owner row by its stable namespace/tenant/control-plane request key. */ + public Optional read( + String namespace, UUID canonicalTenantId, String controlPlaneRequestId) { + requireNoActiveTransaction("World complete launch binding read"); + return readValidated(namespace, canonicalTenantId, controlPlaneRequestId); + } + + /** Reads the same immutable row inside the lifecycle repository's verified owner snapshot. */ + Optional readInOwnerReadOnlyRepeatableRead( + String namespace, UUID canonicalTenantId, String controlPlaneRequestId) { + requireReadOnlyRepeatableReadOwnerTransaction(); + return readValidated(namespace, canonicalTenantId, controlPlaneRequestId); + } + + /** + * Reconstructs the same immutable binding inside the writable canonical activation transaction. + */ + Optional readInOwnerActivationTransaction( + String namespace, UUID canonicalTenantId, String controlPlaneRequestId) { + requireWritableActivationTransaction(); + return readValidated(namespace, canonicalTenantId, controlPlaneRequestId); + } + + private Optional readValidated( + String namespace, UUID canonicalTenantId, String controlPlaneRequestId) { + validateKey(namespace, canonicalTenantId, controlPlaneRequestId); + Record row = find(namespace, canonicalTenantId, controlPlaneRequestId); + return row == null ? Optional.empty() : Optional.of(toStoredBinding(row)); + } + + /** + * Retains one complete pair against the exact committed local source receipt. + * + *

The caller must authenticate Game Session, perform all remote and committed reads outside + * the owner transaction, then invoke this method in a fresh writable READ COMMITTED transaction. + */ + public WorldCompleteLaunchBindingReceipt acceptFresh( + String namespace, + WorldAuthoredSourceIntakeReceipt sourceReceipt, + CompleteLaunchBindingEvidence evidence) { + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(sourceReceipt, "sourceReceipt"); + Objects.requireNonNull(evidence, "evidence"); + requireSourceBinding(namespace, sourceReceipt, evidence); + + AuthoredWorldLaunchDescriptorEvidence descriptor = evidence.descriptor(); + String descriptorJson = writeJson(descriptor); + String attestationJson = writeJson(evidence.releaseAttestation()); + UUID operationId = newNonNilUuid(); + int inserted = + dsl.insertInto(BINDING) + .set(BINDING_OPERATION_ID, operationId) + .set(TARGET_NAMESPACE, namespace) + .set(CANONICAL_TENANT_ID, descriptor.canonicalTenantId()) + .set(CANONICAL_VERSION_ID, evidence.releaseAttestation().canonicalVersionId()) + .set(WORLD_SLUG, descriptor.worldSlug()) + .set(CONTROL_PLANE_REQUEST_ID, descriptor.controlPlaneRequestId()) + .set(INTAKE_OPERATION_ID, sourceReceipt.operationId()) + .set(INTAKE_REQUEST_ID, sourceReceipt.intakeRequestId()) + .set(LOCAL_TENANT_KEY, sourceReceipt.localTenantKey()) + .set(SOURCE_OPERATION_ID, sourceReceipt.sourceOperationId()) + .set(SOURCE_EVIDENCE_DIGEST, sourceReceipt.sourceEvidenceDigest()) + .set(INTAKE_RECEIPT_DIGEST, sourceReceipt.receiptDigest()) + .set(DESCRIPTOR_REQUEST_DIGEST, descriptor.requestDigest()) + .set(DESCRIPTOR_RESULT_DIGEST, descriptor.resultDigest()) + .set(RELEASE_ATTESTATION_DIGEST, evidence.releaseAttestation().evidenceDigest()) + .set(DESCRIPTOR_JSON, descriptorJson) + .set(RELEASE_ATTESTATION_JSON, attestationJson) + .onConflictDoNothing() + .execute(); + + Record row = + find(namespace, descriptor.canonicalTenantId(), descriptor.controlPlaneRequestId()); + if (row == null) { + throw new InvalidBindingEvidenceException( + "World complete launch binding is missing after its owner claim"); + } + StoredBinding stored = toStoredBinding(row); + WorldCompleteLaunchBindingReceipt receipt = toReceipt(stored, sourceReceipt); + requireExactEvidence(receipt, evidence); + if (inserted == 0) { + throwIfInsertDidNotSelectOriginal(receipt, sourceReceipt, evidence); + } + return receipt; + } + + /** + * Rehydrates the internal receipt only after the exact local intake has been read independently. + */ + WorldCompleteLaunchBindingReceipt toReceipt( + StoredBinding stored, WorldAuthoredSourceIntakeReceipt sourceReceipt) { + Objects.requireNonNull(stored, "stored"); + Objects.requireNonNull(sourceReceipt, "sourceReceipt"); + if (!stored.targetNamespace().equals(sourceReceipt.targetNamespace()) + || !stored.canonicalTenantId().equals(sourceReceipt.canonicalTenantId()) + || !stored.worldSlug().equals(sourceReceipt.worldSlug()) + || !stored.intakeOperationId().equals(sourceReceipt.operationId()) + || !stored.intakeRequestId().equals(sourceReceipt.intakeRequestId()) + || stored.localTenantKey() != sourceReceipt.localTenantKey() + || !stored.sourceOperationId().equals(sourceReceipt.sourceOperationId()) + || !stored.sourceEvidenceDigest().equals(sourceReceipt.sourceEvidenceDigest()) + || !stored.intakeReceiptDigest().equals(sourceReceipt.receiptDigest())) { + throw new InvalidBindingEvidenceException( + "World complete launch binding differs from its exact local source receipt"); + } + try { + return new WorldCompleteLaunchBindingReceipt( + 1, + stored.operationId(), + stored.targetNamespace(), + stored.canonicalTenantId(), + stored.worldSlug(), + stored.controlPlaneRequestId(), + sourceReceipt, + stored.evidence()); + } catch (RuntimeException exception) { + if (exception instanceof InvalidBindingEvidenceException) { + throw exception; + } + throw new InvalidBindingEvidenceException( + "Persisted World complete launch binding conflicts with its local source", exception); + } + } + + void requireExactEvidence( + WorldCompleteLaunchBindingReceipt receipt, CompleteLaunchBindingEvidence expected) { + AuthoredWorldLaunchDescriptorEvidence descriptor = expected.descriptor(); + if (!receipt.evidence().equals(expected) + || !receipt.targetNamespace().equals(descriptor.targetNamespace()) + || !receipt.canonicalTenantId().equals(descriptor.canonicalTenantId()) + || !receipt.worldSlug().equals(descriptor.worldSlug()) + || !receipt.controlPlaneRequestId().equals(descriptor.controlPlaneRequestId())) { + throw new RegistrationConflictException( + "World complete launch binding request identity was reused with changed evidence"); + } + } + + private void throwIfInsertDidNotSelectOriginal( + WorldCompleteLaunchBindingReceipt receipt, + WorldAuthoredSourceIntakeReceipt sourceReceipt, + CompleteLaunchBindingEvidence expected) { + if (!receipt.sourceIntakeReceipt().equals(sourceReceipt)) { + throw new RegistrationConflictException( + "World complete launch binding request identity changed its source intake"); + } + requireExactEvidence(receipt, expected); + } + + private Record find(String namespace, UUID canonicalTenantId, String controlPlaneRequestId) { + return dsl.selectFrom(BINDING) + .where( + TARGET_NAMESPACE + .eq(namespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(CONTROL_PLANE_REQUEST_ID.eq(controlPlaneRequestId))) + .fetchOne(); + } + + private StoredBinding toStoredBinding(Record row) { + try { + UUID operationId = required(row, BINDING_OPERATION_ID); + String namespace = required(row, TARGET_NAMESPACE); + UUID canonicalTenantId = required(row, CANONICAL_TENANT_ID); + UUID canonicalVersionId = required(row, CANONICAL_VERSION_ID); + String worldSlug = required(row, WORLD_SLUG); + String controlPlaneRequestId = required(row, CONTROL_PLANE_REQUEST_ID); + UUID intakeOperationId = required(row, INTAKE_OPERATION_ID); + UUID intakeRequestId = required(row, INTAKE_REQUEST_ID); + Long localTenantKey = required(row, LOCAL_TENANT_KEY); + UUID sourceOperationId = required(row, SOURCE_OPERATION_ID); + String sourceEvidenceDigest = required(row, SOURCE_EVIDENCE_DIGEST); + String intakeReceiptDigest = required(row, INTAKE_RECEIPT_DIGEST); + String descriptorRequestDigest = required(row, DESCRIPTOR_REQUEST_DIGEST); + String descriptorResultDigest = required(row, DESCRIPTOR_RESULT_DIGEST); + String attestationDigest = required(row, RELEASE_ATTESTATION_DIGEST); + AuthoredWorldLaunchDescriptorEvidence descriptor = + readJson(required(row, DESCRIPTOR_JSON), AuthoredWorldLaunchDescriptorEvidence.class); + AuthoredWorldReleaseAttestationEvidence attestation = + readJson( + required(row, RELEASE_ATTESTATION_JSON), + AuthoredWorldReleaseAttestationEvidence.class); + descriptor.requireValid(); + CompleteLaunchBindingEvidence evidence = + new CompleteLaunchBindingEvidence(descriptor, attestation); + requireStoredColumns( + namespace, + canonicalTenantId, + canonicalVersionId, + worldSlug, + controlPlaneRequestId, + sourceOperationId, + sourceEvidenceDigest, + descriptorRequestDigest, + descriptorResultDigest, + attestationDigest, + descriptor, + attestation); + if (localTenantKey <= 0) { + throw new IllegalArgumentException("Stored local tenant key must be positive"); + } + return new StoredBinding( + operationId, + namespace, + canonicalTenantId, + worldSlug, + controlPlaneRequestId, + intakeOperationId, + intakeRequestId, + localTenantKey, + sourceOperationId, + sourceEvidenceDigest, + intakeReceiptDigest, + descriptorRequestDigest, + descriptorResultDigest, + attestationDigest, + evidence); + } catch (RuntimeException exception) { + if (exception instanceof InvalidBindingEvidenceException) { + throw exception; + } + throw new InvalidBindingEvidenceException( + "Persisted World complete launch binding evidence is invalid", exception); + } + } + + private static void requireStoredColumns( + String namespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + String worldSlug, + String controlPlaneRequestId, + UUID sourceOperationId, + String sourceEvidenceDigest, + String descriptorRequestDigest, + String descriptorResultDigest, + String attestationDigest, + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldReleaseAttestationEvidence attestation) { + if (!namespace.equals(descriptor.targetNamespace()) + || !canonicalTenantId.equals(descriptor.canonicalTenantId()) + || !worldSlug.equals(descriptor.worldSlug()) + || !controlPlaneRequestId.equals(descriptor.controlPlaneRequestId()) + || !sourceOperationId.equals(descriptor.authoredWorldSourceOperationId()) + || !sourceEvidenceDigest.equals(descriptor.authoredWorldSourceEvidenceDigest()) + || !descriptorRequestDigest.equals(descriptor.requestDigest()) + || !descriptorResultDigest.equals(descriptor.resultDigest()) + || !canonicalVersionId.equals(attestation.canonicalVersionId()) + || !attestationDigest.equals(attestation.evidenceDigest())) { + throw new InvalidBindingEvidenceException( + "Persisted World complete launch binding columns differ from their closed evidence"); + } + } + + private static void requireSourceBinding( + String namespace, + WorldAuthoredSourceIntakeReceipt sourceReceipt, + CompleteLaunchBindingEvidence evidence) { + AuthoredWorldLaunchDescriptorEvidence descriptor = evidence.descriptor(); + if (!namespace.equals(descriptor.targetNamespace()) + || !namespace.equals(sourceReceipt.targetNamespace()) + || !descriptor.canonicalTenantId().equals(sourceReceipt.canonicalTenantId()) + || !descriptor.worldSlug().equals(sourceReceipt.worldSlug()) + || !descriptor.authoredWorldSourceOperationId().equals(sourceReceipt.sourceOperationId()) + || !descriptor + .authoredWorldSourceEvidenceDigest() + .equals(sourceReceipt.sourceEvidenceDigest())) { + throw new RegistrationConflictException( + "Complete launch binding does not match the exact World source intake"); + } + } + + private static T required(Record row, Field field) { + return Objects.requireNonNull(row.get(field), "Persisted " + field.getName() + " is null"); + } + + private static String writeJson(Object value) { + try { + return CLOSED_JSON.writeValueAsString(value); + } catch (Exception exception) { + throw new InvalidBindingEvidenceException( + "World complete launch binding evidence could not be encoded", exception); + } + } + + private static T readJson(String json, Class type) { + try { + T value = CLOSED_JSON.readValue(json, type); + if (!writeJson(value).equals(json)) { + throw new IllegalArgumentException("Persisted evidence JSON is not in its closed form"); + } + return value; + } catch (Exception exception) { + throw new InvalidBindingEvidenceException( + "Persisted World complete launch binding JSON is not closed evidence", exception); + } + } + + private static void validateKey( + String namespace, UUID canonicalTenantId, String controlPlaneRequestId) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("namespace must be one canonical DNS label"); + } + if (canonicalTenantId == null || canonicalTenantId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("canonicalTenantId must be a non-nil UUID"); + } + if (controlPlaneRequestId == null || controlPlaneRequestId.isBlank()) { + throw new IllegalArgumentException("controlPlaneRequestId must be nonblank"); + } + } + + private static UUID newNonNilUuid() { + UUID value; + do { + value = UUID.randomUUID(); + } while (value.equals(new UUID(0L, 0L))); + return value; + } + + private static void requireNoActiveTransaction(String label) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException(label + " requires an independent committed owner read"); + } + } + + private void requireReadOnlyRepeatableReadOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World complete launch binding snapshot read requires a read-only REPEATABLE READ owner transaction"); + } + Record state = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"), + "World transaction state query returned no row"); + if (!"repeatable read".equals(state.get("isolation", String.class)) + || !"on".equals(state.get("read_only", String.class))) { + throw new IllegalStateException( + "World complete launch binding snapshot read requires a read-only REPEATABLE READ owner transaction"); + } + } + + private void requireWritableActivationTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World complete launch binding activation read requires a writable READ COMMITTED owner transaction"); + } + Record state = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"), + "World transaction state query returned no row"); + if (!"read committed".equals(state.get("isolation", String.class)) + || !"off".equals(state.get("read_only", String.class))) { + throw new IllegalStateException( + "World complete launch binding activation read requires a writable READ COMMITTED owner transaction"); + } + } + + private static void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World complete launch binding requires an active World owner transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "World complete launch binding requires a writable owner transaction"); + } + Integer declaredIsolation = + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (declaredIsolation != null + && declaredIsolation != java.sql.Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "World complete launch binding requires READ COMMITTED isolation"); + } + } + + static record StoredBinding( + UUID operationId, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + UUID intakeOperationId, + UUID intakeRequestId, + long localTenantKey, + UUID sourceOperationId, + String sourceEvidenceDigest, + String intakeReceiptDigest, + String descriptorRequestDigest, + String descriptorResultDigest, + String releaseAttestationDigest, + CompleteLaunchBindingEvidence evidence) {} + + public static final class RegistrationConflictException extends IllegalStateException { + public RegistrationConflictException(String message) { + super(message); + } + } + + public static final class InvalidBindingEvidenceException extends IllegalStateException { + public InvalidBindingEvidenceException(String message) { + super(message); + } + + public InvalidBindingEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingService.java new file mode 100644 index 0000000000..028f580de9 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingService.java @@ -0,0 +1,695 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +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.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationClient; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Explicitly unwired World owner step for retaining the complete released-content launch binding. + * + *

Neither binding nor its current-Version read proves local content, commit fencing, lifecycle + * preparation, or runtime admission. + */ +public final class WorldCompleteLaunchBindingService { + private final AuthoredWorldLaunchDescriptorClient client; + private final AuthoredWorldVersionStateClient versionStateClient; + private final WorldCompleteLaunchBindingRepository repository; + private final WorldAuthoredSourceIntakeRepository sourceIntakeRepository; + private final CanonicalGameInstanceLaunchAssociationClient gameSessionClient; + private final TransactionTemplate ownerTransaction; + private final String workloadNamespace; + + public WorldCompleteLaunchBindingService( + AuthoredWorldLaunchDescriptorClient client, + WorldCompleteLaunchBindingRepository repository, + WorldAuthoredSourceIntakeRepository sourceIntakeRepository, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this( + client, + repository, + sourceIntakeRepository, + transactionManager, + workloadNamespace, + null, + null, + true); + } + + /** + * Constructs the explicitly unwired binding verifier with its separately authenticated Game + * Design current-version reader. + */ + public WorldCompleteLaunchBindingService( + AuthoredWorldLaunchDescriptorClient client, + WorldCompleteLaunchBindingRepository repository, + WorldAuthoredSourceIntakeRepository sourceIntakeRepository, + PlatformTransactionManager transactionManager, + String workloadNamespace, + AuthoredWorldVersionStateClient versionStateClient) { + this( + client, + repository, + sourceIntakeRepository, + transactionManager, + workloadNamespace, + versionStateClient, + null, + true); + } + + /** + * Constructs the explicitly unwired committed-launch producer with its actual Game Session + * owner-read client. The client is required for the committed-launch entry point. + */ + public WorldCompleteLaunchBindingService( + AuthoredWorldLaunchDescriptorClient client, + WorldCompleteLaunchBindingRepository repository, + WorldAuthoredSourceIntakeRepository sourceIntakeRepository, + PlatformTransactionManager transactionManager, + String workloadNamespace, + AuthoredWorldVersionStateClient versionStateClient, + CanonicalGameInstanceLaunchAssociationClient gameSessionClient) { + this( + client, + repository, + sourceIntakeRepository, + transactionManager, + workloadNamespace, + versionStateClient, + Objects.requireNonNull(gameSessionClient, "gameSessionClient"), + false); + } + + private WorldCompleteLaunchBindingService( + AuthoredWorldLaunchDescriptorClient client, + WorldCompleteLaunchBindingRepository repository, + WorldAuthoredSourceIntakeRepository sourceIntakeRepository, + PlatformTransactionManager transactionManager, + String workloadNamespace, + AuthoredWorldVersionStateClient versionStateClient, + CanonicalGameInstanceLaunchAssociationClient gameSessionClient, + boolean allowMissingGameSessionClient) { + this.client = Objects.requireNonNull(client, "client"); + this.versionStateClient = versionStateClient; + if (!allowMissingGameSessionClient) { + Objects.requireNonNull(gameSessionClient, "gameSessionClient"); + } + this.gameSessionClient = gameSessionClient; + this.repository = Objects.requireNonNull(repository, "repository"); + this.sourceIntakeRepository = + Objects.requireNonNull(sourceIntakeRepository, "sourceIntakeRepository"); + Objects.requireNonNull(transactionManager, "transactionManager"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.workloadNamespace = workloadNamespace; + this.ownerTransaction = new TransactionTemplate(transactionManager); + this.ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.ownerTransaction.setReadOnly(false); + } + + /** + * Authenticates Game Session's exact committed launch association, independently rereads the + * complete immutable pair from Game Design, and retains that pair against its exact committed + * World source intake. This is released-content evidence only; it does not prove local content, + * current authorization, lifecycle preparation, or runtime admission. + */ + public WorldCompleteLaunchBindingReceipt bindCommittedLaunch( + CanonicalGameInstanceLaunchAssociationReadEvidence.Request request) { + requireAuthenticatedGameSessionCaller(); + requireNoAmbientCommittedLaunchTransaction(); + if (gameSessionClient == null) { + throw new IllegalStateException( + "World committed-launch binding has no configured Game Session owner reader"); + } + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new SecurityException( + "Committed launch binding namespace does not match this World workload"); + } + + GetLaunchDescriptorRequest gameDesignReadRequest = + committedLaunchGameDesignReadRequest(request); + CompleteLaunchBindingEvidence fetched = client.getComplete(gameDesignReadRequest); + requireCommittedLaunchEvidence(fetched, gameDesignReadRequest, request); + + CanonicalGameInstanceLaunchAssociationReadEvidence.Result association = + gameSessionClient.read(request); + requireGameSessionBinding(request, association, fetched); + + AuthoredWorldLaunchDescriptorEvidence descriptor = fetched.descriptor(); + WorldAuthoredSourceIntakeReceipt sourceReceipt = readExactSourceReceipt(fetched); + requireFreshCommittedLaunchReadId( + gameDesignReadRequest.getRequestId(), request, descriptor, sourceReceipt); + requireCommittedLaunchSourcePair(fetched, sourceReceipt); + Optional prior = + repository.read( + workloadNamespace, descriptor.canonicalTenantId(), descriptor.controlPlaneRequestId()); + if (prior.isPresent()) { + return loadCommittedLaunchReceipt(prior.orElseThrow(), request, fetched, sourceReceipt); + } + + WorldCompleteLaunchBindingReceipt accepted; + try { + accepted = + ownerTransaction.execute( + status -> repository.acceptFresh(workloadNamespace, sourceReceipt, fetched)); + } catch (RuntimeException ownerFailure) { + Optional uncertainCommit = + repository.read( + workloadNamespace, + descriptor.canonicalTenantId(), + descriptor.controlPlaneRequestId()); + if (uncertainCommit.isEmpty()) { + throw ownerFailure; + } + return loadCommittedLaunchReceipt( + uncertainCommit.orElseThrow(), request, fetched, sourceReceipt); + } + if (accepted == null) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "World owner transaction returned no committed launch binding receipt"); + } + requireCommittedLaunchRequest(accepted, request); + requireSamePair(accepted, fetched); + if (!accepted.sourceIntakeReceipt().equals(sourceReceipt)) { + throw new WorldCompleteLaunchBindingRepository.RegistrationConflictException( + "World committed launch binding changed its exact source intake"); + } + + Optional committed = + repository.read( + workloadNamespace, descriptor.canonicalTenantId(), descriptor.controlPlaneRequestId()); + if (committed.isEmpty()) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "World committed launch binding is missing after its owner commit"); + } + WorldCompleteLaunchBindingReceipt readback = + loadCommittedLaunchReceipt(committed.orElseThrow(), request, fetched, sourceReceipt); + if (!accepted.equals(readback)) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "World committed launch binding changed during independent owner readback"); + } + return readback; + } + + /** + * Binds the exact immutable Game Design read selector to the already committed local source. + * + *

The verified same-namespace Game Session workload is required before any owner read or Game + * Design call. Existing claims are resolved first so retries cannot select newer defaults. + */ + public WorldCompleteLaunchBindingReceipt bind(GetRequest request) { + requireAuthenticatedGameSessionCaller(); + requireNoAmbientTransaction(); + validateRequest(request); + + AuthoredWorldLaunchDescriptorEvidence.Request expected = request.expectedRequest(); + Optional prior = + repository.read( + workloadNamespace, expected.canonicalTenantId(), expected.controlPlaneRequestId()); + if (prior.isPresent()) { + WorldCompleteLaunchBindingRepository.StoredBinding stored = prior.orElseThrow(); + requireStoredRequest(stored, request); + WorldCompleteLaunchBindingReceipt receipt = loadExactSourceReceipt(stored); + return receipt; + } + + CompleteLaunchBindingEvidence fetched = + client.getComplete(AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest(request)); + requireFetchedEvidence(fetched, request); + WorldAuthoredSourceIntakeReceipt sourceReceipt = readExactSourceReceipt(fetched); + + WorldCompleteLaunchBindingReceipt accepted; + try { + accepted = + ownerTransaction.execute( + status -> repository.acceptFresh(workloadNamespace, sourceReceipt, fetched)); + } catch (RuntimeException ownerFailure) { + // A commit acknowledgment can be lost after PostgreSQL made the immutable claim durable. + Optional uncertainCommit = + repository.read( + workloadNamespace, expected.canonicalTenantId(), expected.controlPlaneRequestId()); + if (uncertainCommit.isEmpty()) { + throw ownerFailure; + } + WorldCompleteLaunchBindingReceipt recovered = + recoverExactSourceReceipt(uncertainCommit.orElseThrow(), request); + requireSamePair(recovered, fetched); + return recovered; + } + if (accepted == null) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "World owner transaction returned no complete launch binding receipt"); + } + requireStoredRequest(accepted, request); + requireSamePair(accepted, fetched); + + Optional committed = + repository.read( + workloadNamespace, expected.canonicalTenantId(), expected.controlPlaneRequestId()); + if (committed.isEmpty()) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "World complete launch binding is missing after its owner commit"); + } + WorldCompleteLaunchBindingRepository.StoredBinding stored = committed.orElseThrow(); + requireStoredRequest(stored, request); + WorldCompleteLaunchBindingReceipt readback = loadExactSourceReceipt(stored); + if (!accepted.equals(readback)) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "World complete launch binding changed during independent commit readback"); + } + return readback; + } + + /** + * Reads current Game Design version evidence for an already committed, exact World binding. + * + *

This read never creates or changes the historical binding. It establishes only current + * source-owned Version eligibility at the descriptor epoch; it does not prove World content, + * commit fencing, preparation, or admission. + */ + public AuthoredWorldVersionStateEvidence readCurrentVersionState( + GetRequest request, UUID currentReadId) { + requireAuthenticatedGameSessionCaller(); + requireNoAmbientTransaction(); + validateRequest(request); + requireNonNilCurrentReadId(currentReadId); + if (versionStateClient == null) { + throw new IllegalStateException( + "World current-version verification has no configured Game Design reader"); + } + + AuthoredWorldLaunchDescriptorEvidence.Request expected = request.expectedRequest(); + WorldCompleteLaunchBindingRepository.StoredBinding stored = + repository + .read(workloadNamespace, expected.canonicalTenantId(), expected.controlPlaneRequestId()) + .orElseThrow( + () -> + new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "World current-version verification requires a committed launch binding")); + requireStoredRequest(stored, request); + WorldCompleteLaunchBindingReceipt committed = loadExactSourceReceipt(stored); + requireStoredRequest(committed, request); + requireFreshCurrentReadId(currentReadId, request, committed); + + AuthoredWorldLaunchDescriptorEvidence descriptor = committed.descriptor(); + // This is the Game Design-owned Version selector, never World's private local tenant key. + AuthoredWorldVersionStateEvidence.Request currentRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + descriptor.targetNamespace(), + currentReadId, + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.versionId()); + AuthoredWorldVersionStateEvidence current; + try { + current = versionStateClient.read(currentRequest); + } catch (RuntimeException exception) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "Current Game Design version-state evidence is unavailable or invalid", exception); + } + if (current == null + || !currentRequest.equals(current.request()) + || !committed.sourceIntakeReceipt().source().equals(current.sourceEvidence())) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "Game Design current-version evidence differs from the exact committed World source"); + } + UUID committedCanonicalVersionId = + committed.evidence().releaseAttestation().canonicalVersionId(); + if (!committedCanonicalVersionId.equals(current.canonicalVersionId())) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "Game Design current canonical version UUID differs from the committed release attestation"); + } + if (current.versionState() != VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED + && current.versionState() != VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "Game Design current Version is not PUBLISHED or ACTIVE"); + } + if (current.versionStateEpoch() != descriptor.versionStateEpoch()) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "Game Design current Version epoch differs from the immutable launch descriptor"); + } + return current; + } + + private WorldCompleteLaunchBindingReceipt loadExactSourceReceipt( + WorldCompleteLaunchBindingRepository.StoredBinding stored) { + CompleteLaunchBindingEvidence evidence = stored.evidence(); + WorldAuthoredSourceIntakeReceipt sourceReceipt = readExactSourceReceipt(evidence); + return repository.toReceipt(stored, sourceReceipt); + } + + private WorldCompleteLaunchBindingReceipt recoverExactSourceReceipt( + WorldCompleteLaunchBindingRepository.StoredBinding stored, GetRequest request) { + requireStoredRequest(stored, request); + return loadExactSourceReceipt(stored); + } + + private WorldAuthoredSourceIntakeReceipt readExactSourceReceipt( + CompleteLaunchBindingEvidence evidence) { + AuthoredWorldLaunchDescriptorEvidence descriptor = evidence.descriptor(); + return sourceIntakeRepository + .readBySource( + workloadNamespace, + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest()) + .orElseThrow( + () -> + new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "Complete launch binding has no exact committed World source intake")); + } + + private void requireFreshCommittedLaunchReadId( + String readRequestId, + CanonicalGameInstanceLaunchAssociationReadEvidence.Request associationRequest, + AuthoredWorldLaunchDescriptorEvidence descriptor, + WorldAuthoredSourceIntakeReceipt sourceReceipt) { + if (readRequestId.equals(associationRequest.readRequestId().toString()) + || readRequestId.equals(descriptor.authoredWorldSourceOperationId().toString()) + || readRequestId.equals(sourceReceipt.operationId().toString()) + || readRequestId.equals(sourceReceipt.intakeRequestId().toString()) + || readRequestId.equals(sourceReceipt.sourceOperationId().toString()) + || readRequestId.equals(sourceReceipt.source().registrationRequestId().toString()) + || readRequestId.equals(descriptor.controlPlaneRequestId())) { + throw new IllegalArgumentException( + "Game Design committed-launch read ID must be distinct from original source and association identities"); + } + } + + private void requireCommittedLaunchSourcePair( + CompleteLaunchBindingEvidence evidence, WorldAuthoredSourceIntakeReceipt sourceReceipt) { + AuthoredWorldLaunchDescriptorEvidence descriptor = evidence.descriptor(); + if (!workloadNamespace.equals(sourceReceipt.targetNamespace()) + || !descriptor.canonicalTenantId().equals(sourceReceipt.canonicalTenantId()) + || !descriptor.worldSlug().equals(sourceReceipt.worldSlug()) + || !descriptor.authoredWorldSourceOperationId().equals(sourceReceipt.sourceOperationId()) + || !descriptor + .authoredWorldSourceEvidenceDigest() + .equals(sourceReceipt.sourceEvidenceDigest()) + || !sourceReceipt + .intakeRequestId() + .equals( + evidence + .releaseAttestation() + .worldStartLocationEvidence() + .request() + .intakeRequestId())) { + throw new WorldCompleteLaunchBindingRepository.RegistrationConflictException( + "Complete launch binding differs from the exact committed World source intake"); + } + } + + private GetLaunchDescriptorRequest committedLaunchGameDesignReadRequest( + CanonicalGameInstanceLaunchAssociationReadEvidence.Request request) { + UUID requestId; + do { + requestId = UUID.randomUUID(); + } while (requestId.equals(request.readRequestId()) + || requestId.equals(request.canonicalTenantId()) + || requestId.equals(request.gameInstanceUuid()) + || requestId.toString().equals(request.controlPlaneRequestId())); + return GetLaunchDescriptorRequest.newBuilder() + .setRequestId(requestId.toString()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .setControlPlaneRequestId(request.controlPlaneRequestId()) + .setExpectedRequestDigest(request.expectedDescriptorRequestDigest()) + .setExpectedResultDigest(request.expectedDescriptorResultDigest()) + .build(); + } + + private void requireCommittedLaunchEvidence( + CompleteLaunchBindingEvidence evidence, + GetLaunchDescriptorRequest gameDesignReadRequest, + CanonicalGameInstanceLaunchAssociationReadEvidence.Request associationRequest) { + if (evidence == null) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "Game Design returned no complete committed launch binding evidence"); + } + AuthoredWorldLaunchDescriptorEvidence descriptor = evidence.descriptor(); + descriptor.requireValid(); + evidence.releaseAttestation().requireValid(descriptor); + if (gameDesignReadRequest + .getRequestId() + .equals(descriptor.authoredWorldSourceOperationId().toString())) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "Game Design committed launch read ID is not distinct from its source operation"); + } + if (!workloadNamespace.equals(descriptor.targetNamespace()) + || !associationRequest.canonicalTenantId().equals(descriptor.canonicalTenantId()) + || !associationRequest.worldSlug().equals(descriptor.worldSlug()) + || !associationRequest.controlPlaneRequestId().equals(descriptor.controlPlaneRequestId()) + || !associationRequest.launchDescriptorId().equals(descriptor.launchDescriptorId()) + || !associationRequest.expectedDescriptorRequestDigest().equals(descriptor.requestDigest()) + || !associationRequest.expectedDescriptorResultDigest().equals(descriptor.resultDigest()) + || !associationRequest + .expectedReleaseAttestationEvidenceDigest() + .equals(evidence.releaseAttestation().evidenceDigest()) + || !gameDesignReadRequest + .getCanonicalTenantId() + .equals(descriptor.canonicalTenantId().toString()) + || !gameDesignReadRequest.getWorldSlug().equals(descriptor.worldSlug()) + || !gameDesignReadRequest + .getControlPlaneRequestId() + .equals(descriptor.controlPlaneRequestId()) + || !gameDesignReadRequest.getExpectedRequestDigest().equals(descriptor.requestDigest()) + || !gameDesignReadRequest.getExpectedResultDigest().equals(descriptor.resultDigest())) { + throw new WorldCompleteLaunchBindingRepository.RegistrationConflictException( + "Game Design complete launch pair differs from the exact committed association selector"); + } + if (!AuthoredWorldReleaseAttestationEvidence.requiresWorldStartLocationEvidence( + evidence.releaseAttestation().schemaVersion()) + || evidence.releaseAttestation().worldStartLocationEvidence() == null) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "Committed launch binding requires full selected-release selector evidence"); + } + } + + private WorldCompleteLaunchBindingReceipt loadCommittedLaunchReceipt( + WorldCompleteLaunchBindingRepository.StoredBinding stored, + CanonicalGameInstanceLaunchAssociationReadEvidence.Request request, + CompleteLaunchBindingEvidence expectedPair, + WorldAuthoredSourceIntakeReceipt expectedSourceReceipt) { + requireCommittedLaunchRequest(stored, request); + requireSameStoredPair(stored.evidence(), expectedPair); + WorldAuthoredSourceIntakeReceipt sourceReadback = readExactSourceReceipt(expectedPair); + if (!expectedSourceReceipt.equals(sourceReadback)) { + throw new WorldCompleteLaunchBindingRepository.RegistrationConflictException( + "World committed launch binding source intake changed during exact readback"); + } + WorldCompleteLaunchBindingReceipt receipt = repository.toReceipt(stored, sourceReadback); + requireCommittedLaunchRequest(receipt, request); + requireSamePair(receipt, expectedPair); + return receipt; + } + + private void requireCommittedLaunchRequest( + WorldCompleteLaunchBindingRepository.StoredBinding stored, + CanonicalGameInstanceLaunchAssociationReadEvidence.Request request) { + AuthoredWorldLaunchDescriptorEvidence descriptor = stored.evidence().descriptor(); + if (!workloadNamespace.equals(stored.targetNamespace()) + || !request.canonicalTenantId().equals(stored.canonicalTenantId()) + || !request.controlPlaneRequestId().equals(stored.controlPlaneRequestId()) + || !request.worldSlug().equals(stored.worldSlug()) + || !workloadNamespace.equals(descriptor.targetNamespace()) + || !request.canonicalTenantId().equals(descriptor.canonicalTenantId()) + || !request.worldSlug().equals(descriptor.worldSlug()) + || !request.controlPlaneRequestId().equals(descriptor.controlPlaneRequestId()) + || !request.launchDescriptorId().equals(descriptor.launchDescriptorId()) + || !request.expectedDescriptorRequestDigest().equals(descriptor.requestDigest()) + || !request.expectedDescriptorResultDigest().equals(descriptor.resultDigest()) + || !request + .expectedReleaseAttestationEvidenceDigest() + .equals(stored.evidence().releaseAttestation().evidenceDigest())) { + throw new WorldCompleteLaunchBindingRepository.RegistrationConflictException( + "World committed launch binding differs from its exact Game Session selector"); + } + } + + private void requireCommittedLaunchRequest( + WorldCompleteLaunchBindingReceipt receipt, + CanonicalGameInstanceLaunchAssociationReadEvidence.Request request) { + AuthoredWorldLaunchDescriptorEvidence descriptor = receipt.descriptor(); + if (!workloadNamespace.equals(receipt.targetNamespace()) + || !request.canonicalTenantId().equals(receipt.canonicalTenantId()) + || !request.worldSlug().equals(receipt.worldSlug()) + || !request.controlPlaneRequestId().equals(receipt.controlPlaneRequestId()) + || !workloadNamespace.equals(descriptor.targetNamespace()) + || !request.canonicalTenantId().equals(descriptor.canonicalTenantId()) + || !request.worldSlug().equals(descriptor.worldSlug()) + || !request.controlPlaneRequestId().equals(descriptor.controlPlaneRequestId()) + || !request.launchDescriptorId().equals(descriptor.launchDescriptorId()) + || !request.expectedDescriptorRequestDigest().equals(descriptor.requestDigest()) + || !request.expectedDescriptorResultDigest().equals(descriptor.resultDigest()) + || !request + .expectedReleaseAttestationEvidenceDigest() + .equals(receipt.evidence().releaseAttestation().evidenceDigest())) { + throw new WorldCompleteLaunchBindingRepository.RegistrationConflictException( + "World committed launch binding differs from its exact Game Session selector"); + } + } + + private void requireSameStoredPair( + CompleteLaunchBindingEvidence stored, CompleteLaunchBindingEvidence expected) { + if (stored == null + || !stored.equals(expected) + || !stored.descriptor().equals(expected.descriptor()) + || !stored.releaseAttestation().equals(expected.releaseAttestation())) { + throw new WorldCompleteLaunchBindingRepository.RegistrationConflictException( + "World committed launch binding identity was reused with a changed descriptor or release"); + } + } + + private void requireStoredRequest(WorldCompleteLaunchBindingReceipt receipt, GetRequest request) { + requireStoredRequest(receipt.descriptor(), receipt.targetNamespace(), request); + } + + private void requireStoredRequest( + WorldCompleteLaunchBindingRepository.StoredBinding stored, GetRequest request) { + requireStoredRequest(stored.evidence().descriptor(), stored.targetNamespace(), request); + if (!stored.canonicalTenantId().equals(request.expectedRequest().canonicalTenantId()) + || !stored + .controlPlaneRequestId() + .equals(request.expectedRequest().controlPlaneRequestId())) { + throw new WorldCompleteLaunchBindingRepository.RegistrationConflictException( + "World complete launch binding stable request identity changed"); + } + } + + private void requireStoredRequest( + AuthoredWorldLaunchDescriptorEvidence descriptor, + String targetNamespace, + GetRequest request) { + AuthoredWorldLaunchDescriptorEvidence.Request expected = request.expectedRequest(); + if (!descriptor.request().equals(expected) + || !descriptor.resultDigest().equals(request.expectedResultDigest()) + || !workloadNamespace.equals(descriptor.targetNamespace()) + || !workloadNamespace.equals(targetNamespace)) { + throw new WorldCompleteLaunchBindingRepository.RegistrationConflictException( + "World complete launch binding request identity was reused with changed request or result"); + } + } + + private void requireFetchedEvidence(CompleteLaunchBindingEvidence evidence, GetRequest request) { + if (evidence == null) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "Game Design returned no complete launch binding evidence"); + } + AuthoredWorldLaunchDescriptorEvidence descriptor = evidence.descriptor(); + descriptor.requireValid(); + evidence.releaseAttestation().requireValid(descriptor); + if (!descriptor.request().equals(request.expectedRequest()) + || !descriptor.resultDigest().equals(request.expectedResultDigest()) + || !workloadNamespace.equals(descriptor.targetNamespace())) { + throw new WorldCompleteLaunchBindingRepository.RegistrationConflictException( + "Game Design complete launch binding differs from the exact read request"); + } + } + + private void requireSamePair( + WorldCompleteLaunchBindingReceipt receipt, CompleteLaunchBindingEvidence expected) { + if (!receipt.evidence().equals(expected)) { + throw new WorldCompleteLaunchBindingRepository.RegistrationConflictException( + "World complete launch binding request identity was reused with another release pair"); + } + } + + private void validateRequest(GetRequest request) { + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.expectedRequest().targetNamespace())) { + throw new SecurityException( + "Complete launch binding request namespace does not match this World workload"); + } + } + + private static void requireNonNilCurrentReadId(UUID currentReadId) { + if (currentReadId == null || currentReadId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Current version-state read ID must be a non-nil UUID"); + } + } + + private static void requireFreshCurrentReadId( + UUID currentReadId, GetRequest request, WorldCompleteLaunchBindingReceipt committed) { + WorldAuthoredSourceIntakeReceipt intake = committed.sourceIntakeReceipt(); + if (currentReadId.equals(request.requestId()) + || currentReadId.equals(committed.operationId()) + || currentReadId.equals(intake.operationId()) + || currentReadId.equals(intake.intakeRequestId()) + || currentReadId.equals(intake.sourceOperationId()) + || currentReadId.equals(intake.source().registrationRequestId())) { + throw new IllegalArgumentException( + "Current version-state read ID must be separate from source and registration IDs"); + } + } + + private void requireAuthenticatedGameSessionCaller() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || !peer.isService("game-session-service") + || !peer.isInNamespace(workloadNamespace) + || SessionContext.hasAuthenticatedCallerContext()) { + throw new SecurityException( + "World complete launch binding requires only the authenticated same-namespace Game Session workload"); + } + } + + private static void requireNoAmbientCommittedLaunchTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "World committed launch binding requires independent owner reads outside ambient transactions"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World complete launch binding cannot enter from an ambient transaction"); + } + } + + private static void requireGameSessionBinding( + CanonicalGameInstanceLaunchAssociationReadEvidence.Request request, + CanonicalGameInstanceLaunchAssociationReadEvidence.Result result, + CompleteLaunchBindingEvidence expected) { + if (result == null + || !request.equals(result.request()) + || result.playableStateScope() + != net.firedevops.firemud.common.publication.RealmEntryPolicy.StateScope.SHARED + || !result.publicProduction() + || !expected.equals(result.launchBindingEvidence()) + || !expected.descriptor().equals(result.launchBindingEvidence().descriptor()) + || !expected + .releaseAttestation() + .equals(result.launchBindingEvidence().releaseAttestation())) { + throw new WorldCompleteLaunchBindingRepository.RegistrationConflictException( + "Game Session association differs from the exact World selector or release pair"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidence.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidence.java new file mode 100644 index 0000000000..471b6a5801 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidence.java @@ -0,0 +1,183 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; + +/** Exact caller binding and owner-produced checkpoint for one World publication-freeze attempt. */ +public record WorldDesignPublicationFenceEvidence( + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + UUID versionIdentityOperationId, + long gameDesignVersionId, + UUID intakeRequestId, + UUID intakeOperationId, + String intakeRequestDigest, + UUID sourceOperationId, + String sourceEvidenceDigest, + String intakeReceiptDigest, + String publicationRequestId, + String requestDigest, + long versionStateEpoch, + String publishWorkflowId) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SOURCE_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern REQUEST_DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern CONTENT_DIGEST = Pattern.compile("[0-9a-f]{64}"); + + // requestDigest is retained as the supplied full publication-request digest. The existing + // PublicationDigestRequestBinding is used only for workflow identity derivation here; its + // publicationDigestRequest/v1 read-binding digest is not the full freeze-request digest. + + public WorldDesignPublicationFenceEvidence { + new OwnerBinding( + targetNamespace, + canonicalTenantId, + canonicalVersionId, + versionIdentityOperationId, + gameDesignVersionId, + intakeRequestId, + intakeOperationId, + intakeRequestDigest, + sourceOperationId, + sourceEvidenceDigest, + intakeReceiptDigest); + requirePositive(versionStateEpoch, "versionStateEpoch"); + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.full( + canonicalTenantId.toString(), Long.toString(gameDesignVersionId), publicationRequestId); + if (requestDigest == null || !REQUEST_DIGEST.matcher(requestDigest).matches()) { + throw new IllegalArgumentException("requestDigest must be 64 lowercase hexadecimal digits"); + } + if (!binding.derivedWorkflowIdentity().equals(publishWorkflowId)) { + throw new IllegalArgumentException( + "publishWorkflowId does not match the canonical full-version workflow identity"); + } + } + + /** The common owner scope and complete source binding used by ordinary writers and freezes. */ + public OwnerBinding ownerBinding() { + return new OwnerBinding( + targetNamespace, + canonicalTenantId, + canonicalVersionId, + versionIdentityOperationId, + gameDesignVersionId, + intakeRequestId, + intakeOperationId, + intakeRequestDigest, + sourceOperationId, + sourceEvidenceDigest, + intakeReceiptDigest); + } + + /** + * Scope/source identity needed to serialize an ordinary OPEN writer. It carries no publication + * request, digest, epoch, workflow, fence, or checkpoint. + */ + public record OwnerBinding( + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + UUID versionIdentityOperationId, + long gameDesignVersionId, + UUID intakeRequestId, + UUID intakeOperationId, + String intakeRequestDigest, + UUID sourceOperationId, + String sourceEvidenceDigest, + String intakeReceiptDigest) { + public OwnerBinding { + if (targetNamespace == null || !GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + requireNonNil(versionIdentityOperationId, "versionIdentityOperationId"); + requirePositive(gameDesignVersionId, "gameDesignVersionId"); + requireNonNil(intakeRequestId, "intakeRequestId"); + requireNonNil(intakeOperationId, "intakeOperationId"); + requireDigest(intakeRequestDigest, "intakeRequestDigest"); + requireNonNil(sourceOperationId, "sourceOperationId"); + requireDigest(sourceEvidenceDigest, "sourceEvidenceDigest"); + requireDigest(intakeReceiptDigest, "intakeReceiptDigest"); + } + } + + /** + * Returns the full-version request identity binding used to derive the canonical workflow ID. Its + * separate publicationDigestRequest/v1 digest is not this record's supplied requestDigest. + */ + public PublicationDigestRequestBinding publicationBinding() { + return PublicationDigestRequestBinding.full( + canonicalTenantId.toString(), Long.toString(gameDesignVersionId), publicationRequestId); + } + + /** Owner-local complete digest checkpoint captured only after the shared version lock is held. */ + public record Checkpoint(String appliedCommitId, String contentDigest, int digestSchemaVersion) { + public Checkpoint { + requireText(appliedCommitId, "appliedCommitId"); + if (appliedCommitId.isBlank()) { + throw new IllegalArgumentException("appliedCommitId must not be blank"); + } + if (!CONTENT_DIGEST + .matcher(Objects.requireNonNull(contentDigest, "contentDigest")) + .matches()) { + throw new IllegalArgumentException("contentDigest must be 64 lowercase hexadecimal digits"); + } + if (digestSchemaVersion <= 0) { + throw new IllegalArgumentException("digestSchemaVersion must be positive"); + } + } + + private static void requireText(String value, String label) { + if (value == null || value.isEmpty() || value.getBytes(StandardCharsets.UTF_8).length > 256) { + throw new IllegalArgumentException( + label + " must be non-empty and at most 256 UTF-8 bytes"); + } + for (int index = 0; index < value.length(); index++) { + char current = value.charAt(index); + if (Character.isHighSurrogate(current)) { + if (index + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(index + 1))) { + throw new IllegalArgumentException(label + " contains malformed Unicode"); + } + index++; + } else if (Character.isLowSurrogate(current)) { + throw new IllegalArgumentException(label + " contains malformed Unicode"); + } + } + } + } + + /** Stored freeze result. The UUID is opaque and may only be compared for equality. */ + public record FrozenAttempt( + WorldDesignPublicationFenceEvidence request, UUID publicationFence, Checkpoint checkpoint) { + public FrozenAttempt { + Objects.requireNonNull(request, "request"); + requireNonNil(publicationFence, "publicationFence"); + Objects.requireNonNull(checkpoint, "checkpoint"); + } + } + + private static void requirePositive(long value, String label) { + if (value <= 0L) { + throw new IllegalArgumentException(label + " must be positive"); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private static void requireDigest(String value, String label) { + if (value == null || !SOURCE_DIGEST.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be a canonical prefixed SHA-256 digest"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java new file mode 100644 index 0000000000..d10d51bae1 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java @@ -0,0 +1,561 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.Checkpoint; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.FrozenAttempt; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Internal owner-local persistence for the World publication fence prerequisite. + * + *

This repository is not wired to an RPC or authoring route. A supplied checkpoint is retained + * as owner evidence only; it is not an authenticated Game Design freeze acknowledgement. + */ +@Repository +public class WorldDesignPublicationFenceRepository { + private static final String OPEN = "OPEN"; + private static final String FROZEN = "FROZEN"; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private enum IntakeReadIntent { + COMMITTED_READ, + WRITABLE_OWNER_TRANSACTION + } + + private static final Table OWNER = DSL.table(DSL.name("world_design_publication_fence_owner")); + private static final Table ATTEMPT = + DSL.table(DSL.name("world_design_publication_fence_attempt")); + private static final Table VERSION_IDENTITY = + DSL.table(DSL.name("world_authored_version_identity")); + 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 LOCAL_TENANT_KEY = + DSL.field(DSL.name("local_tenant_key"), Long.class); + private static final Field VERSION_ID = DSL.field(DSL.name("version_id"), Long.class); + private static final Field VERSION_OPERATION_ID = + DSL.field(DSL.name("operation_id"), UUID.class); + private static final Field VERSION_CANONICAL_VERSION_ID = + DSL.field(DSL.name("canonical_version_id"), UUID.class); + private static final Field VERSION_GAME_DESIGN_VERSION_ID = + DSL.field(DSL.name("game_design_version_id"), Long.class); + private static final Field VERSION_LOCAL_VERSION_KEY = + DSL.field(DSL.name("local_version_key"), Long.class); + private static final Field VERSION_WORLD_SLUG = + DSL.field(DSL.name("world_slug"), String.class); + private static final Field VERSION_INTAKE_OPERATION_ID = + DSL.field(DSL.name("intake_operation_id"), UUID.class); + private static final Field VERSION_INTAKE_REQUEST_ID = + DSL.field(DSL.name("intake_request_id"), UUID.class); + private static final Field VERSION_LOCAL_TENANT_KEY = + DSL.field(DSL.name("local_tenant_key"), Long.class); + private static final Field VERSION_INTAKE_REQUEST_DIGEST = + DSL.field(DSL.name("intake_request_digest"), String.class); + private static final Field VERSION_SOURCE_OPERATION_ID = + DSL.field(DSL.name("source_operation_id"), UUID.class); + private static final Field VERSION_SOURCE_EVIDENCE_DIGEST = + DSL.field(DSL.name("source_evidence_digest"), String.class); + private static final Field VERSION_INTAKE_RECEIPT_DIGEST = + DSL.field(DSL.name("intake_receipt_digest"), String.class); + private static final Field INTAKE_OPERATION_ID = + DSL.field(DSL.name("intake_operation_id"), UUID.class); + private static final Field INTAKE_REQUEST_ID = + DSL.field(DSL.name("intake_request_id"), UUID.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 INTAKE_RECEIPT_DIGEST = + DSL.field(DSL.name("intake_receipt_digest"), String.class); + private static final Field OWNER_FREEZE_PHASE = + DSL.field(DSL.name("owner_freeze_phase"), String.class); + private static final Field CURRENT_PUBLICATION_FENCE = + DSL.field(DSL.name("current_publication_fence"), UUID.class); + + private static final Field PUBLICATION_FENCE = + DSL.field(DSL.name("publication_fence"), UUID.class); + private static final Field PUBLICATION_REQUEST_ID = + DSL.field(DSL.name("publication_request_id"), String.class); + private static final Field REQUEST_DIGEST = + DSL.field(DSL.name("request_digest"), String.class); + private static final Field VERSION_STATE_EPOCH = + DSL.field(DSL.name("version_state_epoch"), Long.class); + private static final Field PUBLISH_WORKFLOW_ID = + DSL.field(DSL.name("publish_workflow_id"), String.class); + private static final Field APPLIED_COMMIT_ID = + DSL.field(DSL.name("applied_commit_id"), String.class); + private static final Field CONTENT_DIGEST = + DSL.field(DSL.name("content_digest"), String.class); + private static final Field DIGEST_SCHEMA_VERSION = + DSL.field(DSL.name("digest_schema_version"), Integer.class); + private static final Field OWNER_BINDING_SCHEMA_VERSION = + DSL.field(DSL.name("owner_binding_schema_version"), Short.class); + private static final Field CANONICAL_VERSION_ID = + DSL.field(DSL.name("canonical_version_id"), UUID.class); + private static final Field VERSION_IDENTITY_OPERATION_ID = + DSL.field(DSL.name("version_identity_operation_id"), UUID.class); + private static final Field GAME_DESIGN_VERSION_ID = + DSL.field(DSL.name("game_design_version_id"), Long.class); + private static final Field INTAKE_REQUEST_DIGEST = + DSL.field(DSL.name("intake_request_digest"), String.class); + + private final DSLContext dsl; + private final WorldAuthoredSourceIntakeRepository intakeRepository; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Injected repositories are internal Spring collaborators; construction acquires no resources and this repository has no finalizer.") + public WorldDesignPublicationFenceRepository( + DSLContext dsl, WorldAuthoredSourceIntakeRepository intakeRepository) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + this.intakeRepository = Objects.requireNonNull(intakeRepository, "intakeRepository"); + } + + /** + * Acquires the shared writable version row for an ordinary mutation and holds its row lock until + * the caller's owner transaction ends. The exact committed intake is resolved before row create + * or lock; the private local tenant key is always derived from that immutable intake. + */ + @Transactional(propagation = Propagation.MANDATORY) + public void lockOpen(OwnerBinding binding) { + lockOpenAndResolve(binding); + } + + /** Exact retained source and private keys, available only after the OPEN owner lock is held. */ + record OpenOwner( + OwnerBinding binding, WorldAuthoredSourceIntakeReceipt receipt, long localVersionKey) { + long localTenantKey() { + return receipt.localTenantKey(); + } + } + + @Transactional(propagation = Propagation.MANDATORY) + OpenOwner lockOpenAndResolve(OwnerBinding binding) { + requireWritableReadCommittedOwnerTransaction(); + ResolvedVersion resolvedVersion = + resolveVersion(binding, IntakeReadIntent.WRITABLE_OWNER_TRANSACTION); + Record owner = createAndLockOwner(resolvedVersion); + requireMatchingOwnerBinding(owner, resolvedVersion); + if (!OPEN.equals(owner.get(OWNER_FREEZE_PHASE, String.class))) { + throw new ConflictException("World version is not open for an ordinary Draft mutation"); + } + if (owner.get(CURRENT_PUBLICATION_FENCE, UUID.class) != null) { + throw new ConflictException("Open World version unexpectedly retains a publication fence"); + } + return new OpenOwner(binding, resolvedVersion.receipt(), resolvedVersion.localVersionKey()); + } + + /** + * Claims the owner-local freeze after taking the same version row lock as ordinary writers. + * + *

The checkpoint supplier runs only for the first OPEN-to-FROZEN transition, after this + * transaction holds the row lock. An exact retry returns the stored fence and checkpoint without + * recapturing server-derived output. No producer, caller authentication, or public freeze route + * is established by this internal persistence method. + */ + @Transactional(propagation = Propagation.MANDATORY) + public FrozenAttempt claimFreeze( + WorldDesignPublicationFenceEvidence evidence, Supplier checkpointSupplier) { + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(checkpointSupplier, "checkpointSupplier"); + OwnerBinding binding = evidence.ownerBinding(); + ResolvedVersion resolvedVersion = + resolveVersion(binding, IntakeReadIntent.WRITABLE_OWNER_TRANSACTION); + rejectLegacyAttempt(evidence, resolvedVersion.localVersionKey()); + Record owner = createAndLockOwner(resolvedVersion); + requireMatchingOwnerBinding(owner, resolvedVersion); + + String phase = owner.get(OWNER_FREEZE_PHASE, String.class); + UUID currentFence = owner.get(CURRENT_PUBLICATION_FENCE, UUID.class); + if (FROZEN.equals(phase)) { + if (currentFence == null) { + throw new ConflictException("Frozen World owner row has no publication fence"); + } + FrozenAttempt stored = findAttemptByFence(currentFence); + if (stored == null) { + throw new ConflictException("Frozen World owner row has no immutable attempt record"); + } + requireExactRequest(stored, evidence); + return stored; + } + if (!OPEN.equals(phase) || currentFence != null) { + throw new ConflictException( + "World version cannot start a publication freeze in its current phase"); + } + if (findAttemptByRequest(evidence, resolvedVersion.localVersionKey()) != null) { + throw new ConflictException("World publication request already has an immutable attempt"); + } + + Checkpoint checkpoint = + Objects.requireNonNull( + checkpointSupplier.get(), "checkpointSupplier returned no complete World checkpoint"); + UUID publicationFence = newNonNilUuid(); + int inserted = insertAttempt(evidence, resolvedVersion, publicationFence, checkpoint); + if (inserted != 1) { + throw new ConflictException("World publication attempt was not inserted"); + } + + int updated = + dsl.update(OWNER) + .set(OWNER_FREEZE_PHASE, FROZEN) + .set(CURRENT_PUBLICATION_FENCE, publicationFence) + .where( + TARGET_NAMESPACE + .eq(evidence.targetNamespace()) + .and(CANONICAL_TENANT_ID.eq(evidence.canonicalTenantId())) + .and(VERSION_ID.eq(resolvedVersion.localVersionKey())) + .and(OWNER_FREEZE_PHASE.eq(OPEN)) + .and(CURRENT_PUBLICATION_FENCE.isNull())) + .execute(); + if (updated != 1) { + throw new ConflictException("World publication freeze lost its locked OPEN owner row"); + } + return new FrozenAttempt(evidence, publicationFence, checkpoint); + } + + /** + * Reads one exact immutable attempt by its full request binding without creating or changing + * rows. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readAttempt(WorldDesignPublicationFenceEvidence evidence) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("World publication attempt read requires a committed read"); + } + ResolvedVersion resolvedVersion = + resolveVersion(evidence.ownerBinding(), IntakeReadIntent.COMMITTED_READ); + rejectLegacyAttempt(evidence, resolvedVersion.localVersionKey()); + FrozenAttempt stored = findAttemptByRequest(evidence, resolvedVersion.localVersionKey()); + if (stored == null) { + return Optional.empty(); + } + requireExactRequest(stored, evidence); + return Optional.of(stored); + } + + /** + * Reads one retained attempt by its opaque fence without resolving mutable source state. + * + *

This committed read requires a caller with no owner transaction or synchronization scope. It + * deliberately declares no transaction boundary so Spring does not create an empty + * synchronization scope around the read. + */ + public Optional readAttemptByFence(UUID publicationFence) { + if (publicationFence == null || NIL_UUID.equals(publicationFence)) { + throw new IllegalArgumentException("A non-nil World publication fence is required"); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("World publication attempt read requires a committed read"); + } + FrozenAttempt stored = findAttemptByFence(publicationFence); + return Optional.ofNullable(stored); + } + + private ResolvedVersion resolveVersion(OwnerBinding binding, IntakeReadIntent readIntent) { + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(readIntent, "readIntent"); + Optional intake = + switch (readIntent) { + case COMMITTED_READ -> + intakeRepository.read(binding.targetNamespace(), binding.intakeRequestId()); + case WRITABLE_OWNER_TRANSACTION -> + intakeRepository.readInOwnerPublicationTransaction( + binding.targetNamespace(), binding.intakeRequestId()); + }; + WorldAuthoredSourceIntakeReceipt receipt = + intake.orElseThrow( + () -> + new MissingIntakeException( + "World publication fence requires an already committed authored-source intake")); + requireExactIntake(binding, receipt); + + Record identity = + dsl.selectFrom(VERSION_IDENTITY) + .where(VERSION_OPERATION_ID.eq(binding.versionIdentityOperationId())) + .forShare() + .fetchOne(); + if (identity == null) { + throw new MissingVersionIdentityException( + "World publication fence requires an exact retained V27 authored-Version identity"); + } + requireExactVersionIdentity(identity, binding, receipt); + Long localVersionKey = identity.get(VERSION_LOCAL_VERSION_KEY, Long.class); + if (localVersionKey == null || localVersionKey <= 0L) { + throw new ConflictException("World Version identity has no valid private local Version key"); + } + return new ResolvedVersion(binding, receipt, localVersionKey); + } + + private void requireExactIntake(OwnerBinding binding, WorldAuthoredSourceIntakeReceipt receipt) { + if (!binding.targetNamespace().equals(receipt.targetNamespace()) + || !binding.canonicalTenantId().equals(receipt.canonicalTenantId()) + || !binding.intakeRequestId().equals(receipt.intakeRequestId()) + || !binding.intakeOperationId().equals(receipt.operationId()) + || !binding.intakeRequestDigest().equals(receipt.requestDigest()) + || !binding.sourceOperationId().equals(receipt.sourceOperationId()) + || !binding.sourceEvidenceDigest().equals(receipt.sourceEvidenceDigest()) + || !binding.intakeReceiptDigest().equals(receipt.receiptDigest())) { + throw new ConflictException( + "World publication request differs from the complete committed authored-source intake"); + } + } + + private void requireExactVersionIdentity( + Record identity, OwnerBinding binding, WorldAuthoredSourceIntakeReceipt receipt) { + if (!Objects.equals( + identity.get(VERSION_OPERATION_ID, UUID.class), binding.versionIdentityOperationId()) + || !Objects.equals(identity.get(TARGET_NAMESPACE, String.class), binding.targetNamespace()) + || !Objects.equals( + identity.get(CANONICAL_TENANT_ID, UUID.class), binding.canonicalTenantId()) + || !Objects.equals( + identity.get(VERSION_CANONICAL_VERSION_ID, UUID.class), binding.canonicalVersionId()) + || !Objects.equals( + identity.get(VERSION_GAME_DESIGN_VERSION_ID, Long.class), binding.gameDesignVersionId()) + || !Objects.equals(identity.get(VERSION_WORLD_SLUG, String.class), receipt.worldSlug()) + || !Objects.equals( + identity.get(VERSION_INTAKE_OPERATION_ID, UUID.class), binding.intakeOperationId()) + || !Objects.equals( + identity.get(VERSION_INTAKE_REQUEST_ID, UUID.class), binding.intakeRequestId()) + || !Objects.equals( + identity.get(VERSION_LOCAL_TENANT_KEY, Long.class), receipt.localTenantKey()) + || !Objects.equals( + identity.get(VERSION_INTAKE_REQUEST_DIGEST, String.class), + binding.intakeRequestDigest()) + || !Objects.equals( + identity.get(VERSION_SOURCE_OPERATION_ID, UUID.class), binding.sourceOperationId()) + || !Objects.equals( + identity.get(VERSION_SOURCE_EVIDENCE_DIGEST, String.class), + binding.sourceEvidenceDigest()) + || !Objects.equals( + identity.get(VERSION_INTAKE_RECEIPT_DIGEST, String.class), + binding.intakeReceiptDigest())) { + throw new ConflictException( + "World publication request differs from the exact V27 Version and intake binding"); + } + } + + private Record createAndLockOwner(ResolvedVersion resolvedVersion) { + OwnerBinding binding = resolvedVersion.binding(); + WorldAuthoredSourceIntakeReceipt receipt = resolvedVersion.receipt(); + dsl.insertInto(OWNER) + .set(TARGET_NAMESPACE, binding.targetNamespace()) + .set(CANONICAL_TENANT_ID, binding.canonicalTenantId()) + .set(LOCAL_TENANT_KEY, receipt.localTenantKey()) + .set(VERSION_ID, resolvedVersion.localVersionKey()) + .set(OWNER_FREEZE_PHASE, OPEN) + .onConflictDoNothing() + .execute(); + + Record owner = + dsl.selectFrom(OWNER) + .where( + TARGET_NAMESPACE + .eq(binding.targetNamespace()) + .and(CANONICAL_TENANT_ID.eq(binding.canonicalTenantId())) + .and(VERSION_ID.eq(resolvedVersion.localVersionKey()))) + .forUpdate() + .fetchOne(); + if (owner == null) { + throw new ConflictException("World version owner row could not be created or locked"); + } + return owner; + } + + private void requireMatchingOwnerBinding(Record owner, ResolvedVersion resolvedVersion) { + OwnerBinding binding = resolvedVersion.binding(); + WorldAuthoredSourceIntakeReceipt receipt = resolvedVersion.receipt(); + if (!Objects.equals(owner.get(TARGET_NAMESPACE, String.class), binding.targetNamespace()) + || !Objects.equals(owner.get(CANONICAL_TENANT_ID, UUID.class), binding.canonicalTenantId()) + || !Objects.equals(owner.get(LOCAL_TENANT_KEY, Long.class), receipt.localTenantKey()) + || !Objects.equals(owner.get(VERSION_ID, Long.class), resolvedVersion.localVersionKey())) { + throw new ConflictException( + "World version owner row is bound to a different canonical tenant association"); + } + } + + private int insertAttempt( + WorldDesignPublicationFenceEvidence evidence, + ResolvedVersion resolvedVersion, + UUID publicationFence, + Checkpoint checkpoint) { + OwnerBinding binding = resolvedVersion.binding(); + WorldAuthoredSourceIntakeReceipt receipt = resolvedVersion.receipt(); + return dsl.insertInto(ATTEMPT) + .set(PUBLICATION_FENCE, publicationFence) + .set(TARGET_NAMESPACE, binding.targetNamespace()) + .set(CANONICAL_TENANT_ID, binding.canonicalTenantId()) + .set(LOCAL_TENANT_KEY, receipt.localTenantKey()) + .set(VERSION_ID, resolvedVersion.localVersionKey()) + .set(OWNER_BINDING_SCHEMA_VERSION, (short) 1) + .set(CANONICAL_VERSION_ID, binding.canonicalVersionId()) + .set(VERSION_IDENTITY_OPERATION_ID, binding.versionIdentityOperationId()) + .set(GAME_DESIGN_VERSION_ID, binding.gameDesignVersionId()) + .set(INTAKE_OPERATION_ID, receipt.operationId()) + .set(INTAKE_REQUEST_ID, receipt.intakeRequestId()) + .set(INTAKE_REQUEST_DIGEST, receipt.requestDigest()) + .set(SOURCE_OPERATION_ID, receipt.sourceOperationId()) + .set(SOURCE_EVIDENCE_DIGEST, receipt.sourceEvidenceDigest()) + .set(INTAKE_RECEIPT_DIGEST, receipt.receiptDigest()) + .set(PUBLICATION_REQUEST_ID, evidence.publicationRequestId()) + .set(REQUEST_DIGEST, evidence.requestDigest()) + .set(VERSION_STATE_EPOCH, evidence.versionStateEpoch()) + .set(PUBLISH_WORKFLOW_ID, evidence.publishWorkflowId()) + .set(APPLIED_COMMIT_ID, checkpoint.appliedCommitId()) + .set(CONTENT_DIGEST, checkpoint.contentDigest()) + .set(DIGEST_SCHEMA_VERSION, checkpoint.digestSchemaVersion()) + .execute(); + } + + private FrozenAttempt findAttemptByFence(UUID publicationFence) { + Record record = + dsl.selectFrom(ATTEMPT).where(PUBLICATION_FENCE.eq(publicationFence)).fetchOne(); + return record == null ? null : toFrozenAttempt(record); + } + + private FrozenAttempt findAttemptByRequest( + WorldDesignPublicationFenceEvidence evidence, long localVersionKey) { + Record record = + dsl.selectFrom(ATTEMPT) + .where( + TARGET_NAMESPACE + .eq(evidence.targetNamespace()) + .and(CANONICAL_TENANT_ID.eq(evidence.canonicalTenantId())) + .and(VERSION_ID.eq(localVersionKey)) + .and(PUBLICATION_REQUEST_ID.eq(evidence.publicationRequestId()))) + .fetchOne(); + return record == null ? null : toFrozenAttempt(record); + } + + private void rejectLegacyAttempt( + WorldDesignPublicationFenceEvidence evidence, long localVersionKey) { + Record legacyCandidate = + dsl.selectFrom(ATTEMPT) + .where( + TARGET_NAMESPACE + .eq(evidence.targetNamespace()) + .and(CANONICAL_TENANT_ID.eq(evidence.canonicalTenantId())) + .and(VERSION_ID.eq(localVersionKey)) + .and(PUBLICATION_REQUEST_ID.eq(evidence.publicationRequestId()))) + .fetchOne(); + if (legacyCandidate != null + && !Short.valueOf((short) 1) + .equals(legacyCandidate.get(OWNER_BINDING_SCHEMA_VERSION, Short.class))) { + throw new ConflictException( + "Legacy schema-0 World publication attempts are unqualified and cannot be promoted"); + } + } + + private FrozenAttempt toFrozenAttempt(Record record) { + Short ownerBindingSchemaVersion = record.get(OWNER_BINDING_SCHEMA_VERSION, Short.class); + if (!Short.valueOf((short) 1).equals(ownerBindingSchemaVersion)) { + throw new ConflictException( + "Legacy schema-0 World publication attempts are unqualified and cannot be promoted"); + } + WorldDesignPublicationFenceEvidence request = + new WorldDesignPublicationFenceEvidence( + record.get(TARGET_NAMESPACE), + record.get(CANONICAL_TENANT_ID), + record.get(CANONICAL_VERSION_ID), + record.get(VERSION_IDENTITY_OPERATION_ID), + record.get(GAME_DESIGN_VERSION_ID), + record.get(INTAKE_REQUEST_ID), + record.get(INTAKE_OPERATION_ID), + record.get(INTAKE_REQUEST_DIGEST), + record.get(SOURCE_OPERATION_ID), + record.get(SOURCE_EVIDENCE_DIGEST), + record.get(INTAKE_RECEIPT_DIGEST), + record.get(PUBLICATION_REQUEST_ID), + record.get(REQUEST_DIGEST), + record.get(VERSION_STATE_EPOCH), + record.get(PUBLISH_WORKFLOW_ID)); + Checkpoint checkpoint = + new Checkpoint( + record.get(APPLIED_COMMIT_ID), + record.get(CONTENT_DIGEST), + record.get(DIGEST_SCHEMA_VERSION)); + return new FrozenAttempt(request, record.get(PUBLICATION_FENCE), checkpoint); + } + + private void requireExactRequest( + FrozenAttempt stored, WorldDesignPublicationFenceEvidence supplied) { + if (!stored.request().equals(supplied)) { + throw new ConflictException( + "World publication request identity was reused with changed source or request binding"); + } + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World publication fence requires an active owner transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "World publication fence requires a writable owner transaction"); + } + Integer declaredIsolation = + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (declaredIsolation != null && declaredIsolation != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("World publication fence requires READ COMMITTED isolation"); + } + Record settings = + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS transaction_isolation, " + + "current_setting('transaction_read_only') AS transaction_read_only"); + if (settings == null + || !"read committed".equalsIgnoreCase(settings.get("transaction_isolation", String.class)) + || !"off".equalsIgnoreCase(settings.get("transaction_read_only", String.class))) { + throw new IllegalStateException( + "World publication fence requires a writable READ COMMITTED owner transaction"); + } + } + + private UUID newNonNilUuid() { + UUID value; + do { + value = UUID.randomUUID(); + } while (NIL_UUID.equals(value)); + return value; + } + + private record ResolvedVersion( + OwnerBinding binding, WorldAuthoredSourceIntakeReceipt receipt, long localVersionKey) {} + + /** Exact input conflicts fail closed without changing either owner or attempt history. */ + public static class ConflictException extends IllegalStateException { + public ConflictException(String message) { + super(message); + } + } + + /** No owner state may be created for a missing or not-yet-committed authored-source intake. */ + public static final class MissingIntakeException extends IllegalStateException { + public MissingIntakeException(String message) { + super(message); + } + } + + /** No owner state may be created for a missing V27 source-qualified Version identity. */ + public static final class MissingVersionIdentityException extends ConflictException { + public MissingVersionIdentityException(String message) { + super(message); + } + } +} diff --git a/services/world-management-service/src/main/resources/db/migration/V23.1__world_authored_source_intake.sql b/services/world-management-service/src/main/resources/db/migration/V23.1__world_authored_source_intake.sql new file mode 100644 index 0000000000..8e586e23ea --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V23.1__world_authored_source_intake.sql @@ -0,0 +1,250 @@ +CREATE TABLE world_authored_source_tenant_association ( + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + tenant_slug VARCHAR(120) NOT NULL, + source_game_row_id BIGINT NOT NULL, + source_game_tenant_key VARCHAR(72) NOT NULL, + source_provenance_kind VARCHAR(32) NOT NULL, + local_tenant_key BIGINT NOT NULL, + CONSTRAINT pk_world_authored_source_tenant_association + PRIMARY KEY (target_namespace, canonical_tenant_id), + CONSTRAINT uq_world_authored_source_tenant_local_key UNIQUE (local_tenant_key), + CONSTRAINT uq_world_authored_source_tenant_selector UNIQUE (target_namespace, tenant_slug), + CONSTRAINT uq_world_authored_source_game_row UNIQUE (target_namespace, source_game_row_id), + CONSTRAINT uq_world_authored_source_tenant_binding + UNIQUE (target_namespace, canonical_tenant_id, local_tenant_key), + CONSTRAINT ck_world_authored_source_tenant_canonical_id + CHECK (canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_world_authored_source_tenant_game_row CHECK (source_game_row_id > 0), + CONSTRAINT ck_world_authored_source_tenant_local_key CHECK (local_tenant_key > 0), + CONSTRAINT ck_world_authored_source_tenant_provenance + CHECK (source_provenance_kind = 'NEW_GAME_ROW') +); + +CREATE TABLE world_authored_source_tenant_key_reservation ( + tenant_key BIGINT NOT NULL, + claim_kind VARCHAR(32) NOT NULL, + target_namespace VARCHAR(63), + canonical_tenant_id UUID, + CONSTRAINT pk_world_authored_source_tenant_key_reservation PRIMARY KEY (tenant_key), + CONSTRAINT fk_world_authored_source_tenant_key_canonical_binding + FOREIGN KEY (target_namespace, canonical_tenant_id, tenant_key) + REFERENCES world_authored_source_tenant_association + (target_namespace, canonical_tenant_id, local_tenant_key), + CONSTRAINT ck_world_authored_source_tenant_key_claim_kind CHECK ( + (claim_kind = 'LEGACY_NUMERIC' + AND target_namespace IS NULL + AND canonical_tenant_id IS NULL) + OR + (claim_kind = 'CANONICAL_AUTHORED_SOURCE' + AND target_namespace IS NOT NULL + AND canonical_tenant_id IS NOT NULL + AND tenant_key > 0) + ) +); + +INSERT INTO world_authored_source_tenant_key_reservation (tenant_key, claim_kind) +SELECT DISTINCT tenant_id, 'LEGACY_NUMERIC' +FROM ( + SELECT tenant_id FROM generation_rule + UNION ALL SELECT tenant_id FROM instance + UNION ALL SELECT tenant_id FROM region + UNION ALL SELECT tenant_id FROM region_instance + UNION ALL SELECT tenant_id FROM room + UNION ALL SELECT tenant_id FROM room_exit + UNION ALL SELECT tenant_id FROM room_instance + UNION ALL SELECT tenant_id FROM room_instance_exit + UNION ALL SELECT tenant_id FROM world_design_aggregate_epoch + UNION ALL SELECT tenant_id FROM world_design_revision_ledger + UNION ALL SELECT tenant_id FROM world_design_scope_epoch + UNION ALL SELECT tenant_id FROM world_entity_spawn_binding + UNION ALL SELECT tenant_id FROM world_event + UNION ALL SELECT tenant_id FROM world_instance + UNION ALL SELECT tenant_id FROM zone + UNION ALL SELECT tenant_id FROM zone_instance +) AS existing_world_tenant_keys; + +-- [jooq ignore start] +CREATE FUNCTION world_claim_legacy_numeric_tenant_key() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + claimed_key BIGINT; +BEGIN + INSERT INTO world_authored_source_tenant_key_reservation AS reservation + (tenant_key, claim_kind) + VALUES (NEW.tenant_id, 'LEGACY_NUMERIC') + ON CONFLICT (tenant_key) DO UPDATE + SET tenant_key = EXCLUDED.tenant_key + WHERE reservation.claim_kind = 'LEGACY_NUMERIC' + RETURNING reservation.tenant_key INTO claimed_key; + + IF claimed_key IS NULL THEN + RAISE EXCEPTION 'World tenant key % is reserved for a canonical authored source', NEW.tenant_id + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION world_reject_authored_source_history_mutation() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'World authored-source association and receipt history is immutable' + USING ERRCODE = '55000'; +END; +$$; + +CREATE FUNCTION world_protect_tenant_key_reservation_history() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'UPDATE' THEN + IF OLD.tenant_key IS NOT DISTINCT FROM NEW.tenant_key + AND OLD.claim_kind IS NOT DISTINCT FROM NEW.claim_kind + AND OLD.target_namespace IS NOT DISTINCT FROM NEW.target_namespace + AND OLD.canonical_tenant_id IS NOT DISTINCT FROM NEW.canonical_tenant_id + THEN + RETURN NEW; + END IF; + END IF; + RAISE EXCEPTION 'World tenant-key reservation history cannot be changed or deleted' + USING ERRCODE = '55000'; +END; +$$; + +CREATE TRIGGER trg_world_tenant_key_reservation_immutable + BEFORE UPDATE OR DELETE ON world_authored_source_tenant_key_reservation + FOR EACH ROW EXECUTE FUNCTION world_protect_tenant_key_reservation_history(); + +CREATE TRIGGER trg_world_tenant_key_reservation_no_truncate + BEFORE TRUNCATE ON world_authored_source_tenant_key_reservation + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE TRIGGER trg_world_authored_source_association_immutable + BEFORE UPDATE OR DELETE ON world_authored_source_tenant_association + FOR EACH ROW EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE TRIGGER trg_world_authored_source_association_no_truncate + BEFORE TRUNCATE ON world_authored_source_tenant_association + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE TRIGGER trg_reserve_generation_rule_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON generation_rule + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_instance_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON instance + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_region_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON region + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_region_instance_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON region_instance + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_room_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON room + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_room_exit_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON room_exit + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_room_instance_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON room_instance + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_room_instance_exit_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON room_instance_exit + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_world_design_aggregate_epoch_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON world_design_aggregate_epoch + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_world_design_revision_ledger_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON world_design_revision_ledger + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_world_design_scope_epoch_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON world_design_scope_epoch + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_world_entity_spawn_binding_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON world_entity_spawn_binding + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_world_event_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON world_event + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_world_instance_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON world_instance + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_zone_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON zone + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +CREATE TRIGGER trg_reserve_zone_instance_tenant_key + BEFORE INSERT OR UPDATE OF tenant_id ON zone_instance + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); +-- [jooq ignore stop] + +CREATE TABLE world_authored_source_intake ( + operation_id UUID NOT NULL, + schema_version SMALLINT NOT NULL, + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + request_digest VARCHAR(71) NOT NULL, + local_tenant_key BIGINT NOT NULL, + source_schema_version SMALLINT NOT NULL, + source_registration_request_id UUID NOT NULL, + source_operation_id UUID NOT NULL, + source_request_digest VARCHAR(71) NOT NULL, + canonical_tenant_id UUID NOT NULL, + tenant_slug VARCHAR(120) NOT NULL, + world_slug VARCHAR(120) NOT NULL, + world_display_name VARCHAR(200) NOT NULL, + source_game_row_id BIGINT NOT NULL, + source_game_tenant_key VARCHAR(72) NOT NULL, + source_provenance_kind VARCHAR(32) NOT NULL, + source_evidence_digest VARCHAR(71) NOT NULL, + receipt_digest VARCHAR(71) NOT NULL, + CONSTRAINT pk_world_authored_source_intake PRIMARY KEY (operation_id), + CONSTRAINT uq_world_authored_source_intake_request + UNIQUE (target_namespace, intake_request_id), + CONSTRAINT uq_world_authored_source_intake_source_operation + UNIQUE (target_namespace, source_operation_id), + CONSTRAINT uq_world_authored_source_intake_source_request + UNIQUE (target_namespace, source_registration_request_id), + CONSTRAINT uq_world_authored_source_intake_world + UNIQUE (target_namespace, canonical_tenant_id, world_slug), + CONSTRAINT fk_world_authored_source_intake_tenant_binding + FOREIGN KEY (target_namespace, canonical_tenant_id, local_tenant_key) + REFERENCES world_authored_source_tenant_association + (target_namespace, canonical_tenant_id, local_tenant_key), + CONSTRAINT ck_world_authored_source_intake_schema CHECK (schema_version = 1), + CONSTRAINT ck_world_authored_source_intake_source_schema CHECK (source_schema_version = 1), + CONSTRAINT ck_world_authored_source_intake_local_key CHECK (local_tenant_key > 0), + CONSTRAINT ck_world_authored_source_intake_source_game_row CHECK (source_game_row_id > 0), + CONSTRAINT ck_world_authored_source_intake_provenance + CHECK (source_provenance_kind = 'NEW_GAME_ROW'), + CONSTRAINT ck_world_authored_source_intake_request_digest + CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT ck_world_authored_source_intake_source_request_digest + CHECK (source_request_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT ck_world_authored_source_intake_source_evidence_digest + CHECK (source_evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT ck_world_authored_source_intake_receipt_digest + CHECK (receipt_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT ck_world_authored_source_intake_non_nil_ids CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_registration_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + ) +); + +-- [jooq ignore start] +CREATE TRIGGER trg_world_authored_source_intake_immutable + BEFORE UPDATE OR DELETE ON world_authored_source_intake + FOR EACH ROW EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE TRIGGER trg_world_authored_source_intake_no_truncate + BEFORE TRUNCATE ON world_authored_source_intake + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_source_history_mutation(); +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V24__world_canonical_tenant_mutation_guard.sql b/services/world-management-service/src/main/resources/db/migration/V24__world_canonical_tenant_mutation_guard.sql new file mode 100644 index 0000000000..56b19ac59d --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V24__world_canonical_tenant_mutation_guard.sql @@ -0,0 +1,219 @@ +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION world_claim_legacy_numeric_tenant_key() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + claimed_key BIGINT; +BEGIN + IF TG_OP = 'DELETE' THEN + IF EXISTS ( + SELECT 1 + FROM world_authored_source_tenant_key_reservation + WHERE tenant_key = OLD.tenant_id + AND claim_kind = 'CANONICAL_AUTHORED_SOURCE' + ) THEN + RAISE EXCEPTION + 'World tenant key % is reserved for a canonical authored source', OLD.tenant_id + USING ERRCODE = '23514'; + END IF; + RETURN OLD; + END IF; + + IF TG_OP = 'UPDATE' AND EXISTS ( + SELECT 1 + FROM world_authored_source_tenant_key_reservation + WHERE tenant_key = OLD.tenant_id + AND claim_kind = 'CANONICAL_AUTHORED_SOURCE' + ) THEN + RAISE EXCEPTION + 'World tenant key % is reserved for a canonical authored source', OLD.tenant_id + USING ERRCODE = '23514'; + END IF; + + IF EXISTS ( + SELECT 1 + FROM world_authored_source_tenant_key_reservation + WHERE tenant_key = NEW.tenant_id + AND claim_kind = 'CANONICAL_AUTHORED_SOURCE' + ) THEN + RAISE EXCEPTION + 'World tenant key % is reserved for a canonical authored source', NEW.tenant_id + USING ERRCODE = '23514'; + END IF; + + INSERT INTO world_authored_source_tenant_key_reservation AS reservation + (tenant_key, claim_kind) + VALUES (NEW.tenant_id, 'LEGACY_NUMERIC') + ON CONFLICT (tenant_key) DO UPDATE + SET tenant_key = EXCLUDED.tenant_key + WHERE reservation.claim_kind = 'LEGACY_NUMERIC' + RETURNING reservation.tenant_key INTO claimed_key; + + IF claimed_key IS NULL THEN + RAISE EXCEPTION 'World tenant key % is reserved for a canonical authored source', NEW.tenant_id + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION world_reject_tenant_table_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION + 'World tenant-bearing tables require owner-qualified row mutation; TRUNCATE is forbidden' + USING ERRCODE = '23514'; +END; +$$; + +DROP TRIGGER trg_reserve_generation_rule_tenant_key ON generation_rule; +CREATE TRIGGER trg_reserve_generation_rule_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON generation_rule + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_instance_tenant_key ON instance; +CREATE TRIGGER trg_reserve_instance_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON instance + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_region_tenant_key ON region; +CREATE TRIGGER trg_reserve_region_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON region + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_region_instance_tenant_key ON region_instance; +CREATE TRIGGER trg_reserve_region_instance_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON region_instance + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_room_tenant_key ON room; +CREATE TRIGGER trg_reserve_room_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON room + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_room_exit_tenant_key ON room_exit; +CREATE TRIGGER trg_reserve_room_exit_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON room_exit + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_room_instance_tenant_key ON room_instance; +CREATE TRIGGER trg_reserve_room_instance_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON room_instance + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_room_instance_exit_tenant_key ON room_instance_exit; +CREATE TRIGGER trg_reserve_room_instance_exit_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON room_instance_exit + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_world_design_aggregate_epoch_tenant_key + ON world_design_aggregate_epoch; +CREATE TRIGGER trg_reserve_world_design_aggregate_epoch_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON world_design_aggregate_epoch + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_world_design_revision_ledger_tenant_key + ON world_design_revision_ledger; +CREATE TRIGGER trg_reserve_world_design_revision_ledger_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON world_design_revision_ledger + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_world_design_scope_epoch_tenant_key + ON world_design_scope_epoch; +CREATE TRIGGER trg_reserve_world_design_scope_epoch_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON world_design_scope_epoch + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_world_entity_spawn_binding_tenant_key + ON world_entity_spawn_binding; +CREATE TRIGGER trg_reserve_world_entity_spawn_binding_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON world_entity_spawn_binding + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_world_event_tenant_key ON world_event; +CREATE TRIGGER trg_reserve_world_event_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON world_event + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_world_instance_tenant_key ON world_instance; +CREATE TRIGGER trg_reserve_world_instance_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON world_instance + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_zone_tenant_key ON zone; +CREATE TRIGGER trg_reserve_zone_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON zone + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +DROP TRIGGER trg_reserve_zone_instance_tenant_key ON zone_instance; +CREATE TRIGGER trg_reserve_zone_instance_tenant_key + BEFORE INSERT OR UPDATE OR DELETE ON zone_instance + FOR EACH ROW EXECUTE FUNCTION world_claim_legacy_numeric_tenant_key(); + +CREATE TRIGGER trg_generation_rule_no_truncate + BEFORE TRUNCATE ON generation_rule + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_instance_no_truncate + BEFORE TRUNCATE ON instance + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_region_no_truncate + BEFORE TRUNCATE ON region + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_region_instance_no_truncate + BEFORE TRUNCATE ON region_instance + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_room_no_truncate + BEFORE TRUNCATE ON room + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_room_exit_no_truncate + BEFORE TRUNCATE ON room_exit + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_room_instance_no_truncate + BEFORE TRUNCATE ON room_instance + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_room_instance_exit_no_truncate + BEFORE TRUNCATE ON room_instance_exit + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_world_design_aggregate_epoch_no_truncate + BEFORE TRUNCATE ON world_design_aggregate_epoch + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_world_design_revision_ledger_no_truncate + BEFORE TRUNCATE ON world_design_revision_ledger + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_world_design_scope_epoch_no_truncate + BEFORE TRUNCATE ON world_design_scope_epoch + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_world_entity_spawn_binding_no_truncate + BEFORE TRUNCATE ON world_entity_spawn_binding + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_world_event_no_truncate + BEFORE TRUNCATE ON world_event + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_world_instance_no_truncate + BEFORE TRUNCATE ON world_instance + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_zone_no_truncate + BEFORE TRUNCATE ON zone + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); + +CREATE TRIGGER trg_zone_instance_no_truncate + BEFORE TRUNCATE ON zone_instance + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_tenant_table_truncate(); +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V25__world_design_publication_fence.sql b/services/world-management-service/src/main/resources/db/migration/V25__world_design_publication_fence.sql new file mode 100644 index 0000000000..1542829b59 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V25__world_design_publication_fence.sql @@ -0,0 +1,220 @@ +ALTER TABLE world_authored_source_intake + ADD CONSTRAINT uq_world_authored_source_intake_publication_binding UNIQUE ( + operation_id, + target_namespace, + canonical_tenant_id, + local_tenant_key, + intake_request_id, + source_operation_id, + source_evidence_digest, + receipt_digest + ); + +CREATE TABLE world_design_publication_fence_attempt ( + publication_fence UUID NOT NULL, + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + local_tenant_key BIGINT NOT NULL, + version_id BIGINT NOT NULL, + intake_operation_id UUID NOT NULL, + intake_request_id UUID NOT NULL, + source_operation_id UUID NOT NULL, + source_evidence_digest VARCHAR(71) NOT NULL, + intake_receipt_digest VARCHAR(71) NOT NULL, + publication_request_id VARCHAR(256) NOT NULL, + request_digest VARCHAR(64) NOT NULL, + version_state_epoch BIGINT NOT NULL, + publish_workflow_id VARCHAR(537) NOT NULL, + applied_commit_id VARCHAR(256) NOT NULL, + content_digest VARCHAR(64) NOT NULL, + digest_schema_version INTEGER NOT NULL, + CONSTRAINT pk_world_design_publication_fence_attempt + PRIMARY KEY (publication_fence), + CONSTRAINT uq_world_design_publication_attempt_scope_request + UNIQUE (target_namespace, canonical_tenant_id, version_id, publication_request_id), + CONSTRAINT uq_world_design_publication_attempt_owner_fence + UNIQUE ( + publication_fence, + target_namespace, + canonical_tenant_id, + local_tenant_key, + version_id + ), + CONSTRAINT fk_world_design_publication_attempt_tenant_association + FOREIGN KEY (target_namespace, canonical_tenant_id, local_tenant_key) + REFERENCES world_authored_source_tenant_association + (target_namespace, canonical_tenant_id, local_tenant_key), + CONSTRAINT fk_world_design_publication_attempt_intake + FOREIGN KEY ( + intake_operation_id, + target_namespace, + canonical_tenant_id, + local_tenant_key, + intake_request_id, + source_operation_id, + source_evidence_digest, + intake_receipt_digest + ) + REFERENCES world_authored_source_intake ( + operation_id, + target_namespace, + canonical_tenant_id, + local_tenant_key, + intake_request_id, + source_operation_id, + source_evidence_digest, + receipt_digest + ), + CONSTRAINT ck_world_design_publication_attempt_scope + CHECK (version_id > 0 AND version_state_epoch > 0 AND digest_schema_version > 0), + CONSTRAINT ck_world_design_publication_attempt_namespace + CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + ), + CONSTRAINT ck_world_design_publication_attempt_ids + CHECK ( + publication_fence <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND local_tenant_key > 0 + ), + CONSTRAINT ck_world_design_publication_attempt_source_digest + CHECK (source_evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT ck_world_design_publication_attempt_receipt_digest + CHECK (intake_receipt_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT ck_world_design_publication_attempt_request + CHECK ( + octet_length(publication_request_id) BETWEEN 1 AND 256 + AND position(':' IN publication_request_id) = 0 + AND octet_length(request_digest) = 64 + AND request_digest ~ '^[0-9a-f]{64}$' + AND publish_workflow_id = + 'publish:' || canonical_tenant_id::TEXT || ':publish-request:' || publication_request_id + AND octet_length(publish_workflow_id) <= 537 + ), + CONSTRAINT ck_world_design_publication_attempt_checkpoint + CHECK ( + octet_length(applied_commit_id) BETWEEN 1 AND 256 + AND content_digest ~ '^[0-9a-f]{64}$' + ) +); + +CREATE TABLE world_design_publication_fence_owner ( + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + local_tenant_key BIGINT NOT NULL, + version_id BIGINT NOT NULL, + owner_freeze_phase VARCHAR(32) NOT NULL, + current_publication_fence UUID, + CONSTRAINT pk_world_design_publication_fence_owner + PRIMARY KEY (local_tenant_key, version_id), + CONSTRAINT uq_world_design_publication_fence_owner_scope + UNIQUE (target_namespace, canonical_tenant_id, version_id), + CONSTRAINT fk_world_design_publication_owner_tenant_association + FOREIGN KEY (target_namespace, canonical_tenant_id, local_tenant_key) + REFERENCES world_authored_source_tenant_association + (target_namespace, canonical_tenant_id, local_tenant_key), + CONSTRAINT fk_world_design_publication_owner_current_attempt + FOREIGN KEY ( + current_publication_fence, + target_namespace, + canonical_tenant_id, + local_tenant_key, + version_id + ) + REFERENCES world_design_publication_fence_attempt ( + publication_fence, + target_namespace, + canonical_tenant_id, + local_tenant_key, + version_id + ), + CONSTRAINT ck_world_design_publication_fence_owner_scope + CHECK (version_id > 0 AND local_tenant_key > 0), + CONSTRAINT ck_world_design_publication_fence_owner_ids + CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT ck_world_design_publication_fence_owner_namespace + CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + ), + CONSTRAINT ck_world_design_publication_fence_owner_phase + CHECK ( + (owner_freeze_phase = 'OPEN' AND current_publication_fence IS NULL) + OR + (owner_freeze_phase IN ( + 'FROZEN', + 'PUBLISHED', + 'ABORTED', + 'RECONCILIATION_REQUIRED' + ) AND current_publication_fence IS NOT NULL) + ) +); + +-- [jooq ignore start] +CREATE FUNCTION world_reject_publication_attempt_history_mutation() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'World publication-fence attempt history is immutable' + USING ERRCODE = '55000'; +END; +$$; + +CREATE FUNCTION world_protect_publication_fence_owner() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'World publication-fence owner rows cannot be deleted' + USING ERRCODE = '55000'; + END IF; + + IF TG_OP = 'INSERT' THEN + IF NEW.owner_freeze_phase = 'OPEN' AND NEW.current_publication_fence IS NULL THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'World publication-fence owner rows must be created OPEN without a fence' + USING ERRCODE = '55000'; + END IF; + + IF OLD.target_namespace IS NOT DISTINCT FROM NEW.target_namespace + AND OLD.canonical_tenant_id IS NOT DISTINCT FROM NEW.canonical_tenant_id + AND OLD.local_tenant_key IS NOT DISTINCT FROM NEW.local_tenant_key + AND OLD.version_id IS NOT DISTINCT FROM NEW.version_id + AND OLD.owner_freeze_phase = 'OPEN' + AND NEW.owner_freeze_phase = 'FROZEN' + AND OLD.current_publication_fence IS NULL + AND NEW.current_publication_fence IS NOT NULL + THEN + RETURN NEW; + END IF; + + RAISE EXCEPTION 'World publication-fence owner binding or phase transition is immutable' + USING ERRCODE = '55000'; +END; +$$; + +CREATE TRIGGER trg_world_publication_attempt_immutable + BEFORE UPDATE OR DELETE ON world_design_publication_fence_attempt + FOR EACH ROW EXECUTE FUNCTION world_reject_publication_attempt_history_mutation(); + +CREATE TRIGGER trg_world_publication_attempt_no_truncate + BEFORE TRUNCATE ON world_design_publication_fence_attempt + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_publication_attempt_history_mutation(); + +CREATE TRIGGER trg_world_publication_owner_protect + BEFORE INSERT OR UPDATE OR DELETE ON world_design_publication_fence_owner + FOR EACH ROW EXECUTE FUNCTION world_protect_publication_fence_owner(); + +CREATE TRIGGER trg_world_publication_owner_no_truncate + BEFORE TRUNCATE ON world_design_publication_fence_owner + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_publication_attempt_history_mutation(); +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V26__world_complete_launch_binding.sql b/services/world-management-service/src/main/resources/db/migration/V26__world_complete_launch_binding.sql new file mode 100644 index 0000000000..28f26a6f8f --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V26__world_complete_launch_binding.sql @@ -0,0 +1,72 @@ +CREATE TABLE world_complete_launch_binding ( + binding_operation_id UUID NOT NULL, + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + world_slug VARCHAR(120) NOT NULL, + control_plane_request_id TEXT NOT NULL, + intake_operation_id UUID NOT NULL, + intake_request_id UUID NOT NULL, + local_tenant_key BIGINT NOT NULL, + source_operation_id UUID NOT NULL, + source_evidence_digest VARCHAR(71) NOT NULL, + intake_receipt_digest VARCHAR(71) NOT NULL, + descriptor_request_digest VARCHAR(71) NOT NULL, + descriptor_result_digest VARCHAR(71) NOT NULL, + release_attestation_digest VARCHAR(71) NOT NULL, + descriptor_json TEXT NOT NULL, + release_attestation_json TEXT NOT NULL, + CONSTRAINT pk_world_complete_launch_binding PRIMARY KEY (binding_operation_id), + CONSTRAINT fk_world_complete_launch_binding_source + FOREIGN KEY ( + intake_operation_id, target_namespace, canonical_tenant_id, local_tenant_key, + intake_request_id, source_operation_id, source_evidence_digest, intake_receipt_digest + ) REFERENCES world_authored_source_intake ( + operation_id, target_namespace, canonical_tenant_id, local_tenant_key, + intake_request_id, source_operation_id, source_evidence_digest, receipt_digest + ), + CONSTRAINT ck_world_complete_launch_binding_ids CHECK ( + binding_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND local_tenant_key > 0 + ), + CONSTRAINT ck_world_complete_launch_binding_namespace CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + ), + CONSTRAINT ck_world_complete_launch_binding_world CHECK ( + world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + ), + CONSTRAINT ck_world_complete_launch_binding_request CHECK ( + length(btrim(control_plane_request_id)) > 0 + ), + CONSTRAINT ck_world_complete_launch_binding_digests CHECK ( + source_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND intake_receipt_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_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT ck_world_complete_launch_binding_components CHECK ( + length(descriptor_json) > 0 AND length(release_attestation_json) > 0 + ) +); + +-- [jooq ignore start] +-- The DDL export backend cannot index TEXT. PostgreSQL still enforces this exact +-- unbounded request identity; the runtime repository does not use generated keys. +ALTER TABLE world_complete_launch_binding + ADD CONSTRAINT uq_world_complete_launch_binding_request + UNIQUE (target_namespace, canonical_tenant_id, control_plane_request_id); + +CREATE TRIGGER trg_world_complete_launch_binding_immutable + BEFORE UPDATE OR DELETE ON world_complete_launch_binding + FOR EACH ROW EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE TRIGGER trg_world_complete_launch_binding_no_truncate + BEFORE TRUNCATE ON world_complete_launch_binding + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_source_history_mutation(); +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V27.1__world_publication_owner_binding.sql b/services/world-management-service/src/main/resources/db/migration/V27.1__world_publication_owner_binding.sql new file mode 100644 index 0000000000..4ee813e4f6 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V27.1__world_publication_owner_binding.sql @@ -0,0 +1,73 @@ +-- This moves the publication-binding clauses from the deferred V28 graph-snapshot migration: +-- uq_world_authored_version_snapshot_attempt_binding, the five attempt binding columns, +-- ck_world_publication_attempt_owner_binding, and +-- fk_world_publication_attempt_version_identity. Reconcile those clauses when V28 is integrated. +ALTER TABLE world_authored_version_identity + ADD CONSTRAINT uq_world_authored_version_snapshot_attempt_binding UNIQUE ( + operation_id, + target_namespace, + canonical_tenant_id, + canonical_version_id, + game_design_version_id, + local_version_key, + intake_operation_id, + intake_request_id, + intake_request_digest, + local_tenant_key, + source_operation_id, + source_evidence_digest, + intake_receipt_digest + ); + +ALTER TABLE world_design_publication_fence_attempt + ADD COLUMN owner_binding_schema_version SMALLINT NOT NULL DEFAULT 0, + ADD COLUMN canonical_version_id UUID, + ADD COLUMN version_identity_operation_id UUID, + ADD COLUMN game_design_version_id BIGINT, + ADD COLUMN intake_request_digest VARCHAR(71), + ADD CONSTRAINT ck_world_publication_attempt_owner_binding CHECK ( + (owner_binding_schema_version = 0 + AND canonical_version_id IS NULL + AND version_identity_operation_id IS NULL + AND game_design_version_id IS NULL + AND intake_request_digest IS NULL) + OR + (owner_binding_schema_version = 1 + AND canonical_version_id IS NOT NULL + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND version_identity_operation_id IS NOT NULL + AND version_identity_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND game_design_version_id IS NOT NULL + AND game_design_version_id > 0 + AND intake_request_digest IS NOT NULL + AND intake_request_digest ~ '^sha256:[0-9a-f]{64}$') + ), + ADD CONSTRAINT fk_world_publication_attempt_version_identity FOREIGN KEY ( + version_identity_operation_id, + target_namespace, + canonical_tenant_id, + canonical_version_id, + game_design_version_id, + version_id, + intake_operation_id, + intake_request_id, + intake_request_digest, + local_tenant_key, + source_operation_id, + source_evidence_digest, + intake_receipt_digest + ) REFERENCES world_authored_version_identity ( + operation_id, + target_namespace, + canonical_tenant_id, + canonical_version_id, + game_design_version_id, + local_version_key, + intake_operation_id, + intake_request_id, + intake_request_digest, + local_tenant_key, + source_operation_id, + source_evidence_digest, + intake_receipt_digest + ); diff --git a/services/world-management-service/src/main/resources/db/migration/V27.2__world_legacy_tenant_claim_concurrency.sql b/services/world-management-service/src/main/resources/db/migration/V27.2__world_legacy_tenant_claim_concurrency.sql new file mode 100644 index 0000000000..ec1e6b9b77 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V27.2__world_legacy_tenant_claim_concurrency.sql @@ -0,0 +1,65 @@ +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION world_claim_legacy_numeric_tenant_key() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + claimed_kind VARCHAR(32); +BEGIN + IF TG_OP = 'DELETE' THEN + IF EXISTS ( + SELECT 1 + FROM world_authored_source_tenant_key_reservation + WHERE tenant_key = OLD.tenant_id + AND claim_kind = 'CANONICAL_AUTHORED_SOURCE' + ) THEN + RAISE EXCEPTION + 'World tenant key % is reserved for a canonical authored source', OLD.tenant_id + USING ERRCODE = '23514'; + END IF; + RETURN OLD; + END IF; + + IF TG_OP = 'UPDATE' AND EXISTS ( + SELECT 1 + FROM world_authored_source_tenant_key_reservation + WHERE tenant_key = OLD.tenant_id + AND claim_kind = 'CANONICAL_AUTHORED_SOURCE' + ) THEN + RAISE EXCEPTION + 'World tenant key % is reserved for a canonical authored source', OLD.tenant_id + USING ERRCODE = '23514'; + END IF; + + IF EXISTS ( + SELECT 1 + FROM world_authored_source_tenant_key_reservation + WHERE tenant_key = NEW.tenant_id + AND claim_kind = 'CANONICAL_AUTHORED_SOURCE' + ) THEN + RAISE EXCEPTION + 'World tenant key % is reserved for a canonical authored source', NEW.tenant_id + USING ERRCODE = '23514'; + END IF; + + IF TG_OP = 'UPDATE' AND OLD.tenant_id = NEW.tenant_id THEN + RETURN NEW; + END IF; + + INSERT INTO world_authored_source_tenant_key_reservation (tenant_key, claim_kind) + VALUES (NEW.tenant_id, 'LEGACY_NUMERIC') + ON CONFLICT (tenant_key) DO NOTHING; + + SELECT claim_kind + INTO claimed_kind + FROM world_authored_source_tenant_key_reservation + WHERE tenant_key = NEW.tenant_id; + + IF claimed_kind IS DISTINCT FROM 'LEGACY_NUMERIC' THEN + RAISE EXCEPTION 'World tenant key % is reserved for a canonical authored source', NEW.tenant_id + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V27__world_authored_version_identity.sql b/services/world-management-service/src/main/resources/db/migration/V27__world_authored_version_identity.sql new file mode 100644 index 0000000000..d6465727fe --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V27__world_authored_version_identity.sql @@ -0,0 +1,80 @@ +CREATE TABLE world_authored_version_identity ( + operation_id UUID NOT NULL, + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + world_slug VARCHAR(120) NOT NULL, + canonical_version_id UUID NOT NULL, + game_design_version_id BIGINT NOT NULL, + local_version_key BIGINT GENERATED ALWAYS AS IDENTITY NOT NULL, + intake_operation_id UUID NOT NULL, + intake_request_id UUID NOT NULL, + local_tenant_key BIGINT NOT NULL, + intake_request_digest VARCHAR(71) NOT NULL, + source_operation_id UUID NOT NULL, + source_evidence_digest VARCHAR(71) NOT NULL, + intake_receipt_digest VARCHAR(71) NOT NULL, + version_state_schema_version SMALLINT NOT NULL, + version_state_read_request_id UUID NOT NULL, + version_state_state VARCHAR(32) NOT NULL, + version_state_epoch BIGINT NOT NULL, + version_state_evidence_digest VARCHAR(71) NOT NULL, + version_state_evidence_json TEXT NOT NULL, + CONSTRAINT pk_world_authored_version_identity PRIMARY KEY (operation_id), + CONSTRAINT uq_world_authored_version_identity_local_key UNIQUE (local_version_key), + CONSTRAINT uq_world_authored_version_identity_canonical UNIQUE ( + target_namespace, canonical_tenant_id, world_slug, canonical_version_id + ), + CONSTRAINT uq_world_authored_version_identity_game_design_version UNIQUE ( + target_namespace, canonical_tenant_id, world_slug, game_design_version_id + ), + CONSTRAINT fk_world_authored_version_identity_intake FOREIGN KEY ( + intake_operation_id, target_namespace, canonical_tenant_id, local_tenant_key, + intake_request_id, source_operation_id, source_evidence_digest, intake_receipt_digest + ) REFERENCES world_authored_source_intake ( + operation_id, target_namespace, canonical_tenant_id, local_tenant_key, + intake_request_id, source_operation_id, source_evidence_digest, receipt_digest + ), + CONSTRAINT ck_world_authored_version_identity_scope CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + AND octet_length(world_slug) BETWEEN 1 AND 120 + ), + CONSTRAINT ck_world_authored_version_identity_counters CHECK ( + game_design_version_id > 0 + AND local_version_key > 0 + AND local_tenant_key > 0 + AND version_state_epoch > 0 + AND version_state_schema_version = 1 + ), + CONSTRAINT ck_world_authored_version_identity_ids CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND version_state_read_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT ck_world_authored_version_identity_state CHECK ( + version_state_state IN ('DRAFT', 'PUBLISHED', 'ACTIVE') + ), + CONSTRAINT ck_world_authored_version_identity_digests CHECK ( + intake_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND intake_receipt_digest ~ '^sha256:[0-9a-f]{64}$' + AND version_state_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT ck_world_authored_version_identity_json CHECK ( + octet_length(version_state_evidence_json) > 0 + ) +); + +-- [jooq ignore start] +CREATE TRIGGER trg_world_authored_version_identity_immutable + BEFORE UPDATE OR DELETE ON world_authored_version_identity + FOR EACH ROW EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE TRIGGER trg_world_authored_version_identity_no_truncate + BEFORE TRUNCATE ON world_authored_version_identity + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_source_history_mutation(); +-- [jooq ignore stop] diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java new file mode 100644 index 0000000000..0271fa56a4 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java @@ -0,0 +1,1531 @@ +package net.firedevops.firemud.worldmanagement; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.TestContainerImages; +import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; +import net.firedevops.firemud.worldmanagement.client.GameDesignClient; +import net.firedevops.firemud.worldmanagement.client.GameSessionClient; +import net.firedevops.firemud.worldmanagement.client.GrpcGameSessionInitialAdmissionBindProofClient; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationInfo; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.exception.DataAccessException; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.IllegalTransactionStateException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class WorldAuthoredSourceIntakeIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final Set PROTECTED_TENANT_TABLES = + Set.of( + "generation_rule", + "instance", + "region", + "region_instance", + "room", + "room_exit", + "room_instance", + "room_instance_exit", + "world_design_aggregate_epoch", + "world_design_revision_ledger", + "world_design_scope_epoch", + "world_entity_spawn_binding", + "world_event", + "world_instance", + "zone", + "zone_instance"); + private static final String OCCUPIED_LEGACY_KEYS = + "SELECT COUNT(*) FROM (" + + "SELECT tenant_id AS occupied_key FROM generation_rule UNION ALL " + + "SELECT tenant_id FROM instance UNION ALL " + + "SELECT tenant_id FROM region UNION ALL " + + "SELECT tenant_id FROM region_instance UNION ALL " + + "SELECT tenant_id FROM room UNION ALL " + + "SELECT tenant_id FROM room_exit UNION ALL " + + "SELECT tenant_id FROM room_instance UNION ALL " + + "SELECT tenant_id FROM room_instance_exit UNION ALL " + + "SELECT tenant_id FROM world_design_aggregate_epoch UNION ALL " + + "SELECT tenant_id FROM world_design_revision_ledger UNION ALL " + + "SELECT tenant_id FROM world_design_scope_epoch UNION ALL " + + "SELECT tenant_id FROM world_entity_spawn_binding UNION ALL " + + "SELECT tenant_id FROM world_event UNION ALL " + + "SELECT tenant_id FROM world_instance UNION ALL " + + "SELECT tenant_id FROM zone UNION ALL " + + "SELECT tenant_id FROM zone_instance" + + ") AS occupied_world_keys WHERE occupied_key = ?"; + private static final String MAX_OCCUPIED_TENANT_KEY = + "SELECT COALESCE(MAX(occupied_key), 0) FROM (" + + "SELECT tenant_id AS occupied_key FROM generation_rule UNION ALL " + + "SELECT tenant_id FROM instance UNION ALL " + + "SELECT tenant_id FROM region UNION ALL " + + "SELECT tenant_id FROM region_instance UNION ALL " + + "SELECT tenant_id FROM room UNION ALL " + + "SELECT tenant_id FROM room_exit UNION ALL " + + "SELECT tenant_id FROM room_instance UNION ALL " + + "SELECT tenant_id FROM room_instance_exit UNION ALL " + + "SELECT tenant_id FROM world_design_aggregate_epoch UNION ALL " + + "SELECT tenant_id FROM world_design_revision_ledger UNION ALL " + + "SELECT tenant_id FROM world_design_scope_epoch UNION ALL " + + "SELECT tenant_id FROM world_entity_spawn_binding UNION ALL " + + "SELECT tenant_id FROM world_event UNION ALL " + + "SELECT tenant_id FROM world_instance UNION ALL " + + "SELECT tenant_id FROM zone UNION ALL " + + "SELECT tenant_id FROM zone_instance UNION ALL " + + "SELECT tenant_key FROM world_authored_source_tenant_key_reservation UNION ALL " + + "SELECT local_tenant_key FROM world_authored_source_tenant_association" + + ") AS occupied_tenant_keys"; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "world_management_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private WorldAuthoredSourceIntakeRepository repository; + @Autowired private Flyway flyway; + @Autowired private DSLContext dsl; + @Autowired private PlatformTransactionManager transactionManager; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @MockitoBean(enforceOverride = true) + private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private EntityManagementClient entityManagementClient; + + @Test + void persistsCompleteFreshReceiptAndReusesExactTenantAssociationAcrossWorlds() { + assertThat(Arrays.stream(flyway.info().applied()).map(MigrationInfo::getScript).toList()) + .containsSubsequence( + "V23__initial_admission_bind_hold.sql", "V23.1__world_authored_source_intake.sql"); + long existingLegacyTenantKey = + 8_000_000_000L + ThreadLocalRandom.current().nextLong(1_000_000L); + Long legacyRegionId = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO region (tenant_id, name) VALUES (?, ?) RETURNING id", + existingLegacyTenantKey, + "retained-world-allocation-guard"), + "retained region insert did not return its row") + .get(0, Long.class); + dsl.execute( + "INSERT INTO region (tenant_id, name) VALUES (?, ?)", + existingLegacyTenantKey, + "same-legacy-selector-remains-valid"); + dsl.execute( + "UPDATE region SET tenant_id = ? WHERE id = ?", existingLegacyTenantKey, legacyRegionId); + + UUID canonicalTenantId = UUID.randomUUID(); + String tenantSlug = tenantSlug(canonicalTenantId); + long sourceRowId = sourceRowId(canonicalTenantId); + AuthoredWorldSourceEvidence firstSource = + source(canonicalTenantId, tenantSlug, "violet-wilds", sourceRowId, "Café 🐉"); + UUID firstRequestId = UUID.randomUUID(); + WorldAuthoredSourceIntakeReceipt first = accept(firstRequestId, firstSource); + + assertThat(first.source()).isEqualTo(firstSource); + assertThat(first.localTenantKey()).isGreaterThan(existingLegacyTenantKey); + assertThat( + Objects.requireNonNull( + dsl.fetchOne(OCCUPIED_LEGACY_KEYS, first.localTenantKey()), + "legacy key occupancy query returned no row") + .get(0, Long.class)) + .isZero(); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM world_authored_source_tenant_key_reservation " + + "WHERE tenant_key = ? AND claim_kind = 'CANONICAL_AUTHORED_SOURCE' " + + "AND target_namespace = ? AND canonical_tenant_id = ?", + first.localTenantKey(), + NAMESPACE, + canonicalTenantId), + "canonical tenant-key reservation count query returned no row") + .get(0, Long.class)) + .isEqualTo(1L); + assertThat(read(firstRequestId)).contains(first); + + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO region (tenant_id, name) VALUES (?, ?)", + first.localTenantKey(), + "cannot-claim-canonical-selector")) + .isInstanceOf(DataIntegrityViolationException.class) + .satisfies(this::assertReservedCanonicalSelectorRejected); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE region SET tenant_id = ? WHERE id = ?", + first.localTenantKey(), + legacyRegionId)) + .isInstanceOf(DataIntegrityViolationException.class) + .satisfies(this::assertReservedCanonicalSelectorRejected); + assertThat( + Objects.requireNonNull( + dsl.fetchOne("SELECT tenant_id FROM region WHERE id = ?", legacyRegionId), + "retained region tenant readback returned no row") + .get(0, Long.class)) + .isEqualTo(existingLegacyTenantKey); + + UUID nextCanonicalTenantId = UUID.randomUUID(); + WorldAuthoredSourceIntakeReceipt nextCanonicalTenant = + accept( + UUID.randomUUID(), + source( + nextCanonicalTenantId, + tenantSlug(nextCanonicalTenantId), + "next-canonical-tenant-world", + sourceRowId(nextCanonicalTenantId), + "Next Canonical Tenant")); + assertThat(nextCanonicalTenant.localTenantKey()).isGreaterThan(first.localTenantKey()); + + AuthoredWorldSourceEvidence secondSource = + source(canonicalTenantId, tenantSlug, "amber-coast", sourceRowId, "Amber Coast"); + WorldAuthoredSourceIntakeReceipt second = accept(UUID.randomUUID(), secondSource); + + assertThat(second.localTenantKey()).isEqualTo(first.localTenantKey()); + assertThat(second.source().tenantSlug()).isEqualTo(first.source().tenantSlug()); + assertThat(second.source().sourceGameRowId()).isEqualTo(first.source().sourceGameRowId()); + assertThat(second.source().sourceGameTenantKey()) + .isEqualTo(first.source().sourceGameTenantKey()); + assertThat(second.source().provenanceKind()).isEqualTo("NEW_GAME_ROW"); + } + + @Test + void readBySourceReturnsExactCommittedReceiptOnRepeatedCallsWithoutGrowth() { + UUID tenant = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = + source(tenant, tenantSlug(tenant), "source-read-world", sourceRowId(tenant), "Source Read"); + WorldAuthoredSourceIntakeReceipt receipt = accept(UUID.randomUUID(), source); + long intakeCount = countRows("world_authored_source_intake"); + long associationCount = countRows("world_authored_source_tenant_association"); + long reservationCount = countRows("world_authored_source_tenant_key_reservation"); + + assertThat( + repository.readBySource( + NAMESPACE, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) + .contains(receipt); + assertThat( + repository.readBySource( + NAMESPACE, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) + .contains(receipt); + assertThat(countRows("world_authored_source_intake")).isEqualTo(intakeCount); + assertThat(countRows("world_authored_source_tenant_association")).isEqualTo(associationCount); + assertThat(countRows("world_authored_source_tenant_key_reservation")) + .isEqualTo(reservationCount); + } + + @Test + void readBySourceRejectsAnyChangedBindingAndRetainedOrUnmappedEvidence() { + UUID tenant = UUID.randomUUID(); + String tenantSlug = tenantSlug(tenant); + long sourceRowId = sourceRowId(tenant); + AuthoredWorldSourceEvidence source = + source(tenant, tenantSlug, "source-binding-world", sourceRowId, "Source Binding"); + accept(UUID.randomUUID(), source); + + assertThat( + repository.readBySource( + "other-namespace", + tenant, + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) + .isEmpty(); + assertThat( + repository.readBySource( + NAMESPACE, + UUID.randomUUID(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) + .isEmpty(); + assertThat( + repository.readBySource( + NAMESPACE, tenant, "another-world", source.operationId(), source.evidenceDigest())) + .isEmpty(); + assertThat( + repository.readBySource( + NAMESPACE, tenant, source.worldSlug(), UUID.randomUUID(), source.evidenceDigest())) + .isEmpty(); + assertThat( + repository.readBySource( + NAMESPACE, + tenant, + source.worldSlug(), + source.operationId(), + "sha256:" + "0".repeat(64))) + .isEmpty(); + + AuthoredWorldSourceEvidence retainedSource = + source(tenant, tenantSlug, "retained-world", sourceRowId, "Retained", "RETAINED_GAME_V29"); + assertThat( + repository.readBySource( + NAMESPACE, + retainedSource.canonicalTenantId(), + retainedSource.worldSlug(), + retainedSource.operationId(), + retainedSource.evidenceDigest())) + .isEmpty(); + assertThat( + repository.readBySource( + NAMESPACE, + UUID.randomUUID(), + "unmapped-world", + UUID.randomUUID(), + source.evidenceDigest())) + .isEmpty(); + } + + @Test + void readBySourceRejectsMalformedBinding() { + UUID tenant = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = + source( + tenant, tenantSlug(tenant), "malformed-read-world", sourceRowId(tenant), "Malformed"); + UUID nilUuid = new UUID(0L, 0L); + + assertThatThrownBy( + () -> + repository.readBySource( + "FireMud", + tenant, + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + repository.readBySource( + NAMESPACE, + nilUuid, + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + repository.readBySource( + NAMESPACE, + tenant, + "Malformed-World", + source.operationId(), + source.evidenceDigest())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + repository.readBySource( + NAMESPACE, tenant, source.worldSlug(), nilUuid, source.evidenceDigest())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + repository.readBySource( + NAMESPACE, tenant, source.worldSlug(), source.operationId(), "sha256:BAD")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void readBySourceDoesNotExposeUncommittedOwnerEvidence() { + UUID tenant = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = + source( + tenant, + tenantSlug(tenant), + "uncommitted-read-world", + sourceRowId(tenant), + "Uncommitted"); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + + transactionTemplate.execute( + status -> { + repository.acceptFresh(NAMESPACE, requestId, source); + assertThat( + repository.readBySource( + NAMESPACE, + tenant, + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) + .isEmpty(); + return null; + }); + + assertThat( + repository.readBySource( + NAMESPACE, + tenant, + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) + .contains(repository.read(NAMESPACE, requestId).orElseThrow()); + } + + @Test + void deniesRetainedEvidenceAndChangedRequestOrTenantScopeBeforeAddingClaims() { + UUID tenant = UUID.randomUUID(); + String tenantSlug = tenantSlug(tenant); + long sourceRowId = sourceRowId(tenant); + AuthoredWorldSourceEvidence firstSource = + source(tenant, tenantSlug, "violet-wilds", sourceRowId, "Violet Wilds"); + UUID requestId = UUID.randomUUID(); + WorldAuthoredSourceIntakeReceipt first = accept(requestId, firstSource); + + AuthoredWorldSourceEvidence changedRequestSource = + source(tenant, tenantSlug, "amber-coast", sourceRowId, "Amber Coast"); + assertThatThrownBy(() -> accept(requestId, changedRequestSource)) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); + assertThatThrownBy( + () -> + accept( + requestId, + source( + UUID.randomUUID(), + "unrelated-tenant-selector", + "violet-wilds", + 7_456_321_987L, + "Violet Wilds"))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); + + AuthoredWorldSourceEvidence changedWorldSource = + source(tenant, tenantSlug, "violet-wilds", sourceRowId, "Changed Display"); + assertThatThrownBy(() -> accept(UUID.randomUUID(), changedWorldSource)) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); + assertThatThrownBy(() -> accept(UUID.randomUUID(), firstSource)) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); + + AuthoredWorldSourceEvidence changedTenantSource = + source( + tenant, + "renamed-" + tenant.toString().replace("-", ""), + "new-world", + sourceRowId, + "New World"); + assertThatThrownBy(() -> accept(UUID.randomUUID(), changedTenantSource)) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); + + UUID retainedTenantId = UUID.randomUUID(); + AuthoredWorldSourceEvidence retainedSource = + source( + retainedTenantId, + tenantSlug(retainedTenantId), + "retained-world", + sourceRowId(retainedTenantId), + "Retained", + "RETAINED_GAME_V29"); + assertThatThrownBy(() -> accept(UUID.randomUUID(), retainedSource)) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException.class); + assertThat(read(requestId)).contains(first); + assertThat(countForCanonicalTenant(tenant)).isEqualTo(1L); + } + + @Test + void ownerTransactionRollbackLeavesNeitherAssociationNorReceipt() { + UUID tenant = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = + source( + tenant, + tenantSlug(tenant), + "rolled-back-world", + sourceRowId(tenant), + "Rolled Back World"); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + + assertThatThrownBy( + () -> + transactionTemplate.execute( + status -> { + repository.acceptFresh(NAMESPACE, requestId, source); + throw new ForcedOwnerRollbackException(); + })) + .isInstanceOf(ForcedOwnerRollbackException.class); + + assertThat(read(requestId)).isEmpty(); + assertThat(countForCanonicalTenant(tenant)).isZero(); + assertThat(countReservationsForCanonicalTenant(tenant)).isZero(); + } + + @Test + void rejectsImmutableHistoryMutationAndTruncation() { + UUID tenant = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = + source( + tenant, tenantSlug(tenant), "immutable-world", sourceRowId(tenant), "Immutable World"); + WorldAuthoredSourceIntakeReceipt receipt = accept(requestId, source); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_authored_source_intake SET world_display_name = ? " + + "WHERE operation_id = ?", + "substituted", + receipt.operationId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM world_authored_source_intake WHERE operation_id = ?", + receipt.operationId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy(() -> dsl.execute("TRUNCATE world_authored_source_intake CASCADE")) + .isInstanceOf(DataAccessException.class); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_authored_source_tenant_association SET tenant_slug = ? " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + "changed-selector", + NAMESPACE, + tenant)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM world_authored_source_tenant_association " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + tenant)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> dsl.execute("TRUNCATE world_authored_source_tenant_association CASCADE")) + .isInstanceOf(DataAccessException.class); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_authored_source_tenant_key_reservation " + + "SET claim_kind = 'LEGACY_NUMERIC' WHERE tenant_key = ?", + receipt.localTenantKey())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM world_authored_source_tenant_key_reservation " + + "WHERE tenant_key = ?", + receipt.localTenantKey())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> dsl.execute("TRUNCATE world_authored_source_tenant_key_reservation CASCADE")) + .isInstanceOf(DataAccessException.class); + + assertThat(read(requestId)).contains(receipt); + assertThat(countForCanonicalTenant(tenant)).isEqualTo(1L); + assertThat(countReservationsForCanonicalTenant(tenant)).isEqualTo(1L); + } + + @Test + void canonicalReservationsGuardEveryWorldRowMutationTrigger() throws SQLException { + String schema = "world_canonical_guard_" + UUID.randomUUID().toString().replace("-", ""); + UUID canonicalTenantId = UUID.randomUUID(); + long canonicalTenantKey = + 80_000_000_000_000L + ThreadLocalRandom.current().nextLong(1_000_000L); + long legacyTenantKey = canonicalTenantKey + 1L; + + try { + migrateFixture(schema, MigrationVersion.fromVersion("23.1")); + long canonicalRegionId = + seedCanonicalRegionBeforeGuard(schema, canonicalTenantId, canonicalTenantKey); + migrateFixture(schema, MigrationVersion.fromVersion("24")); + migrateFixture(schema, MigrationVersion.fromVersion("27.2")); + + try (Connection connection = fixtureConnection(schema)) { + assertProtectedReservationTriggerCatalog(connection); + assertProtectedTenantTruncateTriggerCatalog(connection); + + for (String table : PROTECTED_TENANT_TABLES) { + assertSqlState("23514", () -> insertTenantKeyRow(connection, table, canonicalTenantKey)); + long expectedRows = table.equals("region") ? 1L : 0L; + assertThat(countRowsForTenant(connection, table, canonicalTenantKey)) + .as("canonical-key insert side effects for %s", table) + .isEqualTo(expectedRows); + } + + long legacyRegionId = insertRegion(connection, legacyTenantKey, "legacy-before-update"); + assertSqlState( + "23514", + () -> + updateRegion( + connection, + canonicalRegionId, + legacyTenantKey, + "attempted move from canonical key")); + assertCanonicalRegion( + connection, canonicalRegionId, canonicalTenantKey, "test-only canonical row"); + assertThat(countRowsForTenant(connection, "region", legacyTenantKey)).isEqualTo(1L); + assertThat(readReservationClaimKind(connection, legacyTenantKey)) + .isEqualTo("LEGACY_NUMERIC"); + + assertSqlState( + "23514", + () -> updateRegionPayload(connection, canonicalRegionId, "attempted payload update")); + assertCanonicalRegion( + connection, canonicalRegionId, canonicalTenantKey, "test-only canonical row"); + + assertSqlState("23514", () -> deleteRegion(connection, canonicalRegionId)); + assertCanonicalRegion( + connection, canonicalRegionId, canonicalTenantKey, "test-only canonical row"); + assertThat(readReservationClaimKind(connection, canonicalTenantKey)) + .isEqualTo("CANONICAL_AUTHORED_SOURCE"); + + updateRegionPayload(connection, legacyRegionId, "legacy payload update remains allowed"); + assertThat(readRegionName(connection, legacyRegionId)) + .isEqualTo("legacy payload update remains allowed"); + deleteRegion(connection, legacyRegionId); + assertThat(countRowsForTenant(connection, "region", legacyTenantKey)).isZero(); + assertThat(readReservationClaimKind(connection, legacyTenantKey)) + .isEqualTo("LEGACY_NUMERIC"); + + assertSqlState("23514", () -> truncateTenantTable(connection, "region")); + assertCanonicalRegion( + connection, canonicalRegionId, canonicalTenantKey, "test-only canonical row"); + assertThat(countRowsForTenant(connection, "region", canonicalTenantKey)).isEqualTo(1L); + assertThat(readReservationClaimKind(connection, canonicalTenantKey)) + .isEqualTo("CANONICAL_AUTHORED_SOURCE"); + assertThat(countCanonicalAssociations(connection, canonicalTenantId)).isEqualTo(1L); + } + } finally { + dropFixtureSchema(schema); + } + } + + @Test + void sameLegacyTenantUpdatesDoNotLockTheSharedReservationRow() throws Exception { + long legacyTenantKey = 7_000_000_000L + ThreadLocalRandom.current().nextLong(1_000_000L); + long firstRegionId = insertRegion(legacyTenantKey, "first-before-concurrent-update"); + long secondRegionId = insertRegion(legacyTenantKey, "second-before-concurrent-update"); + TransactionTemplate firstTransaction = new TransactionTemplate(transactionManager); + TransactionTemplate secondTransaction = new TransactionTemplate(transactionManager); + CountDownLatch firstUpdateFinished = new CountDownLatch(1); + CountDownLatch allowFirstCommit = new CountDownLatch(1); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = + executor.submit( + () -> + firstTransaction.execute( + status -> { + dsl.execute( + "UPDATE region SET name = ? WHERE id = ?", + "first-uncommitted-update", + firstRegionId); + firstUpdateFinished.countDown(); + await(allowFirstCommit, 20); + return null; + })); + + try { + assertThat(firstUpdateFinished.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat(first.isDone()).isFalse(); + + Future second = + executor.submit( + () -> + secondTransaction.execute( + status -> { + dsl.execute( + "UPDATE region SET name = ? WHERE id = ?", + "second-committed-update", + secondRegionId); + return null; + })); + second.get(5, TimeUnit.SECONDS); + assertThat(first.isDone()).isFalse(); + } finally { + allowFirstCommit.countDown(); + } + + first.get(20, TimeUnit.SECONDS); + } + + assertThat(readRegionName(firstRegionId)).isEqualTo("first-uncommitted-update"); + assertThat(readRegionName(secondRegionId)).isEqualTo("second-committed-update"); + } + + @Test + void freshIntakeLockTimeoutRollsBackAndExactRequestRetriesAfterWriterCommits() throws Exception { + long legacyTenantKey = 9_000_000_000L + ThreadLocalRandom.current().nextLong(1_000_000L); + UUID tenant = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = + source( + tenant, + tenantSlug(tenant), + "lock-timeout-world", + sourceRowId(tenant), + "Lock Timeout World"); + TransactionTemplate legacyTransaction = new TransactionTemplate(transactionManager); + TransactionTemplate intakeTransaction = new TransactionTemplate(transactionManager); + CountDownLatch legacyInserted = new CountDownLatch(1); + CountDownLatch allowLegacyCommit = new CountDownLatch(1); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future legacyWrite = + executor.submit( + () -> + legacyTransaction.execute( + status -> { + dsl.execute( + "INSERT INTO region (tenant_id, name) VALUES (?, ?)", + legacyTenantKey, + "lock-timeout-writer"); + legacyInserted.countDown(); + await(allowLegacyCommit, 20); + return null; + })); + + try { + assertThat(legacyInserted.await(5, TimeUnit.SECONDS)).isTrue(); + long attemptStartedNanos = System.nanoTime(); + Future failedIntake = + executor.submit( + () -> { + try { + intakeTransaction.execute( + status -> repository.acceptFresh(NAMESPACE, requestId, source)); + return null; + } catch (RuntimeException exception) { + return exception; + } + }); + RuntimeException lockTimeout = failedIntake.get(5, TimeUnit.SECONDS); + long attemptDurationNanos = System.nanoTime() - attemptStartedNanos; + + assertThat(lockTimeout) + .isInstanceOf(org.springframework.dao.CannotAcquireLockException.class); + assertThat(sqlStateFrom(lockTimeout)).isEqualTo("55P03"); + assertThat(attemptDurationNanos).isLessThan(TimeUnit.SECONDS.toNanos(5)); + assertThat(countForCanonicalTenant(tenant)).isZero(); + assertThat(countReservationsForCanonicalTenant(tenant)).isZero(); + assertThat(read(requestId)).isEmpty(); + } finally { + allowLegacyCommit.countDown(); + } + + legacyWrite.get(20, TimeUnit.SECONDS); + } + + WorldAuthoredSourceIntakeReceipt receipt = + intakeTransaction.execute(status -> repository.acceptFresh(NAMESPACE, requestId, source)); + assertThat(receipt).isNotNull(); + assertThat(receipt.localTenantKey()).isGreaterThan(legacyTenantKey); + assertThat(countForCanonicalTenant(tenant)).isEqualTo(1L); + assertThat(countReservationsForCanonicalTenant(tenant)).isEqualTo(1L); + assertThat(read(requestId)).contains(receipt); + } + + @Test + void preservesTighterCallerLockTimeoutAndResetsItAfterCommit() { + UUID tenant = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = + source( + tenant, + tenantSlug(tenant), + "tighter-lock-timeout-world", + sourceRowId(tenant), + "Tighter Lock Timeout World"); + TransactionTemplate intakeTransaction = new TransactionTemplate(transactionManager); + + WorldAuthoredSourceIntakeReceipt receipt = + intakeTransaction.execute( + status -> { + dsl.fetchOne("SELECT set_config('lock_timeout', '250ms', true)"); + WorldAuthoredSourceIntakeReceipt accepted = + repository.acceptFresh(NAMESPACE, requestId, source); + Integer activeTimeoutMillis = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT setting::integer FROM pg_settings WHERE name = 'lock_timeout'"), + "PostgreSQL lock_timeout setting query returned no row") + .get(0, Integer.class); + assertThat(activeTimeoutMillis).isEqualTo(250); + return accepted; + }); + + assertThat(receipt).isNotNull(); + var lockTimeoutSettings = + Objects.requireNonNull( + dsl.fetchOne("SELECT setting, reset_val FROM pg_settings WHERE name = 'lock_timeout'"), + "PostgreSQL lock_timeout setting query returned no row"); + assertThat(lockTimeoutSettings.get("setting", String.class)) + .isEqualTo(lockTimeoutSettings.get("reset_val", String.class)); + } + + @Test + void rejectsReadOnlyAndNonReadCommittedOwnerTransactionsWithoutClaims() { + UUID tenant = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = + source( + tenant, + tenantSlug(tenant), + "unsupported-transaction-world", + sourceRowId(tenant), + "Unsupported Transaction World"); + + TransactionTemplate readOnly = new TransactionTemplate(transactionManager); + readOnly.setReadOnly(true); + assertThatThrownBy( + () -> readOnly.execute(status -> repository.acceptFresh(NAMESPACE, requestId, source))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable owner transaction"); + assertThat(countForCanonicalTenant(tenant)).isZero(); + assertThat(countReservationsForCanonicalTenant(tenant)).isZero(); + assertThat(read(requestId)).isEmpty(); + + TransactionTemplate repeatableRead = new TransactionTemplate(transactionManager); + repeatableRead.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThatThrownBy( + () -> + repeatableRead.execute( + status -> repository.acceptFresh(NAMESPACE, requestId, source))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("READ COMMITTED"); + assertThat(countForCanonicalTenant(tenant)).isZero(); + assertThat(countReservationsForCanonicalTenant(tenant)).isZero(); + assertThat(read(requestId)).isEmpty(); + + assertThatThrownBy(() -> repository.acceptFresh(NAMESPACE, requestId, source)) + .isInstanceOf(IllegalTransactionStateException.class); + assertThat(countForCanonicalTenant(tenant)).isZero(); + assertThat(countReservationsForCanonicalTenant(tenant)).isZero(); + assertThat(read(requestId)).isEmpty(); + } + + @Test + void concurrentExactRetriesReturnTheSingleCommittedReceipt() throws Exception { + UUID tenant = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = + source( + tenant, + tenantSlug(tenant), + "concurrent-world", + sourceRowId(tenant), + "Concurrent World"); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = + executor.submit( + () -> acceptWhenReleased(transactionTemplate, ready, start, requestId, source)); + Future second = + executor.submit( + () -> acceptWhenReleased(transactionTemplate, ready, start, requestId, source)); + + assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + WorldAuthoredSourceIntakeReceipt firstReceipt = first.get(20, TimeUnit.SECONDS); + WorldAuthoredSourceIntakeReceipt secondReceipt = second.get(20, TimeUnit.SECONDS); + assertThat(firstReceipt).isEqualTo(secondReceipt); + assertThat(read(requestId)).contains(firstReceipt); + } + } + + @Test + void concurrentLegacyNumericClaimSerializesBeforeFreshSelectorAllocation() throws Exception { + long legacyTenantKey = 6_000_000_000L + ThreadLocalRandom.current().nextLong(1_000_000L); + UUID tenant = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = + source( + tenant, + tenantSlug(tenant), + "concurrent-numeric-allocation-world", + sourceRowId(tenant), + "Concurrent Numeric Allocation World"); + TransactionTemplate legacyTransaction = new TransactionTemplate(transactionManager); + TransactionTemplate intakeTransaction = new TransactionTemplate(transactionManager); + CountDownLatch legacyInserted = new CountDownLatch(1); + CountDownLatch allowLegacyCommit = new CountDownLatch(1); + CountDownLatch intakeStarted = new CountDownLatch(1); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future legacyWrite = + executor.submit( + () -> + legacyTransaction.execute( + status -> { + dsl.execute( + "INSERT INTO region (tenant_id, name) VALUES (?, ?)", + legacyTenantKey, + "concurrent-legacy-selector"); + legacyInserted.countDown(); + await(allowLegacyCommit, 20); + return null; + })); + assertThat(legacyInserted.await(5, TimeUnit.SECONDS)).isTrue(); + + Future intake = + executor.submit( + () -> { + intakeStarted.countDown(); + return intakeTransaction.execute( + status -> repository.acceptFresh(NAMESPACE, requestId, source)); + }); + assertThat(intakeStarted.await(5, TimeUnit.SECONDS)).isTrue(); + awaitAllocatorLockWait(); + allowLegacyCommit.countDown(); + + legacyWrite.get(20, TimeUnit.SECONDS); + WorldAuthoredSourceIntakeReceipt receipt = intake.get(20, TimeUnit.SECONDS); + assertThat(receipt.localTenantKey()).isGreaterThan(legacyTenantKey); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM region WHERE tenant_id = ?", legacyTenantKey), + "legacy region count query returned no row") + .get(0, Long.class)) + .isEqualTo(1L); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM world_authored_source_tenant_key_reservation " + + "WHERE tenant_key = ? AND claim_kind = 'LEGACY_NUMERIC'", + legacyTenantKey), + "legacy tenant-key reservation count query returned no row") + .get(0, Long.class)) + .isEqualTo(1L); + assertThat(countForCanonicalTenant(tenant)).isEqualTo(1L); + assertThat(read(requestId)).contains(receipt); + } + } + + @Test + void concurrentLegacyClaimAfterAllocationCannotTakeTheReservedSelector() throws Exception { + UUID tenant = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = + source( + tenant, + tenantSlug(tenant), + "concurrent-reserved-selector-world", + sourceRowId(tenant), + "Concurrent Reserved Selector World"); + TransactionTemplate ownerTransaction = new TransactionTemplate(transactionManager); + TransactionTemplate legacyTransaction = new TransactionTemplate(transactionManager); + CountDownLatch intakePrepared = new CountDownLatch(1); + CountDownLatch allowIntakeCommit = new CountDownLatch(1); + AtomicReference preparedReceipt = new AtomicReference<>(); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future intake = + executor.submit( + () -> + ownerTransaction.execute( + status -> { + WorldAuthoredSourceIntakeReceipt receipt = + repository.acceptFresh(NAMESPACE, requestId, source); + preparedReceipt.set(receipt); + intakePrepared.countDown(); + await(allowIntakeCommit, 20); + return receipt; + })); + assertThat(intakePrepared.await(5, TimeUnit.SECONDS)).isTrue(); + WorldAuthoredSourceIntakeReceipt receipt = preparedReceipt.get(); + assertThat(receipt).isNotNull(); + + Future legacyWrite = + executor.submit( + () -> { + try { + legacyTransaction.execute( + status -> { + dsl.execute( + "INSERT INTO region (tenant_id, name) VALUES (?, ?)", + receipt.localTenantKey(), + "cannot-race-private-selector"); + return null; + }); + return true; + } catch (DataIntegrityViolationException expectedReservedKeyRejection) { + assertReservedCanonicalSelectorRejected(expectedReservedKeyRejection); + return false; + } + }); + + awaitLegacyWriterLockWait(); + allowIntakeCommit.countDown(); + assertThat(intake.get(20, TimeUnit.SECONDS)).isEqualTo(receipt); + assertThat(legacyWrite.get(20, TimeUnit.SECONDS)).isFalse(); + assertThat(read(requestId)).contains(receipt); + assertThat(countForCanonicalTenant(tenant)).isEqualTo(1L); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM region WHERE tenant_id = ?", + receipt.localTenantKey()), + "canonical-selector region count query returned no row") + .get(0, Long.class)) + .isZero(); + } + } + + private static void migrateFixture(String schema, MigrationVersion target) { + var configuration = + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private static long seedCanonicalRegionBeforeGuard( + String schema, UUID canonicalTenantId, long canonicalTenantKey) throws SQLException { + try (Connection connection = fixtureConnection(schema); + Statement controls = connection.createStatement()) { + // Test-only bypass in this isolated V23.1 schema; restore triggers before applying V24. + controls.execute("SET session_replication_role = replica"); + try { + String tenantSlug = tenantSlug(canonicalTenantId); + String sourceKey = "src-" + canonicalTenantId.toString().replace("-", ""); + try (PreparedStatement association = + connection.prepareStatement( + "INSERT INTO world_authored_source_tenant_association " + + "(target_namespace, canonical_tenant_id, tenant_slug, " + + "source_game_row_id, source_game_tenant_key, " + + "source_provenance_kind, local_tenant_key) " + + "VALUES (?, ?, ?, ?, ?, 'NEW_GAME_ROW', ?)")) { + association.setString(1, NAMESPACE); + association.setObject(2, canonicalTenantId); + association.setString(3, tenantSlug); + association.setLong(4, sourceRowId(canonicalTenantId)); + association.setString(5, sourceKey); + association.setLong(6, canonicalTenantKey); + association.executeUpdate(); + } + try (PreparedStatement reservation = + connection.prepareStatement( + "INSERT INTO world_authored_source_tenant_key_reservation " + + "(tenant_key, claim_kind, target_namespace, canonical_tenant_id) " + + "VALUES (?, 'CANONICAL_AUTHORED_SOURCE', ?, ?)")) { + reservation.setLong(1, canonicalTenantKey); + reservation.setString(2, NAMESPACE); + reservation.setObject(3, canonicalTenantId); + reservation.executeUpdate(); + } + try (PreparedStatement region = + connection.prepareStatement( + "INSERT INTO region (tenant_id, name) VALUES (?, ?) RETURNING id")) { + region.setLong(1, canonicalTenantKey); + region.setString(2, "test-only canonical row"); + try (ResultSet result = region.executeQuery()) { + if (!result.next()) { + throw new SQLException("Test-only canonical region seed returned no row"); + } + return result.getLong(1); + } + } + } finally { + controls.execute("SET session_replication_role = origin"); + } + } + } + + private static Connection fixtureConnection(String schema) throws SQLException { + Connection connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + connection.setSchema(schema); + return connection; + } + + private static void dropFixtureSchema(String schema) throws SQLException { + try (Connection connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + Statement statement = connection.createStatement()) { + statement.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } + } + + private static void assertProtectedReservationTriggerCatalog(Connection connection) + throws SQLException { + Set actualTables = new HashSet<>(); + try (Statement statement = connection.createStatement(); + ResultSet result = + statement.executeQuery( + "SELECT table_row.relname, trigger_row.tgname, function_row.proname, " + + "trigger_row.tgtype, trigger_row.tgenabled " + + "FROM pg_trigger AS trigger_row " + + "JOIN pg_class AS table_row ON table_row.oid = trigger_row.tgrelid " + + "JOIN pg_namespace AS namespace_row " + + "ON namespace_row.oid = table_row.relnamespace " + + "JOIN pg_proc AS function_row ON function_row.oid = trigger_row.tgfoid " + + "WHERE namespace_row.nspname = current_schema() " + + "AND trigger_row.tgname LIKE 'trg_reserve_%_tenant_key' " + + "AND NOT trigger_row.tgisinternal")) { + while (result.next()) { + String table = result.getString(1); + actualTables.add(table); + assertThat(result.getString(2)).isEqualTo("trg_reserve_" + table + "_tenant_key"); + assertThat(result.getString(3)).isEqualTo("world_claim_legacy_numeric_tenant_key"); + assertThat(result.getInt(4)).isEqualTo(31); + assertThat(result.getString(5)).isEqualTo("O"); + } + } + assertThat(actualTables).containsExactlyInAnyOrderElementsOf(PROTECTED_TENANT_TABLES); + } + + private static void assertProtectedTenantTruncateTriggerCatalog(Connection connection) + throws SQLException { + Set actualTables = new HashSet<>(); + try (Statement statement = connection.createStatement(); + ResultSet result = + statement.executeQuery( + "SELECT table_row.relname, trigger_row.tgname, trigger_row.tgtype, " + + "trigger_row.tgenabled " + + "FROM pg_trigger AS trigger_row " + + "JOIN pg_class AS table_row ON table_row.oid = trigger_row.tgrelid " + + "JOIN pg_namespace AS namespace_row " + + "ON namespace_row.oid = table_row.relnamespace " + + "JOIN pg_proc AS function_row ON function_row.oid = trigger_row.tgfoid " + + "WHERE namespace_row.nspname = current_schema() " + + "AND function_row.proname = 'world_reject_tenant_table_truncate' " + + "AND NOT trigger_row.tgisinternal")) { + while (result.next()) { + String table = result.getString(1); + actualTables.add(table); + assertThat(result.getString(2)).isEqualTo("trg_" + table + "_no_truncate"); + assertThat(result.getInt(3)).isEqualTo(34); + assertThat(result.getString(4)).isEqualTo("O"); + } + } + assertThat(actualTables).containsExactlyInAnyOrderElementsOf(PROTECTED_TENANT_TABLES); + } + + private static void truncateTenantTable(Connection connection, String table) throws SQLException { + try (Statement statement = connection.createStatement()) { + statement.execute("TRUNCATE " + table + " CASCADE"); + } + } + + private static void insertTenantKeyRow(Connection connection, String table, long tenantKey) + throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement("INSERT INTO " + table + " (tenant_id) VALUES (?)")) { + statement.setLong(1, tenantKey); + statement.executeUpdate(); + } + } + + private static long insertRegion(Connection connection, long tenantKey, String name) + throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement( + "INSERT INTO region (tenant_id, name) VALUES (?, ?) RETURNING id")) { + statement.setLong(1, tenantKey); + statement.setString(2, name); + try (ResultSet result = statement.executeQuery()) { + if (!result.next()) { + throw new SQLException("Region fixture insert returned no row"); + } + return result.getLong(1); + } + } + } + + private long insertRegion(long tenantKey, String name) { + return Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO region (tenant_id, name) VALUES (?, ?) RETURNING id", tenantKey, name), + "Region concurrency fixture insert returned no row") + .get(0, Long.class); + } + + private static void updateRegion( + Connection connection, long regionId, long tenantKey, String name) throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement("UPDATE region SET tenant_id = ?, name = ? WHERE id = ?")) { + statement.setLong(1, tenantKey); + statement.setString(2, name); + statement.setLong(3, regionId); + statement.executeUpdate(); + } + } + + private static void updateRegionPayload(Connection connection, long regionId, String name) + throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement("UPDATE region SET name = ? WHERE id = ?")) { + statement.setString(1, name); + statement.setLong(2, regionId); + statement.executeUpdate(); + } + } + + private static void deleteRegion(Connection connection, long regionId) throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement("DELETE FROM region WHERE id = ?")) { + statement.setLong(1, regionId); + statement.executeUpdate(); + } + } + + private static long countRowsForTenant(Connection connection, String table, long tenantKey) + throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement("SELECT COUNT(*) FROM " + table + " WHERE tenant_id = ?")) { + statement.setLong(1, tenantKey); + try (ResultSet result = statement.executeQuery()) { + result.next(); + return result.getLong(1); + } + } + } + + private static String readRegionName(Connection connection, long regionId) throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement("SELECT name FROM region WHERE id = ?")) { + statement.setLong(1, regionId); + try (ResultSet result = statement.executeQuery()) { + if (!result.next()) { + throw new SQLException("Expected region fixture row was missing"); + } + return result.getString(1); + } + } + } + + private String readRegionName(long regionId) { + return Objects.requireNonNull( + dsl.fetchOne("SELECT name FROM region WHERE id = ?", regionId), + "Region concurrency fixture read returned no row") + .get(0, String.class); + } + + private static void assertCanonicalRegion( + Connection connection, long regionId, long tenantKey, String name) throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement("SELECT tenant_id, name FROM region WHERE id = ?")) { + statement.setLong(1, regionId); + try (ResultSet result = statement.executeQuery()) { + assertThat(result.next()).isTrue(); + assertThat(result.getLong(1)).isEqualTo(tenantKey); + assertThat(result.getString(2)).isEqualTo(name); + } + } + } + + private static String readReservationClaimKind(Connection connection, long tenantKey) + throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement( + "SELECT claim_kind FROM world_authored_source_tenant_key_reservation " + + "WHERE tenant_key = ?")) { + statement.setLong(1, tenantKey); + try (ResultSet result = statement.executeQuery()) { + return result.next() ? result.getString(1) : null; + } + } + } + + private static long countCanonicalAssociations(Connection connection, UUID canonicalTenantId) + throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement( + "SELECT COUNT(*) FROM world_authored_source_tenant_association " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?")) { + statement.setString(1, NAMESPACE); + statement.setObject(2, canonicalTenantId); + try (ResultSet result = statement.executeQuery()) { + result.next(); + return result.getLong(1); + } + } + } + + private static void assertSqlState(String expected, SqlAction action) throws SQLException { + SQLException rejected = null; + try { + action.execute(); + } catch (SQLException exception) { + rejected = exception; + } + if (rejected == null) { + throw new AssertionError("Expected PostgreSQL rejection with SQLSTATE " + expected); + } + assertThat(rejected.getSQLState()).isEqualTo(expected); + } + + @FunctionalInterface + private interface SqlAction { + void execute() throws SQLException; + } + + private WorldAuthoredSourceIntakeReceipt accept( + UUID requestId, AuthoredWorldSourceEvidence source) { + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + return transactionTemplate.execute( + status -> repository.acceptFresh(NAMESPACE, requestId, source)); + } + + private WorldAuthoredSourceIntakeReceipt acceptWhenReleased( + TransactionTemplate transactionTemplate, + CountDownLatch ready, + CountDownLatch start, + UUID requestId, + AuthoredWorldSourceEvidence source) { + ready.countDown(); + await(start); + return transactionTemplate.execute( + status -> repository.acceptFresh(NAMESPACE, requestId, source)); + } + + private java.util.Optional read(UUID requestId) { + return repository.read(NAMESPACE, requestId); + } + + private long countRows(String tableName) { + return Objects.requireNonNull( + dsl.fetchOne("SELECT COUNT(*) FROM " + tableName), + "table row count query returned no row") + .get(0, Long.class); + } + + private long countForCanonicalTenant(UUID tenantId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM world_authored_source_tenant_association WHERE " + + "target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + tenantId), + "canonical tenant association count query returned no row") + .get(0, Long.class); + } + + private void assertReservedCanonicalSelectorRejected(Throwable throwable) { + assertThat(throwable).hasStackTraceContaining("is reserved for a canonical authored source"); + + Throwable cause = throwable; + while (cause != null && !(cause instanceof SQLException)) { + cause = cause.getCause(); + } + assertThat(cause).isInstanceOf(SQLException.class); + assertThat(((SQLException) cause).getSQLState()).isEqualTo("23514"); + } + + private static String sqlStateFrom(Throwable throwable) { + for (Throwable cause = throwable; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException exception) { + return exception.getSQLState(); + } + } + throw new AssertionError("Expected a PostgreSQL SQLState in the failure cause chain"); + } + + private long countReservationsForCanonicalTenant(UUID tenantId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM world_authored_source_tenant_key_reservation " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + tenantId), + "canonical tenant-key reservation count query returned no row") + .get(0, Long.class); + } + + private void awaitAllocatorLockWait() { + long deadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < deadlineNanos) { + Long waiting = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM pg_stat_activity WHERE datname = current_database() " + + "AND wait_event_type = 'Lock' " + + "AND lower(query) LIKE 'lock table generation_rule%'"), + "allocator lock-wait query returned no row") + .get(0, Long.class); + if (waiting != null && waiting > 0L) { + return; + } + try { + TimeUnit.MILLISECONDS.sleep(25); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while observing PostgreSQL lock wait", exception); + } + } + throw new IllegalStateException( + "Fresh intake did not wait for the retained tenant-table writer"); + } + + private void awaitLegacyWriterLockWait() { + long deadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < deadlineNanos) { + Long waiting = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM pg_stat_activity WHERE datname = current_database() " + + "AND wait_event_type = 'Lock' " + + "AND lower(query) LIKE 'insert into region%'"), + "legacy writer lock-wait query returned no row") + .get(0, Long.class); + if (waiting != null && waiting > 0L) { + return; + } + try { + TimeUnit.MILLISECONDS.sleep(25); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while observing PostgreSQL legacy-writer lock wait", exception); + } + } + throw new IllegalStateException( + "Legacy numeric writer did not wait for the fresh intake owner transaction"); + } + + private static final class ForcedOwnerRollbackException extends RuntimeException { + private ForcedOwnerRollbackException() { + super("Force the test owner transaction to roll back"); + } + } + + private static AuthoredWorldSourceEvidence source( + UUID tenantId, String tenantSlug, String worldSlug, long sourceRowId, String displayName) { + return source(tenantId, tenantSlug, worldSlug, sourceRowId, displayName, "NEW_GAME_ROW"); + } + + private static String tenantSlug(UUID tenantId) { + return "tenant-" + tenantId.toString().replace("-", ""); + } + + private static long sourceRowId(UUID tenantId) { + long positive = tenantId.getLeastSignificantBits() & Long.MAX_VALUE; + return positive == 0L ? 1L : positive; + } + + private static AuthoredWorldSourceEvidence source( + UUID tenantId, + String tenantSlug, + String worldSlug, + long sourceRowId, + String displayName, + String provenance) { + UUID registrationId = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + String sourceGameTenantKey = "gd-row-" + sourceRowId; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationId, tenantId, tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceRowId, + sourceGameTenantKey, + provenance); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceRowId, + sourceGameTenantKey, + provenance, + evidenceDigest); + } + + private static void await(CountDownLatch latch) { + await(latch, 5); + } + + private static void await(CountDownLatch latch, long timeoutSeconds) { + try { + if (!latch.await(timeoutSeconds, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for concurrent intake test gate"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Concurrent intake test was interrupted", exception); + } + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeMtlsIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeMtlsIntegrationTest.java new file mode 100644 index 0000000000..390b4eb634 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeMtlsIntegrationTest.java @@ -0,0 +1,782 @@ +package net.firedevops.firemud.worldmanagement; + +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.clearInvocations; +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.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.Message; +import io.grpc.ForwardingServerCall; +import io.grpc.ManagedChannel; +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 java.math.BigInteger; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.Security; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.Base64; +import java.util.Date; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; +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.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ReadRequest; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.TestContainerImages; +import net.firedevops.firemud.worldmanagement.client.GrpcGameSessionInitialAdmissionBindProofClient; +import net.firedevops.firemud.worldmanagement.service.impl.WorldManagementGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeService; +import net.firedevops.firemud.worldmanagement.v1.ApplyWorldDesignMutationRequest; +import net.firedevops.firemud.worldmanagement.v1.ApplyWorldDesignMutationResponse; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeResponse; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationResult; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.BasicConstraints; +import org.bouncycastle.asn1.x509.ExtendedKeyUsage; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.asn1.x509.KeyPurposeId; +import org.bouncycastle.asn1.x509.KeyUsage; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.jooq.DSLContext; +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.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * PostgreSQL owner commit and exact receipt readback over the unregistered physical mTLS boundary. + * Game Design source evidence is synthetic; this does not exercise its producer or network. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class WorldAuthoredSourceIntakeMtlsIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final List WORLD_MUTATION_SNAPSHOT_TABLES = + List.of( + "region", + "zone", + "room", + "instance", + "room_exit", + "generation_rule", + "world_instance", + "region_instance", + "zone_instance", + "room_instance", + "room_instance_exit", + "world_event", + "world_design_revision_ledger", + "world_design_aggregate_epoch", + "world_design_scope_epoch", + "world_entity_spawn_binding", + "initial_admission_bind_hold", + "world_authored_source_tenant_association", + "world_authored_source_tenant_key_reservation", + "world_authored_source_intake", + "world_design_publication_fence_attempt", + "world_design_publication_fence_owner", + "world_complete_launch_binding", + "world_authored_version_identity"); + private static final String WORLD_SERVER_URI = + "spiffe://firemud/ns/firemud/sa/world-management-service"; + private static final AtomicLong CERTIFICATE_SERIAL = new AtomicLong(1); + private static TestPki pki; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + @TempDir Path tempDirectory; + + @Autowired private WorldAuthoredSourceIntakeRepository repository; + @Autowired private DSLContext dsl; + @Autowired private PlatformTransactionManager transactionManager; + @Autowired private WorldManagementGrpcService worldManagementGrpcService; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @MockitoBean(enforceOverride = true) + private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + + @MockitoBean + private net.firedevops.firemud.worldmanagement.client.GameDesignClient gameDesignClient; + + @MockitoBean + private net.firedevops.firemud.worldmanagement.client.GameSessionClient gameSessionClient; + + @MockitoBean + private net.firedevops.firemud.worldmanagement.client.EntityManagementClient + entityManagementClient; + + private Server server; + private ConcurrentLinkedQueue wireResponses; + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "world_management_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @BeforeAll + static void createFreshTestPki() throws Exception { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { + Security.addProvider(new BouncyCastleProvider()); + } + KeyPair caKeyPair = newRsaKeyPair(); + X500Name caName = new X500Name("CN=World Intake Integration Test CA, O=FireMUD Test"); + X509Certificate caCertificate = + issueCertificate(caName, caKeyPair.getPublic(), caName, caKeyPair.getPrivate(), true, null); + pki = + new TestPki( + caCertificate, + issueLeaf(caName, caKeyPair.getPrivate(), "world-management-service", WORLD_SERVER_URI), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "game-design-service", + "spiffe://firemud/ns/firemud/sa/game-design-service"), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "account-service", + "spiffe://firemud/ns/firemud/sa/account-service")); + } + + @AfterEach + void stopPhysicalReceiver() throws Exception { + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void commitsFreshWorldOwnerReceiptThenReturnsExactReceiptOverAuthenticatedSocket() + throws Exception { + Scenario scenario = newScenario("violet-wilds"); + AuthoredWorldSourceClient syntheticSource = sourceBoundary(scenario); + startReceiver(syntheticSource, new AtomicBoolean(false)); + + try (WorldAuthoredSourceIntakeClient client = + intakeClient(pki.gameDesignClient(), "gd-first")) { + CommittedReceipt intakeReceipt = client.intake(scenario.intakeRequest()); + WorldAuthoredSourceIntakeReceipt persisted = + repository.read(NAMESPACE, scenario.intakeRequestId()).orElseThrow(); + CommittedReceipt exactRead = client.read(scenario.readRequest()); + + assertThat(persisted.source()).isEqualTo(scenario.sourceEvidence()); + assertThat(intakeReceipt).isEqualTo(publicReceipt(persisted)); + assertThat(exactRead).isEqualTo(intakeReceipt); + assertThat(repository.read(NAMESPACE, scenario.intakeRequestId())).contains(persisted); + assertThat(dbCounts(scenario)).isEqualTo(new DbCounts(1L, 1L, 1L)); + assertNoPrivateLocalTenantKeyOnWire(); + verify(syntheticSource, times(1)).read(any(AuthoredWorldSourceGrpcCodec.ReadRequest.class)); + verifyNoMoreInteractions(syntheticSource); + } + } + + @Test + void reconcilesLostSuccessAcknowledgementWithExactRetryAndCommittedReadback() throws Exception { + Scenario scenario = newScenario("amber-coast"); + AuthoredWorldSourceClient syntheticSource = sourceBoundary(scenario); + AtomicBoolean dropNextSuccess = new AtomicBoolean(true); + startReceiver(syntheticSource, dropNextSuccess); + + try (WorldAuthoredSourceIntakeClient client = + intakeClient(pki.gameDesignClient(), "gd-retry")) { + assertThatThrownBy(() -> client.intake(scenario.intakeRequest())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); + + WorldAuthoredSourceIntakeReceipt committedAfterLostAck = + repository.read(NAMESPACE, scenario.intakeRequestId()).orElseThrow(); + DbCounts afterCommit = dbCounts(scenario); + assertThat(committedAfterLostAck.source()).isEqualTo(scenario.sourceEvidence()); + assertThat(afterCommit).isEqualTo(new DbCounts(1L, 1L, 1L)); + assertThat(dropNextSuccess.get()).isFalse(); + + CommittedReceipt retryReceipt = client.intake(scenario.intakeRequest()); + CommittedReceipt readReceipt = client.read(scenario.readRequest()); + + assertThat(retryReceipt).isEqualTo(publicReceipt(committedAfterLostAck)); + assertThat(readReceipt).isEqualTo(publicReceipt(committedAfterLostAck)); + assertThat(retryReceipt.operationId()).isEqualTo(committedAfterLostAck.operationId()); + assertThat(retryReceipt.requestDigest()).isEqualTo(committedAfterLostAck.requestDigest()); + assertThat(retryReceipt.receiptDigest()).isEqualTo(committedAfterLostAck.receiptDigest()); + assertThat(repository.read(NAMESPACE, scenario.intakeRequestId())) + .contains(committedAfterLostAck); + assertThat(dbCounts(scenario)).isEqualTo(afterCommit); + assertNoPrivateLocalTenantKeyOnWire(); + verify(syntheticSource, times(1)).read(any(AuthoredWorldSourceGrpcCodec.ReadRequest.class)); + verifyNoMoreInteractions(syntheticSource); + } + } + + @Test + void deniesWrongWorkloadAndChangedBindingWithoutOwnerMutation() throws Exception { + Scenario scenario = newScenario("silver-marsh"); + AuthoredWorldSourceClient syntheticSource = sourceBoundary(scenario); + startReceiver(syntheticSource, new AtomicBoolean(false)); + + try (WorldAuthoredSourceIntakeClient wrongCaller = + intakeClient(pki.accountClient(), "account")) { + assertStatus( + Status.Code.PERMISSION_DENIED, () -> wrongCaller.intake(scenario.intakeRequest())); + assertStatus(Status.Code.PERMISSION_DENIED, () -> wrongCaller.read(scenario.readRequest())); + } + assertThat(dbCounts(scenario)).isEqualTo(new DbCounts(0L, 0L, 0L)); + verifyNoInteractions(syntheticSource); + + try (WorldAuthoredSourceIntakeClient client = + intakeClient(pki.gameDesignClient(), "gd-scope")) { + CommittedReceipt accepted = client.intake(scenario.intakeRequest()); + WorldAuthoredSourceIntakeReceipt original = + repository.read(NAMESPACE, scenario.intakeRequestId()).orElseThrow(); + assertThat(client.read(scenario.readRequest())).isEqualTo(accepted); + + IntakeRequest changedIntake = + new IntakeRequest( + 1, + NAMESPACE, + scenario.intakeRequestId(), + scenario.canonicalTenantId(), + "changed-world-selector", + scenario.sourceOperationId(), + scenario.sourceEvidence().evidenceDigest()); + ReadRequest changedRead = new ReadRequest(changedIntake, UUID.randomUUID()); + + assertStatus(Status.Code.FAILED_PRECONDITION, () -> client.intake(changedIntake)); + assertStatus(Status.Code.FAILED_PRECONDITION, () -> client.read(changedRead)); + + assertThat(repository.read(NAMESPACE, scenario.intakeRequestId())).contains(original); + assertThat(original.source()).isEqualTo(scenario.sourceEvidence()); + assertThat(dbCounts(scenario)).isEqualTo(new DbCounts(1L, 1L, 1L)); + verify(syntheticSource, times(1)).read(any(AuthoredWorldSourceGrpcCodec.ReadRequest.class)); + verifyNoMoreInteractions(syntheticSource); + } + } + + @Test + void registeredDraftMutationDeniesGameDesignPeerBeforeOwnerReadOrMutation() throws Exception { + startRegisteredWorldManagementReceiver(); + clearInvocations(gameDesignClient, gameSessionClient, entityManagementClient); + Map> before = worldMutationRowSnapshot(); + + ApplyWorldDesignMutationResponse response = + applyWorldDesignMutation( + pki.gameDesignClient(), "gd-draft-denial", canonicalLookingDraftMutation()); + + assertDraftMutationDenied(response); + assertThat(worldMutationRowSnapshot()) + .as("World content, source, association, lifecycle and publication rows stay unchanged") + .isEqualTo(before); + verifyNoInteractions(gameDesignClient, gameSessionClient, entityManagementClient); + } + + @Test + void registeredDraftMutationDeniesOtherAuthenticatedPeerBeforeOwnerReadOrMutation() + throws Exception { + startRegisteredWorldManagementReceiver(); + clearInvocations(gameDesignClient, gameSessionClient, entityManagementClient); + Map> before = worldMutationRowSnapshot(); + + ApplyWorldDesignMutationResponse response = + applyWorldDesignMutation( + pki.accountClient(), "account-draft-denial", canonicalLookingDraftMutation()); + + assertDraftMutationDenied(response); + assertThat(worldMutationRowSnapshot()) + .as("World content, source, association, lifecycle and publication rows stay unchanged") + .isEqualTo(before); + verifyNoInteractions(gameDesignClient, gameSessionClient, entityManagementClient); + } + + private AuthoredWorldSourceClient sourceBoundary(Scenario scenario) { + AuthoredWorldSourceClient syntheticSource = mock(AuthoredWorldSourceClient.class); + when(syntheticSource.read(any(AuthoredWorldSourceGrpcCodec.ReadRequest.class))) + .thenAnswer( + invocation -> { + AuthoredWorldSourceGrpcCodec.ReadRequest request = invocation.getArgument(0); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(request.operationId()).isEqualTo(scenario.sourceOperationId()); + assertThat(request.canonicalTenantId()).isEqualTo(scenario.canonicalTenantId()); + assertThat(request.worldSlug()).isEqualTo(scenario.worldSlug()); + AuthoredWorldSourceEvidence answer = scenario.sourceEvidence(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return answer; + }); + return syntheticSource; + } + + private void startReceiver( + AuthoredWorldSourceClient syntheticSource, AtomicBoolean dropNextSuccess) throws Exception { + WorldAuthoredSourceIntakeService owner = + new WorldAuthoredSourceIntakeService( + syntheticSource, repository, transactionManager, NAMESPACE); + WorldAuthoredSourceIntakeGrpcService handler = + new WorldAuthoredSourceIntakeGrpcService(owner, NAMESPACE); + wireResponses = new ConcurrentLinkedQueue<>(); + var withPeerIdentity = ServerInterceptors.intercept(handler, new GrpcPeerIdentityInterceptor()); + var withResponseCapture = + ServerInterceptors.intercept( + withPeerIdentity, responseCaptureAndDrop(wireResponses, dropNextSuccess)); + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.worldServer().privateKey(), pki.worldServer().certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(withResponseCapture) + .build() + .start(); + } + + private void startRegisteredWorldManagementReceiver() throws Exception { + var withPeerIdentity = + ServerInterceptors.intercept(worldManagementGrpcService, new GrpcPeerIdentityInterceptor()); + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.worldServer().privateKey(), pki.worldServer().certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(withPeerIdentity) + .build() + .start(); + } + + private ApplyWorldDesignMutationResponse applyWorldDesignMutation( + TestCertificate certificate, String label, ApplyWorldDesignMutationRequest request) + throws Exception { + ManagedChannel channel = + new GrpcChannelFactory() + .buildChannel( + "127.0.0.1:" + server.getPort(), + server.getPort(), + tlsProperties(certificate, label), + false); + try { + return WorldManagementServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .applyWorldDesignMutation(request); + } finally { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } + + private WorldAuthoredSourceIntakeClient intakeClient(TestCertificate certificate, String label) + throws Exception { + WorldAuthoredSourceIntakeClient client = + new WorldAuthoredSourceIntakeClient( + endpoints(), tlsProperties(certificate, label), new GrpcChannelFactory(), NAMESPACE); + client.init(); + return client; + } + + private ServiceEndpointsProperties endpoints() { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("127.0.0.1:" + server.getPort()); + return endpoints; + } + + private CommonGrpcClientProperties tlsProperties(TestCertificate certificate, String label) + throws Exception { + Path clientCertificate = tempDirectory.resolve(label + "-client.crt"); + Path clientPrivateKey = tempDirectory.resolve(label + "-client.key"); + Path caCertificate = tempDirectory.resolve("test-ca.crt"); + Files.writeString( + clientCertificate, pem("CERTIFICATE", certificate.certificate().getEncoded())); + Files.writeString(clientPrivateKey, pem("PRIVATE KEY", certificate.privateKey().getEncoded())); + Files.writeString(caCertificate, pem("CERTIFICATE", pki.caCertificate().getEncoded())); + + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(clientCertificate.toString()); + tls.setPrivateKey(clientPrivateKey.toString()); + tls.setCaCert(caCertificate.toString()); + return tls; + } + + private static ServerInterceptor responseCaptureAndDrop( + ConcurrentLinkedQueue capturedResponses, AtomicBoolean dropNextSuccess) { + return new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + ServerCall forwardingCall = + new ForwardingServerCall.SimpleForwardingServerCall<>(call) { + private boolean droppedResponse; + + @Override + public void sendMessage(RespT message) { + if (message instanceof Message protobufMessage) { + capturedResponses.add(protobufMessage); + } + if (message instanceof IntakeAuthoredWorldSourceResponse + && dropNextSuccess.compareAndSet(true, false)) { + droppedResponse = true; + return; + } + super.sendMessage(message); + } + + @Override + public void close(Status status, Metadata trailers) { + if (droppedResponse && status.isOk()) { + super.close( + Status.UNAVAILABLE.withDescription( + "Test deliberately lost a committed intake acknowledgement"), + trailers); + return; + } + super.close(status, trailers); + } + }; + return next.startCall(forwardingCall, headers); + } + }; + } + + private void assertNoPrivateLocalTenantKeyOnWire() { + assertThat( + IntakeAuthoredWorldSourceResponse.getDescriptor().findFieldByName("local_tenant_key")) + .isNull(); + assertThat( + ReadAuthoredWorldSourceIntakeResponse.getDescriptor() + .findFieldByName("local_tenant_key")) + .isNull(); + assertThat(wireResponses).isNotEmpty(); + for (Message response : wireResponses) { + assertThat(response.getDescriptorForType().findFieldByName("local_tenant_key")).isNull(); + assertThat(response.getUnknownFields().asMap()).isEmpty(); + assertThat(response.getAllFields().keySet()) + .noneMatch(field -> field.getName().equals("local_tenant_key")); + } + } + + private DbCounts dbCounts(Scenario scenario) { + return new DbCounts( + count( + "SELECT COUNT(*) FROM world_authored_source_intake " + + "WHERE target_namespace = ? AND intake_request_id = ?", + NAMESPACE, + scenario.intakeRequestId()), + count( + "SELECT COUNT(*) FROM world_authored_source_tenant_association " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + scenario.canonicalTenantId()), + count( + "SELECT COUNT(*) FROM world_authored_source_tenant_key_reservation " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? " + + "AND claim_kind = 'CANONICAL_AUTHORED_SOURCE'", + NAMESPACE, + scenario.canonicalTenantId())); + } + + private Map> worldMutationRowSnapshot() { + Map> snapshot = new LinkedHashMap<>(); + for (String table : WORLD_MUTATION_SNAPSHOT_TABLES) { + snapshot.put( + table, + dsl.fetch("SELECT to_jsonb(world_row)::text FROM " + table + " AS world_row ORDER BY 1") + .getValues(0, String.class)); + } + return snapshot; + } + + private long count(String query, Object... bindings) { + return Objects.requireNonNull( + dsl.fetchOne(query, bindings), "World intake count query returned no row") + .get(0, Long.class); + } + + private static CommittedReceipt publicReceipt(WorldAuthoredSourceIntakeReceipt receipt) { + return new CommittedReceipt( + receipt.schemaVersion(), + receipt.targetNamespace(), + receipt.intakeRequestId(), + receipt.operationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + receipt.requestDigest(), + receipt.receiptDigest()); + } + + private static Scenario newScenario(String worldSlug) { + UUID tenantId = UUID.randomUUID(); + UUID intakeRequestId = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + UUID registrationRequestId = UUID.randomUUID(); + String tenantSlug = "tenant-" + tenantId.toString().replace("-", "").substring(0, 12); + String displayName = "World " + worldSlug; + long sourceGameRowId = + Math.abs(UUID.randomUUID().getMostSignificantBits() % 1_000_000_000L) + 1L; + String sourceGameTenantKey = "src-" + UUID.randomUUID().toString().replace("-", ""); + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequestId, tenantId, tenantSlug, worldSlug, displayName); + String sourceEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + sourceOperationId, + sourceRequestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence evidence = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + sourceOperationId, + sourceRequestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW", + sourceEvidenceDigest); + return new Scenario( + tenantId, intakeRequestId, sourceOperationId, UUID.randomUUID(), worldSlug, evidence); + } + + private static void assertStatus(Status.Code expected, ThrowingAction action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + private static ApplyWorldDesignMutationRequest canonicalLookingDraftMutation() { + return ApplyWorldDesignMutationRequest.newBuilder() + .setTenantId("42") + .setVersionId("2045") + .setCommitId("commit-1") + .setRevisionId("revision-1") + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId("44") + .setRegion(RegionDesignMutation.newBuilder().setName("North").build()) + .build(); + } + + private static void assertDraftMutationDenied(ApplyWorldDesignMutationResponse response) { + assertThat(response.hasError()).isTrue(); + assertThat(response.getError().getCode()).isEqualTo("FAILED_PRECONDITION"); + assertThat(response.getError().getMessage()) + .isEqualTo( + "Complete Draft caller/tenant authorization and owner publication proof are unavailable."); + assertThat(response.getResult()) + .isEqualTo(WorldDesignMutationResult.WORLD_DESIGN_MUTATION_RESULT_UNSPECIFIED); + assertThat(response.getTenantId()).isEmpty(); + assertThat(response.getVersionId()).isEmpty(); + assertThat(response.getAggregateId()).isEmpty(); + assertThat(response.getDraftRevisionEpoch()).isZero(); + assertThat(response.getDraftScopeRevisionEpoch()).isZero(); + assertThat(response.getAllFields().keySet()) + .containsExactly(ApplyWorldDesignMutationResponse.getDescriptor().findFieldByName("error")); + } + + private static String pem(String type, byte[] bytes) { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return "-----BEGIN " + type + "-----\n" + body + "\n-----END " + type + "-----\n"; + } + + private static TestCertificate issueLeaf( + X500Name caName, PrivateKey caPrivateKey, String commonName, String workloadUri) + throws Exception { + KeyPair keyPair = newRsaKeyPair(); + X500Name subject = new X500Name("CN=" + commonName + ", O=FireMUD Test"); + GeneralNames subjectAltNames = + new GeneralNames( + new GeneralName[] { + new GeneralName(GeneralName.uniformResourceIdentifier, workloadUri), + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + }); + X509Certificate certificate = + issueCertificate( + subject, keyPair.getPublic(), caName, caPrivateKey, false, subjectAltNames); + return new TestCertificate(keyPair.getPrivate(), certificate); + } + + private static X509Certificate issueCertificate( + X500Name subject, + java.security.PublicKey publicKey, + X500Name issuer, + PrivateKey issuerPrivateKey, + boolean ca, + GeneralNames subjectAltNames) + throws Exception { + Instant now = Instant.now().minusSeconds(60); + JcaX509v3CertificateBuilder builder = + new JcaX509v3CertificateBuilder( + issuer, + BigInteger.valueOf(CERTIFICATE_SERIAL.getAndIncrement()), + Date.from(now), + Date.from(now.plusSeconds(60L * 60L * 24L * 14L)), + subject, + publicKey); + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(ca)); + if (ca) { + builder.addExtension( + Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign)); + } else { + builder.addExtension( + Extension.keyUsage, + true, + new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); + builder.addExtension( + Extension.extendedKeyUsage, + false, + new ExtendedKeyUsage( + new KeyPurposeId[] {KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth})); + builder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); + } + return new JcaX509CertificateConverter() + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .getCertificate( + builder.build( + new JcaContentSignerBuilder("SHA256withRSA") + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .build(issuerPrivateKey))); + } + + private static KeyPair newRsaKeyPair() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return generator.generateKeyPair(); + } + + private record Scenario( + UUID canonicalTenantId, + UUID intakeRequestId, + UUID sourceOperationId, + UUID readRequestId, + String worldSlug, + AuthoredWorldSourceEvidence sourceEvidence) { + IntakeRequest intakeRequest() { + return new IntakeRequest( + 1, + NAMESPACE, + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + sourceEvidence.evidenceDigest()); + } + + ReadRequest readRequest() { + return new ReadRequest(intakeRequest(), readRequestId); + } + } + + private record DbCounts(long receipts, long associations, long reservations) {} + + private record TestCertificate(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestCertificate worldServer, + TestCertificate gameDesignClient, + TestCertificate accountClient) {} + + @FunctionalInterface + private interface ThrowingAction { + void run() throws Throwable; + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredVersionIdentityIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredVersionIdentityIntegrationTest.java new file mode 100644 index 0000000000..cb9576c36a --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredVersionIdentityIntegrationTest.java @@ -0,0 +1,959 @@ +package net.firedevops.firemud.worldmanagement; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.LinkedHashMap; +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.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.TestContainerImages; +import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; +import net.firedevops.firemud.worldmanagement.client.GameDesignClient; +import net.firedevops.firemud.worldmanagement.client.GameSessionClient; +import net.firedevops.firemud.worldmanagement.client.GrpcGameSessionInitialAdmissionBindProofClient; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository.RegistrationConflictException; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityService; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.exception.DataAccessException; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class WorldAuthoredVersionIdentityIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final UUID OTHER_CANONICAL_VERSION = + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + private static final List WORLD_CONTENT_AND_LIFECYCLE_TABLES = + List.of( + "generation_rule", + "instance", + "region", + "region_instance", + "room", + "room_exit", + "room_instance", + "room_instance_exit", + "world_design_aggregate_epoch", + "world_design_revision_ledger", + "world_design_scope_epoch", + "world_entity_spawn_binding", + "world_event", + "world_instance", + "zone", + "zone_instance"); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "world_management_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private DSLContext dsl; + @Autowired private WorldAuthoredSourceIntakeRepository sourceRepository; + @Autowired private PlatformTransactionManager transactionManager; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @MockitoBean(enforceOverride = true) + private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private EntityManagementClient entityManagementClient; + + @Test + void persistsExactIdentityAndPrivateKeyWithoutContentOrLifecycleWrites() { + long legacyTenantKey = + 6_900_000_000L + Math.floorMod(UUID.randomUUID().getLeastSignificantBits(), 100_000L); + String legacyRegionName = "unmapped-legacy-region-" + UUID.randomUUID(); + long legacyRegionId = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO region (tenant_id, name) VALUES (?, ?) RETURNING id", + legacyTenantKey, + legacyRegionName), + "legacy region insert returned no row") + .get(0, Long.class); + long legacyGameInstanceId = positiveLong(); + String legacyControlRequest = "retained-legacy-" + UUID.randomUUID(); + long legacyWorldInstanceId = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO world_instance (tenant_id, game_instance_id, game_template_id, " + + "control_plane_request_id, launch_descriptor_id, version_id, " + + "generation_config_revision, release_bundle_id, " + + "published_release_bundle_ref, version_state_epoch, status) " + + "VALUES (?, ?, 17, ?, 'retained-descriptor', 29, 'legacy-config', " + + "31, 'retained-release', 3, 'ACTIVE') RETURNING id", + legacyTenantKey, + legacyGameInstanceId, + legacyControlRequest), + "legacy world-instance insert returned no row") + .get(0, Long.class); + + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + WorldAuthoredSourceIntakeReceipt sourceReceipt = acceptSource(source); + Map rowsBeforeIdentity = worldContentAndLifecycleCounts(); + assertThat(sourceReceipt.localTenantKey()).isNotEqualTo(legacyTenantKey); + + UUID canonicalVersionId = UUID.randomUUID(); + long gameDesignVersionId = 103L; + AuthoredWorldVersionStateClient client = mock(AuthoredWorldVersionStateClient.class); + when(client.read(any())) + .thenAnswer( + invocation -> { + AuthoredWorldVersionStateEvidence.Request request = invocation.getArgument(0); + return versionEvidence( + request, + source, + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 5L); + }); + WorldAuthoredVersionIdentityRepository repository = + new WorldAuthoredVersionIdentityRepository(dsl); + WorldAuthoredVersionIdentityService service = service(client, repository, transactionManager); + UUID readRequestId = UUID.randomUUID(); + + WorldAuthoredVersionIdentityReceipt receipt = + withGameDesign( + () -> + service.associate( + NAMESPACE, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + canonicalVersionId, + gameDesignVersionId, + readRequestId)); + WorldAuthoredVersionIdentityReceipt independentReadback = + repository + .readByCanonicalVersion( + NAMESPACE, source.canonicalTenantId(), source.worldSlug(), canonicalVersionId) + .orElseThrow(); + + assertThat(receipt).isEqualTo(independentReadback); + assertThat(receipt.sourceIntakeReceipt()).isEqualTo(sourceReceipt); + assertThat(receipt.canonicalVersionId()).isEqualTo(canonicalVersionId); + assertThat(receipt.gameDesignVersionId()).isEqualTo(gameDesignVersionId); + assertThat(receipt.localVersionKey()).isPositive(); + assertThat(receipt.versionStateEvidence().request().readRequestId()).isEqualTo(readRequestId); + assertThat( + repository.readByGameDesignVersion( + NAMESPACE, source.canonicalTenantId(), source.worldSlug(), gameDesignVersionId)) + .contains(receipt); + assertThat(identityCount(source)).isEqualTo(1L); + assertThat(worldContentAndLifecycleCounts()).isEqualTo(rowsBeforeIdentity); + + var storedRow = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM world_authored_version_identity WHERE operation_id = ?", + receipt.operationId()), + "World authored-Version identity row was not persisted"); + assertThat(storedRow.get("operation_id", UUID.class)).isEqualTo(receipt.operationId()); + assertThat(storedRow.get("target_namespace", String.class)).isEqualTo(NAMESPACE); + assertThat(storedRow.get("canonical_tenant_id", UUID.class)) + .isEqualTo(source.canonicalTenantId()); + assertThat(storedRow.get("world_slug", String.class)).isEqualTo(source.worldSlug()); + assertThat(storedRow.get("canonical_version_id", UUID.class)).isEqualTo(canonicalVersionId); + assertThat(storedRow.get("game_design_version_id", Long.class)).isEqualTo(gameDesignVersionId); + assertThat(storedRow.get("local_version_key", Long.class)).isEqualTo(receipt.localVersionKey()); + assertThat(storedRow.get("intake_operation_id", UUID.class)) + .isEqualTo(sourceReceipt.operationId()); + assertThat(storedRow.get("intake_request_id", UUID.class)) + .isEqualTo(sourceReceipt.intakeRequestId()); + assertThat(storedRow.get("local_tenant_key", Long.class)) + .isEqualTo(sourceReceipt.localTenantKey()); + assertThat(storedRow.get("intake_request_digest", String.class)) + .isEqualTo(sourceReceipt.requestDigest()); + assertThat(storedRow.get("source_operation_id", UUID.class)).isEqualTo(source.operationId()); + assertThat(storedRow.get("source_evidence_digest", String.class)) + .isEqualTo(source.evidenceDigest()); + assertThat(storedRow.get("intake_receipt_digest", String.class)) + .isEqualTo(sourceReceipt.receiptDigest()); + assertThat(storedRow.get("version_state_read_request_id", UUID.class)).isEqualTo(readRequestId); + assertThat(storedRow.get("version_state_evidence_digest", String.class)) + .isEqualTo(receipt.versionStateEvidence().evidenceDigest()); + assertThat(storedRow.get("version_state_evidence_json", String.class)) + .contains(source.operationId().toString(), canonicalVersionId.toString()); + var localKeyColumn = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT is_identity, identity_generation FROM information_schema.columns " + + "WHERE table_schema = current_schema() " + + "AND table_name = 'world_authored_version_identity' " + + "AND column_name = 'local_version_key'"), + "World local version key identity metadata was not found"); + assertThat(localKeyColumn.get("is_identity", String.class)).isEqualTo("YES"); + assertThat(localKeyColumn.get("identity_generation", String.class)).isEqualTo("ALWAYS"); + + var retainedRegion = + Objects.requireNonNull( + dsl.fetchOne("SELECT tenant_id, name FROM region WHERE id = ?", legacyRegionId), + "unmapped legacy region disappeared"); + assertThat(retainedRegion.get("tenant_id", Long.class)).isEqualTo(legacyTenantKey); + assertThat(retainedRegion.get("name", String.class)).isEqualTo(legacyRegionName); + var retainedWorld = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT tenant_id, game_instance_id, control_plane_request_id, version_id, status " + + "FROM world_instance WHERE id = ?", + legacyWorldInstanceId), + "unmapped legacy world-instance row disappeared"); + assertThat(retainedWorld.get("tenant_id", Long.class)).isEqualTo(legacyTenantKey); + assertThat(retainedWorld.get("game_instance_id", Long.class)).isEqualTo(legacyGameInstanceId); + assertThat(retainedWorld.get("control_plane_request_id", String.class)) + .isEqualTo(legacyControlRequest); + assertThat(retainedWorld.get("version_id", Long.class)).isEqualTo(29L); + assertThat(retainedWorld.get("status", String.class)).isEqualTo("ACTIVE"); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_authored_version_identity SET world_slug = ? " + + "WHERE operation_id = ?", + "rewritten-world", + receipt.operationId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM world_authored_version_identity WHERE operation_id = ?", + receipt.operationId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy(() -> dsl.execute("TRUNCATE world_authored_version_identity")) + .isInstanceOf(DataAccessException.class); + assertThat(identityCount(source)).isEqualTo(1L); + verify(client, times(1)).read(any()); + } + + @Test + void deniesWrongGameDesignIdentitySourceNamespaceAndMissingIntakeBeforeOwnerWrites() { + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + acceptSource(source); + UUID canonicalVersionId = UUID.randomUUID(); + long gameDesignVersionId = 211L; + + AuthoredWorldVersionStateClient wrongUuidClient = mock(AuthoredWorldVersionStateClient.class); + when(wrongUuidClient.read(any())) + .thenAnswer( + invocation -> + versionEvidence( + invocation.getArgument(0), + source, + OTHER_CANONICAL_VERSION, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 8L)); + WorldAuthoredVersionIdentityRepository repository = + new WorldAuthoredVersionIdentityRepository(dsl); + WorldAuthoredVersionIdentityService wrongUuidService = + service(wrongUuidClient, repository, transactionManager); + assertThatThrownBy( + () -> + withGameDesign( + () -> + associate( + wrongUuidService, + source, + canonicalVersionId, + gameDesignVersionId, + UUID.randomUUID()))) + .isInstanceOf(InvalidIdentityEvidenceException.class); + assertThat(identityCount(source)).isZero(); + + AuthoredWorldVersionStateClient wrongPeerClient = mock(AuthoredWorldVersionStateClient.class); + WorldAuthoredVersionIdentityService wrongPeerService = + service(wrongPeerClient, repository, transactionManager); + assertThatThrownBy( + () -> + withPeer( + NAMESPACE, + "game-session-service", + () -> + associate( + wrongPeerService, + source, + canonicalVersionId, + gameDesignVersionId, + UUID.randomUUID()))) + .isInstanceOf(SecurityException.class); + verify(wrongPeerClient, never()).read(any()); + assertThat(identityCount(source)).isZero(); + + AuthoredWorldSourceEvidence substitutedSource = source(UUID.randomUUID(), randomWorld()); + AuthoredWorldVersionStateClient wrongSourceClient = mock(AuthoredWorldVersionStateClient.class); + UUID substitutedReadId = UUID.randomUUID(); + when(wrongSourceClient.read(any())) + .thenAnswer( + invocation -> + versionEvidence( + request(substitutedSource, substitutedReadId, gameDesignVersionId), + substitutedSource, + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 9L)); + WorldAuthoredVersionIdentityService wrongSourceService = + service(wrongSourceClient, repository, transactionManager); + assertThatThrownBy( + () -> + withGameDesign( + () -> + associate( + wrongSourceService, + source, + canonicalVersionId, + gameDesignVersionId, + substitutedReadId))) + .isInstanceOf(InvalidIdentityEvidenceException.class); + assertThat(identityCount(source)).isZero(); + assertThat(identityCount(substitutedSource)).isZero(); + + AuthoredWorldVersionStateClient wrongNamespaceClient = + mock(AuthoredWorldVersionStateClient.class); + WorldAuthoredVersionIdentityService wrongNamespaceService = + service(wrongNamespaceClient, repository, transactionManager); + assertThatThrownBy( + () -> + withGameDesign( + () -> + wrongNamespaceService.associate( + "other-namespace", + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + canonicalVersionId, + gameDesignVersionId, + UUID.randomUUID()))) + .isInstanceOf(SecurityException.class); + verify(wrongNamespaceClient, never()).read(any()); + assertThat(identityCount(source)).isZero(); + + AuthoredWorldSourceEvidence missingSource = source(UUID.randomUUID(), randomWorld()); + AuthoredWorldVersionStateClient missingSourceClient = + mock(AuthoredWorldVersionStateClient.class); + when(missingSourceClient.read(any())) + .thenAnswer( + invocation -> + versionEvidence( + invocation.getArgument(0), + missingSource, + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 10L)); + WorldAuthoredVersionIdentityService missingSourceService = + service(missingSourceClient, repository, transactionManager); + assertThatThrownBy( + () -> + withGameDesign( + () -> + associate( + missingSourceService, + missingSource, + canonicalVersionId, + gameDesignVersionId, + UUID.randomUUID()))) + .isInstanceOf(InvalidIdentityEvidenceException.class); + assertThat(identityCount(missingSource)).isZero(); + assertThat( + sourceRepository.readBySource( + NAMESPACE, + missingSource.canonicalTenantId(), + missingSource.worldSlug(), + missingSource.operationId(), + missingSource.evidenceDigest())) + .isEmpty(); + } + + @Test + void concurrentExactStableIdentityReturnsOneOriginalHistoricalReceipt() throws Exception { + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + WorldAuthoredSourceIntakeReceipt sourceReceipt = acceptSource(source); + UUID canonicalVersionId = UUID.randomUUID(); + long gameDesignVersionId = 307L; + UUID firstReadId = UUID.randomUUID(); + UUID secondReadId = UUID.randomUUID(); + CountDownLatch bothRead = new CountDownLatch(2); + AtomicReference firstEvidence = new AtomicReference<>(); + AtomicReference secondEvidence = new AtomicReference<>(); + AuthoredWorldVersionStateClient firstClient = mock(AuthoredWorldVersionStateClient.class); + AuthoredWorldVersionStateClient secondClient = mock(AuthoredWorldVersionStateClient.class); + when(firstClient.read(any())) + .thenAnswer( + invocation -> { + AuthoredWorldVersionStateEvidence.Request request = invocation.getArgument(0); + awaitReadBarrier(bothRead); + AuthoredWorldVersionStateEvidence evidence = + versionEvidence( + request, + source, + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 12L); + firstEvidence.set(evidence); + return evidence; + }); + when(secondClient.read(any())) + .thenAnswer( + invocation -> { + AuthoredWorldVersionStateEvidence.Request request = invocation.getArgument(0); + awaitReadBarrier(bothRead); + AuthoredWorldVersionStateEvidence evidence = + versionEvidence( + request, + source, + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE, + 13L); + secondEvidence.set(evidence); + return evidence; + }); + WorldAuthoredVersionIdentityRepository repository = + new WorldAuthoredVersionIdentityRepository(dsl); + WorldAuthoredVersionIdentityService firstService = + service(firstClient, repository, transactionManager); + WorldAuthoredVersionIdentityService secondService = + service(secondClient, repository, transactionManager); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = + executor.submit( + () -> + withGameDesign( + () -> + associate( + firstService, + source, + canonicalVersionId, + gameDesignVersionId, + firstReadId))); + Future second = + executor.submit( + () -> + withGameDesign( + () -> + associate( + secondService, + source, + canonicalVersionId, + gameDesignVersionId, + secondReadId))); + WorldAuthoredVersionIdentityReceipt firstReceipt = first.get(25, TimeUnit.SECONDS); + WorldAuthoredVersionIdentityReceipt secondReceipt = second.get(25, TimeUnit.SECONDS); + + assertThat(firstReceipt).isEqualTo(secondReceipt); + assertThat(firstReceipt.operationId()).isEqualTo(secondReceipt.operationId()); + assertThat(firstReceipt.localVersionKey()).isEqualTo(secondReceipt.localVersionKey()); + assertThat(firstReceipt.sourceIntakeReceipt()).isEqualTo(sourceReceipt); + assertThat(firstReceipt.versionStateEvidence()) + .isIn(firstEvidence.get(), secondEvidence.get()); + assertThat(firstEvidence.get().evidenceDigest()) + .isNotEqualTo(secondEvidence.get().evidenceDigest()); + assertThat(firstEvidence.get().request().readRequestId()) + .isNotEqualTo(secondEvidence.get().request().readRequestId()); + assertThat( + repository.readByCanonicalVersion( + NAMESPACE, source.canonicalTenantId(), source.worldSlug(), canonicalVersionId)) + .contains(firstReceipt); + assertThat(identityCount(source)).isEqualTo(1L); + } + verify(firstClient, times(1)).read(any()); + verify(secondClient, times(1)).read(any()); + } + + @Test + void conflictingUuidOrGameDesignSelectorDoesNotRewriteTheOriginalReceipt() { + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + acceptSource(source); + UUID canonicalVersionId = UUID.randomUUID(); + long gameDesignVersionId = 401L; + AuthoredWorldVersionStateClient client = mock(AuthoredWorldVersionStateClient.class); + when(client.read(any())) + .thenAnswer( + invocation -> { + AuthoredWorldVersionStateEvidence.Request request = invocation.getArgument(0); + UUID returnedCanonicalId = + request.versionId() == gameDesignVersionId + ? canonicalVersionId + : OTHER_CANONICAL_VERSION; + return versionEvidence( + request, + source, + returnedCanonicalId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 16L); + }); + WorldAuthoredVersionIdentityRepository repository = + new WorldAuthoredVersionIdentityRepository(dsl); + WorldAuthoredVersionIdentityService service = service(client, repository, transactionManager); + WorldAuthoredVersionIdentityReceipt original = + withGameDesign( + () -> + associate( + service, source, canonicalVersionId, gameDesignVersionId, UUID.randomUUID())); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + associate( + service, + source, + canonicalVersionId, + gameDesignVersionId + 1, + UUID.randomUUID()))) + .isInstanceOf(RegistrationConflictException.class); + assertThatThrownBy( + () -> + withGameDesign( + () -> + associate( + service, + source, + OTHER_CANONICAL_VERSION, + gameDesignVersionId, + UUID.randomUUID()))) + .isInstanceOf(RegistrationConflictException.class); + + assertThat( + repository.readByCanonicalVersion( + NAMESPACE, source.canonicalTenantId(), source.worldSlug(), canonicalVersionId)) + .contains(original); + assertThat(identityCount(source)).isEqualTo(1L); + verify(client, times(1)).read(any()); + } + + @Test + void recoversLostCommitAcknowledgmentAndRetriesWithoutRereadingOrReminting() { + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + acceptSource(source); + UUID canonicalVersionId = UUID.randomUUID(); + long gameDesignVersionId = 503L; + AuthoredWorldVersionStateClient client = mock(AuthoredWorldVersionStateClient.class); + when(client.read(any())) + .thenAnswer( + invocation -> + versionEvidence( + invocation.getArgument(0), + source, + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 21L)); + WorldAuthoredVersionIdentityRepository repository = + new WorldAuthoredVersionIdentityRepository(dsl); + WorldAuthoredVersionIdentityService service = + service( + client, repository, new LostCommitAcknowledgmentTransactionManager(transactionManager)); + UUID originalReadId = UUID.randomUUID(); + + WorldAuthoredVersionIdentityReceipt recovered = + withGameDesign( + () -> + associate( + service, source, canonicalVersionId, gameDesignVersionId, originalReadId)); + WorldAuthoredVersionIdentityReceipt retry = + withGameDesign( + () -> + associate( + service, source, canonicalVersionId, gameDesignVersionId, UUID.randomUUID())); + + assertThat(recovered).isEqualTo(retry); + assertThat(retry.versionStateEvidence().request().readRequestId()).isEqualTo(originalReadId); + assertThat(identityCount(source)).isEqualTo(1L); + assertThat( + repository.readByCanonicalVersion( + NAMESPACE, source.canonicalTenantId(), source.worldSlug(), canonicalVersionId)) + .contains(recovered); + verify(client, times(1)).read(any()); + } + + @Test + void forwardV27MigrationPreservesRetainedRowsWithoutInferringIdentityAssociations() + throws SQLException { + String schema = "world_version_identity_" + UUID.randomUUID().toString().replace("-", ""); + long legacyTenantKey = + 8_300_000_000L + Math.floorMod(UUID.randomUUID().getLeastSignificantBits(), 100_000L); + String firstRegionName = "retained-v26-region-a-" + UUID.randomUUID(); + String secondRegionName = "retained-v26-region-b-" + UUID.randomUUID(); + long legacyGameInstanceId = positiveLong(); + try { + migrateFixture(schema, MigrationVersion.fromVersion("26")); + try (Connection connection = fixtureConnection(schema)) { + try (PreparedStatement region = + connection.prepareStatement("INSERT INTO region (tenant_id, name) VALUES (?, ?)")) { + region.setLong(1, legacyTenantKey); + region.setString(2, firstRegionName); + region.executeUpdate(); + region.setLong(1, legacyTenantKey + 1); + region.setString(2, secondRegionName); + region.executeUpdate(); + } + try (PreparedStatement world = + connection.prepareStatement( + "INSERT INTO world_instance (tenant_id, game_instance_id, game_template_id, " + + "control_plane_request_id, launch_descriptor_id, version_id, " + + "generation_config_revision, release_bundle_id, " + + "published_release_bundle_ref, version_state_epoch, status) " + + "VALUES (?, ?, 23, 'retained-v26-request', 'retained-v26-descriptor', " + + "37, 'retained-v26-config', 41, 'retained-v26-release', 4, 'ACTIVE')")) { + world.setLong(1, legacyTenantKey); + world.setLong(2, legacyGameInstanceId); + world.executeUpdate(); + } + } + + migrateFixture(schema, null); + + try (Connection connection = fixtureConnection(schema); + Statement statement = connection.createStatement()) { + try (PreparedStatement regions = + connection.prepareStatement( + "SELECT tenant_id, name FROM region WHERE tenant_id IN (?, ?) " + + "ORDER BY tenant_id")) { + regions.setLong(1, legacyTenantKey); + regions.setLong(2, legacyTenantKey + 1); + try (ResultSet result = regions.executeQuery()) { + assertThat(result.next()).isTrue(); + assertThat(result.getLong("tenant_id")).isEqualTo(legacyTenantKey); + assertThat(result.getString("name")).isEqualTo(firstRegionName); + assertThat(result.next()).isTrue(); + assertThat(result.getLong("tenant_id")).isEqualTo(legacyTenantKey + 1); + assertThat(result.getString("name")).isEqualTo(secondRegionName); + assertThat(result.next()).isFalse(); + } + } + try (PreparedStatement worlds = + connection.prepareStatement( + "SELECT tenant_id, game_instance_id, version_id, status FROM world_instance " + + "WHERE tenant_id = ?")) { + worlds.setLong(1, legacyTenantKey); + try (ResultSet result = worlds.executeQuery()) { + assertThat(result.next()).isTrue(); + assertThat(result.getLong("tenant_id")).isEqualTo(legacyTenantKey); + assertThat(result.getLong("game_instance_id")).isEqualTo(legacyGameInstanceId); + assertThat(result.getLong("version_id")).isEqualTo(37L); + assertThat(result.getString("status")).isEqualTo("ACTIVE"); + assertThat(result.next()).isFalse(); + } + } + assertCount(statement, "world_authored_version_identity", 0L); + assertCount(statement, "world_authored_source_tenant_association", 0L); + try (PreparedStatement reservations = + connection.prepareStatement( + "SELECT tenant_key, claim_kind, target_namespace, canonical_tenant_id " + + "FROM world_authored_source_tenant_key_reservation " + + "WHERE tenant_key IN (?, ?) ORDER BY tenant_key")) { + reservations.setLong(1, legacyTenantKey); + reservations.setLong(2, legacyTenantKey + 1); + try (ResultSet result = reservations.executeQuery()) { + assertThat(result.next()).isTrue(); + assertThat(result.getLong("tenant_key")).isEqualTo(legacyTenantKey); + assertThat(result.getString("claim_kind")).isEqualTo("LEGACY_NUMERIC"); + assertThat(result.getString("target_namespace")).isNull(); + assertThat(result.getObject("canonical_tenant_id")).isNull(); + assertThat(result.next()).isTrue(); + assertThat(result.getLong("tenant_key")).isEqualTo(legacyTenantKey + 1); + assertThat(result.getString("claim_kind")).isEqualTo("LEGACY_NUMERIC"); + assertThat(result.getString("target_namespace")).isNull(); + assertThat(result.getObject("canonical_tenant_id")).isNull(); + assertThat(result.next()).isFalse(); + } + } + } + } finally { + dropFixtureSchema(schema); + } + } + + private WorldAuthoredSourceIntakeReceipt acceptSource(AuthoredWorldSourceEvidence source) { + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + return Objects.requireNonNull( + transaction.execute( + status -> sourceRepository.acceptFresh(NAMESPACE, UUID.randomUUID(), source)), + "World source intake returned no receipt"); + } + + private WorldAuthoredVersionIdentityService service( + AuthoredWorldVersionStateClient client, + WorldAuthoredVersionIdentityRepository repository, + PlatformTransactionManager manager) { + return new WorldAuthoredVersionIdentityService( + client, repository, sourceRepository, manager, NAMESPACE); + } + + private static WorldAuthoredVersionIdentityReceipt associate( + WorldAuthoredVersionIdentityService service, + AuthoredWorldSourceEvidence source, + UUID canonicalVersionId, + long gameDesignVersionId, + UUID readRequestId) { + return service.associate( + NAMESPACE, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + canonicalVersionId, + gameDesignVersionId, + readRequestId); + } + + private Map worldContentAndLifecycleCounts() { + Map counts = new LinkedHashMap<>(); + for (String table : WORLD_CONTENT_AND_LIFECYCLE_TABLES) { + counts.put( + table, + Objects.requireNonNull( + dsl.fetchOne("SELECT COUNT(*) FROM " + table), + "World content count query returned no row") + .get(0, Long.class)); + } + return Map.copyOf(counts); + } + + private long identityCount(AuthoredWorldSourceEvidence source) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM world_authored_version_identity WHERE target_namespace = ? " + + "AND canonical_tenant_id = ? AND world_slug = ?", + NAMESPACE, + source.canonicalTenantId(), + source.worldSlug()), + "World authored-Version identity count query returned no row") + .get(0, Long.class); + } + + private static AuthoredWorldSourceEvidence source(UUID tenant, String worldSlug) { + UUID registrationRequest = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + String tenantSlug = "tenant-" + tenant.toString().replace("-", ""); + String displayName = "Source " + tenant.toString().substring(0, 8); + long sourceGameRowId = Math.max(1L, tenant.getLeastSignificantBits() & Long.MAX_VALUE); + String sourceGameTenantKey = "source-" + tenant.toString().replace("-", "").substring(0, 24); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequest, tenant, tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequest, + sourceOperationId, + requestDigest, + tenant, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequest, + sourceOperationId, + requestDigest, + tenant, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static AuthoredWorldVersionStateEvidence.Request request( + AuthoredWorldSourceEvidence source, UUID readRequestId, long gameDesignVersionId) { + return new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + readRequestId, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + gameDesignVersionId); + } + + private static AuthoredWorldVersionStateEvidence versionEvidence( + AuthoredWorldVersionStateEvidence.Request request, + AuthoredWorldSourceEvidence source, + UUID canonicalVersionId, + VersionLifecycleState state, + long epoch) { + return AuthoredWorldVersionStateEvidence.create( + request, source, canonicalVersionId, state, epoch); + } + + private static String randomWorld() { + return "world-" + UUID.randomUUID().toString().replace("-", "").substring(0, 18); + } + + private static long positiveLong() { + return Math.max(1L, UUID.randomUUID().getLeastSignificantBits() & Long.MAX_VALUE); + } + + private static T withGameDesign(java.util.function.Supplier action) { + return withPeer(NAMESPACE, "game-design-service", action); + } + + private static T withPeer( + String namespace, String service, java.util.function.Supplier action) { + GrpcPeerIdentity peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + + private static void awaitReadBarrier(CountDownLatch latch) { + latch.countDown(); + try { + if (!latch.await(15, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent Version identity read barrier timed out"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Concurrent Version identity read was interrupted", exception); + } + } + + private static void migrateFixture(String schema, MigrationVersion target) { + var configuration = + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private static Connection fixtureConnection(String schema) throws SQLException { + Connection connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + connection.setSchema(schema); + return connection; + } + + private static void dropFixtureSchema(String schema) throws SQLException { + try (Connection connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + Statement statement = connection.createStatement()) { + statement.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } + } + + private static void assertCount(Statement statement, String table, long expected) + throws SQLException { + try (ResultSet result = statement.executeQuery("SELECT COUNT(*) FROM " + table)) { + assertThat(result.next()).isTrue(); + assertThat(result.getLong(1)).isEqualTo(expected); + } + } + + private static final class LostCommitAcknowledgmentTransactionManager + implements PlatformTransactionManager { + private final PlatformTransactionManager delegate; + private boolean firstCommit = true; + + private LostCommitAcknowledgmentTransactionManager(PlatformTransactionManager delegate) { + this.delegate = delegate; + } + + @Override + public TransactionStatus getTransaction( + org.springframework.transaction.TransactionDefinition definition) { + return delegate.getTransaction(definition); + } + + @Override + public void commit(TransactionStatus status) { + delegate.commit(status); + if (firstCommit) { + firstCommit = false; + throw new IllegalStateException("simulated lost World identity commit acknowledgment"); + } + } + + @Override + public void rollback(TransactionStatus status) { + if (!status.isCompleted()) { + delegate.rollback(status); + } + } + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldCompleteLaunchBindingIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldCompleteLaunchBindingIntegrationTest.java new file mode 100644 index 0000000000..055babdd4e --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldCompleteLaunchBindingIntegrationTest.java @@ -0,0 +1,1150 @@ +package net.firedevops.firemud.worldmanagement; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +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.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import javax.sql.DataSource; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.TestContainerImages; +import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; +import net.firedevops.firemud.worldmanagement.client.GameDesignClient; +import net.firedevops.firemud.worldmanagement.client.GameSessionClient; +import net.firedevops.firemud.worldmanagement.client.GrpcGameSessionInitialAdmissionBindProofClient; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCompleteLaunchBindingReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldCompleteLaunchBindingRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCompleteLaunchBindingRepository.RegistrationConflictException; +import net.firedevops.firemud.worldmanagement.tenant.WorldCompleteLaunchBindingService; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.exception.DataAccessException; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class WorldCompleteLaunchBindingIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final UUID VERSION = UUID.fromString("88888888-8888-4888-8888-888888888888"); + private static final UUID OTHER_CANONICAL_VERSION = + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "world_management_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private DSLContext dsl; + @Autowired private DataSource dataSource; + @Autowired private WorldAuthoredSourceIntakeRepository sourceRepository; + @Autowired private PlatformTransactionManager transactionManager; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @MockitoBean(enforceOverride = true) + private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private EntityManagementClient entityManagementClient; + + @Test + void persistsCompletePairReadsItBackAndLeavesUnmappedRetainedRowsUntouched() { + long retainedLegacyKey = + 7_900_000_000L + Math.abs(UUID.randomUUID().getLeastSignificantBits() % 100_000L); + String retainedName = "unmapped-retained-" + UUID.randomUUID(); + Long retainedRegionId = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO region (tenant_id, name) VALUES (?, ?) RETURNING id", + retainedLegacyKey, + retainedName), + "retained region insert returned no row") + .get(0, Long.class); + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + WorldAuthoredSourceIntakeReceipt sourceReceipt = acceptSource(source); + CompleteLaunchBindingEvidence evidence = evidence(source, controlRequest(), 41L); + GetRequest request = request(evidence); + AuthoredWorldLaunchDescriptorClient client = mock(AuthoredWorldLaunchDescriptorClient.class); + when(client.getComplete(any())).thenReturn(evidence); + WorldCompleteLaunchBindingService service = service(client, transactionManager); + + WorldCompleteLaunchBindingReceipt first = withGameSession(() -> service.bind(request)); + WorldCompleteLaunchBindingReceipt retry = + withGameSession(() -> service.bind(request(evidence))); + + assertThat(first).isEqualTo(retry); + assertThat(first.sourceIntakeReceipt()).isEqualTo(sourceReceipt); + assertThat(first.evidence()).isEqualTo(evidence); + assertThat(first.operationId()).isNotEqualTo(sourceReceipt.operationId()); + verify(client).getComplete(any()); + Record bindingRow = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT binding_operation_id, intake_operation_id, intake_request_id, " + + "local_tenant_key, source_operation_id, source_evidence_digest, " + + "intake_receipt_digest, descriptor_request_digest, descriptor_result_digest, " + + "release_attestation_digest, descriptor_json, release_attestation_json " + + "FROM world_complete_launch_binding WHERE target_namespace = ? " + + "AND canonical_tenant_id = ? AND control_plane_request_id = ?", + NAMESPACE, + source.canonicalTenantId(), + evidence.descriptor().controlPlaneRequestId()), + "complete launch binding row was not persisted"); + assertThat(bindingRow.get("binding_operation_id", UUID.class)).isEqualTo(first.operationId()); + assertThat(bindingRow.get("intake_operation_id", UUID.class)) + .isEqualTo(sourceReceipt.operationId()); + assertThat(bindingRow.get("intake_request_id", UUID.class)) + .isEqualTo(sourceReceipt.intakeRequestId()); + assertThat(bindingRow.get("local_tenant_key", Long.class)) + .isEqualTo(sourceReceipt.localTenantKey()); + assertThat(bindingRow.get("source_operation_id", UUID.class)).isEqualTo(source.operationId()); + assertThat(bindingRow.get("source_evidence_digest", String.class)) + .isEqualTo(source.evidenceDigest()); + assertThat(bindingRow.get("intake_receipt_digest", String.class)) + .isEqualTo(sourceReceipt.receiptDigest()); + assertThat(bindingRow.get("descriptor_request_digest", String.class)) + .isEqualTo(evidence.descriptor().requestDigest()); + assertThat(bindingRow.get("descriptor_result_digest", String.class)) + .isEqualTo(evidence.descriptor().resultDigest()); + assertThat(bindingRow.get("release_attestation_digest", String.class)) + .isEqualTo(evidence.releaseAttestation().evidenceDigest()); + assertThat(bindingRow.get("descriptor_json", String.class)) + .contains(evidence.descriptor().resultDigest()); + assertThat(bindingRow.get("release_attestation_json", String.class)) + .contains(evidence.releaseAttestation().evidenceDigest()); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT tenant_id, name FROM region WHERE id = ?", retainedRegionId), + "retained region readback returned no row") + .get("tenant_id", Long.class)) + .isEqualTo(retainedLegacyKey); + assertThat( + Objects.requireNonNull( + dsl.fetchOne("SELECT name FROM region WHERE id = ?", retainedRegionId), + "retained region name readback returned no row") + .get("name", String.class)) + .isEqualTo(retainedName); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_complete_launch_binding SET world_slug = ? " + + "WHERE binding_operation_id = ?", + "changed-world", + first.operationId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM world_complete_launch_binding WHERE binding_operation_id = ?", + first.operationId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy(() -> dsl.execute("TRUNCATE world_complete_launch_binding")) + .isInstanceOf(DataAccessException.class); + assertThat(countBindings(source.canonicalTenantId())).isEqualTo(1L); + } + + @Test + void forwardV26MigrationPreservesUnmappedRetainedWorldRows() throws SQLException { + String schema = + "world_complete_launch_binding_" + UUID.randomUUID().toString().replace("-", ""); + long retainedLegacyKey = + 8_700_000_000L + Math.floorMod(UUID.randomUUID().getLeastSignificantBits(), 1_000_000L); + String retainedName = "retained-before-v26-" + UUID.randomUUID(); + try { + migrateFixture(schema, MigrationVersion.fromVersion("25")); + try (Connection connection = fixtureConnection(schema); + PreparedStatement statement = + connection.prepareStatement("INSERT INTO region (tenant_id, name) VALUES (?, ?)")) { + statement.setLong(1, retainedLegacyKey); + statement.setString(2, retainedName); + statement.executeUpdate(); + } + migrateFixture(schema, null); + + try (Connection connection = fixtureConnection(schema); + Statement statement = connection.createStatement()) { + try (PreparedStatement retainedQuery = + connection.prepareStatement("SELECT tenant_id, name FROM region WHERE tenant_id = ?")) { + retainedQuery.setLong(1, retainedLegacyKey); + try (ResultSet retained = retainedQuery.executeQuery()) { + assertThat(retained.next()).isTrue(); + assertThat(retained.getLong("tenant_id")).isEqualTo(retainedLegacyKey); + assertThat(retained.getString("name")).isEqualTo(retainedName); + assertThat(retained.next()).isFalse(); + } + } + try (ResultSet bindingTable = + statement.executeQuery("SELECT COUNT(*) FROM world_complete_launch_binding")) { + assertThat(bindingTable.next()).isTrue(); + assertThat(bindingTable.getLong(1)).isZero(); + } + } + } finally { + dropFixtureSchema(schema); + } + } + + @Test + void deniesMissingOrSubstitutedSourceBeforeAnyWorldOwnerWrite() { + AuthoredWorldSourceEvidence retainedSource = source(UUID.randomUUID(), randomWorld()); + acceptSource(retainedSource); + AuthoredWorldSourceEvidence substitutedSource = source(UUID.randomUUID(), randomWorld()); + CompleteLaunchBindingEvidence substituted = evidence(substitutedSource, controlRequest(), 43L); + AuthoredWorldLaunchDescriptorClient client = mock(AuthoredWorldLaunchDescriptorClient.class); + when(client.getComplete(any())).thenReturn(substituted); + WorldCompleteLaunchBindingService service = service(client, transactionManager); + + assertThatThrownBy(() -> withGameSession(() -> service.bind(request(substituted)))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class); + assertThat(countBindings(substitutedSource.canonicalTenantId())).isZero(); + verify(client).getComplete(any()); + } + + @Test + void simultaneousExactRetriesReturnTheSameDurableReceiptAndOwnerOperation() throws Exception { + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + acceptSource(source); + CompleteLaunchBindingEvidence evidence = evidence(source, controlRequest(), 50L); + CountDownLatch bothFetched = new CountDownLatch(2); + AuthoredWorldLaunchDescriptorClient firstClient = + mock(AuthoredWorldLaunchDescriptorClient.class); + AuthoredWorldLaunchDescriptorClient secondClient = + mock(AuthoredWorldLaunchDescriptorClient.class); + when(firstClient.getComplete(any())) + .thenAnswer( + invocation -> { + awaitFetchBarrier(bothFetched); + return evidence; + }); + when(secondClient.getComplete(any())) + .thenAnswer( + invocation -> { + awaitFetchBarrier(bothFetched); + return evidence; + }); + WorldCompleteLaunchBindingService firstService = service(firstClient, transactionManager); + WorldCompleteLaunchBindingService secondService = service(secondClient, transactionManager); + GetRequest firstRequest = request(evidence); + GetRequest secondRequest = request(evidence); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = + executor.submit(() -> withGameSession(() -> firstService.bind(firstRequest))); + Future second = + executor.submit(() -> withGameSession(() -> secondService.bind(secondRequest))); + WorldCompleteLaunchBindingReceipt firstReceipt = first.get(20, TimeUnit.SECONDS); + WorldCompleteLaunchBindingReceipt secondReceipt = second.get(20, TimeUnit.SECONDS); + + assertThat(firstReceipt).isEqualTo(secondReceipt); + assertThat(firstReceipt.operationId()).isEqualTo(secondReceipt.operationId()); + assertThat(firstReceipt.evidence()).isEqualTo(evidence); + assertThat(countBindings(source.canonicalTenantId())).isEqualTo(1L); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT binding_operation_id FROM world_complete_launch_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? " + + "AND control_plane_request_id = ?", + NAMESPACE, + source.canonicalTenantId(), + evidence.descriptor().controlPlaneRequestId()), + "complete launch binding operation readback returned no row") + .get("binding_operation_id", UUID.class)) + .isEqualTo(firstReceipt.operationId()); + } + verify(firstClient).getComplete(any()); + verify(secondClient).getComplete(any()); + } + + @Test + void concurrentExactAndChangedClaimsKeepOneImmutableBinding() throws Exception { + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + acceptSource(source); + String stableControlRequest = controlRequest(); + CompleteLaunchBindingEvidence original = evidence(source, stableControlRequest, 51L); + CompleteLaunchBindingEvidence changed = evidence(source, stableControlRequest, 52L); + CountDownLatch bothFetched = new CountDownLatch(2); + AuthoredWorldLaunchDescriptorClient originalClient = + mock(AuthoredWorldLaunchDescriptorClient.class); + AuthoredWorldLaunchDescriptorClient changedClient = + mock(AuthoredWorldLaunchDescriptorClient.class); + when(originalClient.getComplete(any())) + .thenAnswer( + invocation -> { + awaitFetchBarrier(bothFetched); + return original; + }); + when(changedClient.getComplete(any())) + .thenAnswer( + invocation -> { + awaitFetchBarrier(bothFetched); + return changed; + }); + WorldCompleteLaunchBindingService originalService = service(originalClient, transactionManager); + WorldCompleteLaunchBindingService changedService = service(changedClient, transactionManager); + GetRequest originalRequest = request(original); + GetRequest changedRequest = request(changed); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = executor.submit(() -> attempt(originalService, originalRequest)); + Future second = executor.submit(() -> attempt(changedService, changedRequest)); + Object firstResult = first.get(20, TimeUnit.SECONDS); + Object secondResult = second.get(20, TimeUnit.SECONDS); + WorldCompleteLaunchBindingReceipt receipt; + if (firstResult instanceof WorldCompleteLaunchBindingReceipt firstReceipt) { + receipt = firstReceipt; + assertThat(secondResult).isInstanceOf(RegistrationConflictException.class); + } else { + assertThat(firstResult).isInstanceOf(RegistrationConflictException.class); + assertThat(secondResult).isInstanceOf(WorldCompleteLaunchBindingReceipt.class); + receipt = (WorldCompleteLaunchBindingReceipt) secondResult; + } + assertThat(countBindings(source.canonicalTenantId())).isEqualTo(1L); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT binding_operation_id FROM world_complete_launch_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? " + + "AND control_plane_request_id = ?", + NAMESPACE, + source.canonicalTenantId(), + stableControlRequest), + "complete launch binding operation readback returned no row") + .get("binding_operation_id", UUID.class)) + .isEqualTo(receipt.operationId()); + } + } + + @Test + void recoversCommittedBindingWhenOwnerCommitAcknowledgmentIsLost() { + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + acceptSource(source); + CompleteLaunchBindingEvidence evidence = evidence(source, controlRequest(), 61L); + AuthoredWorldLaunchDescriptorClient client = mock(AuthoredWorldLaunchDescriptorClient.class); + when(client.getComplete(any())).thenReturn(evidence); + LostCommitAcknowledgmentTransactionManager manager = + new LostCommitAcknowledgmentTransactionManager(transactionManager); + WorldCompleteLaunchBindingService service = service(client, manager); + + WorldCompleteLaunchBindingReceipt recovered = + withGameSession(() -> service.bind(request(evidence))); + + assertThat(recovered.evidence()).isEqualTo(evidence); + assertThat(countBindings(source.canonicalTenantId())).isEqualTo(1L); + verify(client).getComplete(any()); + LostCommitAcknowledgmentTransactionManager retryManager = + new LostCommitAcknowledgmentTransactionManager(transactionManager); + AuthoredWorldLaunchDescriptorClient retryClient = + mock(AuthoredWorldLaunchDescriptorClient.class); + WorldCompleteLaunchBindingReceipt retry = + withGameSession(() -> service(retryClient, retryManager).bind(request(evidence))); + assertThat(retry.operationId()).isEqualTo(recovered.operationId()); + verify(retryClient, never()).getComplete(any()); + } + + @Test + void readsCurrentVersionForExactCommittedBindingAndPreservesOriginalReceipt() + throws SQLException { + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + WorldAuthoredSourceIntakeReceipt sourceReceipt = acceptSource(source); + CompleteLaunchBindingEvidence evidence = evidence(source, controlRequest(), 71L); + GetRequest bindingRequest = request(evidence); + AuthoredWorldLaunchDescriptorClient descriptorClient = + mock(AuthoredWorldLaunchDescriptorClient.class); + when(descriptorClient.getComplete(any())).thenReturn(evidence); + AuthoredWorldVersionStateClient versionStateClient = + mock(AuthoredWorldVersionStateClient.class); + UUID firstReadId = UUID.randomUUID(); + UUID retiredReadId = UUID.randomUUID(); + when(versionStateClient.read(any())) + .thenAnswer( + invocation -> { + AuthoredWorldVersionStateEvidence.Request currentRequest = invocation.getArgument(0); + if (currentRequest.readRequestId().equals(firstReadId)) { + return currentVersionState( + currentRequest, + source, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + evidence.descriptor().versionStateEpoch()); + } + if (currentRequest.readRequestId().equals(retiredReadId)) { + return currentVersionState( + currentRequest, + source, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE, + evidence.descriptor().versionStateEpoch() + 1); + } + throw new IllegalArgumentException("Unexpected synthetic current-read request"); + }); + WorldCompleteLaunchBindingService service = + service(descriptorClient, versionStateClient, transactionManager); + + WorldCompleteLaunchBindingReceipt original = + withGameSession(() -> service.bind(bindingRequest)); + Map>> ownerRowsBeforeRead = + worldOwnerRows( + source.canonicalTenantId(), + sourceReceipt.operationId(), + sourceReceipt.localTenantKey(), + evidence.descriptor().controlPlaneRequestId()); + + AuthoredWorldVersionStateEvidence eligible = + withGameSession(() -> service.readCurrentVersionState(bindingRequest, firstReadId)); + + assertThat(eligible.versionState()) + .isEqualTo(VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED); + assertThat(eligible.versionStateEpoch()).isEqualTo(evidence.descriptor().versionStateEpoch()); + assertThat(eligible.request().versionId()).isEqualTo(evidence.descriptor().versionId()); + assertThat( + worldOwnerRows( + source.canonicalTenantId(), + sourceReceipt.operationId(), + sourceReceipt.localTenantKey(), + evidence.descriptor().controlPlaneRequestId())) + .isEqualTo(ownerRowsBeforeRead); + + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(bindingRequest, retiredReadId))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("epoch differs"); + assertThat( + worldOwnerRows( + source.canonicalTenantId(), + sourceReceipt.operationId(), + sourceReceipt.localTenantKey(), + evidence.descriptor().controlPlaneRequestId())) + .isEqualTo(ownerRowsBeforeRead); + + WorldCompleteLaunchBindingReceipt retry = withGameSession(() -> service.bind(bindingRequest)); + assertThat(retry).isEqualTo(original); + assertThat(retry.operationId()).isEqualTo(original.operationId()); + assertThat(retry.sourceIntakeReceipt()).isEqualTo(sourceReceipt); + assertThat(retry.evidence()).isEqualTo(evidence); + assertThat( + worldOwnerRows( + source.canonicalTenantId(), + sourceReceipt.operationId(), + sourceReceipt.localTenantKey(), + evidence.descriptor().controlPlaneRequestId())) + .isEqualTo(ownerRowsBeforeRead); + verify(descriptorClient).getComplete(any()); + verify(versionStateClient, times(2)).read(any()); + } + + @Test + void deniesMixedCurrentVersionEvidenceWithoutChangingCommittedBinding() throws SQLException { + AuthoredWorldSourceEvidence boundSource = source(UUID.randomUUID(), randomWorld()); + WorldAuthoredSourceIntakeReceipt boundSourceReceipt = acceptSource(boundSource); + CompleteLaunchBindingEvidence bindingEvidence = evidence(boundSource, controlRequest(), 73L); + GetRequest bindingRequest = request(bindingEvidence); + AuthoredWorldLaunchDescriptorClient descriptorClient = + mock(AuthoredWorldLaunchDescriptorClient.class); + when(descriptorClient.getComplete(any())).thenReturn(bindingEvidence); + AuthoredWorldVersionStateClient versionStateClient = + mock(AuthoredWorldVersionStateClient.class); + + AuthoredWorldSourceEvidence otherSource = source(UUID.randomUUID(), randomWorld()); + WorldAuthoredSourceIntakeReceipt otherSourceReceipt = acceptSource(otherSource); + AuthoredWorldSourceEvidence missingBindingSource = source(UUID.randomUUID(), randomWorld()); + WorldAuthoredSourceIntakeReceipt missingBindingReceipt = acceptSource(missingBindingSource); + String otherControlPlaneRequestId = controlRequest(); + UUID mixedReadId = UUID.randomUUID(); + UUID changedSelectorReadId = UUID.randomUUID(); + UUID changedCanonicalVersionReadId = UUID.randomUUID(); + UUID unavailableReadId = UUID.randomUUID(); + UUID missingBindingReadId = UUID.randomUUID(); + AuthoredWorldVersionStateEvidence mixedEvidence = + currentVersionState( + otherSource, + mixedReadId, + bindingEvidence.descriptor().versionId() + 1, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + bindingEvidence.descriptor().versionStateEpoch()); + AuthoredWorldVersionStateEvidence changedSelectorEvidence = + currentVersionState( + boundSource, + changedSelectorReadId, + bindingEvidence.descriptor().versionId() + 1, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + bindingEvidence.descriptor().versionStateEpoch()); + AuthoredWorldVersionStateEvidence expectedCanonicalVersionEvidence = + currentVersionState( + boundSource, + changedCanonicalVersionReadId, + bindingEvidence.descriptor().versionId(), + bindingEvidence.releaseAttestation().canonicalVersionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + bindingEvidence.descriptor().versionStateEpoch()); + AuthoredWorldVersionStateEvidence changedCanonicalVersionEvidence = + currentVersionState( + boundSource, + changedCanonicalVersionReadId, + bindingEvidence.descriptor().versionId(), + OTHER_CANONICAL_VERSION, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + bindingEvidence.descriptor().versionStateEpoch()); + mixedEvidence.requireValid(); + changedSelectorEvidence.requireValid(); + changedCanonicalVersionEvidence.requireValid(); + when(versionStateClient.read(any())) + .thenAnswer( + invocation -> { + AuthoredWorldVersionStateEvidence.Request currentRequest = invocation.getArgument(0); + if (currentRequest.readRequestId().equals(mixedReadId)) { + return mixedEvidence; + } + if (currentRequest.readRequestId().equals(changedSelectorReadId)) { + return changedSelectorEvidence; + } + if (currentRequest.readRequestId().equals(changedCanonicalVersionReadId)) { + return changedCanonicalVersionEvidence; + } + if (currentRequest.readRequestId().equals(unavailableReadId)) { + throw new IllegalStateException("Synthetic current-version source is unavailable"); + } + throw new IllegalArgumentException("Unexpected synthetic current-read request"); + }); + WorldCompleteLaunchBindingService service = + service(descriptorClient, versionStateClient, transactionManager); + WorldCompleteLaunchBindingReceipt committed = + withGameSession(() -> service.bind(bindingRequest)); + GetRequest missingBindingRequest = + request(evidence(missingBindingSource, controlRequest(), 74L)); + Map>> committedRowsBeforeRead = + worldOwnerRows( + boundSource.canonicalTenantId(), + boundSourceReceipt.operationId(), + boundSourceReceipt.localTenantKey(), + bindingEvidence.descriptor().controlPlaneRequestId()); + Map>> otherSourceRowsBeforeRead = + worldOwnerRows( + otherSource.canonicalTenantId(), + otherSourceReceipt.operationId(), + otherSourceReceipt.localTenantKey(), + otherControlPlaneRequestId); + Map>> missingBindingRowsBeforeRead = + worldOwnerRows( + missingBindingSource.canonicalTenantId(), + missingBindingReceipt.operationId(), + missingBindingReceipt.localTenantKey(), + missingBindingRequest.expectedRequest().controlPlaneRequestId()); + assertThat(mixedEvidence.request().sourceOperationId()).isEqualTo(otherSource.operationId()); + assertThat(mixedEvidence.request().versionId()) + .isNotEqualTo(bindingEvidence.descriptor().versionId()); + assertThat(changedSelectorEvidence.sourceEvidence()).isEqualTo(boundSource); + assertThat(changedSelectorEvidence.request().versionId()) + .isNotEqualTo(bindingEvidence.descriptor().versionId()); + assertThat(changedCanonicalVersionEvidence.request()) + .isEqualTo(expectedCanonicalVersionEvidence.request()); + assertThat(changedCanonicalVersionEvidence.sourceEvidence()) + .isEqualTo(expectedCanonicalVersionEvidence.sourceEvidence()); + assertThat(changedCanonicalVersionEvidence.versionState()) + .isEqualTo(expectedCanonicalVersionEvidence.versionState()); + assertThat(changedCanonicalVersionEvidence.versionStateEpoch()) + .isEqualTo(expectedCanonicalVersionEvidence.versionStateEpoch()); + assertThat(changedCanonicalVersionEvidence.canonicalVersionId()) + .isNotEqualTo(bindingEvidence.releaseAttestation().canonicalVersionId()); + + assertThatThrownBy( + () -> + withGameSession(() -> service.readCurrentVersionState(bindingRequest, mixedReadId))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("exact committed World source"); + assertThat( + worldOwnerRows( + boundSource.canonicalTenantId(), + boundSourceReceipt.operationId(), + boundSourceReceipt.localTenantKey(), + bindingEvidence.descriptor().controlPlaneRequestId())) + .isEqualTo(committedRowsBeforeRead); + assertThat( + worldOwnerRows( + otherSource.canonicalTenantId(), + otherSourceReceipt.operationId(), + otherSourceReceipt.localTenantKey(), + otherControlPlaneRequestId)) + .isEqualTo(otherSourceRowsBeforeRead); + + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(bindingRequest, changedSelectorReadId))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("exact committed World source"); + assertThat( + worldOwnerRows( + boundSource.canonicalTenantId(), + boundSourceReceipt.operationId(), + boundSourceReceipt.localTenantKey(), + bindingEvidence.descriptor().controlPlaneRequestId())) + .isEqualTo(committedRowsBeforeRead); + + assertThatThrownBy( + () -> + withGameSession( + () -> + service.readCurrentVersionState( + bindingRequest, changedCanonicalVersionReadId))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("canonical version UUID differs"); + assertThat( + worldOwnerRows( + boundSource.canonicalTenantId(), + boundSourceReceipt.operationId(), + boundSourceReceipt.localTenantKey(), + bindingEvidence.descriptor().controlPlaneRequestId())) + .isEqualTo(committedRowsBeforeRead); + assertThat( + worldOwnerRows( + otherSource.canonicalTenantId(), + otherSourceReceipt.operationId(), + otherSourceReceipt.localTenantKey(), + otherControlPlaneRequestId)) + .isEqualTo(otherSourceRowsBeforeRead); + assertThat( + worldOwnerRows( + missingBindingSource.canonicalTenantId(), + missingBindingReceipt.operationId(), + missingBindingReceipt.localTenantKey(), + missingBindingRequest.expectedRequest().controlPlaneRequestId())) + .isEqualTo(missingBindingRowsBeforeRead); + assertThat(committed.evidence()).isEqualTo(bindingEvidence); + assertThat(committed.sourceIntakeReceipt()).isEqualTo(boundSourceReceipt); + + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(bindingRequest, unavailableReadId))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("unavailable or invalid"); + assertThat( + worldOwnerRows( + boundSource.canonicalTenantId(), + boundSourceReceipt.operationId(), + boundSourceReceipt.localTenantKey(), + bindingEvidence.descriptor().controlPlaneRequestId())) + .isEqualTo(committedRowsBeforeRead); + + assertThatThrownBy( + () -> + withGameSession( + () -> + service.readCurrentVersionState( + missingBindingRequest, missingBindingReadId))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("requires a committed launch binding"); + assertThat( + worldOwnerRows( + missingBindingSource.canonicalTenantId(), + missingBindingReceipt.operationId(), + missingBindingReceipt.localTenantKey(), + missingBindingRequest.expectedRequest().controlPlaneRequestId())) + .isEqualTo(missingBindingRowsBeforeRead); + assertThat(missingBindingRowsBeforeRead.get("binding")).isEmpty(); + assertThat(committed.operationId()) + .isEqualTo(committedRowsBeforeRead.get("binding").get(0).get("binding_operation_id")); + assertThat( + worldOwnerRows( + otherSource.canonicalTenantId(), + otherSourceReceipt.operationId(), + otherSourceReceipt.localTenantKey(), + otherControlPlaneRequestId)) + .isEqualTo(otherSourceRowsBeforeRead); + assertThat( + worldOwnerRows( + missingBindingSource.canonicalTenantId(), + missingBindingReceipt.operationId(), + missingBindingReceipt.localTenantKey(), + missingBindingRequest.expectedRequest().controlPlaneRequestId())) + .isEqualTo(missingBindingRowsBeforeRead); + assertThat( + worldOwnerRows( + boundSource.canonicalTenantId(), + boundSourceReceipt.operationId(), + boundSourceReceipt.localTenantKey(), + bindingEvidence.descriptor().controlPlaneRequestId())) + .isEqualTo(committedRowsBeforeRead); + WorldCompleteLaunchBindingReceipt retried = withGameSession(() -> service.bind(bindingRequest)); + assertThat(retried).isEqualTo(committed); + assertThat(retried.evidence()).isEqualTo(bindingEvidence); + assertThat(retried.sourceIntakeReceipt()).isEqualTo(boundSourceReceipt); + assertThat( + worldOwnerRows( + boundSource.canonicalTenantId(), + boundSourceReceipt.operationId(), + boundSourceReceipt.localTenantKey(), + bindingEvidence.descriptor().controlPlaneRequestId())) + .isEqualTo(committedRowsBeforeRead); + verify(descriptorClient).getComplete(any()); + verify(versionStateClient, times(4)).read(any()); + } + + private WorldAuthoredSourceIntakeReceipt acceptSource(AuthoredWorldSourceEvidence source) { + UUID intakeRequestId = UUID.randomUUID(); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + return Objects.requireNonNull( + transaction.execute( + status -> sourceRepository.acceptFresh(NAMESPACE, intakeRequestId, source)), + "World source intake returned no receipt"); + } + + private WorldCompleteLaunchBindingService service( + AuthoredWorldLaunchDescriptorClient client, PlatformTransactionManager manager) { + return new WorldCompleteLaunchBindingService( + client, + new WorldCompleteLaunchBindingRepository(dsl), + sourceRepository, + manager, + NAMESPACE); + } + + private WorldCompleteLaunchBindingService service( + AuthoredWorldLaunchDescriptorClient descriptorClient, + AuthoredWorldVersionStateClient versionStateClient, + PlatformTransactionManager manager) { + return new WorldCompleteLaunchBindingService( + descriptorClient, + new WorldCompleteLaunchBindingRepository(dsl), + sourceRepository, + manager, + NAMESPACE, + versionStateClient); + } + + private Map>> worldOwnerRows( + UUID canonicalTenantId, + UUID sourceIntakeOperationId, + long localTenantKey, + String controlPlaneRequestId) + throws SQLException { + try (Connection connection = dataSource.getConnection()) { + Map>> rows = new LinkedHashMap<>(); + rows.put( + "association", + readOwnerRows( + connection, + "SELECT * FROM world_authored_source_tenant_association " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + canonicalTenantId)); + rows.put( + "reservation", + readOwnerRows( + connection, + "SELECT * FROM world_authored_source_tenant_key_reservation WHERE tenant_key = ?", + localTenantKey)); + rows.put( + "sourceIntake", + readOwnerRows( + connection, + "SELECT * FROM world_authored_source_intake WHERE target_namespace = ? " + + "AND canonical_tenant_id = ? AND operation_id = ?", + NAMESPACE, + canonicalTenantId, + sourceIntakeOperationId)); + rows.put( + "binding", + readOwnerRows( + connection, + "SELECT * FROM world_complete_launch_binding WHERE target_namespace = ? " + + "AND canonical_tenant_id = ? AND control_plane_request_id = ?", + NAMESPACE, + canonicalTenantId, + controlPlaneRequestId)); + return Collections.unmodifiableMap(rows); + } + } + + private static List> readOwnerRows( + Connection connection, String query, Object... parameters) throws SQLException { + try (PreparedStatement statement = connection.prepareStatement(query)) { + for (int index = 0; index < parameters.length; index++) { + statement.setObject(index + 1, parameters[index]); + } + try (ResultSet resultSet = statement.executeQuery()) { + ResultSetMetaData metadata = resultSet.getMetaData(); + List> rows = new ArrayList<>(); + while (resultSet.next()) { + Map row = new LinkedHashMap<>(); + for (int index = 1; index <= metadata.getColumnCount(); index++) { + row.put(metadata.getColumnLabel(index), resultSet.getObject(index)); + } + rows.add(Collections.unmodifiableMap(row)); + } + return List.copyOf(rows); + } + } + } + + private long countBindings(UUID tenant) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM world_complete_launch_binding WHERE target_namespace = ? " + + "AND canonical_tenant_id = ?", + NAMESPACE, + tenant), + "complete launch binding count query returned no row") + .get(0, Long.class); + } + + private static AuthoredWorldSourceEvidence source(UUID tenant, String worldSlug) { + UUID registrationRequest = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + String tenantSlug = "tenant-" + tenant.toString().replace("-", ""); + String displayName = "Source " + tenant.toString().substring(0, 8); + long sourceGameRowId = Math.max(1L, tenant.getLeastSignificantBits() & Long.MAX_VALUE); + String sourceGameTenantKey = "source-" + tenant.toString().replace("-", "").substring(0, 24); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequest, tenant, tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequest, + sourceOperationId, + requestDigest, + tenant, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequest, + sourceOperationId, + requestDigest, + tenant, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static CompleteLaunchBindingEvidence evidence( + AuthoredWorldSourceEvidence source, String controlPlaneRequestId, long gameTemplateId) { + AuthoredWorldLaunchDescriptorEvidence.Request request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + gameTemplateId, + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + "launch-descriptor-" + gameTemplateId, + 42L, + false, + null, + "{}", + "generation-config-42", + 17L, + 51L, + "release-bundle-51", + false, + null); + String commit = "commit-launch-binding"; + List participants = + List.of( + participant("WORLD_MANAGEMENT", 3, "a", false, commit), + participant("ENTITY_MANAGEMENT", 2, "b", false, commit), + participant("GAME_LOGIC", 1, "c", true, commit), + participant("AUTOMATION_SCRIPTING", 5, "d", false, commit), + participant("GAME_DESIGN_CONTROL_PLANE", 1, "e", false, commit)); + AuthoredWorldReleaseAttestationEvidence attestation = + AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + source.canonicalTenantId(), + VERSION, + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish:owner:launch-binding", + commit, + participants, + digest('f'), + 1, + List.of(), + List.of(), + List.of("look"), + descriptor.generationConfigRevision()); + return new CompleteLaunchBindingEvidence(descriptor, attestation); + } + + private static AuthoredWorldVersionStateEvidence currentVersionState( + AuthoredWorldVersionStateEvidence.Request request, + AuthoredWorldSourceEvidence source, + VersionLifecycleState versionState, + long versionStateEpoch) { + return currentVersionState(request, source, VERSION, versionState, versionStateEpoch); + } + + private static AuthoredWorldVersionStateEvidence currentVersionState( + AuthoredWorldVersionStateEvidence.Request request, + AuthoredWorldSourceEvidence source, + UUID canonicalVersionId, + VersionLifecycleState versionState, + long versionStateEpoch) { + return AuthoredWorldVersionStateEvidence.create( + request, source, canonicalVersionId, versionState, versionStateEpoch); + } + + private static AuthoredWorldVersionStateEvidence currentVersionState( + AuthoredWorldSourceEvidence source, + UUID readRequestId, + long versionId, + VersionLifecycleState versionState, + long versionStateEpoch) { + return currentVersionState( + source, readRequestId, versionId, VERSION, versionState, versionStateEpoch); + } + + private static AuthoredWorldVersionStateEvidence currentVersionState( + AuthoredWorldSourceEvidence source, + UUID readRequestId, + long versionId, + UUID canonicalVersionId, + VersionLifecycleState versionState, + long versionStateEpoch) { + AuthoredWorldVersionStateEvidence.Request request = + new AuthoredWorldVersionStateEvidence.Request( + 1, + source.targetNamespace(), + readRequestId, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + versionId); + return currentVersionState( + request, source, canonicalVersionId, versionState, versionStateEpoch); + } + + private static AuthoredWorldReleaseAttestationEvidence.Participant participant( + String owner, int schema, String contentHex, boolean hasAbilityDigest, String commit) { + return new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + "42", + false, + null, + commit, + contentHex.repeat(64), + schema, + hasAbilityDigest, + hasAbilityDigest ? digest('c') : null); + } + + private static GetRequest request(CompleteLaunchBindingEvidence evidence) { + UUID requestId; + do { + requestId = UUID.randomUUID(); + } while (requestId.equals(evidence.descriptor().authoredWorldSourceOperationId())); + return new GetRequest( + requestId, evidence.descriptor().request(), evidence.descriptor().resultDigest()); + } + + private static String randomWorld() { + return "world-" + UUID.randomUUID().toString().replace("-", "").substring(0, 18); + } + + private static String controlRequest() { + return "world-control-" + UUID.randomUUID(); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } + + private static GrpcPeerIdentity peer() { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service", + NAMESPACE, + "game-session-service"); + } + + private static T withGameSession(java.util.function.Supplier action) { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer()); + Context previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + + private static void awaitFetchBarrier(CountDownLatch latch) { + latch.countDown(); + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent launch-binding fetch barrier timed out"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Concurrent launch-binding fetch was interrupted", exception); + } + } + + private static Object attempt(WorldCompleteLaunchBindingService service, GetRequest request) { + return withGameSession( + () -> { + try { + return service.bind(request); + } catch (RegistrationConflictException exception) { + return exception; + } + }); + } + + private static void migrateFixture(String schema, MigrationVersion target) { + var configuration = + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private static Connection fixtureConnection(String schema) throws SQLException { + Connection connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + connection.setSchema(schema); + return connection; + } + + private static void dropFixtureSchema(String schema) throws SQLException { + try (Connection connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + Statement statement = connection.createStatement()) { + statement.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } + } + + private static final class LostCommitAcknowledgmentTransactionManager + implements PlatformTransactionManager { + private final PlatformTransactionManager delegate; + private boolean firstCommit = true; + + private LostCommitAcknowledgmentTransactionManager(PlatformTransactionManager delegate) { + this.delegate = delegate; + } + + @Override + public TransactionStatus getTransaction( + org.springframework.transaction.TransactionDefinition definition) { + return delegate.getTransaction(definition); + } + + @Override + public void commit(TransactionStatus status) { + delegate.commit(status); + if (firstCommit) { + firstCommit = false; + throw new IllegalStateException("simulated lost owner commit acknowledgment"); + } + } + + @Override + public void rollback(TransactionStatus status) { + if (!status.isCompleted()) { + delegate.rollback(status); + } + } + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java new file mode 100644 index 0000000000..c27f702971 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java @@ -0,0 +1,985 @@ +package net.firedevops.firemud.worldmanagement; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.TestContainerImages; +import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; +import net.firedevops.firemud.worldmanagement.client.GameDesignClient; +import net.firedevops.firemud.worldmanagement.client.GameSessionClient; +import net.firedevops.firemud.worldmanagement.client.GrpcGameSessionInitialAdmissionBindProofClient; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.Checkpoint; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.FrozenAttempt; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository; +import org.jooq.DSLContext; +import org.jooq.exception.DataAccessException; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class WorldDesignPublicationFenceIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final String FULL_REQUEST_DIGEST = "f".repeat(64); + private static final long GAME_DESIGN_VERSION_A = 9_000_000_042L; + private static final long GAME_DESIGN_VERSION_B = 9_000_000_043L; + private static final Checkpoint SYNTHETIC_CHECKPOINT = + new Checkpoint("synthetic-commit-42", "c".repeat(64), 3); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "world_management_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private WorldAuthoredSourceIntakeRepository intakeRepository; + @Autowired private WorldDesignPublicationFenceRepository repository; + @Autowired private DSLContext dsl; + @Autowired private PlatformTransactionManager transactionManager; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @MockitoBean(enforceOverride = true) + private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private EntityManagementClient entityManagementClient; + + @Test + void rollbackAndCommittedExactReadbackRetainOneImmutableAttempt() { + WorldAuthoredSourceIntakeReceipt receipt = intake(UUID.randomUUID(), "violet-wilds"); + WorldDesignPublicationFenceEvidence request = + evidence(receipt, "request-7", GAME_DESIGN_VERSION_A, 9L); + + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> { + repository.lockOpen(request.ownerBinding()); + throw new ForcedRollbackException(); + })) + .isInstanceOf(ForcedRollbackException.class); + assertThat(ownerCount(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isZero(); + + FrozenAttempt frozen = + ownerTransaction() + .execute(status -> repository.claimFreeze(request, () -> SYNTHETIC_CHECKPOINT)); + assertThat(frozen).isNotNull(); + assertThat(repository.readAttempt(request)).contains(frozen); + assertThat(frozen.checkpoint().digestSchemaVersion()).isEqualTo(3); + assertThat(ownerPhase(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isEqualTo("FROZEN"); + WorldAuthoredVersionIdentityReceipt identity = identity(receipt, GAME_DESIGN_VERSION_A); + assertThat(identity.localVersionKey()).isNotEqualTo(GAME_DESIGN_VERSION_A); + var storedBinding = + dsl.fetchOne( + "SELECT owner_binding_schema_version, version_id, canonical_version_id, " + + "version_identity_operation_id, game_design_version_id, intake_request_digest " + + "FROM world_design_publication_fence_attempt WHERE publication_fence = ?", + frozen.publicationFence()); + assertThat(storedBinding).isNotNull(); + assertThat(storedBinding.get("owner_binding_schema_version", Short.class)).isEqualTo((short) 1); + assertThat(storedBinding.get("version_id", Long.class)).isEqualTo(identity.localVersionKey()); + assertThat(storedBinding.get("canonical_version_id", UUID.class)) + .isEqualTo(identity.canonicalVersionId()); + assertThat(storedBinding.get("version_identity_operation_id", UUID.class)) + .isEqualTo(identity.operationId()); + assertThat(storedBinding.get("game_design_version_id", Long.class)) + .isEqualTo(GAME_DESIGN_VERSION_A); + assertThat(storedBinding.get("intake_request_digest", String.class)) + .isEqualTo(receipt.requestDigest()); + + AtomicBoolean retryRecapturedCheckpoint = new AtomicBoolean(); + FrozenAttempt retry = + ownerTransaction() + .execute( + status -> + repository.claimFreeze( + request, + () -> { + retryRecapturedCheckpoint.set(true); + return new Checkpoint("synthetic-new-commit", "d".repeat(64), 2); + })); + assertThat(retry).isEqualTo(frozen); + assertThat(retryRecapturedCheckpoint).isFalse(); + assertThat(attemptCount(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isEqualTo(1L); + + assertDatabaseTriggerRejects( + () -> + dsl.execute( + "UPDATE world_design_publication_fence_attempt SET content_digest = ? " + + "WHERE publication_fence = ?", + "d".repeat(64), + frozen.publicationFence()), + "World publication-fence attempt history is immutable"); + assertDatabaseTriggerRejects( + () -> dsl.execute("TRUNCATE world_design_publication_fence_attempt CASCADE"), + "World publication-fence attempt history is immutable"); + assertDatabaseTriggerRejects( + () -> dsl.execute("TRUNCATE world_design_publication_fence_owner"), + "World publication-fence attempt history is immutable"); + assertDatabaseTriggerRejects( + () -> + dsl.execute( + "UPDATE world_design_publication_fence_owner " + + "SET current_publication_fence = NULL WHERE canonical_tenant_id = ? " + + "AND version_id = ?", + receipt.canonicalTenantId(), + localVersionKey(identity(receipt, GAME_DESIGN_VERSION_A))), + "World publication-fence owner binding or phase transition is immutable"); + + assertThat(repository.readAttempt(request)).contains(frozen); + assertThat(ownerCount(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isEqualTo(1L); + assertThat(attemptCount(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isEqualTo(1L); + assertThat(ownerPhase(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isEqualTo("FROZEN"); + } + + @Test + void schemaZeroAttemptAtResolvedLocalKeyCannotBePromotedByNumericCoincidence() { + WorldAuthoredSourceIntakeReceipt receipt = intake(UUID.randomUUID(), "legacy-world"); + WorldAuthoredVersionIdentityReceipt identity = identity(receipt, GAME_DESIGN_VERSION_A); + WorldDesignPublicationFenceEvidence request = + evidence(receipt, "legacy-request", GAME_DESIGN_VERSION_A, 3L); + assertThat(identity.localVersionKey()).isNotEqualTo(GAME_DESIGN_VERSION_A); + + dsl.execute( + "INSERT INTO world_design_publication_fence_attempt (" + + "publication_fence, target_namespace, canonical_tenant_id, local_tenant_key, " + + "version_id, intake_operation_id, intake_request_id, source_operation_id, " + + "source_evidence_digest, intake_receipt_digest, publication_request_id, " + + "request_digest, version_state_epoch, publish_workflow_id, applied_commit_id, " + + "content_digest, digest_schema_version) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + UUID.randomUUID(), + NAMESPACE, + receipt.canonicalTenantId(), + receipt.localTenantKey(), + identity.localVersionKey(), + receipt.operationId(), + receipt.intakeRequestId(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + receipt.receiptDigest(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId(), + "legacy-commit", + "e".repeat(64), + 2); + + assertThatThrownBy(() -> repository.readAttempt(request)) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("schema-0"); + assertThatThrownBy( + () -> + ownerTransaction() + .execute(status -> repository.claimFreeze(request, () -> SYNTHETIC_CHECKPOINT))) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("schema-0"); + assertThat(ownerCount(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isZero(); + assertThat(attemptCount(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isEqualTo(1L); + } + + @Test + void sameGameDesignSelectorUsesDistinctWorldLocalVersionRowsAcrossIntakes() { + UUID canonicalTenantId = UUID.randomUUID(); + String tenantSlug = "tenant-" + canonicalTenantId.toString().replace("-", ""); + WorldAuthoredSourceIntakeReceipt first = + intake(canonicalTenantId, "violet-wilds", tenantSlug, 6_001L); + WorldAuthoredSourceIntakeReceipt second = + intake(canonicalTenantId, "brighter-coast", tenantSlug, 6_001L); + + ownerTransaction() + .execute( + status -> { + repository.lockOpen(ownerBinding(first, GAME_DESIGN_VERSION_A)); + return null; + }); + ownerTransaction() + .execute( + status -> { + repository.lockOpen(ownerBinding(second, GAME_DESIGN_VERSION_A)); + return null; + }); + + assertThat(identity(first, GAME_DESIGN_VERSION_A).localVersionKey()) + .isNotEqualTo(identity(second, GAME_DESIGN_VERSION_A).localVersionKey()); + assertThat(ownerCount(canonicalTenantId, GAME_DESIGN_VERSION_A)).isEqualTo(2L); + assertThat(ownerPhase(canonicalTenantId, GAME_DESIGN_VERSION_A)).isEqualTo("OPEN"); + } + + @Test + void identicalRequestAcrossVersionsUsesOnlyEachResolvedWorldLocalKey() { + UUID canonicalTenantId = UUID.randomUUID(); + String tenantSlug = "tenant-" + canonicalTenantId.toString().replace("-", ""); + WorldAuthoredSourceIntakeReceipt first = + intake(canonicalTenantId, "violet-wilds", tenantSlug, 8_101L); + WorldAuthoredVersionIdentityReceipt firstIdentity = identity(first, GAME_DESIGN_VERSION_A); + long secondGameDesignVersionId = firstIdentity.localVersionKey(); + WorldAuthoredSourceIntakeReceipt second = + intake(canonicalTenantId, "brighter-coast", tenantSlug, 8_101L); + WorldAuthoredVersionIdentityReceipt secondIdentity = + identity(second, secondGameDesignVersionId); + assertThat(secondGameDesignVersionId).isNotEqualTo(GAME_DESIGN_VERSION_A); + assertThat(secondIdentity.localVersionKey()).isNotEqualTo(secondGameDesignVersionId); + assertThatThrownBy(() -> intake(canonicalTenantId, "contradictory-world", tenantSlug, 8_103L)) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class) + .hasMessageContaining("Canonical tenant source or stable tenant selector conflicts"); + + WorldDesignPublicationFenceEvidence firstRequest = + evidence(first, "shared-publication-request", GAME_DESIGN_VERSION_A, 5L); + WorldDesignPublicationFenceEvidence secondRequest = + evidence(second, "shared-publication-request", secondGameDesignVersionId, 5L); + FrozenAttempt firstFrozen = + ownerTransaction() + .execute(status -> repository.claimFreeze(firstRequest, () -> SYNTHETIC_CHECKPOINT)); + FrozenAttempt secondFrozen = + ownerTransaction() + .execute(status -> repository.claimFreeze(secondRequest, () -> SYNTHETIC_CHECKPOINT)); + + assertThat(secondFrozen.publicationFence()).isNotEqualTo(firstFrozen.publicationFence()); + long firstOwnerCount = ownerCount(canonicalTenantId, GAME_DESIGN_VERSION_A); + long secondOwnerCount = ownerCount(canonicalTenantId, secondGameDesignVersionId); + long firstAttemptCount = attemptCount(canonicalTenantId, GAME_DESIGN_VERSION_A); + long secondAttemptCount = attemptCount(canonicalTenantId, secondGameDesignVersionId); + assertThat(firstOwnerCount).isEqualTo(1L); + assertThat(secondOwnerCount).isEqualTo(1L); + assertThat(firstAttemptCount).isEqualTo(1L); + assertThat(secondAttemptCount).isEqualTo(1L); + assertThat(repository.readAttempt(firstRequest)).contains(firstFrozen); + assertThat(repository.readAttempt(secondRequest)).contains(secondFrozen); + assertThat(ownerCount(canonicalTenantId, GAME_DESIGN_VERSION_A)).isEqualTo(1L); + assertThat(ownerCount(canonicalTenantId, secondGameDesignVersionId)).isEqualTo(1L); + assertThat(attemptCount(canonicalTenantId, GAME_DESIGN_VERSION_A)).isEqualTo(1L); + assertThat(attemptCount(canonicalTenantId, secondGameDesignVersionId)).isEqualTo(1L); + assertThat(ownerCount(canonicalTenantId, GAME_DESIGN_VERSION_A)).isEqualTo(firstOwnerCount); + assertThat(ownerCount(canonicalTenantId, secondGameDesignVersionId)) + .isEqualTo(secondOwnerCount); + assertThat(attemptCount(canonicalTenantId, GAME_DESIGN_VERSION_A)).isEqualTo(firstAttemptCount); + assertThat(attemptCount(canonicalTenantId, secondGameDesignVersionId)) + .isEqualTo(secondAttemptCount); + } + + @Test + void concurrentExactFreezeRetryReturnsTheSameFenceAndCheckpoint() throws Exception { + WorldAuthoredSourceIntakeReceipt receipt = intake(UUID.randomUUID(), "violet-wilds"); + WorldDesignPublicationFenceEvidence request = + evidence(receipt, "request-concurrent", GAME_DESIGN_VERSION_A, 9L); + CountDownLatch checkpointCaptured = new CountDownLatch(1); + CountDownLatch releaseFirst = new CountDownLatch(1); + CountDownLatch secondStarted = new CountDownLatch(1); + AtomicBoolean secondCapturedCheckpoint = new AtomicBoolean(); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> + ownerTransaction() + .execute( + status -> + repository.claimFreeze( + request, + () -> { + checkpointCaptured.countDown(); + await(releaseFirst); + return SYNTHETIC_CHECKPOINT; + }))); + await(checkpointCaptured); + Future second = + executor.submit( + () -> { + secondStarted.countDown(); + return ownerTransaction() + .execute( + status -> + repository.claimFreeze( + request, + () -> { + secondCapturedCheckpoint.set(true); + return new Checkpoint("synthetic-second", "d".repeat(64), 3); + })); + }); + await(secondStarted); + awaitOwnerRowLockWait(); + releaseFirst.countDown(); + + FrozenAttempt firstResult = first.get(10, TimeUnit.SECONDS); + FrozenAttempt secondResult = second.get(10, TimeUnit.SECONDS); + assertThat(secondResult).isEqualTo(firstResult); + assertThat(secondCapturedCheckpoint).isFalse(); + assertThat(attemptCount(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isEqualTo(1L); + } finally { + releaseFirst.countDown(); + executor.shutdownNow(); + } + } + + @Test + void writerHoldingTheOpenLockCommitsBeforeFreezeCapturesItsCheckpoint() throws Exception { + WorldAuthoredSourceIntakeReceipt receipt = intake(UUID.randomUUID(), "violet-wilds"); + WorldDesignPublicationFenceEvidence request = + evidence(receipt, "request-writer-first", GAME_DESIGN_VERSION_A, 9L); + CountDownLatch writerLocked = new CountDownLatch(1); + CountDownLatch releaseWriter = new CountDownLatch(1); + CountDownLatch freezeStarted = new CountDownLatch(1); + AtomicBoolean checkpointCaptured = new AtomicBoolean(); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future writer = + executor.submit( + () -> + ownerTransaction() + .execute( + status -> { + repository.lockOpen(request.ownerBinding()); + writerLocked.countDown(); + await(releaseWriter); + return null; + })); + await(writerLocked); + Future freeze = + executor.submit( + () -> { + freezeStarted.countDown(); + return ownerTransaction() + .execute( + status -> + repository.claimFreeze( + request, + () -> { + checkpointCaptured.set(true); + return SYNTHETIC_CHECKPOINT; + })); + }); + await(freezeStarted); + awaitOwnerRowLockWait(); + assertThat(checkpointCaptured).isFalse(); + releaseWriter.countDown(); + writer.get(10, TimeUnit.SECONDS); + + FrozenAttempt frozen = freeze.get(10, TimeUnit.SECONDS); + assertThat(checkpointCaptured).isTrue(); + assertThat(frozen.checkpoint()).isEqualTo(SYNTHETIC_CHECKPOINT); + assertThat(ownerPhase(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)) + .isEqualTo("FROZEN"); + } finally { + releaseWriter.countDown(); + executor.shutdownNow(); + } + } + + @Test + void freezeHoldingTheLockMakesAWaitingOrdinaryWriterFailClosed() throws Exception { + WorldAuthoredSourceIntakeReceipt receipt = intake(UUID.randomUUID(), "violet-wilds"); + WorldDesignPublicationFenceEvidence request = + evidence(receipt, "request-freeze-first", GAME_DESIGN_VERSION_A, 9L); + CountDownLatch freezeLocked = new CountDownLatch(1); + CountDownLatch releaseFreeze = new CountDownLatch(1); + CountDownLatch writerStarted = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future freeze = + executor.submit( + () -> + ownerTransaction() + .execute( + status -> { + FrozenAttempt result = + repository.claimFreeze( + request, + () -> { + freezeLocked.countDown(); + return SYNTHETIC_CHECKPOINT; + }); + await(releaseFreeze); + return result; + })); + await(freezeLocked); + Future writer = + executor.submit( + () -> { + writerStarted.countDown(); + try { + ownerTransaction() + .execute( + status -> { + repository.lockOpen(request.ownerBinding()); + return null; + }); + return false; + } catch (WorldDesignPublicationFenceRepository.ConflictException expected) { + return true; + } + }); + await(writerStarted); + awaitOwnerRowLockWait(); + releaseFreeze.countDown(); + + freeze.get(10, TimeUnit.SECONDS); + assertThat(writer.get(10, TimeUnit.SECONDS)).isTrue(); + assertThat(ownerPhase(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)) + .isEqualTo("FROZEN"); + assertThat(attemptCount(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isEqualTo(1L); + } finally { + releaseFreeze.countDown(); + executor.shutdownNow(); + } + } + + @Test + void changedAssociationSourceRequestDigestEpochAndMissingCheckpointDoNotMutate() { + UUID canonicalTenantId = UUID.randomUUID(); + String tenantSlug = "tenant-" + canonicalTenantId.toString().replace("-", ""); + WorldAuthoredSourceIntakeReceipt first = + intake(canonicalTenantId, "violet-wilds", tenantSlug, 6_002L); + WorldAuthoredSourceIntakeReceipt second = + intake(canonicalTenantId, "brighter-coast", tenantSlug, 6_002L); + WorldDesignPublicationFenceEvidence request = + evidence(first, "request-7", GAME_DESIGN_VERSION_A, 9L); + FrozenAttempt frozen = + ownerTransaction() + .execute(status -> repository.claimFreeze(request, () -> SYNTHETIC_CHECKPOINT)); + + assertNoStateChange( + canonicalTenantId, + GAME_DESIGN_VERSION_A, + () -> + ownerTransaction() + .execute( + status -> + repository.claimFreeze( + new WorldDesignPublicationFenceEvidence( + NAMESPACE, + first.canonicalTenantId(), + identity(first, GAME_DESIGN_VERSION_A).canonicalVersionId(), + identity(first, GAME_DESIGN_VERSION_A).operationId(), + GAME_DESIGN_VERSION_A, + first.intakeRequestId(), + first.operationId(), + first.requestDigest(), + first.sourceOperationId(), + second.sourceEvidenceDigest(), + first.receiptDigest(), + "request-7", + FULL_REQUEST_DIGEST, + 9L, + request.publishWorkflowId()), + () -> SYNTHETIC_CHECKPOINT))); + + UUID changedTenantId = UUID.randomUUID(); + WorldDesignPublicationFenceEvidence changedAssociation = + evidence( + changedTenantId, + first, + "request-7", + identity(first, GAME_DESIGN_VERSION_A), + GAME_DESIGN_VERSION_A, + 9L, + PublicationDigestRequestBinding.full( + changedTenantId.toString(), Long.toString(GAME_DESIGN_VERSION_A), "request-7")); + assertNoStateChange( + canonicalTenantId, + GAME_DESIGN_VERSION_A, + () -> + ownerTransaction() + .execute( + status -> + repository.claimFreeze(changedAssociation, () -> SYNTHETIC_CHECKPOINT))); + assertThat(ownerCount(changedTenantId, GAME_DESIGN_VERSION_A)).isZero(); + + WorldAuthoredVersionIdentityReceipt identity = identity(first, GAME_DESIGN_VERSION_A); + WorldDesignPublicationFenceEvidence changedCanonicalVersion = + new WorldDesignPublicationFenceEvidence( + NAMESPACE, + canonicalTenantId, + UUID.randomUUID(), + identity.operationId(), + GAME_DESIGN_VERSION_A, + first.intakeRequestId(), + first.operationId(), + first.requestDigest(), + first.sourceOperationId(), + first.sourceEvidenceDigest(), + first.receiptDigest(), + "request-7", + FULL_REQUEST_DIGEST, + 9L, + request.publishWorkflowId()); + assertNoStateChange( + canonicalTenantId, + GAME_DESIGN_VERSION_A, + () -> + ownerTransaction() + .execute( + status -> + repository.claimFreeze( + changedCanonicalVersion, () -> SYNTHETIC_CHECKPOINT))); + + String changedSelectorWorkflow = + PublicationDigestRequestBinding.full( + canonicalTenantId.toString(), Long.toString(GAME_DESIGN_VERSION_B), "request-7") + .derivedWorkflowIdentity(); + WorldDesignPublicationFenceEvidence changedGameDesignSelector = + new WorldDesignPublicationFenceEvidence( + NAMESPACE, + canonicalTenantId, + identity.canonicalVersionId(), + identity.operationId(), + GAME_DESIGN_VERSION_B, + first.intakeRequestId(), + first.operationId(), + first.requestDigest(), + first.sourceOperationId(), + first.sourceEvidenceDigest(), + first.receiptDigest(), + "request-7", + FULL_REQUEST_DIGEST, + 9L, + changedSelectorWorkflow); + assertNoStateChange( + canonicalTenantId, + GAME_DESIGN_VERSION_A, + () -> + ownerTransaction() + .execute( + status -> + repository.claimFreeze( + changedGameDesignSelector, () -> SYNTHETIC_CHECKPOINT))); + + WorldDesignPublicationFenceEvidence changedRequest = + evidence(first, "request-8", GAME_DESIGN_VERSION_A, 9L); + assertNoStateChange( + canonicalTenantId, + GAME_DESIGN_VERSION_A, + () -> + ownerTransaction() + .execute( + status -> repository.claimFreeze(changedRequest, () -> SYNTHETIC_CHECKPOINT))); + + WorldDesignPublicationFenceEvidence changedEpoch = + evidence(first, "request-7", GAME_DESIGN_VERSION_A, 10L); + assertNoStateChange( + canonicalTenantId, + GAME_DESIGN_VERSION_A, + () -> + ownerTransaction() + .execute( + status -> repository.claimFreeze(changedEpoch, () -> SYNTHETIC_CHECKPOINT))); + + WorldDesignPublicationFenceEvidence changedDigest = + evidence( + first, + "request-7", + GAME_DESIGN_VERSION_A, + 9L, + "0".repeat(64), + request.publishWorkflowId()); + assertNoStateChange( + canonicalTenantId, + GAME_DESIGN_VERSION_A, + () -> + ownerTransaction() + .execute( + status -> repository.claimFreeze(changedDigest, () -> SYNTHETIC_CHECKPOINT))); + assertThatThrownBy(() -> repository.readAttempt(changedDigest)) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); + + assertThat(repository.readAttempt(request)).contains(frozen); + assertThatThrownBy( + () -> + evidence( + first, + "request-7", + GAME_DESIGN_VERSION_A, + 9L, + "F".repeat(64), + request.publishWorkflowId())) + .isInstanceOf(IllegalArgumentException.class); + + WorldAuthoredSourceIntakeReceipt missingCheckpointReceipt = + intake(UUID.randomUUID(), "uncheckpointed-world"); + WorldDesignPublicationFenceEvidence missingCheckpointRequest = + evidence(missingCheckpointReceipt, "request-missing-checkpoint", GAME_DESIGN_VERSION_B, 1L); + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> repository.claimFreeze(missingCheckpointRequest, () -> null))) + .isInstanceOf(NullPointerException.class); + assertThat(ownerCount(missingCheckpointReceipt.canonicalTenantId(), GAME_DESIGN_VERSION_B)) + .isZero(); + assertThat(ownerPhase(canonicalTenantId, GAME_DESIGN_VERSION_A)).isEqualTo("FROZEN"); + assertThat(attemptCount(canonicalTenantId, GAME_DESIGN_VERSION_A)).isEqualTo(1L); + } + + private void assertNoStateChange( + UUID canonicalTenantId, long gameDesignVersionId, Runnable action) { + long ownersBefore = ownerCount(canonicalTenantId, gameDesignVersionId); + long attemptsBefore = attemptCount(canonicalTenantId, gameDesignVersionId); + String phaseBefore = ownerPhase(canonicalTenantId, gameDesignVersionId); + assertThatThrownBy(action::run) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); + assertThat(ownerCount(canonicalTenantId, gameDesignVersionId)).isEqualTo(ownersBefore); + assertThat(attemptCount(canonicalTenantId, gameDesignVersionId)).isEqualTo(attemptsBefore); + assertThat(ownerPhase(canonicalTenantId, gameDesignVersionId)).isEqualTo(phaseBefore); + } + + private WorldAuthoredSourceIntakeReceipt intake(UUID tenantId, String worldSlug) { + return intake( + tenantId, + worldSlug, + "tenant-" + tenantId.toString().replace("-", ""), + sourceRowId(tenantId)); + } + + private WorldAuthoredSourceIntakeReceipt intake( + UUID tenantId, String worldSlug, String tenantSlug, long sourceRowId) { + UUID requestId = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = source(tenantId, tenantSlug, worldSlug, sourceRowId); + return ownerTransaction() + .execute(status -> intakeRepository.acceptFresh(NAMESPACE, requestId, source)); + } + + private AuthoredWorldSourceEvidence source( + UUID tenantId, String tenantSlug, String worldSlug, long sourceRowId) { + UUID registrationRequestId = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + String displayName = "Synthetic authored world"; + String sourceTenantKey = "gd-row-" + sourceRowId; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequestId, tenantId, tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceRowId, + sourceTenantKey, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceRowId, + sourceTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private WorldDesignPublicationFenceEvidence evidence( + WorldAuthoredSourceIntakeReceipt receipt, + String publishRequestId, + long gameDesignVersionId, + long versionStateEpoch) { + WorldAuthoredVersionIdentityReceipt identity = identity(receipt, gameDesignVersionId); + return evidence( + receipt.canonicalTenantId(), + receipt, + publishRequestId, + identity, + gameDesignVersionId, + versionStateEpoch, + PublicationDigestRequestBinding.full( + receipt.canonicalTenantId().toString(), + Long.toString(gameDesignVersionId), + publishRequestId)); + } + + private OwnerBinding ownerBinding( + WorldAuthoredSourceIntakeReceipt receipt, long gameDesignVersionId) { + WorldAuthoredVersionIdentityReceipt identity = identity(receipt, gameDesignVersionId); + return new OwnerBinding( + NAMESPACE, + receipt.canonicalTenantId(), + identity.canonicalVersionId(), + identity.operationId(), + gameDesignVersionId, + receipt.intakeRequestId(), + receipt.operationId(), + receipt.requestDigest(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + receipt.receiptDigest()); + } + + private static long localVersionKey(WorldAuthoredVersionIdentityReceipt identity) { + return identity.localVersionKey(); + } + + private WorldDesignPublicationFenceEvidence evidence( + UUID tenantId, + WorldAuthoredSourceIntakeReceipt receipt, + String publishRequestId, + WorldAuthoredVersionIdentityReceipt identity, + long gameDesignVersionId, + long versionStateEpoch, + PublicationDigestRequestBinding binding) { + return new WorldDesignPublicationFenceEvidence( + NAMESPACE, + tenantId, + identity.canonicalVersionId(), + identity.operationId(), + gameDesignVersionId, + receipt.intakeRequestId(), + receipt.operationId(), + receipt.requestDigest(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + receipt.receiptDigest(), + publishRequestId, + FULL_REQUEST_DIGEST, + versionStateEpoch, + binding.derivedWorkflowIdentity()); + } + + private WorldDesignPublicationFenceEvidence evidence( + WorldAuthoredSourceIntakeReceipt receipt, + String publishRequestId, + long gameDesignVersionId, + long versionStateEpoch, + String requestDigest, + String workflowId) { + WorldAuthoredVersionIdentityReceipt identity = identity(receipt, gameDesignVersionId); + return new WorldDesignPublicationFenceEvidence( + NAMESPACE, + receipt.canonicalTenantId(), + identity.canonicalVersionId(), + identity.operationId(), + gameDesignVersionId, + receipt.intakeRequestId(), + receipt.operationId(), + receipt.requestDigest(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + receipt.receiptDigest(), + publishRequestId, + requestDigest, + versionStateEpoch, + workflowId); + } + + private WorldAuthoredVersionIdentityReceipt identity( + WorldAuthoredSourceIntakeReceipt receipt, long gameDesignVersionId) { + UUID canonicalVersionId = stableId("canonical-version", receipt, gameDesignVersionId); + UUID readRequestId = stableId("version-state-read", receipt, gameDesignVersionId); + AuthoredWorldVersionStateEvidence.Request stateRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + readRequestId, + receipt.canonicalTenantId(), + receipt.worldSlug(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + gameDesignVersionId); + AuthoredWorldVersionStateEvidence stateEvidence = + AuthoredWorldVersionStateEvidence.create( + stateRequest, + receipt.source(), + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 1L); + return ownerTransaction() + .execute( + status -> + new WorldAuthoredVersionIdentityRepository(dsl) + .acceptFresh(receipt, stateEvidence)); + } + + private static UUID stableId( + String domain, WorldAuthoredSourceIntakeReceipt receipt, long gameDesignVersionId) { + return UUID.nameUUIDFromBytes( + (domain + ":" + receipt.operationId() + ":" + Long.toString(gameDesignVersionId)) + .getBytes(StandardCharsets.UTF_8)); + } + + private TransactionTemplate ownerTransaction() { + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setReadOnly(false); + return transaction; + } + + private long ownerCount(UUID tenantId, long gameDesignVersionId) { + return count( + "SELECT COUNT(*) FROM world_design_publication_fence_owner fence_owner " + + "JOIN world_authored_version_identity version_identity " + + "ON version_identity.target_namespace = fence_owner.target_namespace " + + "AND version_identity.canonical_tenant_id = fence_owner.canonical_tenant_id " + + "AND version_identity.local_version_key = fence_owner.version_id " + + "WHERE fence_owner.canonical_tenant_id = ? " + + "AND version_identity.game_design_version_id = ?", + tenantId, + gameDesignVersionId); + } + + private long attemptCount(UUID tenantId, long gameDesignVersionId) { + return count( + "SELECT COUNT(*) FROM world_design_publication_fence_attempt fence_attempt " + + "JOIN world_authored_version_identity version_identity " + + "ON version_identity.target_namespace = fence_attempt.target_namespace " + + "AND version_identity.canonical_tenant_id = fence_attempt.canonical_tenant_id " + + "AND version_identity.local_version_key = fence_attempt.version_id " + + "WHERE fence_attempt.canonical_tenant_id = ? " + + "AND version_identity.game_design_version_id = ?", + tenantId, + gameDesignVersionId); + } + + private String ownerPhase(UUID tenantId, long gameDesignVersionId) { + var row = + dsl.fetchOne( + "SELECT CASE WHEN COUNT(*) = 0 THEN NULL " + + "WHEN BOOL_AND(fence_owner.owner_freeze_phase = 'OPEN') THEN 'OPEN' " + + "WHEN BOOL_AND(fence_owner.owner_freeze_phase = 'FROZEN') THEN 'FROZEN' " + + "ELSE 'MIXED' END " + + "FROM world_design_publication_fence_owner fence_owner " + + "JOIN world_authored_version_identity version_identity " + + "ON version_identity.target_namespace = fence_owner.target_namespace " + + "AND version_identity.canonical_tenant_id = fence_owner.canonical_tenant_id " + + "AND version_identity.local_version_key = fence_owner.version_id " + + "WHERE fence_owner.canonical_tenant_id = ? " + + "AND version_identity.game_design_version_id = ?", + tenantId, + gameDesignVersionId); + if (row == null) { + throw new IllegalStateException("World publication-fence owner phase query returned no row"); + } + return row.get(0, String.class); + } + + private long count(String sql, UUID tenantId, long gameDesignVersionId) { + return Objects.requireNonNull(dsl.fetchOne(sql, tenantId, gameDesignVersionId)) + .get(0, Long.class); + } + + private void awaitOwnerRowLockWait() { + long deadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < deadlineNanos) { + var waiterRow = + dsl.fetchOne( + "SELECT COUNT(*) FROM pg_stat_activity WHERE datname = current_database() " + + "AND wait_event_type = 'Lock' AND lower(query) " + + "LIKE '%world_design_publication_fence_owner%'"); + if (waiterRow == null) { + throw new IllegalStateException("PostgreSQL owner-row waiter query returned no row"); + } + Long waiters = waiterRow.get(0, Long.class); + if (waiters != null && waiters > 0L) { + return; + } + pauseBriefly(); + } + throw new IllegalStateException("No PostgreSQL waiter was observed on the World owner row"); + } + + private void assertDatabaseTriggerRejects(Runnable action, String expectedTriggerMessage) { + RuntimeException failure = null; + try { + action.run(); + } catch (RuntimeException exception) { + failure = exception; + } + assertThat(failure).isInstanceOf(DataAccessException.class); + + SQLException sqlException = null; + Throwable cause = failure; + while (cause != null) { + if (cause instanceof SQLException) { + sqlException = (SQLException) cause; + } + cause = cause.getCause(); + } + assertThat((Throwable) sqlException).isNotNull(); + assertThat(sqlException.getSQLState()).isEqualTo("55000"); + assertThat(sqlException.getMessage()).contains(expectedTriggerMessage); + } + + private long sourceRowId(UUID tenantId) { + long positive = tenantId.getLeastSignificantBits() & Long.MAX_VALUE; + return positive == 0L ? 1L : positive; + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for the publication-fence test gate"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Publication-fence test was interrupted", exception); + } + } + + private static void pauseBriefly() { + try { + TimeUnit.MILLISECONDS.sleep(25); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Publication-fence test wait was interrupted", exception); + } + } + + private static final class ForcedRollbackException extends RuntimeException {} +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldPublicationOwnerBindingMigrationIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldPublicationOwnerBindingMigrationIntegrationTest.java new file mode 100644 index 0000000000..1f25708190 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldPublicationOwnerBindingMigrationIntegrationTest.java @@ -0,0 +1,411 @@ +package net.firedevops.firemud.worldmanagement; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.junit.jupiter.api.Test; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class WorldPublicationOwnerBindingMigrationIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final String DIGEST = "a".repeat(64); + private static final String REQUEST_DIGEST = "sha256:" + DIGEST; + private static final long GAME_DESIGN_VERSION_ID = 9_000_000_042L; + private static final String WORKFLOW_ID_PREFIX = "publish:"; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void freshV27PointOneMigrationAcceptsOnlyExactVersionIdentityBindings() throws SQLException { + String schema = newSchema("world_publication_owner_fresh_"); + try { + migrateFixture(schema, MigrationVersion.fromVersion("27.1")); + try (Connection connection = fixtureConnection(schema)) { + Fixture fixture = seedOwnerBindingData(connection); + insertAttempt( + connection, + fixture, + "fresh-exact", + 1, + fixture.versionIdentityOperationId(), + fixture.canonicalVersionId(), + GAME_DESIGN_VERSION_ID, + REQUEST_DIGEST); + + assertRejected( + connection, + () -> + insertAttempt( + connection, + fixture, + "fresh-incomplete", + 1, + fixture.versionIdentityOperationId(), + null, + GAME_DESIGN_VERSION_ID, + REQUEST_DIGEST), + "23514"); + assertRejected( + connection, + () -> + insertAttempt( + connection, + fixture, + "fresh-unknown-schema", + 2, + fixture.versionIdentityOperationId(), + fixture.canonicalVersionId(), + GAME_DESIGN_VERSION_ID, + REQUEST_DIGEST), + "23514"); + assertRejected( + connection, + () -> + insertAttempt( + connection, + fixture, + "fresh-cross-bound", + 1, + fixture.versionIdentityOperationId(), + fixture.canonicalVersionId(), + GAME_DESIGN_VERSION_ID + 1, + REQUEST_DIGEST), + "23503"); + } + } finally { + dropFixtureSchema(schema); + } + } + + @Test + void v27UpgradeRetainsAttemptsAsSchemaZeroWithoutInferringIdentity() throws SQLException { + String schema = newSchema("world_publication_owner_v27_"); + UUID legacyFence = UUID.randomUUID(); + try { + migrateFixture(schema, MigrationVersion.fromVersion("27")); + try (Connection connection = fixtureConnection(schema)) { + Fixture fixture = seedOwnerBindingData(connection); + assertThat(fixture.localVersionKey()).isNotEqualTo(GAME_DESIGN_VERSION_ID); + insertLegacyAttempt(connection, fixture, legacyFence); + } + + migrateFixture(schema, MigrationVersion.fromVersion("27.1")); + + try (Connection connection = fixtureConnection(schema)) { + try (PreparedStatement statement = + connection.prepareStatement( + "SELECT owner_binding_schema_version, canonical_version_id, " + + "version_identity_operation_id, game_design_version_id, " + + "intake_request_digest, version_id FROM world_design_publication_fence_attempt " + + "WHERE publication_fence = ?")) { + statement.setObject(1, legacyFence); + try (ResultSet result = statement.executeQuery()) { + assertThat(result.next()).isTrue(); + assertThat(result.getShort("owner_binding_schema_version")).isZero(); + assertThat(result.getObject("canonical_version_id")).isNull(); + assertThat(result.getObject("version_identity_operation_id")).isNull(); + assertThat(result.getObject("game_design_version_id")).isNull(); + assertThat(result.getString("intake_request_digest")).isNull(); + assertThat(result.getLong("version_id")).isEqualTo(GAME_DESIGN_VERSION_ID); + assertThat(result.next()).isFalse(); + } + } + + assertRejected( + connection, () -> updateLegacyAttemptBinding(connection, legacyFence), "55000"); + } + } finally { + dropFixtureSchema(schema); + } + } + + private static Fixture seedOwnerBindingData(Connection connection) throws SQLException { + UUID canonicalTenantId = UUID.randomUUID(); + UUID intakeOperationId = UUID.randomUUID(); + UUID intakeRequestId = UUID.randomUUID(); + UUID sourceRegistrationRequestId = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + UUID canonicalVersionId = UUID.randomUUID(); + UUID versionIdentityOperationId = UUID.randomUUID(); + long localTenantKey = 7_001L; + String tenantSlug = "tenant-" + canonicalTenantId.toString().replace("-", ""); + String worldSlug = "migration-proof-world"; + + try (PreparedStatement statement = + connection.prepareStatement( + "INSERT INTO world_authored_source_tenant_association " + + "(target_namespace, canonical_tenant_id, tenant_slug, source_game_row_id, " + + "source_game_tenant_key, source_provenance_kind, local_tenant_key) " + + "VALUES (?, ?, ?, 77, 'migration-proof-source', 'NEW_GAME_ROW', ?)")) { + statement.setString(1, NAMESPACE); + statement.setObject(2, canonicalTenantId); + statement.setString(3, tenantSlug); + statement.setLong(4, localTenantKey); + statement.executeUpdate(); + } + try (PreparedStatement statement = + connection.prepareStatement( + "INSERT INTO world_authored_source_tenant_key_reservation " + + "(tenant_key, claim_kind, target_namespace, canonical_tenant_id) " + + "VALUES (?, 'CANONICAL_AUTHORED_SOURCE', ?, ?)")) { + statement.setLong(1, localTenantKey); + statement.setString(2, NAMESPACE); + statement.setObject(3, canonicalTenantId); + statement.executeUpdate(); + } + try (PreparedStatement statement = + connection.prepareStatement( + "INSERT INTO world_authored_source_intake (operation_id, schema_version, " + + "target_namespace, intake_request_id, request_digest, local_tenant_key, " + + "source_schema_version, source_registration_request_id, source_operation_id, " + + "source_request_digest, canonical_tenant_id, tenant_slug, world_slug, " + + "world_display_name, source_game_row_id, source_game_tenant_key, " + + "source_provenance_kind, source_evidence_digest, receipt_digest) " + + "VALUES (?, 1, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, 'Migration proof', 77, " + + "'migration-proof-source', 'NEW_GAME_ROW', ?, ?)")) { + statement.setObject(1, intakeOperationId); + statement.setString(2, NAMESPACE); + statement.setObject(3, intakeRequestId); + statement.setString(4, REQUEST_DIGEST); + statement.setLong(5, localTenantKey); + statement.setObject(6, sourceRegistrationRequestId); + statement.setObject(7, sourceOperationId); + statement.setString(8, REQUEST_DIGEST); + statement.setObject(9, canonicalTenantId); + statement.setString(10, tenantSlug); + statement.setString(11, worldSlug); + statement.setString(12, REQUEST_DIGEST); + statement.setString(13, REQUEST_DIGEST); + statement.executeUpdate(); + } + + long localVersionKey; + try (PreparedStatement statement = + connection.prepareStatement( + "INSERT INTO world_authored_version_identity (operation_id, target_namespace, " + + "canonical_tenant_id, world_slug, canonical_version_id, game_design_version_id, " + + "intake_operation_id, intake_request_id, local_tenant_key, intake_request_digest, " + + "source_operation_id, source_evidence_digest, intake_receipt_digest, " + + "version_state_schema_version, version_state_read_request_id, " + + "version_state_state, version_state_epoch, version_state_evidence_digest, " + + "version_state_evidence_json) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, 'PUBLISHED', 1, ?, '{}') " + + "RETURNING local_version_key")) { + statement.setObject(1, versionIdentityOperationId); + statement.setString(2, NAMESPACE); + statement.setObject(3, canonicalTenantId); + statement.setString(4, worldSlug); + statement.setObject(5, canonicalVersionId); + statement.setLong(6, GAME_DESIGN_VERSION_ID); + statement.setObject(7, intakeOperationId); + statement.setObject(8, intakeRequestId); + statement.setLong(9, localTenantKey); + statement.setString(10, REQUEST_DIGEST); + statement.setObject(11, sourceOperationId); + statement.setString(12, REQUEST_DIGEST); + statement.setString(13, REQUEST_DIGEST); + statement.setObject(14, UUID.randomUUID()); + statement.setString(15, REQUEST_DIGEST); + try (ResultSet result = statement.executeQuery()) { + assertThat(result.next()).isTrue(); + localVersionKey = result.getLong(1); + } + } + + return new Fixture( + canonicalTenantId, + localTenantKey, + intakeOperationId, + intakeRequestId, + sourceOperationId, + canonicalVersionId, + versionIdentityOperationId, + localVersionKey); + } + + private static void insertLegacyAttempt( + Connection connection, Fixture fixture, UUID publicationFence) throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement( + "INSERT INTO world_design_publication_fence_attempt (publication_fence, " + + "target_namespace, canonical_tenant_id, local_tenant_key, version_id, " + + "intake_operation_id, intake_request_id, source_operation_id, " + + "source_evidence_digest, intake_receipt_digest, publication_request_id, " + + "request_digest, version_state_epoch, publish_workflow_id, applied_commit_id, " + + "content_digest, digest_schema_version) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")) { + bindCommonAttempt( + statement, + fixture, + publicationFence, + GAME_DESIGN_VERSION_ID, + "legacy-request", + "legacy-commit"); + statement.executeUpdate(); + } + } + + private static void insertAttempt( + Connection connection, + Fixture fixture, + String publicationRequestId, + int ownerBindingSchemaVersion, + UUID versionIdentityOperationId, + UUID canonicalVersionId, + long gameDesignVersionId, + String intakeRequestDigest) + throws SQLException { + String sql = + "INSERT INTO world_design_publication_fence_attempt (publication_fence, " + + "target_namespace, canonical_tenant_id, local_tenant_key, version_id, " + + "intake_operation_id, intake_request_id, source_operation_id, " + + "source_evidence_digest, intake_receipt_digest, publication_request_id, " + + "request_digest, version_state_epoch, publish_workflow_id, applied_commit_id, " + + "content_digest, digest_schema_version, owner_binding_schema_version, " + + "canonical_version_id, version_identity_operation_id, game_design_version_id, " + + "intake_request_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + + "?, ?, ?, ?, ?, ?)"; + try (PreparedStatement statement = connection.prepareStatement(sql)) { + UUID fence = UUID.randomUUID(); + bindCommonAttempt( + statement, + fixture, + fence, + fixture.localVersionKey(), + publicationRequestId, + "bound-commit"); + statement.setInt(18, ownerBindingSchemaVersion); + statement.setObject(19, canonicalVersionId); + statement.setObject(20, versionIdentityOperationId); + if (gameDesignVersionId > 0L) { + statement.setLong(21, gameDesignVersionId); + } else { + statement.setNull(21, java.sql.Types.BIGINT); + } + statement.setString(22, intakeRequestDigest); + statement.executeUpdate(); + } + } + + private static void bindCommonAttempt( + PreparedStatement statement, + Fixture fixture, + UUID publicationFence, + long versionId, + String publicationRequestId, + String commitId) + throws SQLException { + statement.setObject(1, publicationFence); + statement.setString(2, NAMESPACE); + statement.setObject(3, fixture.canonicalTenantId()); + statement.setLong(4, fixture.localTenantKey()); + statement.setLong(5, versionId); + statement.setObject(6, fixture.intakeOperationId()); + statement.setObject(7, fixture.intakeRequestId()); + statement.setObject(8, fixture.sourceOperationId()); + statement.setString(9, REQUEST_DIGEST); + statement.setString(10, REQUEST_DIGEST); + statement.setString(11, publicationRequestId); + statement.setString(12, DIGEST); + statement.setLong(13, 1L); + statement.setString( + 14, + WORKFLOW_ID_PREFIX + + fixture.canonicalTenantId() + + ":publish-request:" + + publicationRequestId); + statement.setString(15, commitId); + statement.setString(16, DIGEST); + statement.setInt(17, 3); + } + + private static void assertRejected( + Connection connection, SqlAction action, String expectedSqlState) throws SQLException { + try { + action.run(); + } catch (SQLException exception) { + assertThat(exception.getSQLState()).isEqualTo(expectedSqlState); + return; + } + throw new AssertionError("Expected PostgreSQL SQLSTATE " + expectedSqlState); + } + + private static void updateLegacyAttemptBinding(Connection connection, UUID legacyFence) + throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement( + "UPDATE world_design_publication_fence_attempt " + + "SET owner_binding_schema_version = 1, canonical_version_id = " + + "'11111111-1111-4111-8111-111111111111'::uuid " + + "WHERE publication_fence = ?")) { + statement.setObject(1, legacyFence); + statement.executeUpdate(); + } + } + + private static void migrateFixture(String schema, MigrationVersion target) { + var configuration = + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private static Connection fixtureConnection(String schema) throws SQLException { + Connection connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + connection.setSchema(schema); + return connection; + } + + private static String newSchema(String prefix) { + return prefix + UUID.randomUUID().toString().replace("-", ""); + } + + private static void dropFixtureSchema(String schema) throws SQLException { + try (Connection connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + Statement statement = connection.createStatement()) { + statement.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } + } + + private record Fixture( + UUID canonicalTenantId, + long localTenantKey, + UUID intakeOperationId, + UUID intakeRequestId, + UUID sourceOperationId, + UUID canonicalVersionId, + UUID versionIdentityOperationId, + long localVersionKey) {} + + @FunctionalInterface + private interface SqlAction { + void run() throws SQLException; + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java index efe6e396fb..61d587427a 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import io.grpc.Context; import io.grpc.stub.StreamObserver; @@ -23,7 +24,6 @@ import net.firedevops.firemud.worldmanagement.dto.InitialAdmissionBindHoldDto; import net.firedevops.firemud.worldmanagement.dto.RoomSnapshotDto; import net.firedevops.firemud.worldmanagement.dto.RuntimeRoomDto; -import net.firedevops.firemud.worldmanagement.dto.WorldDesignMutationResultDto; import net.firedevops.firemud.worldmanagement.dto.WorldInstanceLifecycleSnapshotDto; import net.firedevops.firemud.worldmanagement.service.InitialAdmissionBindHoldService; import net.firedevops.firemud.worldmanagement.service.PingService; @@ -51,7 +51,6 @@ import net.firedevops.firemud.worldmanagement.v1.ValidateWorldUpgradeMappingsResponse; import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; -import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationResult; import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; @@ -122,6 +121,56 @@ private static GetDraftDesignDigestResponse invokeDigestWithPeer( return ref.get(); } + private static ApplyWorldDesignMutationResponse invokeMutation( + WorldManagementGrpcService service, ApplyWorldDesignMutationRequest request) { + AtomicReference ref = new AtomicReference<>(); + service.applyWorldDesignMutation( + request, + new StreamObserver<>() { + @Override + public void onNext(ApplyWorldDesignMutationResponse value) { + ref.set(value); + } + + @Override + public void onError(Throwable t) { + throw new AssertionError("Draft mutation RPC failed", t); + } + + @Override + public void onCompleted() {} + }); + return ref.get(); + } + + private static ApplyWorldDesignMutationRequest draftMutation(String tenantId) { + return ApplyWorldDesignMutationRequest.newBuilder() + .setTenantId(tenantId) + .setVersionId("7") + .setCommitId("commit-1") + .setRevisionId("revision-1") + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId("44") + .setRegion(RegionDesignMutation.newBuilder().setName("North").build()) + .build(); + } + + private static void assertDraftMutationUnavailable(ApplyWorldDesignMutationResponse response) { + assertNotNull(response); + assertEquals("FAILED_PRECONDITION", response.getError().getCode()); + assertEquals( + "Complete Draft caller/tenant authorization and owner publication proof are unavailable.", + response.getError().getMessage()); + assertEquals(1, response.getAllFields().size()); + assertTrue( + response + .getAllFields() + .containsKey( + ApplyWorldDesignMutationResponse.getDescriptor().findFieldByName("error"))); + } + private static AcquireInitialAdmissionBindHoldResponse invokeInitialBindAcquire( WorldManagementGrpcService service, AcquireInitialAdmissionBindHoldRequest request) { AtomicReference ref = new AtomicReference<>(); @@ -587,112 +636,53 @@ void getDraftDesignDigestRejectsOwnerTenantMismatch() { } @Test - void applyWorldDesignMutationReturnsTypedResult() { - PingService pingService = Mockito.mock(PingService.class); - RoomService roomService = Mockito.mock(RoomService.class); - WorldDraftDesignDigestService digestService = Mockito.mock(WorldDraftDesignDigestService.class); + void applyWorldDesignMutationFailsClosedBeforeOwnerReadsOrMutation() { WorldDesignMutationService mutationService = Mockito.mock(WorldDesignMutationService.class); - MeterRegistry meterRegistry = new SimpleMeterRegistry(); - Mockito.when(mutationService.applyMutation(Mockito.any())) - .thenReturn(new WorldDesignMutationResultDto("APPLIED", 1L, 7L, 44L, 1L, null)); - SessionContext.setContext( - "test-account", List.of(), Map.of(), true, "game-session-service", "test-instance"); WorldManagementGrpcService service = new WorldManagementGrpcService( - pingService, - roomService, + Mockito.mock(PingService.class), + Mockito.mock(RoomService.class), Mockito.mock(WorldInstanceActivationService.class), - digestService, + Mockito.mock(WorldDraftDesignDigestService.class), mutationService, Mockito.mock(WorldUpgradeValidationService.class), Mockito.mock(GameplaySessionAttestationService.class), - meterRegistry, + new SimpleMeterRegistry(), new ObjectMapper(), (PublicationReadGuard) null); - AtomicReference ref = new AtomicReference<>(); - service.applyWorldDesignMutation( - ApplyWorldDesignMutationRequest.newBuilder() - .setTenantId("1") - .setVersionId("7") - .setCommitId("commit-1") - .setRevisionId("revision-1") - .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) - .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) - .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) - .setScopeId("44") - .setRegion(RegionDesignMutation.newBuilder().setName("North").build()) - .build(), - new StreamObserver<>() { - @Override - public void onNext(ApplyWorldDesignMutationResponse value) { - ref.set(value); - } + SessionContext.clear(); + assertDraftMutationUnavailable(invokeMutation(service, draftMutation("42"))); - @Override - public void onError(Throwable t) {} + AtomicReference gameDesignResponse = new AtomicReference<>(); + runWithPeer( + peer("game-design-service"), + () -> gameDesignResponse.set(invokeMutation(service, draftMutation("42")))); + assertDraftMutationUnavailable(gameDesignResponse.get()); - @Override - public void onCompleted() {} - }); + AtomicReference otherWorkloadResponse = + new AtomicReference<>(); + runWithPeer( + peer("account-service"), + () -> otherWorkloadResponse.set(invokeMutation(service, draftMutation("42")))); + assertDraftMutationUnavailable(otherWorkloadResponse.get()); - assertEquals( - WorldDesignMutationResult.WORLD_DESIGN_MUTATION_RESULT_APPLIED, ref.get().getResult()); - assertEquals("44", ref.get().getAggregateId()); - assertEquals(1L, ref.get().getDraftRevisionEpoch()); - } + AtomicReference crossTenantResponse = new AtomicReference<>(); + runWithPeer( + peer("game-design-service"), + () -> crossTenantResponse.set(invokeMutation(service, draftMutation("84")))); + assertDraftMutationUnavailable(crossTenantResponse.get()); - @Test - void applyWorldDesignMutationRejectsZeroVersionIdBeforeMutation() { - PingService pingService = Mockito.mock(PingService.class); - RoomService roomService = Mockito.mock(RoomService.class); - WorldDraftDesignDigestService digestService = Mockito.mock(WorldDraftDesignDigestService.class); - WorldDesignMutationService mutationService = Mockito.mock(WorldDesignMutationService.class); - MeterRegistry meterRegistry = new SimpleMeterRegistry(); SessionContext.setContext( "test-account", List.of(), Map.of(), true, "game-session-service", "test-instance"); - WorldManagementGrpcService service = - new WorldManagementGrpcService( - pingService, - roomService, - Mockito.mock(WorldInstanceActivationService.class), - digestService, - mutationService, - Mockito.mock(WorldUpgradeValidationService.class), - Mockito.mock(GameplaySessionAttestationService.class), - meterRegistry, - new ObjectMapper(), - (PublicationReadGuard) null); - - AtomicReference ref = new AtomicReference<>(); - service.applyWorldDesignMutation( - ApplyWorldDesignMutationRequest.newBuilder() - .setTenantId("1") - .setVersionId("0") - .setCommitId("commit-1") - .setRevisionId("revision-1") - .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) - .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) - .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) - .setScopeId("44") - .setRegion(RegionDesignMutation.newBuilder().setName("North").build()) - .build(), - new StreamObserver<>() { - @Override - public void onNext(ApplyWorldDesignMutationResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); + AtomicReference gameSessionResponse = new AtomicReference<>(); + runWithPeer( + peer("game-session-service"), + () -> gameSessionResponse.set(invokeMutation(service, draftMutation("42")))); + assertDraftMutationUnavailable(gameSessionResponse.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("versionId must be positive", ref.get().getError().getMessage()); Mockito.verifyNoInteractions(mutationService); + SessionContext.clear(); } @Test diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeDigestTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeDigestTest.java new file mode 100644 index 0000000000..3231c170f7 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeDigestTest.java @@ -0,0 +1,131 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import org.junit.jupiter.api.Test; + +class WorldAuthoredSourceIntakeDigestTest { + private static final String NAMESPACE = "firemud"; + private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID REGISTRATION = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID SOURCE_OPERATION = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID INTAKE_REQUEST = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID WORLD_OPERATION = + UUID.fromString("55555555-5555-4555-8555-555555555555"); + + @Test + void emitsSharedUnicodeAndFramingVectorsForCompleteSourceAndPrivateAssociation() { + AuthoredWorldSourceEvidence source = source("violet-wilds", "Café 🐉", "NEW_GAME_ROW"); + + assertThat(source.requestDigest()) + .isEqualTo("sha256:2f2e50fd98aede5418d7b52b8c837e12b092edd4044624b4047d21123cb35ba3"); + assertThat(source.evidenceDigest()) + .isEqualTo("sha256:0084bd312cf3c13540d453c6a1e173b6b8ef5436a57a55db3363e2cd6879cbda"); + String requestDigest = + WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, INTAKE_REQUEST, source); + assertThat(requestDigest) + .isEqualTo("sha256:1946ce9cb46af17732c4ec06445d7d9e297ac9bc22e30e7dde2858f9e1626c1f"); + assertThat( + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, WORLD_OPERATION, requestDigest, source, 9001L)) + .isEqualTo("sha256:7d0ab0104385d80e5a2bc1f72386ca09b50473d262a0389840a90136a4778fb7"); + } + + @Test + void requestAndReceiptDigestsBindEveryLocalScopeAndAllocationInput() { + AuthoredWorldSourceEvidence source = source("violet-wilds", "Café 🐉", "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence changedWorld = source("amber-coast", "Café 🐉", "NEW_GAME_ROW"); + String request = + WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, INTAKE_REQUEST, source); + String receipt = + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, WORLD_OPERATION, request, source, 9001L); + + assertThat(WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, WORLD_OPERATION, source)) + .isNotEqualTo(request); + assertThat( + WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, INTAKE_REQUEST, changedWorld)) + .isNotEqualTo(request); + assertThat( + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, UUID.randomUUID(), request, source, 9001L)) + .isNotEqualTo(receipt); + assertThat( + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, WORLD_OPERATION, request, source, 9002L)) + .isNotEqualTo(receipt); + } + + @Test + void rejectsNilMalformedMismatchedAndRetainedInputs() { + AuthoredWorldSourceEvidence fresh = source("violet-wilds", "A world", "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence retained = source("violet-wilds", "A world", "RETAINED_GAME_V29"); + + assertThatThrownBy( + () -> WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, new UUID(0L, 0L), fresh)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldAuthoredSourceIntakeDigest.requestDigest( + "other-namespace", INTAKE_REQUEST, fresh)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, INTAKE_REQUEST, retained)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, WORLD_OPERATION, "sha256:bad", fresh, 9001L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, + WORLD_OPERATION, + WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, INTAKE_REQUEST, fresh), + fresh, + 0L)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static AuthoredWorldSourceEvidence source( + String worldSlug, String displayName, String provenanceKind) { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, REGISTRATION, TENANT, "north-star", worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION, + SOURCE_OPERATION, + requestDigest, + TENANT, + "north-star", + worldSlug, + displayName, + 42L, + "legacy-game-tenant-42", + provenanceKind); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + REGISTRATION, + SOURCE_OPERATION, + requestDigest, + TENANT, + "north-star", + worldSlug, + displayName, + 42L, + "legacy-game-tenant-42", + provenanceKind, + evidenceDigest); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcServiceTest.java new file mode 100644 index 0000000000..304ebe79ab --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcServiceTest.java @@ -0,0 +1,719 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.doThrow; +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.UnknownFieldSet; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Context; +import io.grpc.Metadata; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +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.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeByIdRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeByIdResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeResponse; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DataAccessResourceFailureException; + +class WorldAuthoredSourceIntakeGrpcServiceTest { + private static final Metadata.Key UPSTREAM_DETAIL = + Metadata.Key.of("x-upstream-detail", Metadata.ASCII_STRING_MARSHALLER); + private static final String NAMESPACE = "firemud"; + private static final UUID INTAKE_REQUEST_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID READ_REQUEST_ID = + UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID OPERATION_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final String WORLD_SLUG = "violet-wilds"; + private static final String SOURCE_DIGEST = + source(NAMESPACE, TENANT_ID, SOURCE_OPERATION_ID, WORLD_SLUG).evidenceDigest(); + + private final WorldAuthoredSourceIntakeService intakeService = + mock(WorldAuthoredSourceIntakeService.class); + private final WorldAuthoredSourceIntakeGrpcService grpcService = + new WorldAuthoredSourceIntakeGrpcService(intakeService, NAMESPACE); + + @Test + void intakeReturnsOnlyTheExactCommittedReceiptBinding() { + IntakeRequest binding = binding(); + WorldAuthoredSourceIntakeReceipt receipt = receipt(binding, 9001L); + when(intakeService.intake( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST)) + .thenReturn(receipt); + RecordingObserver observer = new RecordingObserver<>(); + + withGameDesign(() -> grpcService.intakeAuthoredWorldSource(intakeRequest(), observer)); + + assertThat(observer.error).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(observer.values).hasSize(1); + IntakeAuthoredWorldSourceResponse response = observer.values.get(0); + CommittedReceipt decoded = + WorldAuthoredSourceIntakeGrpcCodec.fromIntakeResponse(binding, response); + assertThat(decoded.operationId()).isEqualTo(OPERATION_ID); + assertThat(decoded.requestDigest()) + .isEqualTo(WorldAuthoredSourceIntakeGrpcCodec.requestDigest(binding)); + assertThat(response.getReceiptDigest()).isEqualTo(receipt.receiptDigest()); + assertThat(response.getAllFields().keySet()) + .extracting(field -> field.getName()) + .doesNotContain("local_tenant_key", "localTenantKey"); + verify(intakeService) + .intake( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST); + } + + @Test + void readReturnsCommittedReceiptAndEchoesSeparateRequestIdentity() { + IntakeRequest binding = binding(); + WorldAuthoredSourceIntakeReceipt receipt = receipt(binding, 9001L); + when(intakeService.readCommittedReceipt( + 1, + NAMESPACE, + READ_REQUEST_ID, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST)) + .thenReturn(Optional.of(receipt)); + RecordingObserver observer = new RecordingObserver<>(); + + withGameDesign(() -> grpcService.readAuthoredWorldSourceIntake(readRequest(), observer)); + + assertThat(observer.error).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(observer.values).hasSize(1); + ReadAuthoredWorldSourceIntakeResponse response = observer.values.get(0); + assertThat(response.getRequestId()).isEqualTo(READ_REQUEST_ID.toString()); + assertThat(response.getIntakeRequestId()).isEqualTo(INTAKE_REQUEST_ID.toString()); + CommittedReceipt decoded = + WorldAuthoredSourceIntakeGrpcCodec.fromReadResponse( + new WorldAuthoredSourceIntakeGrpcCodec.ReadRequest(binding, READ_REQUEST_ID), response); + assertThat(decoded.operationId()).isEqualTo(OPERATION_ID); + assertThat(decoded.requestDigest()) + .isEqualTo(WorldAuthoredSourceIntakeGrpcCodec.requestDigest(binding)); + verify(intakeService) + .readCommittedReceipt( + 1, + NAMESPACE, + READ_REQUEST_ID, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST); + } + + @Test + void readByIdReturnsFullPublicReceiptAndExactRequestEcho() { + AuthoredWorldSourceEvidence source = + source(NAMESPACE, TENANT_ID, SOURCE_OPERATION_ID, WORLD_SLUG); + WorldAuthoredSourceIntakeReceipt receipt = receipt(binding(), 9001L); + var request = readByIdRequest(); + when(intakeService.readCommittedReceiptById( + 1, NAMESPACE, READ_REQUEST_ID, INTAKE_REQUEST_ID, TENANT_ID)) + .thenReturn(Optional.of(receipt)); + RecordingObserver observer = + new RecordingObserver<>(); + + withGameDesign(() -> grpcService.readAuthoredWorldSourceIntakeById(request, observer)); + + assertThat(observer.error).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(observer.values).hasSize(1); + var response = observer.values.get(0); + assertThat(response.getReadRequestId()).isEqualTo(READ_REQUEST_ID.toString()); + assertThat(response.getIntakeRequestId()).isEqualTo(INTAKE_REQUEST_ID.toString()); + var decoded = WorldAuthoredSourceIntakeGrpcCodec.fromReadByIdResponse(readById(), response); + assertThat(decoded.source()).isEqualTo(source); + assertThat(decoded.operationId()).isEqualTo(OPERATION_ID); + assertThat(decoded.receiptDigest()).isEqualTo(receipt.receiptDigest()); + assertThat(response.getReceipt().getAllFields().keySet()) + .extracting(field -> field.getName()) + .doesNotContain("local_tenant_key", "localTenantKey", "local_version_key"); + assertThat(response.getReceipt().getSource().getAllFields().keySet()) + .extracting(field -> field.getName()) + .contains("registration_request_id", "source_game_row_id", "source_game_tenant_key"); + verify(intakeService) + .readCommittedReceiptById(1, NAMESPACE, READ_REQUEST_ID, INTAKE_REQUEST_ID, TENANT_ID); + } + + @Test + void readByIdRejectsWrongPeerEndUserContextAndUnknownFieldsBeforeOwnerAccess() { + var request = readByIdRequest(); + RecordingObserver wrongPeer = + new RecordingObserver<>(); + withPeer( + NAMESPACE, + "game-session-service", + () -> grpcService.readAuthoredWorldSourceIntakeById(request, wrongPeer)); + assertThat(Status.fromThrowable(wrongPeer.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + + RecordingObserver userContext = + new RecordingObserver<>(); + SessionContext.setContext("account", List.of(), Map.of()); + try { + withGameDesign(() -> grpcService.readAuthoredWorldSourceIntakeById(request, userContext)); + } finally { + SessionContext.clear(); + } + assertThat(Status.fromThrowable(userContext.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + + RecordingObserver unknown = + new RecordingObserver<>(); + ReadAuthoredWorldSourceIntakeByIdRequest withUnknown = + request.toBuilder().setUnknownFields(unknownField()).build(); + withGameDesign(() -> grpcService.readAuthoredWorldSourceIntakeById(withUnknown, unknown)); + assertThat(Status.fromThrowable(unknown.error).getCode()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + + RecordingObserver wrongNamespace = + new RecordingObserver<>(); + withGameDesign( + () -> + grpcService.readAuthoredWorldSourceIntakeById( + request.toBuilder().setTargetNamespace("other").build(), wrongNamespace)); + assertThat(Status.fromThrowable(wrongNamespace.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + + for (ReadAuthoredWorldSourceIntakeByIdRequest invalidRequest : + List.of( + request.toBuilder().setSchemaVersion(2).build(), + request.toBuilder().setReadRequestId(INTAKE_REQUEST_ID.toString()).build(), + request.toBuilder().setCanonicalTenantId("not-a-canonical-uuid").build())) { + RecordingObserver invalid = + new RecordingObserver<>(); + withGameDesign(() -> grpcService.readAuthoredWorldSourceIntakeById(invalidRequest, invalid)); + assertThat(Status.fromThrowable(invalid.error).getCode()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + } + verifyNoInteractions(intakeService); + } + + @Test + void readByIdReportsMissingAndRejectsSubstitutedTenantReceipt() { + var request = readByIdRequest(); + when(intakeService.readCommittedReceiptById( + 1, NAMESPACE, READ_REQUEST_ID, INTAKE_REQUEST_ID, TENANT_ID)) + .thenReturn(Optional.empty()); + RecordingObserver missing = + new RecordingObserver<>(); + withGameDesign(() -> grpcService.readAuthoredWorldSourceIntakeById(request, missing)); + assertThat(Status.fromThrowable(missing.error).getCode()).isEqualTo(Status.Code.NOT_FOUND); + assertThat(missing.values).isEmpty(); + + UUID otherTenant = UUID.fromString("77777777-7777-4777-8777-777777777777"); + IntakeRequest otherBinding = + new IntakeRequest( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + otherTenant, + WORLD_SLUG, + SOURCE_OPERATION_ID, + source(NAMESPACE, otherTenant, SOURCE_OPERATION_ID, WORLD_SLUG).evidenceDigest()); + when(intakeService.readCommittedReceiptById( + 1, NAMESPACE, READ_REQUEST_ID, INTAKE_REQUEST_ID, TENANT_ID)) + .thenReturn(Optional.of(receipt(otherBinding, 9001L))); + RecordingObserver changed = + new RecordingObserver<>(); + withGameDesign(() -> grpcService.readAuthoredWorldSourceIntakeById(request, changed)); + assertThat(Status.fromThrowable(changed.error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(changed.values).isEmpty(); + } + + @Test + void rejectsUnknownWireFieldsBeforeCallingOwnerService() { + IntakeAuthoredWorldSourceRequest request = + intakeRequest().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + RecordingObserver observer = new RecordingObserver<>(); + + grpcService.intakeAuthoredWorldSource(request, observer); + + assertThat(Status.fromThrowable(observer.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(observer.values).isEmpty(); + assertThat(observer.completed).isFalse(); + verifyNoInteractions(intakeService); + + RecordingObserver invalid = new RecordingObserver<>(); + withGameDesign(() -> grpcService.intakeAuthoredWorldSource(request, invalid)); + assertThat(Status.fromThrowable(invalid.error).getCode()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(invalid.values).isEmpty(); + verifyNoInteractions(intakeService); + + RecordingObserver wrongTargetNamespace = + new RecordingObserver<>(); + IntakeAuthoredWorldSourceRequest crossNamespaceRequest = + intakeRequest().toBuilder().setTargetNamespace("other").build(); + withGameDesign( + () -> grpcService.intakeAuthoredWorldSource(crossNamespaceRequest, wrongTargetNamespace)); + assertThat(Status.fromThrowable(wrongTargetNamespace.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrongTargetNamespace.values).isEmpty(); + verifyNoInteractions(intakeService); + + RecordingObserver wrongWorkload = + new RecordingObserver<>(); + withPeer( + NAMESPACE, + "game-session-service", + () -> grpcService.readAuthoredWorldSourceIntake(readRequest(), wrongWorkload)); + assertThat(Status.fromThrowable(wrongWorkload.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrongWorkload.values).isEmpty(); + verifyNoInteractions(intakeService); + + RecordingObserver wrongNamespace = new RecordingObserver<>(); + withPeer( + "other", + "game-design-service", + () -> grpcService.intakeAuthoredWorldSource(intakeRequest(), wrongNamespace)); + assertThat(Status.fromThrowable(wrongNamespace.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrongNamespace.values).isEmpty(); + verifyNoInteractions(intakeService); + + RecordingObserver wrongReadTargetNamespace = + new RecordingObserver<>(); + ReadAuthoredWorldSourceIntakeRequest crossNamespaceReadRequest = + readRequest().toBuilder().setTargetNamespace("other").build(); + withGameDesign( + () -> + grpcService.readAuthoredWorldSourceIntake( + crossNamespaceReadRequest, wrongReadTargetNamespace)); + assertThat(Status.fromThrowable(wrongReadTargetNamespace.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrongReadTargetNamespace.values).isEmpty(); + verifyNoInteractions(intakeService); + } + + @Test + void intakeAndExactReadRejectCallerContextBeforeDecodeAndOwnerAccess() { + RecordingObserver intakeObserver = new RecordingObserver<>(); + RecordingObserver readObserver = + new RecordingObserver<>(); + + SessionContext.setContext("account", List.of(), java.util.Map.of()); + try { + withGameDesign( + () -> + grpcService.intakeAuthoredWorldSource( + intakeRequest().toBuilder().setSchemaVersion(2).build(), intakeObserver)); + withGameDesign( + () -> + grpcService.readAuthoredWorldSourceIntake( + readRequest().toBuilder().setRequestId("not-a-uuid").build(), readObserver)); + } finally { + SessionContext.clear(); + } + + assertThat(Status.fromThrowable(intakeObserver.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(Status.fromThrowable(readObserver.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(intakeObserver.values).isEmpty(); + assertThat(readObserver.values).isEmpty(); + verifyNoInteractions(intakeService); + } + + @Test + void mapsPeerDenialAndRepositoryConflictToNonSuccessGrpcOutcomes() { + doThrow( + new SecurityException("not the Game Design workload"), + new WorldAuthoredSourceIntakeRepository.RegistrationConflictException("changed source")) + .when(intakeService) + .intake( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST); + RecordingObserver denied = new RecordingObserver<>(); + withGameDesign(() -> grpcService.intakeAuthoredWorldSource(intakeRequest(), denied)); + assertThat(Status.fromThrowable(denied.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(denied.values).isEmpty(); + + RecordingObserver conflict = new RecordingObserver<>(); + withGameDesign(() -> grpcService.intakeAuthoredWorldSource(intakeRequest(), conflict)); + assertThat(Status.fromThrowable(conflict.error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(conflict.values).isEmpty(); + } + + @Test + void preservesTransientStorageFailureAndReportsAbsentReadWithoutReceipt() { + when(intakeService.intake( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST)) + .thenThrow(new DataAccessResourceFailureException("database unavailable")); + RecordingObserver unavailable = new RecordingObserver<>(); + withGameDesign(() -> grpcService.intakeAuthoredWorldSource(intakeRequest(), unavailable)); + assertThat(Status.fromThrowable(unavailable.error).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE); + assertThat(unavailable.values).isEmpty(); + + when(intakeService.readCommittedReceipt( + 1, + NAMESPACE, + READ_REQUEST_ID, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST)) + .thenReturn(Optional.empty()); + RecordingObserver missing = new RecordingObserver<>(); + withGameDesign(() -> grpcService.readAuthoredWorldSourceIntake(readRequest(), missing)); + assertThat(Status.fromThrowable(missing.error).getCode()).isEqualTo(Status.Code.NOT_FOUND); + assertThat(missing.values).isEmpty(); + verify(intakeService) + .readCommittedReceipt( + 1, + NAMESPACE, + READ_REQUEST_ID, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST); + } + + @Test + void mapsLockTimeoutAndDeadlockSqlStatesToUnavailableButOtherSqlErrorsToInternal() { + Status lockTimeout = + intakeFailureStatus( + new org.jooq.exception.DataAccessException( + "jOOQ lock failure", new SQLException("lock detail", "55P03"))); + assertThat(lockTimeout.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(lockTimeout.getDescription()).isEqualTo("World intake is temporarily unavailable"); + + Status deadlock = + intakeFailureStatus( + new org.springframework.jdbc.UncategorizedSQLException( + "World intake", + "LOCK TABLE region IN SHARE MODE", + new SQLException("deadlock detail", "40P01"))); + assertThat(deadlock.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(deadlock.getDescription()).isEqualTo("World intake is temporarily unavailable"); + + Status serializationFailure = + intakeFailureStatus( + new org.springframework.dao.ConcurrencyFailureException( + "retryable serialization", new SQLException("serialization detail", "40001"))); + assertThat(serializationFailure.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + + Status storageUnavailable = + intakeFailureStatus( + new DataAccessResourceFailureException( + "storage unavailable", new SQLException("shutdown detail", "57P01"))); + assertThat(storageUnavailable.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + + Status unrelatedSqlError = + intakeFailureStatus( + new org.jooq.exception.DataAccessException( + "jOOQ constraint failure", new SQLException("constraint detail", "23505"))); + assertThat(unrelatedSqlError.getCode()).isEqualTo(Status.Code.INTERNAL); + assertThat(unrelatedSqlError.getDescription()) + .isEqualTo("World intake storage could not complete the request"); + } + + @Test + void mapsUpstreamStatusFailuresToSafeWorldOutcomes() { + for (Status.Code upstreamCode : + List.of( + Status.Code.UNAVAILABLE, + Status.Code.DEADLINE_EXCEEDED, + Status.Code.NOT_FOUND, + Status.Code.PERMISSION_DENIED)) { + Metadata upstreamTrailers = new Metadata(); + upstreamTrailers.put(UPSTREAM_DETAIL, "untrusted upstream trailer"); + StatusRuntimeException upstreamFailure = + Status.fromCode(upstreamCode) + .withDescription("untrusted upstream description") + .asRuntimeException(upstreamTrailers); + doThrow(upstreamFailure) + .when(intakeService) + .intake( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST); + RecordingObserver observer = new RecordingObserver<>(); + + withGameDesign(() -> grpcService.intakeAuthoredWorldSource(intakeRequest(), observer)); + + Status response = Status.fromThrowable(observer.error); + boolean retryable = + upstreamCode == Status.Code.UNAVAILABLE || upstreamCode == Status.Code.DEADLINE_EXCEEDED; + assertThat(response.getCode()) + .isEqualTo(retryable ? upstreamCode : Status.Code.FAILED_PRECONDITION); + assertThat(response.getDescription()) + .isEqualTo( + switch (upstreamCode) { + case UNAVAILABLE -> "World intake dependency is temporarily unavailable"; + case DEADLINE_EXCEEDED -> "World intake dependency read timed out"; + default -> "World authored-source intake has no exact committed proof"; + }); + assertThat(response.getDescription()).doesNotContain("untrusted upstream"); + assertThat(((StatusRuntimeException) observer.error).getTrailers()).isNull(); + assertThat(observer.values).isEmpty(); + assertThat(observer.completed).isFalse(); + } + } + + @Test + void refusesToReturnAnOwnerReceiptWhoseBindingDoesNotMatch() { + WorldAuthoredSourceIntakeReceipt changed = receipt(binding("other-world"), 9001L); + when(intakeService.intake( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST)) + .thenReturn(changed); + RecordingObserver observer = new RecordingObserver<>(); + + withGameDesign(() -> grpcService.intakeAuthoredWorldSource(intakeRequest(), observer)); + + assertThat(Status.fromThrowable(observer.error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(observer.values).isEmpty(); + verify(intakeService) + .intake( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST); + } + + private Status intakeFailureStatus(RuntimeException failure) { + doThrow(failure) + .when(intakeService) + .intake( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + SOURCE_DIGEST); + RecordingObserver observer = new RecordingObserver<>(); + + withGameDesign(() -> grpcService.intakeAuthoredWorldSource(intakeRequest(), observer)); + + assertThat(observer.error).isNotNull(); + assertThat(observer.values).isEmpty(); + assertThat(observer.completed).isFalse(); + return Status.fromThrowable(observer.error); + } + + private static IntakeRequest binding() { + return binding(WORLD_SLUG); + } + + private static IntakeRequest binding(String worldSlug) { + AuthoredWorldSourceEvidence source = + source(NAMESPACE, TENANT_ID, SOURCE_OPERATION_ID, worldSlug); + return new IntakeRequest( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + worldSlug, + SOURCE_OPERATION_ID, + source.evidenceDigest()); + } + + private static IntakeAuthoredWorldSourceRequest intakeRequest() { + return WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(binding()); + } + + private static ReadAuthoredWorldSourceIntakeRequest readRequest() { + return WorldAuthoredSourceIntakeGrpcCodec.toReadRequest( + new WorldAuthoredSourceIntakeGrpcCodec.ReadRequest(binding(), READ_REQUEST_ID)); + } + + private static WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest readById() { + return new WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest( + 1, NAMESPACE, READ_REQUEST_ID, INTAKE_REQUEST_ID, TENANT_ID); + } + + private static ReadAuthoredWorldSourceIntakeByIdRequest readByIdRequest() { + return WorldAuthoredSourceIntakeGrpcCodec.toReadByIdRequest(readById()); + } + + private static WorldAuthoredSourceIntakeReceipt receipt( + IntakeRequest binding, long localTenantKey) { + AuthoredWorldSourceEvidence source = + source( + binding.targetNamespace(), + binding.canonicalTenantId(), + binding.sourceOperationId(), + binding.worldSlug()); + if (!binding.expectedSourceEvidenceDigest().equals(source.evidenceDigest())) { + throw new IllegalArgumentException("Test source evidence does not match intake binding"); + } + String requestDigest = + WorldAuthoredSourceIntakeDigest.requestDigest( + binding.targetNamespace(), binding.intakeRequestId(), source); + return new WorldAuthoredSourceIntakeReceipt( + 1, + binding.targetNamespace(), + binding.intakeRequestId(), + OPERATION_ID, + binding.canonicalTenantId(), + binding.worldSlug(), + binding.sourceOperationId(), + binding.expectedSourceEvidenceDigest(), + requestDigest, + WorldAuthoredSourceIntakeDigest.receiptDigest( + binding.targetNamespace(), OPERATION_ID, requestDigest, source, localTenantKey), + localTenantKey, + source); + } + + private static AuthoredWorldSourceEvidence source( + String namespace, UUID tenantId, UUID sourceOperationId, String worldSlug) { + UUID registrationRequestId = UUID.fromString("11111111-1111-4111-8111-111111111111"); + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + namespace, registrationRequestId, tenantId, "north-star", worldSlug, "Café 🐉"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + namespace, + registrationRequestId, + sourceOperationId, + sourceRequestDigest, + tenantId, + "north-star", + worldSlug, + "Café 🐉", + 42L, + "legacy-game-tenant-42", + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + namespace, + registrationRequestId, + sourceOperationId, + sourceRequestDigest, + tenantId, + "north-star", + worldSlug, + "Café 🐉", + 42L, + "legacy-game-tenant-42", + "NEW_GAME_ROW", + evidenceDigest); + } + + private static UnknownFieldSet unknownField() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } + + private static void withGameDesign(Runnable action) { + withPeer(NAMESPACE, "game-design-service", action); + } + + private static void withPeer(String namespace, String service, Runnable action) { + GrpcPeerIdentity peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + action.run(); + } finally { + context.detach(previous); + } + } + + private static final class RecordingObserver implements StreamObserver { + private final List values = new ArrayList<>(); + private Throwable error; + private boolean completed; + + @Override + public void onNext(T value) { + values.add(value); + } + + @Override + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "The test recorder retains the exact original throwable solely for assertion.") + public void onError(Throwable throwable) { + error = throwable; + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeMtlsTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeMtlsTest.java new file mode 100644 index 0000000000..0e5cb1d834 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeMtlsTest.java @@ -0,0 +1,695 @@ +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.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.UnknownFieldSet; +import io.grpc.ForwardingServerCall; +import io.grpc.ManagedChannel; +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.ServerServiceDefinition; +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.NettyChannelBuilder; +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.MetadataUtils; +import java.math.BigInteger; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.Security; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.Base64; +import java.util.Date; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ReadRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldAuthoredSourceIntakeServiceGrpc; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.BasicConstraints; +import org.bouncycastle.asn1.x509.ExtendedKeyUsage; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.asn1.x509.KeyPurposeId; +import org.bouncycastle.asn1.x509.KeyUsage; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +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; + +/** Physical socket proof with a mocked owner service, not database-to-socket proof. */ +class WorldAuthoredSourceIntakeMtlsTest { + private static final String NAMESPACE = "test"; + private static final String WORLD_PEER_URI = + "spiffe://firemud/ns/test/sa/world-management-service"; + private static final Metadata.Key AUTHORIZATION = + Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER); + private static final UUID INTAKE_ID = UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID TENANT_ID = UUID.fromString("22345678-1234-4234-8234-123456789abc"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("32345678-1234-4234-8234-123456789abc"); + private static final UUID READ_ID = UUID.fromString("42345678-1234-4234-8234-123456789abc"); + private static final UUID WORLD_OPERATION_ID = + UUID.fromString("52345678-1234-4234-8234-123456789abc"); + private static final long PRIVATE_WORLD_TENANT_KEY = 987654321L; + private static final AtomicLong CERTIFICATE_SERIAL = new AtomicLong(1); + private static final UnknownFieldSet UNKNOWN_FIELD = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + private static TestPki pki; + + @TempDir Path tempDirectory; + + private Server server; + private WorldAuthoredSourceIntakeService intakeService; + + private static final AuthoredWorldSourceEvidence SOURCE_EVIDENCE = sourceEvidence(); + private static final String SOURCE_EVIDENCE_DIGEST = SOURCE_EVIDENCE.evidenceDigest(); + private static final IntakeRequest INTAKE_REQUEST = + new IntakeRequest( + 1, + NAMESPACE, + INTAKE_ID, + TENANT_ID, + "world-one", + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE_DIGEST); + private static final ReadRequest READ_REQUEST = new ReadRequest(INTAKE_REQUEST, READ_ID); + private static final WorldAuthoredSourceIntakeReceipt WORLD_RECEIPT = worldReceipt(); + + @BeforeAll + static void generateFreshTestPki() throws Exception { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { + Security.addProvider(new BouncyCastleProvider()); + } + KeyPair caKeyPair = newRsaKeyPair(); + X500Name caName = new X500Name("CN=Fresh World Authored Intake Test CA, O=FireMUD Test"); + X509Certificate caCertificate = + issueCertificate(caName, caKeyPair.getPublic(), caName, caKeyPair.getPrivate(), true, null); + pki = + new TestPki( + caCertificate, + issueLeaf(caName, caKeyPair.getPrivate(), "world-management-server", WORLD_PEER_URI), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "wrong-world-server-identity", + "spiffe://firemud/ns/test/sa/game-design-service"), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "game-design-service", + "spiffe://firemud/ns/test/sa/game-design-service"), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "account-service", + "spiffe://firemud/ns/test/sa/account-service"), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "game-session-service", + "spiffe://firemud/ns/test/sa/game-session-service"), + issueLeaf(caName, caKeyPair.getPrivate(), "world-management-service", WORLD_PEER_URI), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "wrong-namespace-game-design-service", + "spiffe://firemud/ns/other-test/sa/game-design-service"), + issueLeaf(caName, caKeyPair.getPrivate(), "shared-workload-certificate", null)); + } + + @AfterEach + void stopPhysicalReceiver() throws Exception { + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } + + @Test + void sameNamespaceGameDesignIntakesThenReadsExactReceiptOverSocketMtls() throws Exception { + startServer(pki.worldServer(), null); + try (WorldAuthoredSourceIntakeClient client = client(pki.gameDesignClient(), "game-design")) { + CommittedReceipt accepted = client.intake(INTAKE_REQUEST); + CommittedReceipt readback = client.read(READ_REQUEST); + + assertPublicReceipt(accepted); + assertPublicReceipt(readback); + verify(intakeService) + .intake( + 1, + NAMESPACE, + INTAKE_ID, + TENANT_ID, + "world-one", + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE_DIGEST); + verify(intakeService) + .readCommittedReceipt( + 1, + NAMESPACE, + READ_ID, + INTAKE_ID, + TENANT_ID, + "world-one", + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE_DIGEST); + } + } + + @Test + void wrongWorkloadsAndWrongNamespaceAreDeniedBeforeDecodeOrOwnerAccess() throws Exception { + startServer(pki.worldServer(), null); + for (TestCertificate wrongCaller : + List.of( + pki.accountClient(), + pki.gameSessionClient(), + pki.worldClient(), + pki.otherNamespaceClient())) { + try (WorldAuthoredSourceIntakeClient client = client(wrongCaller, "caller")) { + assertPermissionDenied(() -> client.intake(INTAKE_REQUEST)); + assertPermissionDenied(() -> client.read(READ_REQUEST)); + } + } + + ManagedChannel malformedCallerChannel = rawMtlsChannel(pki.accountClient()); + try { + WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub stub = + WorldAuthoredSourceIntakeServiceGrpc.newBlockingStub(malformedCallerChannel) + .withDeadlineAfter(3, TimeUnit.SECONDS); + Throwable failure = + catchFailure( + () -> + stub.intakeAuthoredWorldSource( + IntakeAuthoredWorldSourceRequest.getDefaultInstance())); + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + stopChannel(malformedCallerChannel); + } + verifyNoInteractions(intakeService); + } + + @Test + void sharedCertificateWithoutWorkloadUriCannotReachOwner() throws Exception { + startServer(pki.worldServer(), null); + try (WorldAuthoredSourceIntakeClient client = + client(pki.noWorkloadUriClient(), "shared-certificate")) { + assertPermissionDenied(() -> client.intake(INTAKE_REQUEST)); + assertPermissionDenied(() -> client.read(READ_REQUEST)); + } + verifyNoInteractions(intakeService); + } + + @Test + void jwtOnlyAndPlaintextCallersFailAtThePhysicalTransportBoundary() throws Exception { + startServer(pki.worldServer(), null); + Metadata jwtOnlyHeaders = new Metadata(); + jwtOnlyHeaders.put(AUTHORIZATION, "Bearer header.payload.signature"); + ManagedChannel noCertificateChannel = rawMtlsChannel(null); + try { + assertTransportFailure( + () -> + WorldAuthoredSourceIntakeServiceGrpc.newBlockingStub(noCertificateChannel) + .withInterceptors(MetadataUtils.newAttachHeadersInterceptor(jwtOnlyHeaders)) + .withDeadlineAfter(3, TimeUnit.SECONDS) + .intakeAuthoredWorldSource( + WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(INTAKE_REQUEST))); + } finally { + stopChannel(noCertificateChannel); + } + + ManagedChannel plaintextChannel = + NettyChannelBuilder.forAddress(new InetSocketAddress("127.0.0.1", server.getPort())) + .usePlaintext() + .build(); + try { + assertTransportFailure( + () -> + WorldAuthoredSourceIntakeServiceGrpc.newBlockingStub(plaintextChannel) + .withDeadlineAfter(3, TimeUnit.SECONDS) + .intakeAuthoredWorldSource( + WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(INTAKE_REQUEST))); + } finally { + stopChannel(plaintextChannel); + } + + CommonGrpcClientProperties plaintext = tlsProperties(pki.gameDesignClient(), "constructor"); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new WorldAuthoredSourceIntakeClient( + endpoints(), + plaintext, + new net.firedevops.firemud.common.grpc.GrpcChannelFactory(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + verifyNoInteractions(intakeService); + } + + @Test + void clientRejectsAResponseFromTheWrongAuthenticatedWorldServerIdentity() throws Exception { + startServer(pki.wrongWorldServer(), null); + try (WorldAuthoredSourceIntakeClient client = client(pki.gameDesignClient(), "wrong-server")) { + assertUnauthenticated(() -> client.intake(INTAKE_REQUEST)); + assertUnauthenticated(() -> client.read(READ_REQUEST)); + } + verifyNoInteractions(intakeService); + } + + @Test + void changedEchoDigestAndUnknownFieldsAreRejectedAfterSocketResponse() throws Exception { + startServer(pki.worldServer(), responseMutation(ResponseMutation.CHANGED_ECHO)); + try (WorldAuthoredSourceIntakeClient client = client(pki.gameDesignClient(), "changed-echo")) { + assertThatThrownBy(() -> client.intake(INTAKE_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-source intake receipt"); + } + stopServer(); + + startServer(pki.worldServer(), responseMutation(ResponseMutation.CHANGED_DIGEST)); + try (WorldAuthoredSourceIntakeClient client = + client(pki.gameDesignClient(), "changed-digest")) { + assertThatThrownBy(() -> client.intake(INTAKE_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-source intake receipt"); + } + stopServer(); + + startServer(pki.worldServer(), responseMutation(ResponseMutation.UNKNOWN_FIELDS)); + try (WorldAuthoredSourceIntakeClient client = + client(pki.gameDesignClient(), "unknown-fields")) { + assertThatThrownBy(() -> client.intake(INTAKE_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-source intake receipt"); + } + stopServer(); + + startServer(pki.worldServer(), responseMutation(ResponseMutation.CHANGED_READ_ID)); + try (WorldAuthoredSourceIntakeClient client = + client(pki.gameDesignClient(), "changed-read-id")) { + assertThatThrownBy(() -> client.read(READ_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-source intake readback"); + } + } + + @Test + void publicWireMessagesNeverContainWorldPrivateNumericTenantKey() { + List messages = + List.of( + IntakeAuthoredWorldSourceRequest.getDescriptor(), + IntakeAuthoredWorldSourceResponse.getDescriptor(), + ReadAuthoredWorldSourceIntakeRequest.getDescriptor(), + ReadAuthoredWorldSourceIntakeResponse.getDescriptor()); + + for (var descriptor : messages) { + assertThat(descriptor.getFields()) + .extracting(field -> field.getName()) + .doesNotContain("local_tenant_key", "world_tenant_key", "tenant_id"); + } + assertThat(WORLD_RECEIPT.localTenantKey()).isEqualTo(PRIVATE_WORLD_TENANT_KEY); + } + + private void startServer(TestCertificate serverCertificate, ServerInterceptor responseInterceptor) + throws Exception { + intakeService = mock(WorldAuthoredSourceIntakeService.class); + when(intakeService.intake( + eq(1), + eq(NAMESPACE), + eq(INTAKE_ID), + eq(TENANT_ID), + eq("world-one"), + eq(SOURCE_OPERATION_ID), + eq(SOURCE_EVIDENCE_DIGEST))) + .thenReturn(WORLD_RECEIPT); + when(intakeService.readCommittedReceipt( + eq(1), + eq(NAMESPACE), + eq(READ_ID), + eq(INTAKE_ID), + eq(TENANT_ID), + eq("world-one"), + eq(SOURCE_OPERATION_ID), + eq(SOURCE_EVIDENCE_DIGEST))) + .thenReturn(Optional.of(WORLD_RECEIPT)); + + WorldAuthoredSourceIntakeGrpcService handler = + new WorldAuthoredSourceIntakeGrpcService(intakeService, NAMESPACE); + ServerServiceDefinition intercepted = + ServerInterceptors.intercept(handler, new GrpcPeerIdentityInterceptor()); + if (responseInterceptor != null) { + intercepted = ServerInterceptors.intercept(intercepted, responseInterceptor); + } + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverCertificate.privateKey(), serverCertificate.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(intercepted) + .build() + .start(); + } + + private void stopServer() throws Exception { + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + private WorldAuthoredSourceIntakeClient client(TestCertificate certificate, String label) + throws Exception { + WorldAuthoredSourceIntakeClient client = + new WorldAuthoredSourceIntakeClient( + endpoints(), + tlsProperties(certificate, label), + new net.firedevops.firemud.common.grpc.GrpcChannelFactory(), + NAMESPACE); + client.init(); + return client; + } + + private ServiceEndpointsProperties endpoints() { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("127.0.0.1:" + server.getPort()); + return endpoints; + } + + private CommonGrpcClientProperties tlsProperties(TestCertificate certificate, String label) + throws Exception { + Path clientCertificate = tempDirectory.resolve(label + "-client.crt"); + Path clientPrivateKey = tempDirectory.resolve(label + "-client.key"); + Files.writeString( + clientCertificate, pem("CERTIFICATE", certificate.certificate().getEncoded())); + Files.writeString(clientPrivateKey, pem("PRIVATE KEY", certificate.privateKey().getEncoded())); + Path caCertificate = tempDirectory.resolve("test-ca.crt"); + Files.writeString(caCertificate, pem("CERTIFICATE", pki.caCertificate().getEncoded())); + + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(clientCertificate.toString()); + tls.setPrivateKey(clientPrivateKey.toString()); + tls.setCaCert(caCertificate.toString()); + return tls; + } + + private ManagedChannel rawMtlsChannel(TestCertificate certificate) throws Exception { + var sslBuilder = GrpcSslContexts.forClient().trustManager(pki.caCertificate()); + if (certificate != null) { + sslBuilder.keyManager(certificate.privateKey(), certificate.certificate()); + } + return NettyChannelBuilder.forAddress(new InetSocketAddress("127.0.0.1", server.getPort())) + .sslContext(sslBuilder.build()) + .build(); + } + + private static ServerInterceptor responseMutation(ResponseMutation mutation) { + return new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + ServerCall forwardingCall = + new ForwardingServerCall.SimpleForwardingServerCall<>(call) { + @Override + public void sendMessage(RespT message) { + Object changed = mutateResponse(message, mutation); + @SuppressWarnings("unchecked") + RespT typedChanged = (RespT) changed; + super.sendMessage(typedChanged); + } + }; + return next.startCall(forwardingCall, headers); + } + }; + } + + private static Object mutateResponse(Object response, ResponseMutation mutation) { + if (response instanceof IntakeAuthoredWorldSourceResponse intake) { + return switch (mutation) { + case CHANGED_ECHO -> intake.toBuilder().setWorldSlug("other-world").build(); + case CHANGED_DIGEST -> + intake.toBuilder().setRequestDigest("sha256:" + "c".repeat(64)).build(); + case UNKNOWN_FIELDS -> intake.toBuilder().setUnknownFields(UNKNOWN_FIELD).build(); + case CHANGED_READ_ID -> intake; + }; + } + if (response instanceof ReadAuthoredWorldSourceIntakeResponse read) { + return switch (mutation) { + case CHANGED_READ_ID -> read.toBuilder().setRequestId(INTAKE_ID.toString()).build(); + case UNKNOWN_FIELDS -> read.toBuilder().setUnknownFields(UNKNOWN_FIELD).build(); + case CHANGED_ECHO, CHANGED_DIGEST -> read; + }; + } + return response; + } + + private static void assertPublicReceipt(CommittedReceipt actual) { + assertThat(actual.schemaVersion()).isEqualTo(1); + assertThat(actual.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(actual.intakeRequestId()).isEqualTo(INTAKE_ID); + assertThat(actual.operationId()).isEqualTo(WORLD_OPERATION_ID); + assertThat(actual.canonicalTenantId()).isEqualTo(TENANT_ID); + assertThat(actual.worldSlug()).isEqualTo("world-one"); + assertThat(actual.sourceOperationId()).isEqualTo(SOURCE_OPERATION_ID); + assertThat(actual.sourceEvidenceDigest()).isEqualTo(SOURCE_EVIDENCE_DIGEST); + assertThat(actual.requestDigest()).isEqualTo(WORLD_RECEIPT.requestDigest()); + assertThat(actual.receiptDigest()).isEqualTo(WORLD_RECEIPT.receiptDigest()); + } + + private static void assertPermissionDenied(Runnable call) { + Throwable failure = catchFailure(call); + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.PERMISSION_DENIED); + } + + private static void assertUnauthenticated(Runnable call) { + Throwable failure = catchFailure(call); + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + } + + private static void assertTransportFailure(Runnable call) { + Throwable failure = catchFailure(call); + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isNotEqualTo(Status.Code.DEADLINE_EXCEEDED); + } + + private static Throwable catchFailure(Runnable call) { + try { + call.run(); + return null; + } catch (Throwable throwable) { + return throwable; + } + } + + private static void stopChannel(ManagedChannel channel) throws InterruptedException { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + + private static AuthoredWorldSourceEvidence sourceEvidence() { + UUID registrationId = UUID.fromString("62345678-1234-4234-8234-123456789abc"); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationId, TENANT_ID, "tenant-one", "world-one", "World One"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationId, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + "tenant-one", + "world-one", + "World One", + 17L, + "source-game-key", + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationId, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + "tenant-one", + "world-one", + "World One", + 17L, + "source-game-key", + "NEW_GAME_ROW", + evidenceDigest); + } + + private static WorldAuthoredSourceIntakeReceipt worldReceipt() { + String requestDigest = + WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, INTAKE_ID, SOURCE_EVIDENCE); + String receiptDigest = + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, + WORLD_OPERATION_ID, + requestDigest, + SOURCE_EVIDENCE, + PRIVATE_WORLD_TENANT_KEY); + return new WorldAuthoredSourceIntakeReceipt( + 1, + NAMESPACE, + INTAKE_ID, + WORLD_OPERATION_ID, + TENANT_ID, + "world-one", + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE_DIGEST, + requestDigest, + receiptDigest, + PRIVATE_WORLD_TENANT_KEY, + SOURCE_EVIDENCE); + } + + private static String pem(String type, byte[] bytes) { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return "-----BEGIN " + type + "-----\n" + body + "\n-----END " + type + "-----\n"; + } + + private static TestCertificate issueLeaf( + X500Name caName, PrivateKey caPrivateKey, String commonName, String workloadUri) + throws Exception { + KeyPair keyPair = newRsaKeyPair(); + X500Name subject = new X500Name("CN=" + commonName + ", O=FireMUD Test"); + GeneralName[] subjectAltNames = + workloadUri == null + ? new GeneralName[] { + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + } + : new GeneralName[] { + new GeneralName(GeneralName.uniformResourceIdentifier, workloadUri), + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + }; + X509Certificate certificate = + issueCertificate( + subject, + keyPair.getPublic(), + caName, + caPrivateKey, + false, + new GeneralNames(subjectAltNames)); + return new TestCertificate(keyPair.getPrivate(), certificate); + } + + private static X509Certificate issueCertificate( + X500Name subject, + java.security.PublicKey publicKey, + X500Name issuer, + PrivateKey issuerPrivateKey, + boolean ca, + GeneralNames subjectAltNames) + throws Exception { + Instant now = Instant.now().minusSeconds(60); + JcaX509v3CertificateBuilder builder = + new JcaX509v3CertificateBuilder( + issuer, + BigInteger.valueOf(CERTIFICATE_SERIAL.getAndIncrement()), + Date.from(now), + Date.from(now.plusSeconds(60L * 60L * 24L * 14L)), + subject, + publicKey); + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(ca)); + if (ca) { + builder.addExtension( + Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign)); + } else { + builder.addExtension( + Extension.keyUsage, + true, + new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); + builder.addExtension( + Extension.extendedKeyUsage, + false, + new ExtendedKeyUsage( + new KeyPurposeId[] {KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth})); + builder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); + } + return new JcaX509CertificateConverter() + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .getCertificate( + builder.build( + new JcaContentSignerBuilder("SHA256withRSA") + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .build(issuerPrivateKey))); + } + + private static KeyPair newRsaKeyPair() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return generator.generateKeyPair(); + } + + private enum ResponseMutation { + CHANGED_ECHO, + CHANGED_DIGEST, + UNKNOWN_FIELDS, + CHANGED_READ_ID + } + + private record TestCertificate(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestCertificate worldServer, + TestCertificate wrongWorldServer, + TestCertificate gameDesignClient, + TestCertificate accountClient, + TestCertificate gameSessionClient, + TestCertificate worldClient, + TestCertificate otherNamespaceClient, + TestCertificate noWorkloadUriClient) {} +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java new file mode 100644 index 0000000000..b2196d41da --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java @@ -0,0 +1,751 @@ +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.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec.ReadRequest; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldAuthoredSourceIntakeServiceTest { + private static final String NAMESPACE = "firemud"; + private static final UUID INTAKE_REQUEST = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID READ_REQUEST = UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final String WORLD = "violet-wilds"; + + private final AuthoredWorldSourceClient client = mock(AuthoredWorldSourceClient.class); + private final WorldAuthoredSourceIntakeRepository repository = + mock(WorldAuthoredSourceIntakeRepository.class); + private final RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + private final WorldAuthoredSourceIntakeService service = + new WorldAuthoredSourceIntakeService(client, repository, transactionManager, NAMESPACE); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void requiresExactAuthenticatedGameDesignPeerBeforeOwnerAccess() { + assertThatThrownBy( + () -> + withoutPeer( + () -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a')))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer("firemud", "game-session-service"), + () -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a')))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer("other", "game-design-service"), + () -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a')))) + .isInstanceOf(SecurityException.class); + + verifyNoInteractions(client, repository); + } + + @Test + void validatesAllRequestSelectorsAndDigestBeforeOwnerAccess() { + withGameDesign( + () -> { + assertThatThrownBy( + () -> service.intake(null, TENANT, WORLD, SOURCE_OPERATION, digest('a'))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.intake( + new UUID(0L, 0L), TENANT, WORLD, SOURCE_OPERATION, digest('a'))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> service.intake(INTAKE_REQUEST, null, WORLD, SOURCE_OPERATION, digest('a'))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.intake( + INTAKE_REQUEST, new UUID(0L, 0L), WORLD, SOURCE_OPERATION, digest('a'))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.intake( + INTAKE_REQUEST, TENANT, "Bad-Slug", SOURCE_OPERATION, digest('a'))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.intake(INTAKE_REQUEST, TENANT, WORLD, new UUID(0L, 0L), digest('a'))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.intake(INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, "sha256:bad")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.intake( + 2, + NAMESPACE, + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + digest('a'))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.intake( + 1, "other", INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a'))) + .isInstanceOf(SecurityException.class); + return null; + }); + + verifyNoInteractions(client, repository); + } + + @Test + void deniesWritableAmbientTransactionBeforeReadingOrWriting() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a')))) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(client, repository); + } + + @Test + void deniesReadOnlyAmbientTransactionBeforeReadingOrWriting() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a')))) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(client, repository); + } + + @Test + void exactStoredRetryReturnsOriginalReceiptWithoutCallingGameDesign() { + AuthoredWorldSourceEvidence source = source(NAMESPACE, TENANT, SOURCE_OPERATION, WORLD); + WorldAuthoredSourceIntakeReceipt receipt = receipt(source, 9001L); + when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.of(receipt)); + + WorldAuthoredSourceIntakeReceipt result = + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())); + + assertThat(result).isSameAs(receipt); + verify(client, never()).read(any(ReadRequest.class)); + verify(repository, never()).acceptFresh(any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void exactCommittedReadReturnsWorldReceiptWithoutSourceReadOrAllocation() { + AuthoredWorldSourceEvidence source = source(NAMESPACE, TENANT, SOURCE_OPERATION, WORLD); + WorldAuthoredSourceIntakeReceipt receipt = receipt(source, 9001L); + when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.of(receipt)); + + Optional result = + withGameDesign( + () -> + service.readCommittedReceipt( + 1, + NAMESPACE, + READ_REQUEST, + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest())); + + assertThat(result).containsSame(receipt); + verify(repository).read(NAMESPACE, INTAKE_REQUEST); + verify(repository, never()).acceptFresh(any(), any(), any()); + verifyNoInteractions(client); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void committedReadByIdReturnsFullExactReceiptWithoutSourceReadOrMutation() { + AuthoredWorldSourceEvidence source = source(NAMESPACE, TENANT, SOURCE_OPERATION, WORLD); + WorldAuthoredSourceIntakeReceipt receipt = receipt(source, 9001L); + when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.of(receipt)); + + Optional result = + withGameDesign( + () -> + service.readCommittedReceiptById( + 1, NAMESPACE, READ_REQUEST, INTAKE_REQUEST, TENANT)); + + assertThat(result).containsSame(receipt); + verify(repository).read(NAMESPACE, INTAKE_REQUEST); + verify(repository, never()).acceptFresh(any(), any(), any()); + verifyNoInteractions(client); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void committedReadByIdRejectsWrongPeerCallerContextAndInvalidScopeBeforeOwnerAccess() { + assertThatThrownBy( + () -> + withoutPeer( + () -> + service.readCommittedReceiptById( + 1, NAMESPACE, READ_REQUEST, INTAKE_REQUEST, TENANT))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer(NAMESPACE, "game-session-service"), + () -> + service.readCommittedReceiptById( + 1, NAMESPACE, READ_REQUEST, INTAKE_REQUEST, TENANT))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withGameDesign( + () -> + withCallerContext( + () -> + service.readCommittedReceiptById( + 1, NAMESPACE, READ_REQUEST, INTAKE_REQUEST, TENANT)))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.readCommittedReceiptById( + 1, "other", READ_REQUEST, INTAKE_REQUEST, TENANT))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.readCommittedReceiptById( + 2, NAMESPACE, READ_REQUEST, INTAKE_REQUEST, TENANT))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.readCommittedReceiptById( + 1, NAMESPACE, INTAKE_REQUEST, INTAKE_REQUEST, TENANT))) + .isInstanceOf(IllegalArgumentException.class); + + verifyNoInteractions(client, repository); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void committedReadByIdReturnsAbsentAndRejectsSubstitutedTenantWithoutMutation() { + when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.empty()); + Optional missing = + withGameDesign( + () -> + service.readCommittedReceiptById( + 1, NAMESPACE, READ_REQUEST, INTAKE_REQUEST, TENANT)); + assertThat(missing).isEmpty(); + + AuthoredWorldSourceEvidence source = source(NAMESPACE, TENANT, SOURCE_OPERATION, WORLD); + when(repository.read(NAMESPACE, INTAKE_REQUEST)) + .thenReturn(Optional.of(receipt(source, 9001L))); + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.readCommittedReceiptById( + 1, + NAMESPACE, + READ_REQUEST, + INTAKE_REQUEST, + UUID.fromString("77777777-7777-4777-8777-777777777777")))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); + + verify(repository, org.mockito.Mockito.times(2)).read(NAMESPACE, INTAKE_REQUEST); + verify(repository, never()).acceptFresh(any(), any(), any()); + verifyNoInteractions(client); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void exactCommittedReadRejectsWrongPeerNamespaceAndChangedReceiptBindingBeforeOwnerAccess() { + AuthoredWorldSourceEvidence source = source(NAMESPACE, TENANT, SOURCE_OPERATION, WORLD); + WorldAuthoredSourceIntakeReceipt receipt = receipt(source, 9001L); + when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.of(receipt)); + + assertThatThrownBy( + () -> + withoutPeer( + () -> + service.readCommittedReceipt( + 1, + NAMESPACE, + READ_REQUEST, + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest()))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer(NAMESPACE, "game-session-service"), + () -> + service.readCommittedReceipt( + 1, + NAMESPACE, + READ_REQUEST, + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest()))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.readCommittedReceipt( + 1, + "other", + READ_REQUEST, + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest()))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.readCommittedReceipt( + 1, + NAMESPACE, + INTAKE_REQUEST, + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest()))) + .isInstanceOf(IllegalArgumentException.class); + + verifyNoInteractions(client, repository); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void exactCommittedReadReturnsAbsentWithoutMutationWhenNoReceiptExists() { + when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.empty()); + + Optional result = + withGameDesign( + () -> + service.readCommittedReceipt( + 1, + NAMESPACE, + READ_REQUEST, + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + digest('a'))); + + assertThat(result).isEmpty(); + verify(repository).read(NAMESPACE, INTAKE_REQUEST); + verify(repository, never()).acceptFresh(any(), any(), any()); + verifyNoInteractions(client); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void changedRequestScopeOrExpectedDigestConflictsBeforeRemoteReadOrMutation() { + AuthoredWorldSourceEvidence source = source(NAMESPACE, TENANT, SOURCE_OPERATION, WORLD); + when(repository.read(NAMESPACE, INTAKE_REQUEST)) + .thenReturn(Optional.of(receipt(source, 9001L))); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, + UUID.fromString("66666666-6666-4666-8666-666666666666"), + WORLD, + SOURCE_OPERATION, + source.evidenceDigest()))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, + TENANT, + "amber-coast", + SOURCE_OPERATION, + source.evidenceDigest()))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, + TENANT, + WORLD, + UUID.fromString("77777777-7777-4777-8777-777777777777"), + source.evidenceDigest()))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('b')))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); + + verify(client, never()).read(any(ReadRequest.class)); + verify(repository, never()).acceptFresh(any(), any(), any()); + } + + @Test + void sourceUnavailableCannotEnterTheOwnerWriteTransaction() { + when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.empty()); + when(client.read(any(ReadRequest.class))) + .thenThrow(new IllegalStateException("source unavailable")); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a')))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("source unavailable"); + + verify(repository).read(NAMESPACE, INTAKE_REQUEST); + verify(repository, never()).acceptFresh(any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void changedAuthenticatedSourceCannotEnterTheOwnerWriteTransaction() { + when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.empty()); + AuthoredWorldSourceEvidence[] substitutedSources = { + source("other", TENANT, SOURCE_OPERATION, WORLD), + source( + NAMESPACE, + UUID.fromString("66666666-6666-4666-8666-666666666666"), + SOURCE_OPERATION, + WORLD), + source(NAMESPACE, TENANT, UUID.fromString("77777777-7777-4777-8777-777777777777"), WORLD), + source(NAMESPACE, TENANT, SOURCE_OPERATION, "amber-coast") + }; + for (AuthoredWorldSourceEvidence substituted : substitutedSources) { + when(client.read(any(ReadRequest.class))).thenReturn(substituted); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + substituted.evidenceDigest()))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException.class); + } + + verify(repository, never()).acceptFresh(any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void callerDigestMustMatchFreshAuthenticatedEvidenceBeforeOpeningTransaction() { + AuthoredWorldSourceEvidence source = source(NAMESPACE, TENANT, SOURCE_OPERATION, WORLD); + when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.empty()); + when(client.read(any(ReadRequest.class))).thenReturn(source); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('b')))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException.class); + + verify(repository, never()).acceptFresh(any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void readsFreshSourceBeforeWritableReadCommittedTransactionAndVerifiesFullCommitReadback() { + AuthoredWorldSourceEvidence source = source(NAMESPACE, TENANT, SOURCE_OPERATION, WORLD); + WorldAuthoredSourceIntakeReceipt receipt = receipt(source, 9001L); + AtomicInteger readCount = new AtomicInteger(); + when(repository.read(NAMESPACE, INTAKE_REQUEST)) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return readCount.incrementAndGet() == 1 ? Optional.empty() : Optional.of(receipt); + }); + when(client.read(any(ReadRequest.class))) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return source; + }); + when(repository.acceptFresh(NAMESPACE, INTAKE_REQUEST, source)) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + return receipt; + }); + + WorldAuthoredSourceIntakeReceipt result = + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())); + + assertThat(result).isEqualTo(receipt); + assertThat(readCount.get()).isEqualTo(2); + assertThat(transactionManager.startedWith.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(transactionManager.startedWith.isReadOnly()).isFalse(); + assertThat(transactionManager.startedWith.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ArgumentCaptor readRequest = ArgumentCaptor.forClass(ReadRequest.class); + verify(client).read(readRequest.capture()); + assertThat(readRequest.getValue().targetNamespace()).isEqualTo(NAMESPACE); + assertThat(readRequest.getValue().requestId()) + .isNotEqualTo(INTAKE_REQUEST) + .isNotEqualTo(new UUID(0L, 0L)); + assertThat(readRequest.getValue().operationId()).isEqualTo(SOURCE_OPERATION); + assertThat(readRequest.getValue().canonicalTenantId()).isEqualTo(TENANT); + assertThat(readRequest.getValue().worldSlug()).isEqualTo(WORLD); + verify(repository).acceptFresh(NAMESPACE, INTAKE_REQUEST, source); + } + + @Test + void deniesMissingPostCommitReadback() { + AuthoredWorldSourceEvidence source = source(NAMESPACE, TENANT, SOURCE_OPERATION, WORLD); + when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.empty(), Optional.empty()); + when(client.read(any(ReadRequest.class))).thenReturn(source); + when(repository.acceptFresh(NAMESPACE, INTAKE_REQUEST, source)) + .thenReturn(receipt(source, 9001L)); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest()))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException.class) + .hasMessageContaining("missing after commit readback"); + + verify(repository).acceptFresh(NAMESPACE, INTAKE_REQUEST, source); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + } + + @Test + void deniesChangedPostCommitLocalSelectorReadback() { + AuthoredWorldSourceEvidence source = source(NAMESPACE, TENANT, SOURCE_OPERATION, WORLD); + WorldAuthoredSourceIntakeReceipt accepted = receipt(source, 9001L); + WorldAuthoredSourceIntakeReceipt changed = receipt(source, 9002L); + when(repository.read(NAMESPACE, INTAKE_REQUEST)) + .thenReturn(Optional.empty(), Optional.of(changed)); + when(client.read(any(ReadRequest.class))).thenReturn(source); + when(repository.acceptFresh(NAMESPACE, INTAKE_REQUEST, source)).thenReturn(accepted); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.intake( + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest()))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException.class) + .hasMessageContaining("changed during commit readback"); + + verify(repository).acceptFresh(NAMESPACE, INTAKE_REQUEST, source); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + } + + private static AuthoredWorldSourceEvidence source( + String namespace, UUID tenant, UUID operation, String world) { + UUID registration = UUID.fromString("11111111-1111-4111-8111-111111111111"); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + namespace, registration, tenant, "north-star", world, "Café 🐉"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + namespace, + registration, + operation, + requestDigest, + tenant, + "north-star", + world, + "Café 🐉", + 42L, + "legacy-game-tenant-42", + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + namespace, + registration, + operation, + requestDigest, + tenant, + "north-star", + world, + "Café 🐉", + 42L, + "legacy-game-tenant-42", + "NEW_GAME_ROW", + evidenceDigest); + } + + private static WorldAuthoredSourceIntakeReceipt receipt( + AuthoredWorldSourceEvidence source, long localTenantKey) { + String requestDigest = + WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, INTAKE_REQUEST, source); + UUID operationId = UUID.fromString("55555555-5555-4555-8555-555555555555"); + return new WorldAuthoredSourceIntakeReceipt( + 1, + NAMESPACE, + INTAKE_REQUEST, + operationId, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + requestDigest, + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, operationId, requestDigest, source, localTenantKey), + localTenantKey, + source); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static T withGameDesign(Supplier action) { + return withPeer(peer(NAMESPACE, "game-design-service"), action); + } + + private static T withPeer(GrpcPeerIdentity peer, Supplier action) { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + + private static T withoutPeer(Supplier action) { + Context previous = Context.ROOT.attach(); + try { + return action.get(); + } finally { + Context.ROOT.detach(previous); + } + } + + private static T withCallerContext(Supplier action) { + SessionContext.setContext( + "22222222-2222-4222-8222-222222222222", java.util.List.of(), java.util.Map.of()); + try { + return action.get(); + } finally { + SessionContext.clear(); + } + } + + private static final class RecordingTransactionManager + implements org.springframework.transaction.PlatformTransactionManager { + private TransactionDefinition startedWith; + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + startedWith = definition; + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(definition.isReadOnly()); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + TransactionSynchronizationManager.clear(); + } + + @Override + public void rollback(TransactionStatus status) { + TransactionSynchronizationManager.clear(); + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityCanonicalTargetReadTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityCanonicalTargetReadTest.java new file mode 100644 index 0000000000..6c7e5a0d73 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityCanonicalTargetReadTest.java @@ -0,0 +1,94 @@ +package unit.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.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.UUID; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository; +import org.jooq.Condition; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.Result; +import org.jooq.SelectConditionStep; +import org.jooq.SelectWhereStep; +import org.jooq.Table; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldAuthoredVersionIdentityCanonicalTargetReadTest { + private final DSLContext dsl = mock(DSLContext.class); + + @AfterEach + void clearTransactionFixture() { + TransactionSynchronizationManager.clear(); + } + + @Test + void canonicalTargetReadRejectsAmbientTransactionBeforeSql() { + TransactionSynchronizationManager.setActualTransactionActive(true); + var repository = new WorldAuthoredVersionIdentityRepository(dsl); + + assertThatThrownBy( + () -> + repository.readByCanonicalTarget( + "firemud", + UUID.fromString("22222222-2222-4222-8222-222222222222"), + UUID.fromString("33333333-3333-4333-8333-333333333333"), + 42L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("independent committed owner read"); + + verifyNoInteractions(dsl); + } + + @Test + @SuppressWarnings("unchecked") + void canonicalTargetReadRejectsMultipleWorldAssociationsAsAmbiguous() { + SelectWhereStep selectedTable = mock(SelectWhereStep.class); + SelectConditionStep selectedTarget = mock(SelectConditionStep.class); + Result rows = mock(Result.class); + doReturn(selectedTable).when(dsl).selectFrom(any(Table.class)); + when(selectedTable.where(any(Condition.class))).thenReturn(selectedTarget); + when(selectedTarget.fetch()).thenReturn(rows); + when(rows.isEmpty()).thenReturn(false); + when(rows.size()).thenReturn(2); + var repository = new WorldAuthoredVersionIdentityRepository(dsl); + + assertThatThrownBy( + () -> + repository.readByCanonicalTarget( + "firemud", + UUID.fromString("22222222-2222-4222-8222-222222222222"), + UUID.fromString("33333333-3333-4333-8333-333333333333"), + 42L)) + .isInstanceOf(WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException.class) + .hasMessageContaining("ambiguous World associations"); + } + + @Test + @SuppressWarnings("unchecked") + void canonicalTargetReadReturnsEmptyWhenNoExactAssociationExists() { + SelectWhereStep selectedTable = mock(SelectWhereStep.class); + SelectConditionStep selectedTarget = mock(SelectConditionStep.class); + Result rows = mock(Result.class); + doReturn(selectedTable).when(dsl).selectFrom(any(Table.class)); + when(selectedTable.where(any(Condition.class))).thenReturn(selectedTarget); + when(selectedTarget.fetch()).thenReturn(rows); + when(rows.isEmpty()).thenReturn(true); + var repository = new WorldAuthoredVersionIdentityRepository(dsl); + + assertThat( + repository.readByCanonicalTarget( + "firemud", + UUID.fromString("22222222-2222-4222-8222-222222222222"), + UUID.fromString("33333333-3333-4333-8333-333333333333"), + 42L)) + .isEmpty(); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityGrpcServiceTest.java new file mode 100644 index 0000000000..40216c10fe --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityGrpcServiceTest.java @@ -0,0 +1,396 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +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.Metadata; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.sql.SQLException; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.WorldAuthoredVersionIdentityEvidence; +import net.firedevops.firemud.common.authoring.WorldAuthoredVersionIdentityGrpcCodec; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeDigest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityService; +import net.firedevops.firemud.worldmanagement.v1.AssociateAuthoredWorldVersionRequest; +import net.firedevops.firemud.worldmanagement.v1.AssociateAuthoredWorldVersionResponse; +import org.junit.jupiter.api.Test; + +/** Authentication and dispatch proof only; physical owner persistence is separate. */ +class WorldAuthoredVersionIdentityGrpcServiceTest { + private static final Metadata.Key PROVIDER_DETAIL = + Metadata.Key.of("x-provider-detail", Metadata.ASCII_STRING_MARSHALLER); + + @Test + void deniesWrongMissingAndOtherNamespacePeersBeforeDecodingOrOwnerAccess() { + var owner = mock(WorldAuthoredVersionIdentityService.class); + var grpc = new WorldAuthoredVersionIdentityGrpcService(owner, "test"); + var malformed = AssociateAuthoredWorldVersionRequest.getDefaultInstance(); + for (var service : + List.of("account-service", "world-management-service", "game-session-service")) { + assertThat(call(grpc, malformed, peer(service, "test")).code) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } + assertThat(call(grpc, malformed, null).code).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(call(grpc, malformed, peer("game-design-service", "other")).code) + .isEqualTo(Status.Code.PERMISSION_DENIED); + SessionContext.setContext("123", List.of(), Map.of()); + try { + assertThat(call(grpc, malformed, peer("game-design-service", "test")).code) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + SessionContext.clear(); + } + verifyNoInteractions(owner); + } + + @Test + void rejectsUnknownAndInvalidRequestsAndWrongTargetNamespaceWithoutOwnerAccess() { + var owner = mock(WorldAuthoredVersionIdentityService.class); + var grpc = new WorldAuthoredVersionIdentityGrpcService(owner, "test"); + var wire = WorldAuthoredVersionIdentityGrpcCodec.toRequest(request("test", id(5))); + var unknown = + com.google.protobuf.UnknownFieldSet.newBuilder() + .addField( + 99, com.google.protobuf.UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + for (var invalid : + List.of( + AssociateAuthoredWorldVersionRequest.getDefaultInstance(), + wire.toBuilder().setUnknownFields(unknown).build(), + wire.toBuilder().setGameDesignVersionId(0).build())) { + assertThat(call(grpc, invalid, peer("game-design-service", "test")).code) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + } + assertThat( + call( + grpc, + WorldAuthoredVersionIdentityGrpcCodec.toRequest(request("other", id(5))), + peer("game-design-service", "test")) + .code) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(owner); + } + + @Test + void dispatchesExactAssociationParametersAndReturnsOriginalCommittedEvidenceOnRetry() { + var owner = mock(WorldAuthoredVersionIdentityService.class); + var grpc = new WorldAuthoredVersionIdentityGrpcService(owner, "test"); + var original = request("test", id(5)); + var retained = receipt(original); + var retry = request("test", id(9)); + when(owner.associate( + "test", id(1), "north-star", id(3), retry.sourceEvidenceDigest(), id(4), 42L, id(9))) + .thenReturn(retained); + var response = + call( + grpc, + WorldAuthoredVersionIdentityGrpcCodec.toRequest(retry), + peer("game-design-service", "test")); + assertThat(response.code).isEqualTo(Status.Code.OK); + assertThat(response.completed).isTrue(); + var result = WorldAuthoredVersionIdentityGrpcCodec.fromResponse(retry, response.value); + assertThat(result.operationId()).isEqualTo(retained.operationId()); + assertThat(result.versionStateEvidence()).isEqualTo(retained.versionStateEvidence()); + assertThat(result.versionStateEvidence().request().readRequestId()).isEqualTo(id(5)); + verify(owner) + .associate( + "test", id(1), "north-star", id(3), retry.sourceEvidenceDigest(), id(4), 42L, id(9)); + } + + @Test + void storageFailureAndOwnerConflictProduceNoSuccessfulEvidence() { + var owner = mock(WorldAuthoredVersionIdentityService.class); + var grpc = new WorldAuthoredVersionIdentityGrpcService(owner, "test"); + var request = request("test", id(5)); + when(owner.associate( + "test", id(1), "north-star", id(3), request.sourceEvidenceDigest(), id(4), 42L, id(5))) + .thenThrow(new org.jooq.exception.DataAccessException("storage unavailable")) + .thenThrow(new IllegalStateException("conflicting identity")); + for (var code : List.of(Status.Code.INTERNAL, Status.Code.FAILED_PRECONDITION)) { + var response = + call( + grpc, + WorldAuthoredVersionIdentityGrpcCodec.toRequest(request), + peer("game-design-service", "test")); + assertThat(response.code).isEqualTo(code); + assertThat(response.value).isNull(); + assertThat(response.completed).isFalse(); + } + } + + @Test + void classifiesOnlyRetryableStorageFailuresAsUnavailableWithoutLeakingProviderDetails() { + var request = request("test", id(5)); + var failures = + List.of( + new StorageFailure( + new org.jooq.exception.DataAccessException( + "provider secret", new SQLException("provider secret", "08006")), + Status.Code.UNAVAILABLE), + new StorageFailure( + new org.jooq.exception.DataAccessException( + "provider secret", new SQLException("provider secret", "55P03")), + Status.Code.UNAVAILABLE), + new StorageFailure( + new org.jooq.exception.DataAccessException( + "provider secret", new SQLException("provider secret", "40P01")), + Status.Code.UNAVAILABLE), + new StorageFailure( + new org.jooq.exception.DataAccessException( + "provider secret", new SQLException("provider secret", "23505")), + Status.Code.INTERNAL), + new StorageFailure( + new org.jooq.exception.DataAccessException( + "provider secret", new SQLException("provider secret", "42P01")), + Status.Code.INTERNAL), + new StorageFailure( + new org.jooq.exception.DataAccessException("provider secret"), + Status.Code.INTERNAL), + new StorageFailure( + new org.springframework.dao.DataAccessException("provider secret") {}, + Status.Code.INTERNAL), + new StorageFailure( + new org.springframework.dao.DataAccessResourceFailureException("provider secret"), + Status.Code.UNAVAILABLE), + new StorageFailure( + new org.springframework.dao.TransientDataAccessException("provider secret") {}, + Status.Code.UNAVAILABLE)); + + for (var failure : failures) { + var owner = mock(WorldAuthoredVersionIdentityService.class); + var grpc = new WorldAuthoredVersionIdentityGrpcService(owner, "test"); + when(owner.associate( + "test", + id(1), + "north-star", + id(3), + request.sourceEvidenceDigest(), + id(4), + 42L, + id(5))) + .thenThrow(failure.exception()); + + var response = + call( + grpc, + WorldAuthoredVersionIdentityGrpcCodec.toRequest(request), + peer("game-design-service", "test")); + + assertThat(response.code).isEqualTo(failure.expectedCode()); + assertThat(response.description) + .isEqualTo( + failure.expectedCode() == Status.Code.UNAVAILABLE + ? "World Version association storage unavailable" + : "World Version association storage failed"); + assertThat(response.description).doesNotContain("provider secret"); + assertThat(response.trailersPresent).isFalse(); + assertThat(response.value).isNull(); + assertThat(response.completed).isFalse(); + } + } + + @Test + void exposesOnlyRetryableTransportCodesWithSafeLocalDescriptions() { + var request = request("test", id(5)); + for (var code : List.of(Status.Code.UNAVAILABLE, Status.Code.DEADLINE_EXCEEDED)) { + var owner = mock(WorldAuthoredVersionIdentityService.class); + var grpc = new WorldAuthoredVersionIdentityGrpcService(owner, "test"); + var providerTrailers = new Metadata(); + providerTrailers.put(PROVIDER_DETAIL, "provider secret trailer"); + StatusRuntimeException failure = + Status.fromCode(code) + .withDescription("provider secret description") + .asRuntimeException(providerTrailers); + when(owner.associate( + "test", + id(1), + "north-star", + id(3), + request.sourceEvidenceDigest(), + id(4), + 42L, + id(5))) + .thenThrow(failure); + + var response = + call( + grpc, + WorldAuthoredVersionIdentityGrpcCodec.toRequest(request), + peer("game-design-service", "test")); + + assertThat(response.code).isEqualTo(code); + assertThat(response.description) + .isEqualTo( + code == Status.Code.UNAVAILABLE + ? "Game Design Version state is temporarily unavailable" + : "Game Design Version state read timed out"); + assertThat(response.description).doesNotContain("provider secret"); + assertThat(response.trailersPresent).isFalse(); + assertThat(response.value).isNull(); + assertThat(response.completed).isFalse(); + } + + var owner = mock(WorldAuthoredVersionIdentityService.class); + var grpc = new WorldAuthoredVersionIdentityGrpcService(owner, "test"); + var providerTrailers = new Metadata(); + providerTrailers.put(PROVIDER_DETAIL, "provider secret trailer"); + when(owner.associate( + "test", id(1), "north-star", id(3), request.sourceEvidenceDigest(), id(4), 42L, id(5))) + .thenThrow( + Status.INTERNAL + .withDescription("provider secret description") + .asRuntimeException(providerTrailers)); + + var response = + call( + grpc, + WorldAuthoredVersionIdentityGrpcCodec.toRequest(request), + peer("game-design-service", "test")); + + assertThat(response.code).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(response.description) + .isEqualTo("World Version association has no exact committed proof"); + assertThat(response.description).doesNotContain("provider secret"); + assertThat(response.trailersPresent).isFalse(); + assertThat(response.value).isNull(); + assertThat(response.completed).isFalse(); + } + + private static WorldAuthoredVersionIdentityEvidence.Request request(String namespace, UUID read) { + var source = source(namespace); + return new WorldAuthoredVersionIdentityEvidence.Request( + 1, namespace, id(1), "north-star", id(3), source.evidenceDigest(), id(4), 42L, read); + } + + private static WorldAuthoredVersionIdentityReceipt receipt( + WorldAuthoredVersionIdentityEvidence.Request request) { + var source = source(request.targetNamespace()); + var requestDigest = WorldAuthoredSourceIntakeDigest.requestDigest("test", id(6), source); + var intake = + new WorldAuthoredSourceIntakeReceipt( + 1, + "test", + id(6), + id(7), + id(1), + "north-star", + id(3), + source.evidenceDigest(), + requestDigest, + WorldAuthoredSourceIntakeDigest.receiptDigest( + "test", id(7), requestDigest, source, 900L), + 900L, + source); + var version = + AuthoredWorldVersionStateEvidence.create( + request.versionReadRequest(), + source, + id(4), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 1L); + return new WorldAuthoredVersionIdentityReceipt(1, id(8), 901L, intake, version); + } + + private static AuthoredWorldSourceEvidence source(String namespace) { + var digest = + AuthoredWorldSourceDigest.requestDigest( + namespace, id(2), id(1), "north-star", "north-star", "North Star"); + return new AuthoredWorldSourceEvidence( + 1, + namespace, + id(2), + id(3), + digest, + id(1), + "north-star", + "north-star", + "North Star", + 42L, + "game-tenant-42", + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + namespace, + id(2), + id(3), + digest, + id(1), + "north-star", + "north-star", + "North Star", + 42L, + "game-tenant-42", + "NEW_GAME_ROW")); + } + + private static UUID id(int suffix) { + return UUID.fromString("11111111-1111-4111-8111-" + String.format("%012d", suffix)); + } + + private record StorageFailure(RuntimeException exception, Status.Code expectedCode) {} + + private static GrpcPeerIdentity peer(String service, String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static Collector call( + WorldAuthoredVersionIdentityGrpcService grpc, + AssociateAuthoredWorldVersionRequest wire, + GrpcPeerIdentity peer) { + var context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + var previous = context.attach(); + var result = new Collector(); + try { + grpc.associateAuthoredWorldVersion(wire, result); + } finally { + context.detach(previous); + } + return result; + } + + private static final class Collector + implements StreamObserver { + private AssociateAuthoredWorldVersionResponse value; + private Status.Code code = Status.Code.OK; + private String description; + private boolean trailersPresent; + private boolean completed; + + @Override + public void onNext(AssociateAuthoredWorldVersionResponse response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + Status status = Status.fromThrowable(failure); + code = status.getCode(); + description = status.getDescription(); + if (failure instanceof StatusRuntimeException statusFailure) { + trailersPresent = statusFailure.getTrailers() != null; + } + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityServiceTest.java new file mode 100644 index 0000000000..91392429b4 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityServiceTest.java @@ -0,0 +1,543 @@ +package unit.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.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeDigest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldAuthoredVersionIdentityServiceTest { + private static final String NAMESPACE = "firemud"; + private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID SOURCE_REGISTRATION = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID INTAKE_REQUEST = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID INTAKE_OPERATION = + UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID READ_REQUEST = UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final UUID VERSION = UUID.fromString("88888888-8888-4888-8888-888888888888"); + private static final UUID OTHER_VERSION = UUID.fromString("99999999-9999-4999-8999-999999999999"); + private static final String WORLD = "violet-wilds"; + private static final long GAME_DESIGN_VERSION_ID = 42L; + + private final AuthoredWorldVersionStateClient versionStateClient = + mock(AuthoredWorldVersionStateClient.class); + private final WorldAuthoredVersionIdentityRepository repository = + mock(WorldAuthoredVersionIdentityRepository.class); + private final WorldAuthoredSourceIntakeRepository sourceIntakeRepository = + mock(WorldAuthoredSourceIntakeRepository.class); + private final RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + private final WorldAuthoredVersionIdentityService service = + new WorldAuthoredVersionIdentityService( + versionStateClient, repository, sourceIntakeRepository, transactionManager, NAMESPACE); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void requiresExactSameNamespaceGameDesignPeerBeforeAnyOwnerOrRemoteAccess() { + assertThatThrownBy(() -> withoutPeer(() -> associate(VERSION, GAME_DESIGN_VERSION_ID))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer("other", "game-design-service"), + () -> associate(VERSION, GAME_DESIGN_VERSION_ID))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer(NAMESPACE, "game-session-service"), + () -> associate(VERSION, GAME_DESIGN_VERSION_ID))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.associate( + "other", + TENANT, + WORLD, + SOURCE_OPERATION, + source().evidenceDigest(), + VERSION, + GAME_DESIGN_VERSION_ID, + READ_REQUEST))) + .isInstanceOf(SecurityException.class); + verifyNoInteractions(sourceIntakeRepository, repository, versionStateClient); + } + + @Test + void exactRetryReturnsOriginalReceiptWithoutCallingGameDesignAgain() { + AuthoredWorldSourceEvidence source = source(); + WorldAuthoredSourceIntakeReceipt intake = sourceReceipt(source); + AuthoredWorldVersionStateEvidence originalState = + versionState( + source, + READ_REQUEST, + VERSION, + GAME_DESIGN_VERSION_ID, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 7L); + WorldAuthoredVersionIdentityReceipt original = identityReceipt(intake, originalState, 91L); + when(sourceIntakeRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.of(intake)); + when(repository.readByCanonicalVersion(NAMESPACE, TENANT, WORLD, VERSION)) + .thenReturn(Optional.of(original)); + + WorldAuthoredVersionIdentityReceipt result = + withGameDesign(() -> associate(VERSION, GAME_DESIGN_VERSION_ID)); + + assertThat(result).isEqualTo(original); + verifyNoInteractions(versionStateClient); + verify(repository, never()).acceptFresh(any(WorldAuthoredSourceIntakeReceipt.class), any()); + verify(repository, never()) + .readByGameDesignVersion(NAMESPACE, TENANT, WORLD, GAME_DESIGN_VERSION_ID); + verify(sourceIntakeRepository) + .readBySource(NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest()); + } + + @Test + void changedCanonicalUuidForAnAlreadyMappedGameDesignSelectorDeniesBeforeRemoteRead() { + AuthoredWorldSourceEvidence source = source(); + WorldAuthoredSourceIntakeReceipt intake = sourceReceipt(source); + AuthoredWorldVersionStateEvidence oldState = + versionState( + source, + READ_REQUEST, + OTHER_VERSION, + GAME_DESIGN_VERSION_ID, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 7L); + WorldAuthoredVersionIdentityReceipt existing = identityReceipt(intake, oldState, 91L); + when(sourceIntakeRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.of(intake)); + when(repository.readByCanonicalVersion(NAMESPACE, TENANT, WORLD, VERSION)) + .thenReturn(Optional.empty()); + when(repository.readByGameDesignVersion(NAMESPACE, TENANT, WORLD, GAME_DESIGN_VERSION_ID)) + .thenReturn(Optional.of(existing)); + + assertThatThrownBy(() -> withGameDesign(() -> associate(VERSION, GAME_DESIGN_VERSION_ID))) + .isInstanceOf(WorldAuthoredVersionIdentityRepository.RegistrationConflictException.class) + .hasMessageContaining("selector conflicts"); + + verifyNoInteractions(versionStateClient); + verify(repository, never()).acceptFresh(any(WorldAuthoredSourceIntakeReceipt.class), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void retainsExactSourceQualifiedDraftIdentityInItsOwnReadCommittedTransaction() { + AuthoredWorldSourceEvidence source = source(); + WorldAuthoredSourceIntakeReceipt intake = sourceReceipt(source); + AuthoredWorldVersionStateEvidence current = + versionState( + source, + READ_REQUEST, + VERSION, + GAME_DESIGN_VERSION_ID, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 3L); + WorldAuthoredVersionIdentityReceipt accepted = identityReceipt(intake, current, 101L); + when(sourceIntakeRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.of(intake)); + when(repository.readByCanonicalVersion(NAMESPACE, TENANT, WORLD, VERSION)) + .thenReturn(Optional.empty(), Optional.of(accepted)); + when(repository.readByGameDesignVersion(NAMESPACE, TENANT, WORLD, GAME_DESIGN_VERSION_ID)) + .thenReturn(Optional.empty()); + when(versionStateClient.read(any())).thenReturn(current); + when(repository.acceptFresh(intake, current)).thenReturn(accepted); + + WorldAuthoredVersionIdentityReceipt result = + withGameDesign(() -> associate(VERSION, GAME_DESIGN_VERSION_ID)); + + assertThat(result).isEqualTo(accepted); + assertThat(result.localVersionKey()).isEqualTo(101L); + assertThat(result.canonicalVersionId()).isEqualTo(VERSION); + assertThat(result.gameDesignVersionId()).isEqualTo(GAME_DESIGN_VERSION_ID); + assertThat(result.sourceIntakeReceipt()).isEqualTo(intake); + assertThat(result.versionStateEvidence()).isEqualTo(current); + assertThat(transactionManager.startedWith.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(transactionManager.startedWith.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(transactionManager.startedWith.isReadOnly()).isFalse(); + + InOrder order = inOrder(sourceIntakeRepository, repository, versionStateClient); + order + .verify(sourceIntakeRepository) + .readBySource(NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest()); + order.verify(repository).readByCanonicalVersion(NAMESPACE, TENANT, WORLD, VERSION); + order + .verify(repository) + .readByGameDesignVersion(NAMESPACE, TENANT, WORLD, GAME_DESIGN_VERSION_ID); + order.verify(versionStateClient).read(current.request()); + order.verify(repository).acceptFresh(intake, current); + order.verify(repository).readByCanonicalVersion(NAMESPACE, TENANT, WORLD, VERSION); + order + .verify(sourceIntakeRepository) + .readBySource(NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest()); + } + + @Test + void rejectsSubstitutedCanonicalVersionAndUnsupportedLifecycleBeforeMutation() { + AuthoredWorldSourceEvidence source = source(); + WorldAuthoredSourceIntakeReceipt intake = sourceReceipt(source); + when(sourceIntakeRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.of(intake)); + when(repository.readByCanonicalVersion(NAMESPACE, TENANT, WORLD, VERSION)) + .thenReturn(Optional.empty()); + when(repository.readByGameDesignVersion(NAMESPACE, TENANT, WORLD, GAME_DESIGN_VERSION_ID)) + .thenReturn(Optional.empty()); + when(versionStateClient.read(any())) + .thenReturn( + versionState( + source, + READ_REQUEST, + OTHER_VERSION, + GAME_DESIGN_VERSION_ID, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 5L)); + + assertThatThrownBy(() -> withGameDesign(() -> associate(VERSION, GAME_DESIGN_VERSION_ID))) + .isInstanceOf(WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException.class) + .hasMessageContaining("expected UUID"); + verify(repository, never()).acceptFresh(any(WorldAuthoredSourceIntakeReceipt.class), any()); + + when(versionStateClient.read(any())) + .thenReturn( + versionState( + source, + READ_REQUEST, + VERSION, + GAME_DESIGN_VERSION_ID, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_RETIRED, + 6L)); + assertThatThrownBy(() -> withGameDesign(() -> associate(VERSION, GAME_DESIGN_VERSION_ID))) + .isInstanceOf(WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException.class) + .hasMessageContaining("must be DRAFT, PUBLISHED, or ACTIVE"); + verify(repository, never()).acceptFresh(any(WorldAuthoredSourceIntakeReceipt.class), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void propagatesTransientVersionStateReadFailuresWithoutOpeningOwnerTransaction() { + AuthoredWorldSourceEvidence source = source(); + WorldAuthoredSourceIntakeReceipt intake = sourceReceipt(source); + when(sourceIntakeRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.of(intake)); + when(repository.readByCanonicalVersion(NAMESPACE, TENANT, WORLD, VERSION)) + .thenReturn(Optional.empty()); + when(repository.readByGameDesignVersion(NAMESPACE, TENANT, WORLD, GAME_DESIGN_VERSION_ID)) + .thenReturn(Optional.empty()); + + for (Status.Code code : List.of(Status.Code.UNAVAILABLE, Status.Code.DEADLINE_EXCEEDED)) { + StatusRuntimeException failure = + Status.fromCode(code).withDescription("upstream transport failure").asRuntimeException(); + doThrow(failure).when(versionStateClient).read(any()); + + assertThatThrownBy(() -> withGameDesign(() -> associate(VERSION, GAME_DESIGN_VERSION_ID))) + .isSameAs(failure); + } + + verify(repository, never()).acceptFresh(any(WorldAuthoredSourceIntakeReceipt.class), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void keepsMalformedVersionStateReadEvidenceTerminalBeforeOwnerMutation() { + AuthoredWorldSourceEvidence source = source(); + WorldAuthoredSourceIntakeReceipt intake = sourceReceipt(source); + when(sourceIntakeRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.of(intake)); + when(repository.readByCanonicalVersion(NAMESPACE, TENANT, WORLD, VERSION)) + .thenReturn(Optional.empty()); + when(repository.readByGameDesignVersion(NAMESPACE, TENANT, WORLD, GAME_DESIGN_VERSION_ID)) + .thenReturn(Optional.empty()); + when(versionStateClient.read(any())) + .thenThrow( + new IllegalStateException( + "malformed evidence", new IllegalArgumentException("invalid codec evidence"))); + + assertThatThrownBy(() -> withGameDesign(() -> associate(VERSION, GAME_DESIGN_VERSION_ID))) + .isInstanceOf(WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException.class) + .hasCauseInstanceOf(IllegalStateException.class) + .hasRootCauseInstanceOf(IllegalArgumentException.class); + + verify(repository, never()).acceptFresh(any(WorldAuthoredSourceIntakeReceipt.class), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void reconcilesLostCommitAcknowledgmentFromTheOriginalStoredReceipt() { + AuthoredWorldSourceEvidence source = source(); + WorldAuthoredSourceIntakeReceipt intake = sourceReceipt(source); + AuthoredWorldVersionStateEvidence current = + versionState( + source, + READ_REQUEST, + VERSION, + GAME_DESIGN_VERSION_ID, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 8L); + WorldAuthoredVersionIdentityReceipt accepted = identityReceipt(intake, current, 102L); + when(sourceIntakeRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.of(intake)); + when(repository.readByCanonicalVersion(NAMESPACE, TENANT, WORLD, VERSION)) + .thenReturn(Optional.empty(), Optional.of(accepted)); + when(repository.readByGameDesignVersion(NAMESPACE, TENANT, WORLD, GAME_DESIGN_VERSION_ID)) + .thenReturn(Optional.empty()); + when(versionStateClient.read(any())).thenReturn(current); + when(repository.acceptFresh(intake, current)).thenReturn(accepted); + transactionManager.loseCommitAcknowledgment = true; + + WorldAuthoredVersionIdentityReceipt result = + withGameDesign(() -> associate(VERSION, GAME_DESIGN_VERSION_ID)); + + assertThat(result).isEqualTo(accepted); + assertThat(transactionManager.commitFailureThrown).isTrue(); + verify(repository, times(1)).acceptFresh(intake, current); + } + + @Test + void missingExactFreshIntakeCannotCallGameDesignOrAllocateAnIdentity() { + AuthoredWorldSourceEvidence source = source(); + when(sourceIntakeRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.empty()); + + assertThatThrownBy(() -> withGameDesign(() -> associate(VERSION, GAME_DESIGN_VERSION_ID))) + .isInstanceOf(WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException.class) + .hasMessageContaining("exact committed fresh source intake"); + + verifyNoInteractions(repository, versionStateClient); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void substitutedSourceIntakeCannotCallGameDesignOrAllocateAnIdentity() { + AuthoredWorldSourceEvidence requested = source(); + AuthoredWorldSourceEvidence substituted = + source("amber-coast", UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa")); + when(sourceIntakeRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, requested.evidenceDigest())) + .thenReturn(Optional.of(sourceReceipt(substituted))); + + assertThatThrownBy(() -> withGameDesign(() -> associate(VERSION, GAME_DESIGN_VERSION_ID))) + .isInstanceOf(WorldAuthoredVersionIdentityRepository.RegistrationConflictException.class) + .hasMessageContaining("exact fresh NEW_GAME_ROW source intake"); + + verifyNoInteractions(repository, versionStateClient); + assertThat(transactionManager.startedWith).isNull(); + } + + private WorldAuthoredVersionIdentityReceipt associate(UUID canonicalVersionId, long versionId) { + AuthoredWorldSourceEvidence source = source(); + return service.associate( + NAMESPACE, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest(), + canonicalVersionId, + versionId, + READ_REQUEST); + } + + private static WorldAuthoredVersionIdentityReceipt identityReceipt( + WorldAuthoredSourceIntakeReceipt intake, + AuthoredWorldVersionStateEvidence evidence, + long localVersionKey) { + return new WorldAuthoredVersionIdentityReceipt( + 1, + UUID.fromString("77777777-7777-4777-8777-777777777777"), + localVersionKey, + intake, + evidence); + } + + private static AuthoredWorldVersionStateEvidence versionState( + AuthoredWorldSourceEvidence source, + UUID readRequestId, + UUID canonicalVersionId, + long gameDesignVersionId, + VersionLifecycleState state, + long epoch) { + AuthoredWorldVersionStateEvidence.Request request = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + readRequestId, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest(), + gameDesignVersionId); + return AuthoredWorldVersionStateEvidence.create( + request, source, canonicalVersionId, state, epoch); + } + + private static WorldAuthoredSourceIntakeReceipt sourceReceipt( + AuthoredWorldSourceEvidence source) { + String requestDigest = + WorldAuthoredSourceIntakeDigest.requestDigest( + source.targetNamespace(), INTAKE_REQUEST, source); + return new WorldAuthoredSourceIntakeReceipt( + 1, + source.targetNamespace(), + INTAKE_REQUEST, + INTAKE_OPERATION, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + requestDigest, + WorldAuthoredSourceIntakeDigest.receiptDigest( + source.targetNamespace(), INTAKE_OPERATION, requestDigest, source, 90_041L), + 90_041L, + source); + } + + private static AuthoredWorldSourceEvidence source() { + return source(WORLD, SOURCE_OPERATION); + } + + private static AuthoredWorldSourceEvidence source(String worldSlug, UUID sourceOperationId) { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, SOURCE_REGISTRATION, TENANT, "north-star", worldSlug, "Café 🐉"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + SOURCE_REGISTRATION, + sourceOperationId, + requestDigest, + TENANT, + "north-star", + worldSlug, + "Café 🐉", + 42L, + "legacy-game-tenant-42", + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + SOURCE_REGISTRATION, + sourceOperationId, + requestDigest, + TENANT, + "north-star", + worldSlug, + "Café 🐉", + 42L, + "legacy-game-tenant-42", + "NEW_GAME_ROW", + evidenceDigest); + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static T withGameDesign(Supplier action) { + return withPeer(peer(NAMESPACE, "game-design-service"), action); + } + + private static T withPeer(GrpcPeerIdentity peer, Supplier action) { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + + private static T withoutPeer(Supplier action) { + Context previous = Context.ROOT.attach(); + try { + return action.get(); + } finally { + Context.ROOT.detach(previous); + } + } + + private static final class RecordingTransactionManager + implements org.springframework.transaction.PlatformTransactionManager { + private TransactionDefinition startedWith; + private boolean loseCommitAcknowledgment; + private boolean commitFailureThrown; + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + startedWith = definition; + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(definition.isReadOnly()); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + definition.getIsolationLevel()); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + TransactionSynchronizationManager.clear(); + if (loseCommitAcknowledgment) { + loseCommitAcknowledgment = false; + commitFailureThrown = true; + throw new IllegalStateException("simulated lost commit acknowledgment"); + } + } + + @Override + public void rollback(TransactionStatus status) { + TransactionSynchronizationManager.clear(); + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java new file mode 100644 index 0000000000..0ab1cfbae5 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java @@ -0,0 +1,1384 @@ +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.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationClient; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldCompleteLaunchBindingServiceTest { + private static final String NAMESPACE = "firemud"; + private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID INTAKE_REQUEST = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID INTAKE_OPERATION = + UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID BINDING_OPERATION = + UUID.fromString("77777777-7777-4777-8777-777777777777"); + private static final UUID VERSION = UUID.fromString("88888888-8888-4888-8888-888888888888"); + private static final UUID OTHER_CANONICAL_VERSION = + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + private static final UUID CURRENT_READ_ID = + UUID.fromString("99999999-9999-4999-8999-999999999999"); + private static final UUID ADVANCED_READ_ID = + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID OTHER_READ_ID = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID OTHER_SOURCE_OPERATION = + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private static final UUID OTHER_REGISTRATION_REQUEST = + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + private static final String WORLD = "violet-wilds"; + private static final String CONTROL_PLANE_REQUEST = "world-launch-request-41"; + + private final AuthoredWorldLaunchDescriptorClient client = + mock(AuthoredWorldLaunchDescriptorClient.class); + private final AuthoredWorldVersionStateClient versionStateClient = + mock(AuthoredWorldVersionStateClient.class); + private final CanonicalGameInstanceLaunchAssociationClient gameSessionClient = + mock(CanonicalGameInstanceLaunchAssociationClient.class); + private final WorldCompleteLaunchBindingRepository repository = + mock(WorldCompleteLaunchBindingRepository.class); + private final WorldAuthoredSourceIntakeRepository sourceRepository = + mock(WorldAuthoredSourceIntakeRepository.class); + private final RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + private final WorldCompleteLaunchBindingService service = + new WorldCompleteLaunchBindingService( + client, repository, sourceRepository, transactionManager, NAMESPACE, versionStateClient); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + SessionContext.clear(); + } + + @Test + void committedLaunchRequiresSameNamespaceGameSessionWithoutEndUserContextBeforeAccess() { + CommittedLaunchFixture fixture = committedLaunchFixture(); + WorldCompleteLaunchBindingService committedService = committedLaunchService(); + + assertThatThrownBy( + () -> withoutPeer(() -> committedService.bindCommittedLaunch(fixture.request()))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer(NAMESPACE, "game-design-service"), + () -> committedService.bindCommittedLaunch(fixture.request()))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer("other", "game-session-service"), + () -> committedService.bindCommittedLaunch(fixture.request()))) + .isInstanceOf(SecurityException.class); + + SessionContext.setContext( + "99999999-9999-4999-8999-999999999999", List.of(), java.util.Map.of()); + assertThatThrownBy( + () -> withGameSession(() -> committedService.bindCommittedLaunch(fixture.request()))) + .isInstanceOf(SecurityException.class); + + var wrongNamespaceRequest = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + fixture.request().readRequestId(), + "other", + fixture.request().canonicalTenantId(), + fixture.request().worldSlug(), + fixture.request().gameInstanceUuid(), + fixture.request().controlPlaneRequestId(), + fixture.request().launchDescriptorId(), + fixture.request().expectedDescriptorRequestDigest(), + fixture.request().expectedDescriptorResultDigest(), + fixture.request().expectedReleaseAttestationEvidenceDigest()); + SessionContext.clear(); + assertThatThrownBy( + () -> + withGameSession(() -> committedService.bindCommittedLaunch(wrongNamespaceRequest))) + .isInstanceOf(SecurityException.class); + verifyNoInteractions(client, gameSessionClient, repository, sourceRepository); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void committedLaunchFailsClosedWhenGameSessionClientWasNotConfigured() { + CommittedLaunchFixture fixture = committedLaunchFixture(); + + assertThatThrownBy(() -> withGameSession(() -> service.bindCommittedLaunch(fixture.request()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no configured Game Session owner reader"); + verifyNoInteractions(client, gameSessionClient, repository, sourceRepository); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void committedLaunchRefusesAmbientTransactionBeforeRemoteOrOwnerAccess() { + CommittedLaunchFixture fixture = committedLaunchFixture(); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy( + () -> + withGameSession( + () -> committedLaunchService().bindCommittedLaunch(fixture.request()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside ambient transactions"); + verifyNoInteractions(client, gameSessionClient, repository, sourceRepository); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void committedLaunchRejectsChangedDigestAndV1ReleaseBeforeWorldOwnerWrite() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence v1Binding = evidence(source); + var wrongDigestRequest = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + NAMESPACE, + TENANT, + WORLD, + UUID.fromString("abababab-abab-4bab-8bab-abababababab"), + CONTROL_PLANE_REQUEST, + v1Binding.descriptor().launchDescriptorId(), + v1Binding.descriptor().requestDigest(), + digest('a'), + v1Binding.releaseAttestation().evidenceDigest()); + WorldCompleteLaunchBindingService committedService = committedLaunchService(); + when(client.getComplete(any(GetLaunchDescriptorRequest.class))).thenReturn(v1Binding); + + assertThatThrownBy( + () -> withGameSession(() -> committedService.bindCommittedLaunch(wrongDigestRequest))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.RegistrationConflictException.class); + + var v1Request = committedAssociationRequest(v1Binding); + assertThatThrownBy(() -> withGameSession(() -> committedService.bindCommittedLaunch(v1Request))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("full selected-release selector evidence"); + verify(gameSessionClient, never()).read(any()); + verifyNoInteractions(repository, sourceRepository); + verify(repository, never()).acceptFresh(any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void committedLaunchRejectsGameSessionPairThatDiffersFromGameDesignBeforeSourceOrWrite() { + CommittedLaunchFixture fixture = committedLaunchFixture(); + CompleteLaunchBindingEvidence otherPair = + committedPair(fixture.evidence().descriptor(), digest('8')); + CanonicalGameInstanceLaunchAssociationReadEvidence.Result mismatchedAssociation = + mock(CanonicalGameInstanceLaunchAssociationReadEvidence.Result.class); + when(mismatchedAssociation.request()).thenReturn(fixture.request()); + when(mismatchedAssociation.playableStateScope()).thenReturn(RealmEntryPolicy.StateScope.SHARED); + when(mismatchedAssociation.publicProduction()).thenReturn(true); + when(mismatchedAssociation.launchBindingEvidence()).thenReturn(otherPair); + when(client.getComplete(any(GetLaunchDescriptorRequest.class))).thenReturn(fixture.evidence()); + when(gameSessionClient.read(fixture.request())).thenReturn(mismatchedAssociation); + + assertThatThrownBy( + () -> + withGameSession( + () -> committedLaunchService().bindCommittedLaunch(fixture.request()))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.RegistrationConflictException.class); + verify(sourceRepository, never()).readBySource(any(), any(), any(), any(), any()); + verifyNoInteractions(repository); + verify(repository, never()).acceptFresh(any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void committedLaunchRejectsGameSessionReadbackForAChangedSelectorBeforeSourceOrWrite() { + CommittedLaunchFixture fixture = committedLaunchFixture(); + var changedRequest = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.fromString("dededede-dede-4ede-8ede-dededededede"), + fixture.request().targetNamespace(), + fixture.request().canonicalTenantId(), + fixture.request().worldSlug(), + fixture.request().gameInstanceUuid(), + fixture.request().controlPlaneRequestId(), + fixture.request().launchDescriptorId(), + fixture.request().expectedDescriptorRequestDigest(), + fixture.request().expectedDescriptorResultDigest(), + fixture.request().expectedReleaseAttestationEvidenceDigest()); + CanonicalGameInstanceLaunchAssociationReadEvidence.Result changedAssociation = + mock(CanonicalGameInstanceLaunchAssociationReadEvidence.Result.class); + when(changedAssociation.request()).thenReturn(changedRequest); + when(changedAssociation.playableStateScope()).thenReturn(RealmEntryPolicy.StateScope.SHARED); + when(changedAssociation.publicProduction()).thenReturn(true); + when(changedAssociation.launchBindingEvidence()).thenReturn(fixture.evidence()); + when(client.getComplete(any(GetLaunchDescriptorRequest.class))).thenReturn(fixture.evidence()); + when(gameSessionClient.read(fixture.request())).thenReturn(changedAssociation); + + assertThatThrownBy( + () -> + withGameSession( + () -> committedLaunchService().bindCommittedLaunch(fixture.request()))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.RegistrationConflictException.class) + .hasMessageContaining("exact World selector"); + verify(sourceRepository, never()).readBySource(any(), any(), any(), any(), any()); + verifyNoInteractions(repository); + verify(repository, never()).acceptFresh(any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void exactCommittedLaunchRetryUsesTheOriginalPairWithoutAnotherOwnerWrite() { + CommittedLaunchFixture fixture = committedLaunchFixture(); + WorldCompleteLaunchBindingService committedService = committedLaunchService(); + stubCommittedLaunchReads(fixture); + when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.of(fixture.stored())); + when(repository.toReceipt(fixture.stored(), fixture.sourceReceipt())) + .thenReturn(fixture.receipt()); + + WorldCompleteLaunchBindingReceipt result = + withGameSession(() -> committedService.bindCommittedLaunch(fixture.request())); + + assertThat(result).isSameAs(fixture.receipt()); + verify(client).getComplete(any(GetLaunchDescriptorRequest.class)); + verify(gameSessionClient).read(fixture.request()); + verify(repository, never()).acceptFresh(any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void committedLaunchRetryRejectsAChangedRetainedReleasePairWithoutReplacement() { + CommittedLaunchFixture fixture = committedLaunchFixture(); + CompleteLaunchBindingEvidence changedPair = + committedPair(fixture.evidence().descriptor(), digest('8')); + WorldCompleteLaunchBindingRepository.StoredBinding changedStored = + stored(fixture.sourceReceipt(), changedPair); + stubCommittedLaunchReads(fixture); + when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.of(changedStored)); + + assertThatThrownBy( + () -> + withGameSession( + () -> committedLaunchService().bindCommittedLaunch(fixture.request()))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.RegistrationConflictException.class); + verify(repository, never()).acceptFresh(any(), any(), any()); + verify(repository, never()).toReceipt(any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void committedLaunchRequiresExactSourceIntakeBeforeWorldBindingOwnerAccess() { + CommittedLaunchFixture fixture = committedLaunchFixture(); + stubCommittedLaunchReads(fixture); + when(sourceRepository.readBySource( + NAMESPACE, + TENANT, + WORLD, + SOURCE_OPERATION, + fixture.sourceReceipt().sourceEvidenceDigest())) + .thenReturn(Optional.empty()); + + assertThatThrownBy( + () -> + withGameSession( + () -> committedLaunchService().bindCommittedLaunch(fixture.request()))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("no exact committed World source intake"); + verifyNoInteractions(repository); + verify(repository, never()).acceptFresh(any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void committedLaunchRetainsThenIndependentlyReadsBackTheExactPairInFreshOwnerTransaction() { + CommittedLaunchFixture fixture = committedLaunchFixture(); + WorldCompleteLaunchBindingService committedService = committedLaunchService(); + stubCommittedLaunchReads(fixture); + when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty(), Optional.of(fixture.stored())); + when(repository.acceptFresh(NAMESPACE, fixture.sourceReceipt(), fixture.evidence())) + .thenReturn(fixture.receipt()); + when(repository.toReceipt(fixture.stored(), fixture.sourceReceipt())) + .thenReturn(fixture.receipt()); + + WorldCompleteLaunchBindingReceipt result = + withGameSession(() -> committedService.bindCommittedLaunch(fixture.request())); + + assertThat(result).isSameAs(fixture.receipt()); + assertThat(transactionManager.startedWith.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(transactionManager.startedWith.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(transactionManager.startedWith.isReadOnly()).isFalse(); + ArgumentCaptor descriptorRead = + ArgumentCaptor.forClass(GetLaunchDescriptorRequest.class); + verify(client).getComplete(descriptorRead.capture()); + assertThat(descriptorRead.getValue().getRequestId()) + .isNotEqualTo(fixture.request().readRequestId().toString()); + assertThat(descriptorRead.getValue().getCanonicalTenantId()).isEqualTo(TENANT.toString()); + assertThat(descriptorRead.getValue().getWorldSlug()).isEqualTo(WORLD); + assertThat(descriptorRead.getValue().getControlPlaneRequestId()) + .isEqualTo(CONTROL_PLANE_REQUEST); + assertThat(descriptorRead.getValue().getExpectedRequestDigest()) + .isEqualTo(fixture.request().expectedDescriptorRequestDigest()); + assertThat(descriptorRead.getValue().getExpectedResultDigest()) + .isEqualTo(fixture.request().expectedDescriptorResultDigest()); + InOrder committedReadOrder = inOrder(client, gameSessionClient, sourceRepository, repository); + committedReadOrder.verify(client).getComplete(any(GetLaunchDescriptorRequest.class)); + committedReadOrder.verify(gameSessionClient).read(fixture.request()); + committedReadOrder + .verify(sourceRepository) + .readBySource( + NAMESPACE, + TENANT, + WORLD, + SOURCE_OPERATION, + fixture.sourceReceipt().sourceEvidenceDigest()); + committedReadOrder.verify(repository).read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST); + committedReadOrder + .verify(repository) + .acceptFresh(NAMESPACE, fixture.sourceReceipt(), fixture.evidence()); + committedReadOrder.verify(repository).read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST); + committedReadOrder + .verify(sourceRepository) + .readBySource( + NAMESPACE, + TENANT, + WORLD, + SOURCE_OPERATION, + fixture.sourceReceipt().sourceEvidenceDigest()); + committedReadOrder.verify(repository).toReceipt(fixture.stored(), fixture.sourceReceipt()); + verify(gameSessionClient).read(fixture.request()); + verify(repository).acceptFresh(NAMESPACE, fixture.sourceReceipt(), fixture.evidence()); + verify(repository).toReceipt(fixture.stored(), fixture.sourceReceipt()); + } + + @Test + void committedLaunchRecoversLostCommitAcknowledgmentOnlyForTheSamePair() { + CommittedLaunchFixture fixture = committedLaunchFixture(); + stubCommittedLaunchReads(fixture); + when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty(), Optional.of(fixture.stored())); + when(repository.acceptFresh(NAMESPACE, fixture.sourceReceipt(), fixture.evidence())) + .thenReturn(fixture.receipt()); + when(repository.toReceipt(fixture.stored(), fixture.sourceReceipt())) + .thenReturn(fixture.receipt()); + transactionManager.loseCommitAcknowledgment = true; + + WorldCompleteLaunchBindingReceipt recovered = + withGameSession(() -> committedLaunchService().bindCommittedLaunch(fixture.request())); + + assertThat(recovered).isSameAs(fixture.receipt()); + verify(repository).acceptFresh(NAMESPACE, fixture.sourceReceipt(), fixture.evidence()); + verify(repository).toReceipt(fixture.stored(), fixture.sourceReceipt()); + assertThat(transactionManager.commitFailureThrown).isTrue(); + } + + @Test + void committedLaunchRejectsChangedPairDuringLostCommitAcknowledgmentRecovery() { + CommittedLaunchFixture fixture = committedLaunchFixture(); + CompleteLaunchBindingEvidence changedPair = + committedPair(fixture.evidence().descriptor(), digest('8')); + WorldCompleteLaunchBindingRepository.StoredBinding changedStored = + stored(fixture.sourceReceipt(), changedPair); + stubCommittedLaunchReads(fixture); + when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty(), Optional.of(changedStored)); + when(repository.acceptFresh(NAMESPACE, fixture.sourceReceipt(), fixture.evidence())) + .thenReturn(fixture.receipt()); + transactionManager.loseCommitAcknowledgment = true; + + assertThatThrownBy( + () -> + withGameSession( + () -> committedLaunchService().bindCommittedLaunch(fixture.request()))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.RegistrationConflictException.class); + verify(repository).acceptFresh(NAMESPACE, fixture.sourceReceipt(), fixture.evidence()); + verify(repository, never()).toReceipt(any(), any()); + assertThat(transactionManager.commitFailureThrown).isTrue(); + } + + @Test + void requiresExactSameNamespaceGameSessionPeerBeforeOwnerOrGameDesignAccess() { + GetRequest request = request(evidence(source())); + + assertThatThrownBy(() -> withoutPeer(() -> service.bind(request))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> withPeer(peer(NAMESPACE, "game-design-service"), () -> service.bind(request))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> withPeer(peer("other", "game-session-service"), () -> service.bind(request))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> withoutPeer(() -> service.readCurrentVersionState(request, CURRENT_READ_ID))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer(NAMESPACE, "game-design-service"), + () -> service.readCurrentVersionState(request, CURRENT_READ_ID))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer("other", "game-session-service"), + () -> service.readCurrentVersionState(request, CURRENT_READ_ID))) + .isInstanceOf(SecurityException.class); + AuthoredWorldLaunchDescriptorEvidence.Request original = request.expectedRequest(); + AuthoredWorldLaunchDescriptorEvidence.Request wrongNamespace = + new AuthoredWorldLaunchDescriptorEvidence.Request( + "other", + original.controlPlaneRequestId(), + original.canonicalTenantId(), + original.worldSlug(), + original.authoredWorldSourceOperationId(), + original.authoredWorldSourceEvidenceDigest(), + original.gameTemplateId(), + original.requestedScriptPatchVersionPresent(), + original.requestedScriptPatchVersion(), + original.sourceVersionIdPresent(), + original.sourceVersionId(), + original.targetVersionIdPresent(), + original.targetVersionId(), + original.requestedRuntimeFlagsJsonPresent(), + original.requestedRuntimeFlagsJson()); + assertThatThrownBy( + () -> + withGameSession( + () -> + service.bind( + new GetRequest(UUID.randomUUID(), wrongNamespace, digest('a'))))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withGameSession( + () -> + service.readCurrentVersionState( + new GetRequest(UUID.randomUUID(), wrongNamespace, digest('a')), + CURRENT_READ_ID))) + .isInstanceOf(SecurityException.class); + verifyNoInteractions(client, versionStateClient, repository, sourceRepository); + } + + @Test + void retainsCompletePairThenIndependentlyReadsBackTheSameOwnerReceipt() { + AuthoredWorldSourceEvidence source = source(); + WorldAuthoredSourceIntakeReceipt sourceReceipt = sourceReceipt(source); + CompleteLaunchBindingEvidence evidence = evidence(source); + GetRequest request = request(evidence); + WorldCompleteLaunchBindingReceipt receipt = bindingReceipt(sourceReceipt, evidence); + WorldCompleteLaunchBindingRepository.StoredBinding stored = stored(receipt); + when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty(), Optional.of(stored)); + when(client.getComplete(any())).thenReturn(evidence); + when(sourceRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.of(sourceReceipt)); + when(repository.acceptFresh(NAMESPACE, sourceReceipt, evidence)).thenReturn(receipt); + when(repository.toReceipt(stored, sourceReceipt)).thenReturn(receipt); + + WorldCompleteLaunchBindingReceipt result = withGameSession(() -> service.bind(request)); + + assertThat(result).isEqualTo(receipt); + assertThat(transactionManager.startedWith.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(transactionManager.startedWith.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(transactionManager.startedWith.isReadOnly()).isFalse(); + verify(client).getComplete(any()); + verify(repository).acceptFresh(NAMESPACE, sourceReceipt, evidence); + verify(repository).toReceipt(stored, sourceReceipt); + } + + @Test + void exactRetryReadsTheStoredPairBeforeLocalSourceAndDoesNotCallGameDesign() { + AuthoredWorldSourceEvidence source = source(); + WorldAuthoredSourceIntakeReceipt sourceReceipt = sourceReceipt(source); + CompleteLaunchBindingEvidence evidence = evidence(source); + GetRequest request = request(evidence); + WorldCompleteLaunchBindingReceipt receipt = bindingReceipt(sourceReceipt, evidence); + WorldCompleteLaunchBindingRepository.StoredBinding stored = stored(receipt); + when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)).thenReturn(Optional.of(stored)); + when(sourceRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.of(sourceReceipt)); + when(repository.toReceipt(stored, sourceReceipt)).thenReturn(receipt); + + WorldCompleteLaunchBindingReceipt result = withGameSession(() -> service.bind(request)); + + assertThat(result).isEqualTo(receipt); + verify(repository).read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST); + verify(client, never()).getComplete(any()); + verify(repository, never()).acceptFresh(any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void changedExpectedResultConflictsBeforeSourceLookupOrGameDesign() { + AuthoredWorldSourceEvidence source = source(); + WorldAuthoredSourceIntakeReceipt sourceReceipt = sourceReceipt(source); + CompleteLaunchBindingEvidence evidence = evidence(source); + WorldCompleteLaunchBindingReceipt receipt = bindingReceipt(sourceReceipt, evidence); + WorldCompleteLaunchBindingRepository.StoredBinding stored = stored(receipt); + when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)).thenReturn(Optional.of(stored)); + GetRequest changed = + new GetRequest(UUID.randomUUID(), evidence.descriptor().request(), digest('b')); + + assertThatThrownBy(() -> withGameSession(() -> service.bind(changed))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.RegistrationConflictException.class); + verify(repository).read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST); + verifyNoInteractions(client, sourceRepository); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void missingOrSwappedCompletePairCannotReachWorldPersistence() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence expectedEvidence = evidence(source); + CompleteLaunchBindingEvidence otherEvidence = + evidence(source, "another-world-launch-request", 42L); + assertThatThrownBy( + () -> + new CompleteLaunchBindingEvidence( + expectedEvidence.descriptor(), otherEvidence.releaseAttestation())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new CompleteLaunchBindingEvidence(null, null)) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy(() -> new CompleteLaunchBindingEvidence(expectedEvidence.descriptor(), null)) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy( + () -> new CompleteLaunchBindingEvidence(null, expectedEvidence.releaseAttestation())) + .isInstanceOf(NullPointerException.class); + + when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)).thenReturn(Optional.empty()); + when(client.getComplete(any())).thenReturn(null); + + assertThatThrownBy(() -> withGameSession(() -> service.bind(request(expectedEvidence)))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("no complete launch binding"); + verify(repository, never()).acceptFresh(any(), any(), any()); + verifyNoInteractions(sourceRepository); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void refusesAmbientTransactionBeforeReadingOrCallingGameDesign() { + CompleteLaunchBindingEvidence evidence = evidence(source()); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy(() -> withGameSession(() -> service.bind(request(evidence)))) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(request(evidence), CURRENT_READ_ID))) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(client, versionStateClient, repository, sourceRepository); + } + + @Test + void recoversACommitAcknowledgmentLossByReadingTheSameOwnerOperation() { + AuthoredWorldSourceEvidence source = source(); + WorldAuthoredSourceIntakeReceipt sourceReceipt = sourceReceipt(source); + CompleteLaunchBindingEvidence evidence = evidence(source); + GetRequest request = request(evidence); + WorldCompleteLaunchBindingReceipt receipt = bindingReceipt(sourceReceipt, evidence); + WorldCompleteLaunchBindingRepository.StoredBinding stored = stored(receipt); + AtomicReference committed = + new AtomicReference<>(); + when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)) + .thenAnswer( + invocation -> { + WorldCompleteLaunchBindingRepository.StoredBinding value = committed.get(); + return value == null ? Optional.empty() : Optional.of(value); + }); + when(client.getComplete(any())).thenReturn(evidence); + when(sourceRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.of(sourceReceipt)); + when(repository.acceptFresh(NAMESPACE, sourceReceipt, evidence)) + .thenAnswer( + invocation -> { + committed.set(stored); + return receipt; + }); + when(repository.toReceipt(stored, sourceReceipt)).thenReturn(receipt); + transactionManager.loseCommitAcknowledgment = true; + + WorldCompleteLaunchBindingReceipt recovered = withGameSession(() -> service.bind(request)); + + assertThat(recovered.operationId()).isEqualTo(receipt.operationId()); + assertThat(recovered.evidence()).isEqualTo(evidence); + verify(client).getComplete(any()); + verify(repository).acceptFresh(NAMESPACE, sourceReceipt, evidence); + assertThat(transactionManager.commitFailureThrown).isTrue(); + } + + @Test + void readsPublishedCurrentVersionFromTheCommittedPairAndDescriptorVersionId() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence binding = evidence(source); + WorldCompleteLaunchBindingReceipt original = stubCommittedBinding(source, binding); + AuthoredWorldVersionStateEvidence current = + currentVersionState( + source, + CURRENT_READ_ID, + binding.descriptor().versionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + binding.descriptor().versionStateEpoch()); + when(versionStateClient.read(any())).thenReturn(current); + + AuthoredWorldVersionStateEvidence result = + withGameSession(() -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID)); + + assertThat(result).isEqualTo(current); + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(AuthoredWorldVersionStateEvidence.Request.class); + InOrder readOrder = inOrder(repository, sourceRepository, versionStateClient); + readOrder.verify(repository).read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST); + readOrder + .verify(sourceRepository) + .readBySource(NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest()); + readOrder.verify(repository).toReceipt(any(), any()); + readOrder.verify(versionStateClient).read(requestCaptor.capture()); + AuthoredWorldVersionStateEvidence.Request currentRequest = requestCaptor.getValue(); + assertThat(currentRequest.targetNamespace()).isEqualTo(original.targetNamespace()); + assertThat(currentRequest.canonicalTenantId()).isEqualTo(original.canonicalTenantId()); + assertThat(currentRequest.worldSlug()).isEqualTo(original.worldSlug()); + assertThat(currentRequest.sourceOperationId()).isEqualTo(SOURCE_OPERATION); + assertThat(currentRequest.expectedSourceEvidenceDigest()).isEqualTo(source.evidenceDigest()); + assertThat(currentRequest.versionId()).isEqualTo(binding.descriptor().versionId()); + assertThat(currentRequest.versionId()) + .isNotEqualTo(original.sourceIntakeReceipt().localTenantKey()); + assertThat(currentRequest.readRequestId()).isEqualTo(CURRENT_READ_ID); + assertThat(original.evidence()).isEqualTo(binding); + assertThat(original.operationId()).isEqualTo(BINDING_OPERATION); + assertThat(transactionManager.startedWith).isNull(); + verify(client, never()).getComplete(any()); + verify(repository, never()).acceptFresh(any(), any(), any()); + } + + @Test + void acceptsActiveCurrentVersionAtTheDescriptorEpoch() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence binding = evidence(source); + stubCommittedBinding(source, binding); + AuthoredWorldVersionStateEvidence current = + currentVersionState( + source, + CURRENT_READ_ID, + binding.descriptor().versionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE, + binding.descriptor().versionStateEpoch()); + when(versionStateClient.read(any())).thenReturn(current); + + AuthoredWorldVersionStateEvidence result = + withGameSession(() -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID)); + + assertThat(result).isEqualTo(current); + verify(repository, never()).acceptFresh(any(), any(), any()); + } + + @Test + void repeatedCurrentReadsObserveVersionAdvanceAndRejectTheStaleDescriptorPair() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence binding = evidence(source); + WorldCompleteLaunchBindingReceipt original = stubCommittedBinding(source, binding); + AuthoredWorldVersionStateEvidence first = + currentVersionState( + source, + CURRENT_READ_ID, + binding.descriptor().versionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + binding.descriptor().versionStateEpoch()); + AuthoredWorldVersionStateEvidence advanced = + currentVersionState( + source, + ADVANCED_READ_ID, + binding.descriptor().versionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE, + binding.descriptor().versionStateEpoch() + 1); + when(versionStateClient.read(any())).thenReturn(first, advanced); + + AuthoredWorldVersionStateEvidence firstRead = + withGameSession(() -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID)); + assertThat(firstRead).isEqualTo(first); + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), ADVANCED_READ_ID))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("epoch differs"); + + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(AuthoredWorldVersionStateEvidence.Request.class); + verify(versionStateClient, times(2)).read(requestCaptor.capture()); + assertThat(requestCaptor.getAllValues()) + .extracting(AuthoredWorldVersionStateEvidence.Request::readRequestId) + .containsExactly(CURRENT_READ_ID, ADVANCED_READ_ID); + assertThat(original.evidence()).isEqualTo(binding); + assertThat(original.operationId()).isEqualTo(BINDING_OPERATION); + verify(client, never()).getComplete(any()); + verify(repository, never()).acceptFresh(any(), any(), any()); + } + + @Test + void rejectsCurrentEvidenceForAnotherAuthoredSource() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence binding = evidence(source); + stubCommittedBinding(source, binding); + AuthoredWorldSourceEvidence otherSource = + source("other-world", OTHER_REGISTRATION_REQUEST, OTHER_SOURCE_OPERATION); + AuthoredWorldVersionStateEvidence swappedSource = + currentVersionState( + otherSource, + CURRENT_READ_ID, + binding.descriptor().versionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + binding.descriptor().versionStateEpoch()); + when(versionStateClient.read(any())).thenReturn(swappedSource); + + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("exact committed World source"); + verify(repository, never()).acceptFresh(any(), any(), any()); + } + + @Test + void rejectsAChangedVersionSelectorInCurrentOwnerEvidence() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence binding = evidence(source); + stubCommittedBinding(source, binding); + AuthoredWorldVersionStateEvidence swappedSelector = + currentVersionState( + source, + CURRENT_READ_ID, + binding.descriptor().versionId() + 1, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + binding.descriptor().versionStateEpoch()); + when(versionStateClient.read(any())).thenReturn(swappedSelector); + + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("exact committed World source"); + verify(repository, never()).acceptFresh(any(), any(), any()); + } + + @Test + void rejectsCurrentEvidenceWithCanonicalVersionUuidDifferentFromReleaseAttestation() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence binding = evidence(source); + stubCommittedBinding(source, binding); + UUID committedCanonicalVersionId = binding.releaseAttestation().canonicalVersionId(); + AuthoredWorldVersionStateEvidence expected = + currentVersionState( + source, + committedCanonicalVersionId, + CURRENT_READ_ID, + binding.descriptor().versionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + binding.descriptor().versionStateEpoch()); + AuthoredWorldVersionStateEvidence substituted = + currentVersionState( + source, + OTHER_CANONICAL_VERSION, + CURRENT_READ_ID, + binding.descriptor().versionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + binding.descriptor().versionStateEpoch()); + assertThat(substituted.request()).isEqualTo(expected.request()); + assertThat(substituted.sourceEvidence()).isEqualTo(expected.sourceEvidence()); + assertThat(substituted.versionState()).isEqualTo(expected.versionState()); + assertThat(substituted.versionStateEpoch()).isEqualTo(expected.versionStateEpoch()); + assertThat(substituted.canonicalVersionId()).isNotEqualTo(committedCanonicalVersionId); + when(versionStateClient.read(any())).thenReturn(substituted); + + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("canonical version UUID differs"); + verify(repository, never()).acceptFresh(any(), any(), any()); + } + + @Test + void changedBindingRequestIsRejectedBeforeReadingCurrentOwnerEvidence() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence binding = evidence(source); + stubCommittedBinding(source, binding); + GetRequest substituted = + new GetRequest(UUID.randomUUID(), binding.descriptor().request(), digest('b')); + + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(substituted, CURRENT_READ_ID))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.RegistrationConflictException.class); + verifyNoInteractions(versionStateClient); + verify(repository, never()).acceptFresh(any(), any(), any()); + } + + @Test + void requiresAnAlreadyCommittedPairWithoutRegisteringOne() { + CompleteLaunchBindingEvidence binding = evidence(source()); + when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)).thenReturn(Optional.empty()); + + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("requires a committed launch binding"); + verifyNoInteractions(client, versionStateClient, sourceRepository); + verify(repository, never()).acceptFresh(any(), any(), any()); + } + + @Test + void deniesDraftRetiredAndUnavailableCurrentVersionEvidenceWithoutChangingThePair() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence binding = evidence(source); + WorldCompleteLaunchBindingReceipt original = stubCommittedBinding(source, binding); + AuthoredWorldVersionStateEvidence draft = + currentVersionState( + source, + CURRENT_READ_ID, + binding.descriptor().versionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + binding.descriptor().versionStateEpoch()); + when(versionStateClient.read(any())).thenReturn(draft); + + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("not PUBLISHED or ACTIVE"); + + AuthoredWorldVersionStateEvidence retired = + currentVersionState( + source, + OTHER_READ_ID, + binding.descriptor().versionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_RETIRED, + binding.descriptor().versionStateEpoch()); + when(versionStateClient.read(any())).thenReturn(retired); + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), OTHER_READ_ID))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("not PUBLISHED or ACTIVE"); + + when(versionStateClient.read(any())) + .thenThrow(new IllegalStateException("Game Design is unavailable")); + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), ADVANCED_READ_ID))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("unavailable or invalid"); + assertThat(original.evidence()).isEqualTo(binding); + verify(repository, never()).acceptFresh(any(), any(), any()); + } + + @Test + void rejectsReadCorrelationIdsReusedFromSourceOrRegistration() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence binding = evidence(source); + stubCommittedBinding(source, binding); + + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), SOURCE_OPERATION))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("separate from source and registration IDs"); + assertThatThrownBy( + () -> + withGameSession( + () -> + service.readCurrentVersionState( + request(binding), source.registrationRequestId()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("separate from source and registration IDs"); + assertThatThrownBy( + () -> + withGameSession( + () -> + service.readCurrentVersionState( + request(binding), request(binding).requestId()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("separate from source and registration IDs"); + verifyNoInteractions(versionStateClient); + } + + private WorldCompleteLaunchBindingService committedLaunchService() { + return new WorldCompleteLaunchBindingService( + client, + repository, + sourceRepository, + transactionManager, + NAMESPACE, + versionStateClient, + gameSessionClient); + } + + private void stubCommittedLaunchReads(CommittedLaunchFixture fixture) { + when(client.getComplete(any(GetLaunchDescriptorRequest.class))).thenReturn(fixture.evidence()); + when(gameSessionClient.read(fixture.request())).thenReturn(fixture.associationResult()); + when(sourceRepository.readBySource( + NAMESPACE, + TENANT, + WORLD, + SOURCE_OPERATION, + fixture.sourceReceipt().sourceEvidenceDigest())) + .thenReturn(Optional.of(fixture.sourceReceipt())); + } + + private static CommittedLaunchFixture committedLaunchFixture() { + AuthoredWorldSourceEvidence source = source(); + WorldAuthoredSourceIntakeReceipt sourceReceipt = sourceReceipt(source); + AuthoredWorldLaunchDescriptorEvidence descriptor = evidence(source).descriptor(); + CompleteLaunchBindingEvidence pair = committedPair(descriptor, digest('7')); + var request = committedAssociationRequest(pair); + var associationResult = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Result( + request, + UUID.fromString("abababab-abab-4bab-8bab-abababababab"), + RealmEntryPolicy.StateScope.SHARED, + true, + CurrentGameInstanceStatus.RUNNING, + 7L, + UUID.fromString("cdcdcdcd-cdcd-4dcd-8dcd-cdcdcdcdcdcd"), + 1L, + pair); + WorldCompleteLaunchBindingReceipt receipt = mock(WorldCompleteLaunchBindingReceipt.class); + when(receipt.targetNamespace()).thenReturn(NAMESPACE); + when(receipt.canonicalTenantId()).thenReturn(TENANT); + when(receipt.worldSlug()).thenReturn(WORLD); + when(receipt.controlPlaneRequestId()).thenReturn(CONTROL_PLANE_REQUEST); + when(receipt.sourceIntakeReceipt()).thenReturn(sourceReceipt); + when(receipt.evidence()).thenReturn(pair); + when(receipt.descriptor()).thenReturn(descriptor); + + WorldCompleteLaunchBindingRepository.StoredBinding stored = + new WorldCompleteLaunchBindingRepository.StoredBinding( + BINDING_OPERATION, + NAMESPACE, + TENANT, + WORLD, + CONTROL_PLANE_REQUEST, + sourceReceipt.operationId(), + sourceReceipt.intakeRequestId(), + sourceReceipt.localTenantKey(), + sourceReceipt.sourceOperationId(), + sourceReceipt.sourceEvidenceDigest(), + sourceReceipt.receiptDigest(), + descriptor.requestDigest(), + descriptor.resultDigest(), + pair.releaseAttestation().evidenceDigest(), + pair); + return new CommittedLaunchFixture( + source, sourceReceipt, pair, request, associationResult, stored, receipt); + } + + private static WorldCompleteLaunchBindingRepository.StoredBinding stored( + WorldAuthoredSourceIntakeReceipt sourceReceipt, CompleteLaunchBindingEvidence pair) { + AuthoredWorldLaunchDescriptorEvidence descriptor = pair.descriptor(); + return new WorldCompleteLaunchBindingRepository.StoredBinding( + BINDING_OPERATION, + NAMESPACE, + TENANT, + WORLD, + CONTROL_PLANE_REQUEST, + sourceReceipt.operationId(), + sourceReceipt.intakeRequestId(), + sourceReceipt.localTenantKey(), + sourceReceipt.sourceOperationId(), + sourceReceipt.sourceEvidenceDigest(), + sourceReceipt.receiptDigest(), + descriptor.requestDigest(), + descriptor.resultDigest(), + pair.releaseAttestation().evidenceDigest(), + pair); + } + + // The closed pair is mocked in these component tests; this is not authenticated owner-storage + // proof. + private static CompleteLaunchBindingEvidence committedPair( + AuthoredWorldLaunchDescriptorEvidence descriptor, String releaseEvidenceDigest) { + AuthoredWorldReleaseAttestationEvidence release = + mock(AuthoredWorldReleaseAttestationEvidence.class); + WorldPublishedStartLocationEvidence selector = mock(WorldPublishedStartLocationEvidence.class); + WorldPublishedStartLocationEvidence.Request selectorRequest = + mock(WorldPublishedStartLocationEvidence.Request.class); + when(selector.request()).thenReturn(selectorRequest); + when(selectorRequest.intakeRequestId()).thenReturn(INTAKE_REQUEST); + when(release.schemaVersion()) + .thenReturn(AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + when(release.evidenceDigest()).thenReturn(releaseEvidenceDigest); + when(release.worldStartLocationEvidence()).thenReturn(selector); + CompleteLaunchBindingEvidence pair = mock(CompleteLaunchBindingEvidence.class); + when(pair.descriptor()).thenReturn(descriptor); + when(pair.releaseAttestation()).thenReturn(release); + return pair; + } + + private static CanonicalGameInstanceLaunchAssociationReadEvidence.Request + committedAssociationRequest(CompleteLaunchBindingEvidence evidence) { + return new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + NAMESPACE, + evidence.descriptor().canonicalTenantId(), + evidence.descriptor().worldSlug(), + UUID.fromString("abababab-abab-4bab-8bab-abababababab"), + evidence.descriptor().controlPlaneRequestId(), + evidence.descriptor().launchDescriptorId(), + evidence.descriptor().requestDigest(), + evidence.descriptor().resultDigest(), + evidence.releaseAttestation().evidenceDigest()); + } + + private record CommittedLaunchFixture( + AuthoredWorldSourceEvidence source, + WorldAuthoredSourceIntakeReceipt sourceReceipt, + CompleteLaunchBindingEvidence evidence, + CanonicalGameInstanceLaunchAssociationReadEvidence.Request request, + CanonicalGameInstanceLaunchAssociationReadEvidence.Result associationResult, + WorldCompleteLaunchBindingRepository.StoredBinding stored, + WorldCompleteLaunchBindingReceipt receipt) {} + + private WorldCompleteLaunchBindingReceipt stubCommittedBinding( + AuthoredWorldSourceEvidence source, CompleteLaunchBindingEvidence evidence) { + WorldAuthoredSourceIntakeReceipt sourceReceipt = sourceReceipt(source); + WorldCompleteLaunchBindingReceipt receipt = bindingReceipt(sourceReceipt, evidence); + WorldCompleteLaunchBindingRepository.StoredBinding stored = stored(receipt); + when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)).thenReturn(Optional.of(stored)); + when(sourceRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.of(sourceReceipt)); + when(repository.toReceipt(stored, sourceReceipt)).thenReturn(receipt); + return receipt; + } + + private static AuthoredWorldVersionStateEvidence currentVersionState( + AuthoredWorldSourceEvidence source, + UUID readId, + long versionId, + VersionLifecycleState state, + long epoch) { + return currentVersionState(source, VERSION, readId, versionId, state, epoch); + } + + private static AuthoredWorldVersionStateEvidence currentVersionState( + AuthoredWorldSourceEvidence source, + UUID canonicalVersionId, + UUID readId, + long versionId, + VersionLifecycleState state, + long epoch) { + AuthoredWorldVersionStateEvidence.Request request = + new AuthoredWorldVersionStateEvidence.Request( + 1, + source.targetNamespace(), + readId, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + versionId); + return AuthoredWorldVersionStateEvidence.create( + request, source, canonicalVersionId, state, epoch); + } + + private static WorldCompleteLaunchBindingRepository.StoredBinding stored( + WorldCompleteLaunchBindingReceipt receipt) { + AuthoredWorldLaunchDescriptorEvidence descriptor = receipt.descriptor(); + return new WorldCompleteLaunchBindingRepository.StoredBinding( + receipt.operationId(), + receipt.targetNamespace(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + receipt.controlPlaneRequestId(), + receipt.sourceIntakeReceipt().operationId(), + receipt.sourceIntakeReceipt().intakeRequestId(), + receipt.sourceIntakeReceipt().localTenantKey(), + receipt.sourceIntakeReceipt().sourceOperationId(), + receipt.sourceIntakeReceipt().sourceEvidenceDigest(), + receipt.sourceIntakeReceipt().receiptDigest(), + descriptor.requestDigest(), + descriptor.resultDigest(), + receipt.evidence().releaseAttestation().evidenceDigest(), + receipt.evidence()); + } + + private static WorldCompleteLaunchBindingReceipt bindingReceipt( + WorldAuthoredSourceIntakeReceipt sourceReceipt, CompleteLaunchBindingEvidence evidence) { + return new WorldCompleteLaunchBindingReceipt( + 1, + BINDING_OPERATION, + NAMESPACE, + TENANT, + WORLD, + CONTROL_PLANE_REQUEST, + sourceReceipt, + evidence); + } + + private static GetRequest request(CompleteLaunchBindingEvidence evidence) { + return new GetRequest( + UUID.fromString("66666666-6666-4666-8666-666666666666"), + evidence.descriptor().request(), + evidence.descriptor().resultDigest()); + } + + private static CompleteLaunchBindingEvidence evidence(AuthoredWorldSourceEvidence source) { + return evidence(source, CONTROL_PLANE_REQUEST, 41L); + } + + private static CompleteLaunchBindingEvidence evidence( + AuthoredWorldSourceEvidence source, String controlPlaneRequestId, long gameTemplateId) { + AuthoredWorldLaunchDescriptorEvidence.Request request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest(), + gameTemplateId, + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + "launch-descriptor-" + gameTemplateId, + 42L, + false, + null, + "{}", + "generation-config-41", + 7L, + 51L, + "release-bundle-51", + false, + null); + String commitId = "commit-41"; + List participants = + List.of( + participant("WORLD_MANAGEMENT", 3, "a", false), + participant("ENTITY_MANAGEMENT", 2, "b", false), + participant("GAME_LOGIC", 1, "c", true), + participant("AUTOMATION_SCRIPTING", 5, "d", false), + participant("GAME_DESIGN_CONTROL_PLANE", 1, "e", false)); + AuthoredWorldReleaseAttestationEvidence attestation = + AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + TENANT, + VERSION, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish:owner:launch-41", + commitId, + participants, + digest('f'), + 1, + List.of(), + List.of(), + List.of("look"), + descriptor.generationConfigRevision()); + return new CompleteLaunchBindingEvidence(descriptor, attestation); + } + + private static AuthoredWorldReleaseAttestationEvidence.Participant participant( + String owner, int schema, String contentHex, boolean hasAbilityDigest) { + return new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + "42", + false, + null, + "commit-41", + contentHex.repeat(64), + schema, + hasAbilityDigest, + hasAbilityDigest ? digest('c') : null); + } + + private static WorldAuthoredSourceIntakeReceipt sourceReceipt( + AuthoredWorldSourceEvidence source) { + String requestDigest = + WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, INTAKE_REQUEST, source); + return new WorldAuthoredSourceIntakeReceipt( + 1, + NAMESPACE, + INTAKE_REQUEST, + INTAKE_OPERATION, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest(), + requestDigest, + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, INTAKE_OPERATION, requestDigest, source, 90_041L), + 90_041L, + source); + } + + private static AuthoredWorldSourceEvidence source() { + return source(WORLD, UUID.fromString("11111111-1111-4111-8111-111111111111"), SOURCE_OPERATION); + } + + private static AuthoredWorldSourceEvidence source( + String worldSlug, UUID registrationRequest, UUID sourceOperation) { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequest, TENANT, "north-star", worldSlug, "Café 🐉"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequest, + sourceOperation, + requestDigest, + TENANT, + "north-star", + worldSlug, + "Café 🐉", + 42L, + "legacy-game-tenant-42", + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequest, + sourceOperation, + requestDigest, + TENANT, + "north-star", + worldSlug, + "Café 🐉", + 42L, + "legacy-game-tenant-42", + "NEW_GAME_ROW", + evidenceDigest); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static T withGameSession(Supplier action) { + return withPeer(peer(NAMESPACE, "game-session-service"), action); + } + + private static T withPeer(GrpcPeerIdentity peer, Supplier action) { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + + private static T withoutPeer(Supplier action) { + Context previous = Context.ROOT.attach(); + try { + return action.get(); + } finally { + Context.ROOT.detach(previous); + } + } + + private static final class RecordingTransactionManager + implements org.springframework.transaction.PlatformTransactionManager { + private TransactionDefinition startedWith; + private boolean loseCommitAcknowledgment; + private boolean commitFailureThrown; + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + startedWith = definition; + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(definition.isReadOnly()); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + definition.getIsolationLevel()); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + TransactionSynchronizationManager.clear(); + if (loseCommitAcknowledgment) { + loseCommitAcknowledgment = false; + commitFailureThrown = true; + throw new IllegalStateException("simulated lost commit acknowledgment"); + } + } + + @Override + public void rollback(TransactionStatus status) { + TransactionSynchronizationManager.clear(); + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceCommittedReadTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceCommittedReadTest.java new file mode 100644 index 0000000000..7f8d343ffa --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceCommittedReadTest.java @@ -0,0 +1,106 @@ +package unit.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.Mockito.doReturn; +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 java.util.UUID; +import javax.sql.DataSource; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository; +import org.jooq.Condition; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SelectConditionStep; +import org.jooq.SelectWhereStep; +import org.jooq.Table; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.aop.framework.ProxyFactory; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource; +import org.springframework.transaction.interceptor.TransactionInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldDesignPublicationFenceCommittedReadTest { + private static final UUID PUBLICATION_FENCE = + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + + @AfterEach + void clearTransactionState() { + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + @Test + void springProxyReadsWithNoAmbientTransactionOrSynchronization() { + DSLContext dsl = mockMissingAttemptQuery(); + WorldDesignPublicationFenceRepository repository = proxiedRepository(dsl); + + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(repository.readAttemptByFence(PUBLICATION_FENCE)).isEmpty(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + verify(dsl).selectFrom(any(Table.class)); + } + + @Test + void rejectsAnAmbientActualTransactionBeforeQuerying() { + DSLContext dsl = mock(DSLContext.class); + WorldDesignPublicationFenceRepository repository = proxiedRepository(dsl); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> repository.readAttemptByFence(PUBLICATION_FENCE)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("World publication attempt read requires a committed read"); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + verifyNoInteractions(dsl); + } + + @Test + void rejectsAnAmbientEmptySynchronizationBeforeQuerying() { + DSLContext dsl = mock(DSLContext.class); + WorldDesignPublicationFenceRepository repository = proxiedRepository(dsl); + TransactionSynchronizationManager.initSynchronization(); + + assertThatThrownBy(() -> repository.readAttemptByFence(PUBLICATION_FENCE)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("World publication attempt read requires a committed read"); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + verifyNoInteractions(dsl); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private static DSLContext mockMissingAttemptQuery() { + DSLContext dsl = mock(DSLContext.class); + SelectWhereStep selectedTable = mock(SelectWhereStep.class); + SelectConditionStep selectedAttempt = mock(SelectConditionStep.class); + doReturn(selectedTable).when(dsl).selectFrom(any(Table.class)); + when(selectedTable.where(any(Condition.class))).thenReturn(selectedAttempt); + when(selectedAttempt.fetchOne()).thenReturn(null); + return dsl; + } + + private static WorldDesignPublicationFenceRepository proxiedRepository(DSLContext dsl) { + var repository = + new WorldDesignPublicationFenceRepository( + dsl, mock(WorldAuthoredSourceIntakeRepository.class)); + var transactionInterceptor = new TransactionInterceptor(); + transactionInterceptor.setTransactionManager( + new DataSourceTransactionManager(mock(DataSource.class))); + transactionInterceptor.setTransactionAttributeSource( + new AnnotationTransactionAttributeSource()); + var proxy = new ProxyFactory(repository); + proxy.setProxyTargetClass(true); + proxy.addAdvice(transactionInterceptor); + return (WorldDesignPublicationFenceRepository) proxy.getProxy(); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidenceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidenceTest.java new file mode 100644 index 0000000000..efc37b84fc --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidenceTest.java @@ -0,0 +1,237 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; + +import java.util.UUID; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import org.junit.jupiter.api.Test; + +class WorldDesignPublicationFenceEvidenceTest { + private static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID NIL_TENANT_ID = new UUID(0L, 0L); + private static final UUID INTAKE_REQUEST_ID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID INTAKE_OPERATION_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID CANONICAL_VERSION_ID = + UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID VERSION_IDENTITY_OPERATION_ID = + UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final String INTAKE_REQUEST_DIGEST = "sha256:" + "1".repeat(64); + private static final String SOURCE_EVIDENCE_DIGEST = "sha256:" + "a".repeat(64); + private static final String INTAKE_RECEIPT_DIGEST = "sha256:" + "2".repeat(64); + private static final String FULL_REQUEST_DIGEST = "f".repeat(64); + private static final String CONTENT_DIGEST = "b".repeat(64); + private static final long GAME_DESIGN_VERSION_ID = 9_000_000_042L; + + @Test + void bindsFullVersionToTheCanonicalPublicationDigestRequestGrammar() { + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.full( + TENANT_ID.toString(), Long.toString(GAME_DESIGN_VERSION_ID), "request-7"); + WorldDesignPublicationFenceEvidence evidence = + evidence("request-7", FULL_REQUEST_DIGEST, binding.derivedWorkflowIdentity()); + + assertThat(evidence.publicationBinding()).usingRecursiveComparison().isEqualTo(binding); + assertThat(evidence.publicationBinding().scopeKindValue()).isEqualTo("FULL_VERSION"); + assertThat(evidence.publicationBinding().versionId()) + .isEqualTo(Long.toString(GAME_DESIGN_VERSION_ID)); + assertThat(evidence.publicationBinding().baseVersionId()).isEmpty(); + assertThat(evidence.publicationBinding().scriptPatchVersion()).isEmpty(); + assertThat(evidence.requestDigest()).isEqualTo(FULL_REQUEST_DIGEST); + assertThat(evidence.requestDigest()).isNotEqualTo(binding.requestDigest()); + assertThat(evidence.publishWorkflowId()) + .isEqualTo("publish:" + TENANT_ID + ":publish-request:request-7"); + assertThat(evidence.gameDesignVersionId()).isEqualTo(GAME_DESIGN_VERSION_ID); + assertThat(evidence.canonicalVersionId()).isEqualTo(CANONICAL_VERSION_ID); + assertThat(evidence.versionIdentityOperationId()).isEqualTo(VERSION_IDENTITY_OPERATION_ID); + assertThat(evidence.ownerBinding().intakeRequestDigest()).isEqualTo(INTAKE_REQUEST_DIGEST); + } + + @Test + void rejectsChangedOrOmittedRequestAndWorkflowBindings() { + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.full( + TENANT_ID.toString(), Long.toString(GAME_DESIGN_VERSION_ID), "request-7"); + + assertThatIllegalArgumentException() + .isThrownBy(() -> evidence("request-7", FULL_REQUEST_DIGEST, "publish:wrong")); + assertThatIllegalArgumentException() + .isThrownBy(() -> evidence("request-7", null, binding.derivedWorkflowIdentity())); + assertThatIllegalArgumentException() + .isThrownBy(() -> evidence("request-7", "F".repeat(64), binding.derivedWorkflowIdentity())); + assertThatIllegalArgumentException() + .isThrownBy(() -> evidence("request-7", FULL_REQUEST_DIGEST, null)); + } + + @Test + void rejectsMalformedScopeAndAuthoredSourceIdentifiers() { + assertThatIllegalArgumentException() + .isThrownBy(() -> evidence("request-7", validDigest(), validWorkflow(), 0, 1L)); + assertThatIllegalArgumentException() + .isThrownBy(() -> evidence("request-7", validDigest(), validWorkflow(), 42, 0L)); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new WorldDesignPublicationFenceEvidence( + "FireMUD", + TENANT_ID, + CANONICAL_VERSION_ID, + VERSION_IDENTITY_OPERATION_ID, + 42, + INTAKE_REQUEST_ID, + INTAKE_OPERATION_ID, + INTAKE_REQUEST_DIGEST, + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE_DIGEST, + INTAKE_RECEIPT_DIGEST, + "request-7", + validDigest(), + 9, + validWorkflow())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new WorldDesignPublicationFenceEvidence( + "firemud", + TENANT_ID, + CANONICAL_VERSION_ID, + VERSION_IDENTITY_OPERATION_ID, + GAME_DESIGN_VERSION_ID, + INTAKE_REQUEST_ID, + INTAKE_OPERATION_ID, + INTAKE_REQUEST_DIGEST, + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE_DIGEST, + INTAKE_RECEIPT_DIGEST.substring("sha256:".length()), + "request-7", + validDigest(), + 9, + validWorkflow())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new WorldDesignPublicationFenceEvidence( + "firemud", + NIL_TENANT_ID, + CANONICAL_VERSION_ID, + VERSION_IDENTITY_OPERATION_ID, + GAME_DESIGN_VERSION_ID, + INTAKE_REQUEST_ID, + INTAKE_OPERATION_ID, + INTAKE_REQUEST_DIGEST, + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE_DIGEST, + INTAKE_RECEIPT_DIGEST, + "request-7", + validDigest(), + 9, + validWorkflow(NIL_TENANT_ID))); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new WorldDesignPublicationFenceEvidence( + "firemud", + TENANT_ID, + CANONICAL_VERSION_ID, + VERSION_IDENTITY_OPERATION_ID, + 42, + INTAKE_REQUEST_ID, + INTAKE_OPERATION_ID, + INTAKE_REQUEST_DIGEST, + SOURCE_OPERATION_ID, + "a".repeat(64), + INTAKE_RECEIPT_DIGEST, + "request-7", + validDigest(), + 9, + validWorkflow())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new WorldDesignPublicationFenceEvidence( + "firemud", + TENANT_ID, + CANONICAL_VERSION_ID, + VERSION_IDENTITY_OPERATION_ID, + GAME_DESIGN_VERSION_ID, + INTAKE_REQUEST_ID, + INTAKE_OPERATION_ID, + INTAKE_REQUEST_DIGEST.substring("sha256:".length()), + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE_DIGEST, + INTAKE_RECEIPT_DIGEST, + "request-7", + validDigest(), + 9, + validWorkflow())); + } + + @Test + void checkpointRequiresACompleteCanonicalDigestTuple() { + var checkpoint = + new WorldDesignPublicationFenceEvidence.Checkpoint("version:42", CONTENT_DIGEST, 2); + + assertThat(checkpoint.appliedCommitId()).isEqualTo("version:42"); + assertThat(checkpoint.contentDigest()).isEqualTo(CONTENT_DIGEST); + assertThat(checkpoint.digestSchemaVersion()).isPositive(); + assertThatIllegalArgumentException() + .isThrownBy( + () -> new WorldDesignPublicationFenceEvidence.Checkpoint("", CONTENT_DIGEST, 2)); + assertThatIllegalArgumentException() + .isThrownBy( + () -> new WorldDesignPublicationFenceEvidence.Checkpoint(" \t", CONTENT_DIGEST, 2)); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new WorldDesignPublicationFenceEvidence.Checkpoint( + "version:42", "B".repeat(64), 2)); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new WorldDesignPublicationFenceEvidence.Checkpoint( + "version:42", CONTENT_DIGEST, 0)); + } + + private static WorldDesignPublicationFenceEvidence evidence( + String requestId, String digest, String workflowId) { + return evidence(requestId, digest, workflowId, GAME_DESIGN_VERSION_ID, 9L); + } + + private static WorldDesignPublicationFenceEvidence evidence( + String requestId, String digest, String workflowId, long versionId, long epoch) { + return new WorldDesignPublicationFenceEvidence( + "firemud", + TENANT_ID, + CANONICAL_VERSION_ID, + VERSION_IDENTITY_OPERATION_ID, + versionId, + INTAKE_REQUEST_ID, + INTAKE_OPERATION_ID, + INTAKE_REQUEST_DIGEST, + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE_DIGEST, + INTAKE_RECEIPT_DIGEST, + requestId, + digest, + epoch, + workflowId); + } + + private static String validDigest() { + return FULL_REQUEST_DIGEST; + } + + private static String validWorkflow() { + return validWorkflow(TENANT_ID); + } + + private static String validWorkflow(UUID tenantId) { + return PublicationDigestRequestBinding.full( + tenantId.toString(), Long.toString(GAME_DESIGN_VERSION_ID), "request-7") + .derivedWorkflowIdentity(); + } +}